/**
 * Ubesafe.js 
 * This file creates a single global object Ubesafe on
 * whitch all other objects and properites are defined under.   
 * 
 * 
 **/
 
 var Ubisafe;
 if(!Ubisafe)
 	Ubisafe = {};
 Ubisafe.HOST = "http://openid.ubisafe.no";
 /**
  * The main function for crateing an OpenID login field
  */
 Ubisafe.OpenID = function(container){
 	Ubisafe.CONTAINER = container;
 	Ubisafe._init();
 	Ubisafe._createLogin(container);
 	
 	this.setStyleSheet = function(stylesheet){ 		
 		Ubisafe.Utils.includeCssFile(stylesheet);
 	}
 	this.setSuccessCallback = function(success_callback){
 		if(Ubisafe.Utils.readCookie("ubisafe_openid_result") == "SUCCESS"){
 			document.cookie = "ubisafe_openid_result=; path=/";
 			success_callback();
 		}
 	}
 	this.setSetupCallback = function(setup_callback){
 		if(Ubisafe.Utils.readCookie("ubisafe_openid_result") == "SETUP"){
 			document.cookie = "ubisafe_openid_result=; path=/";
 			setup_callback();
 		}	
 	}
 	this.setFailureCallback = function(failure_callback){
 		if(Ubisafe.Utils.readCookie("ubisafe_openid_result") == "FAILURE"){
 			document.cookie = "ubisafe_openid_result=; path=/";
 			failure_callback();
 		}
 	}	
 	this.setCancelCallback = function(cancel_callback){
 		if(Ubisafe.Utils.readCookie("ubisafe_openid_result") == "CANCEL"){
 			document.cookie = "ubisafe_openid_result=; path=/";
 			cancel_callback();
 		}
 	}	
 	this.setCreateAccountCallback = function(create_callback){
 		if(Ubisafe.Utils.readCookie("ubisafe_openid_result") == "SETUP"){
 			document.cookie = "ubisafe_openid_result=; path=/";
 			openid_url 		= unescape(Ubisafe.Utils.readCookie("ubisafe_openid_url"));
 			openid_email 	= unescape(Ubisafe.Utils.readCookie("ubisafe_openid_email"));
 			openid_nickname = unescape(Ubisafe.Utils.readCookie("ubisafe_openid_nickname")) || "+";
 			openid_fullname = unescape(Ubisafe.Utils.readCookie("ubisafe_openid_fullname")) || "+"; 			
 			create_callback({openid_url: openid_url, email: openid_email, nickname: openid_nickname, fullname: openid_fullname});			
 		}	 		
 	}
 	this.linkOpenidWithAccount = function(openid_url, token){
 		Ubisafe.Ajax.get("link_openid_with_account", {openid_url: openid_url, token: token}, function(json){
 			if(Ubisafe.link_ok_callback)
 				Ubisafe.link_ok_callback();
 		});
 	}
 	this.setLinkOKCallback = function(link_ok_callback){
 		Ubisafe.link_ok_callback = link_ok_callback;
 	}
 }

 Ubisafe.OpenidManager = function(container, token){
 	Ubisafe._init(); 	
 	/* Append the ids to the container */
 	Ubisafe.Ajax.get("list_openids", {token: token}, function(json){ 		
 		Ubisafe._populateOpenids(container, token, json) 		
 	}); 	
 }

Ubisafe._populateOpenids = function(container, token, json){
	Ubisafe.Utils.clearNode(container);
	var openids = json.openids; 		
	for(var i in openids){
		var div = Ubisafe.Utils.div("ubisafe_id_div");
		div.openid_url = openids[i];		
		div.appendChild(Ubisafe.Utils.openidInput(openids[i]));		
		div.appendChild(Ubisafe.Utils.button("Update", "ubisafe_update_id", function(){
			Ubisafe.Ajax.get("update_openid", {openid: this.parentNode.openid_url, new_openid: div.firstChild.value, token: token}, function(json){
				Ubisafe._populateOpenids(container, token, json);
			});
		}));	
		div.appendChild(Ubisafe.Utils.button("Delete", "ubisafe_delete_id", function(){
			Ubisafe.Ajax.get("delete_openid", {openid: this.parentNode.openid_url, token: token}, function(json){
				Ubisafe._populateOpenids(container, token, json);
			});
		}));
			
		container.appendChild(div); 			
	}
	var add_button = Ubisafe.Utils.button("Add an OpenID", "ubisafe_add_id", function(){
		var div = Ubisafe.Utils.div("ubisafe_id_div");
		var input = Ubisafe.Utils.openidInput();
		div.appendChild(input);		
		div.appendChild(Ubisafe.Utils.button("Add", "ubisafe_add_id2", function(){
			Ubisafe.Ajax.get("add_openid", {openid: input.value, token: token}, function(json){
				Ubisafe._populateOpenids(container, token, json);
			});
		}));	
		div.appendChild(Ubisafe.Utils.button("Delete", "ubisafe_delete_id2", function(){
			container.removeChild(div);
		}));			
		container.insertBefore(div, add_button);
	});
	container.appendChild(add_button);			
}

 Ubisafe._createLogin = function(container){ 	
 	/*create elements*/
 	var inner = "<form id='ubisafe_login_form' name='ubisafe_login_form' onsubmit='Ubisafe._doLogin(); return false; '>" +
 					"<div id='ubisafe_login_field'>" +
 						"<img src='http://www.plaxo.com/images/openid/login-bg.gif' id='ubisafe_openid_logo'/>"+
 						"<input id='ubisafe_login_input' type='text'/>" +
 					"</div>"+
 					"<input id='ubisafe_login_button' type='button' value='login' onclick='Ubisafe._doLogin()'/>" +
 				"</form>"+
 				"<a id='ubisafe_get_id'href='http://openid.ubisafe.no/'>Get OpenID</a>"+
 				"<p id='ubisafe_error_field'></p>";
 				
 	container.innerHTML = inner;
 	Ubisafe.openid_input = container.firstChild.firstChild.childNodes[1];
 	Ubisafe.Utils.attachFocus(Ubisafe.openid_input, "OpenID", "text");
 	Ubisafe.Utils.attachEnter(Ubisafe.openid_input, function(){ Ubisafe._doLogin(); }); 
 	Ubisafe.err_field = container.childNodes[2]; 	
 }
 
 Ubisafe._createManager = function(container, openids){
 					
 }
  
 Ubisafe._init = function(){ 	 
 	Ubisafe.Utils.includeCssFile(Ubisafe.HOST+"/css/openid_widget.css");
 }
 
 
 /** Function called when hitting the login button*/
 Ubisafe._doLogin = function(){
 	var params = { openid_identifier: Ubisafe.openid_input.value };
 	Ubisafe.Ajax.get("authenticate", params, function(json){ 		
 		if(json.status_code == 200){ 			
 			//alert(json.redirect ? "redirect" : "from");	
	 		if(json.redirect){
	 			window.location = json.redirect;
	 		}		
	 		else if(json.form){ 			
	 			var form = document.createElement("form");
	 			for(var i in json.form.form_tag_attributes){
	 				form[i] = json.form.form_tag_attributes[i];
	 			}
	 			for(var name in json.form.fields){
	 				var input = document.createElement("input");
	 				input.type = "hidden";
	 				input.name = name;
	 				input.value = json.form.fields[name]; 
	 				form.appendChild(input);	
	 			}
	 			
				document.body.appendChild(form);			
				form.submit(); 			
	 		}
 		}
 		else
 			Ubisafe._setError(json.status_text); 
 	});
 }
 
 Ubisafe._setError = function(err_string_){
 	Ubisafe.err_field.innerHTML = err_string_;
 }
 
 
 Ubisafe.Ajax = {};
 
 Ubisafe.Ajax.HOST = "Ubisafe_openid/Openid_server.php";
 
 if(Ubisafe.getAjaxHost){
 	Ubisafe.Ajax.HOST = Ubisafe.getAjaxHost(); 	
 }
 
 Ubisafe.Ajax.get = function(function_, params_, callback_){
 	var xmlhttp = Ubisafe.Ajax._xmlHttp();
 	
 	var url = Ubisafe.Ajax.HOST+"?f="+function_+"&rand="+Math.random()+Ubisafe.Ajax.serializeParams(params_);
 	var async = (callback_ ? 1:0);
 	xmlhttp.open("GET", url, async);	
	xmlhttp.send("");
	
	if(!async){
		var response = xmlhttp.responseText;
		var json = Ubisafe.Ajax.parseToObject(xmlhttp.responseText);
		return json;
	}
	else{
		xmlhttp.onreadystatechange = function() { 
			if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {								
				var json = Ubisafe.Ajax.parseToObject(xmlhttp.responseText);			
				callback_(json);			
			}							
	 	}
	}							
 }
 
 Ubisafe.Ajax._xmlHttp = function(){
 	var req = null;
    // branch for native XMLHttpRequest object. IE 7 seems to support this as well.
    if (window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = null;
        }
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
       	try {
          	req = new ActiveXObject("Microsoft.XMLHTTP");
      	} catch(e) {
        	try {
        		req = new ActiveXObject("Msxml2.XMLHTTP");
        	} catch(e) {
          		req = null;
        	}
		}
    }
    return req;
 
 }
 
 
 Ubisafe.Ajax.parseToObject = function(data){
	try{
		object = eval("("+data+")");
	}catch(ex){
		object = {status_code: 400, status_text: 'standard_error_string'};
	}
	return object;
 }
 
 Ubisafe.Ajax.serializeParams = function(object){
	var param_string = ""; 
	if(!object)
		return param_string;
	for(var param in object){
		var val = object[param].toString();
		val = encodeURI(val).replace(/;/gim, "%3B").replace(/&/gim, escape("&").replace(/\\/gim, escape("\\")));
		param_string += "&"+param+"="+val;
	}	
	return param_string; 
}
 
 
Ubisafe.Handler = {};

if(document.addEventListener){
	Ubisafe.Handler.add = function(element, event, handler, bubble){
		element.addEventListener(event, handler, bubble);		
	};
	Ubisafe.Handler.remove = function(element, event, handler, bubble){
		element.removeEventListener(event, handler, bubble);
	};
}
else if(document.attachEvent){
	Ubisafe.Handler.add = function(element, event, handler){
		if(Ubisafe.Handler._find(element, event, handler))
			return;
		var wrappedHandler = function(e){
			if(!e) e = window.event;
			var event = {
				_event: e,
				type: e.type,
				target: e.srcElement, 
				currentTarget: element, 
				relatedTarget: e.fromElement ? e.fromElement : e.toElement,
				eventPhase: (e.srcElement == element) ? 2 : 3, 
				
				clientX: e.clientX, 
				clientY: e.clientY, 
				screenX: e.screenX, 
				screenY: e.screenY,
				
				stopPropagation: function(){ 	this._event.cancelBubble = true; 	},
				preventDefault:  function(){	this._event.returnValue = false;	}
			}
			handler.call(element, event);
		};
		element.attachEvent("on"+event, wrappedHandler);		
				
		var h = {			
			element: 		element,
			event: 			event, 
			handler: 		handler, 
			wrappedHandler: wrappedHandler
		};
		if(!Ubisafe.Handler._allHandlers)
			Ubisafe.Handler._allHandlers = [];
		Ubisafe.Handler._allHandlers.push(h);
		//alert("Added handler width id: "+h.id+" there are "+Handler._allHandlers.length+" handlers registered.");
			
	};
	Ubisafe.Handler.remove = function(element, event, handler){		
		var h = Ubisafe.Handler._find(element, event, handler);
		if(!h) return;
		element.detachEvent("on"+event, h.wrappedHandler);		
		Ubisafe.Handler._allHandlers.splice(h.index, 1);		
		
		//alert("Removed handler width id: "+h.id+" there are "+Handler._allHandlers.length+" handlers registered.");
	};
}
	
Ubisafe.Handler._find = function(element_, event_, handler_){
	if(!Handler._allHandlers)
		return null;
	for(var i in Ubisafe.Handler._allHandlers){
		if(Ubisafe.Handler._allHandlers[i].element == element_ && Ubisafe.Handler._allHandlers[i].event == event_ && Ubisafe.Handler._allHandlers[i].handler == handler_){
			Ubisafe.Handler._allHandlers[i].index = i;
			return Ubisafe.Handler._allHandlers[i];
		}
	}
	return null;
}



/* Used for adding level 2 DOM events */
function addUniversalListener(element, event, func, bubble){
	if(element.addEventListener){
		element.addEventListener(event, func, bubble);
	}
	else if(element.attachEvent){
		element.attachEvent("on"+event, func);		
	}
}

function removeUniversalListener(element, event, func, bubble){
	if(element.removeEventListener)
		element.removeEventListener(event, func, bubble);
	else if(element.detachEvent)
		element.detachEvent("on"+event, func);

}




function SuperMouseover(element, over_func, out_func){
	var box_bounds;
 	var isOver = false;
 	
	var box_pos = getPosition(element);
	box_bounds = {
		left: 	box_pos.x,
		right: 	box_pos.x+element.offsetWidth, 
		top: 	box_pos.y,
		bottom: box_pos.y+element.offsetHeight
	};		

 
	
	var mouseMove = function(ev){		
		var mouse = mouseCoords(ev);				
		//fix_log.innerHTML= "top: "+mouse.y+" left: "+mouse.x+" box bouds top: "+box_bounds.top+ " bottom: "+box_bounds.bottom;		
		if(	mouse.x > box_bounds.left && mouse.x < box_bounds.right && mouse.y > box_bounds.top && mouse.y < box_bounds.bottom){	
			if(isOver == true)
				return;				
			isOver = true;
			over_func();			
		}
		else{
			if(isOver == false)
				return;				
			isOver = false;
			out_func();
		}
	}
	Ubisafe.Handler.add(document, "mousemove", mouseMove);	
	
	this.enable = function(){
		Ubisafe.Handler.add(document, "mousemove", mouseMove);		 		
	}
	
	this.disable = function(){		
		out_func();
		Ubisafe.Handler.remove(document, "mousemove", mouseMove);
	}
	
	this.reposition = function(){
		box_pos = getPosition(element);
		box_bounds = {
			left: 	box_pos.x,
			right: 	box_pos.x+element.offsetWidth, 
			top: 	box_pos.y,
			bottom: box_pos.y+element.offsetHeight
		};	
	}
}



 Ubisafe.Localisation = {};
 Ubisafe.Localisation.local_string = {
 	default_login: "Write your OpenID here", 
 	login: "Log in",
 	get_openid:	"Get OpenID"
 };
 
 Ubisafe.Localisation.localString = function(string_){
 	if(Ubisafe.Localisation.local_string[string_])
 		return Ubisafe.Localisation.local_string[string_];
 	return "::"+string_;	
 }


 Ubisafe.ModalWindow = {};
 Ubisafe.Utils = {};
 Ubisafe.Utils.input = function(default_, class_, enter_){
 	var utils = Ubisafe.Utils;
 	
	var div = document.createElement("input");
	if(default_){
		div.value = default_;
		div.style.color = "#555";
		utils.addListener(div, "focus", function(){
			if(div.value == default_)
				div.value = ""; 
			div.style.color = "#000";
		});
		utils.addListener(div, "blur", function(){
			if(!div.value){
				div.value = default_;
				div.style.color = "#555";
			} 			
		});
	} 	 
	div.className = "ubisafe";
	if(class_)
		div.className += " "+class_;
	if(enter_){
		utils.addListener(div, "keyup", function(e){
			e = e || window.event;
			var keynum = e.keyCode || e.which;
			if(keynum == 13)
				enter_();
		});
	}
	
	return div;
 }
 
 Ubisafe.Utils.div = function(class_){
 	var div = document.createElement("div");
 	if(class_)
 		div.className = class_;
 	return div;
 }
 
 Ubisafe.Utils.image = function(src_, class_){
 	var img = document.createElement("img");
 	img.src = src_;
 	if(class_)
 		img.className = class_;
 	return img;
 }
 
 Ubisafe.Utils.link = function(text_, url_){
 	var link = document.createElement("a");
 	link.href = url_;
 	link.innerHTML = text_;
 	link.className = "ubisafe";
 	return link;
 }
 
 Ubisafe.Utils.button = function(value_, class_, click_){
 	var button = document.createElement("input");
 	button.type = "button";
 	button.value = value_;
 	if(click_){
 		this.addListener(button, "click", click_);
 	}
 	button.className = "ubisafe";
	if(class_)
		button.className += " "+class_;
 	
 	return button; 		
 }
 
 Ubisafe.Utils.openidInput = function(value_){ 	
 	var input = document.createElement("input");
 	value_ = value_ || "";
	input.value = value_;
	input.className = "ubisafe_openid_inputfield";
	return input;	
 }
 
 
 Ubisafe.Utils.addListener = function(element, event, func, bubble){
 	if(element.addEventListener){
		element.addEventListener(event, func, bubble || false);
	}
	else if(element.attachEvent){
		element.attachEvent("on"+event, func);		
	}
 	else
 		element["on"+event] = func;
 }
 
 Ubisafe.Utils.removeListener = function(element, event, func, bubble){
	if(element.removeEventListener)
		element.removeEventListener(event, func, bubble || false);
	else if(element.detachEvent)
		element.detachEvent("on"+event, func);
 	else
 		element["on"+event] = null;
 }

 Ubisafe.Utils.includeCssFile = function(url) {
	if (document.body == null) {
        try {
            document.write("<link rel='stylesheet' href='" + url + "' type='text/css'/>");
            return;
        } catch (e) {}
    }
    
    var link = document.createElement("link");
    link.setAttribute("rel", "stylesheet");
    link.setAttribute("type", "text/css");
    link.setAttribute("href", url);
    document.getElementsByTagName("head")[0].appendChild(link);
 }
 
 Ubisafe.Utils.attachFocus = function(input, text_, type_){
 	input.style.color = "#555";
	input.value = text_;
	input.onfocus = function(){
		if(input.value == text_){		
			input.value = "";
			input.style.color = "#000";
		}
		input.type = type_;
	}
	input.onblur = function(){
		if(input.value == ""){
			input.value = text_;
			input.style.color = "#555";
			input.type = "text";
		}
	
	}
 	
 }
 
 
 Ubisafe.Utils.attachEnter = function(input, func_){
	input.onkeyup = function(e){			
		e = e || window.event				
		var keynum = e.keyCode || e.which;				
		if(keynum == 13){
			func_();
		}		
	}
}
 Ubisafe.Utils.readCookie = function(name){
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
 
 Ubisafe.Utils.clearNode = function(node){
 	while(node.firstChild){
 		node.removeChild(node.firstChild);
 	}
 }
 
 Ubisafe.Utils.displayMessage = function(header, message, ok_callback, cancel_callback){
	if(!Ubisafe.dialog_bg){
		Ubisafe.dialog_bg 		= Ubisafe.Utils.div("ubisafe_transparent");
		Ubisafe.dialog_bg.id 	= "ubisafe_modal_background";
		
		Ubisafe.dialog 			= Ubisafe.Utils.div();
		Ubisafe.dialog.id 		= "ubisafe_modal_message";
		
		Ubisafe.dialog.innerHTML= "<div id='ubisafe_modal_message_inner'>"+
									"<H3 id=''></H3>"+
								  	"<p></p>"+
								  	"<div id='ubisafe_modal_message_buttons'><input type='button' value='cancel' /><input type='button' value='ok' /></div>"+
								  "</div>";
		
		document.body.appendChild(Ubisafe.dialog_bg);		
		document.body.appendChild(Ubisafe.dialog);				
	}
	Ubisafe.dialog_bg.style.display = "block";
	Ubisafe.dialog.style.display 	= "block";
	Ubisafe.dialog.firstChild.childNodes[0].innerHTML = header;
	Ubisafe.dialog.firstChild.childNodes[1].innerHTML = message;
	Ubisafe.dialog.firstChild.childNodes[2].childNodes[0].onclick = function(){		
		Ubisafe.dialog_bg.style.display = "none";
		Ubisafe.dialog.style.display 	= "none";		
		if(cancel_callback)
			cancel_callback();				
		
	}
	Ubisafe.dialog.firstChild.childNodes[2].childNodes[1].onclick = function(){
		Ubisafe.dialog_bg.style.display = "none";
		Ubisafe.dialog.style.display 	= "none";
		if(ok_callback)
			ok_callback();				
	}
 }
