/*
Stato.js
*/
 document.createElement('statoelement');


if(!String.prototype.startsWith){
	String.prototype.startsWith = function(str){return (this.match("^"+str)==str)}
}
if(!String.prototype.endsWith){
	String.prototype.endsWith = function(str){return (this.match(str+"$")==str)}
}

/*if(!Node.prototype.getElementsByAttribute){
	Node.prototype.getElementsByAttribute = function(attribute, value, tagName) {
		var children = this.getElementsByTagName((tagName || '*'));	
		var elements = [];
		for(var i=0;i<children.length;i++){
			if(children[i].hasAttribute(attribute)){
				if(!value || children[i].getAttribute(attribute) == value) {
					elements.push(children[i]);
				}
			}
		}
		return elements;
	};
}
*/


function BrowserDetect(){
	var ua = navigator.userAgent.toLowerCase();
	this.isIE = ( (ua.indexOf('msie') != -1) && (ua.indexOf('opera') == -1));
}

var browser = new BrowserDetect();

if(!browser.isIE){
	if(!Node.prototype.swapNode){
		Node.prototype.swapNode = function (node) {
			var nextSibling = this.nextSibling;
			var parentNode = this.parentNode;
			node.parentNode.replaceChild(this, node);
			parentNode.insertBefore(node, nextSibling);
		};
	}
}

function StatoObj(){
	var thissi= this;
	this.charset = "UTF-8";
	this.brokerURL	= null;
	this.brokerpath	= "/Session/Broker";
	this.confirmStr		= "Haluatko varmasti poistaa?";
	this.pistejono = ".";
	this.originaltitle = "";
	this.loaderDiv = null;
	this.storeparams = true;
	
	try {
	this.DBTree	= (top.Stato)?top.Stato.DBTree:new Array();
	}catch(ex){
	this.DBTree	= new Array();
		}
	
	this.requestpool = new Array();
	this.jkloops = new Array();
	this.jkloopwait = 1000;
	//this.brokerpath	= "/Browser/Broker";

	this.brokervalue = "";
	this.broker = new Array();
	try {
	this.brokerListeners = (top.Stato)?top.Stato.brokerListeners:new Array();
	}catch(ex){
	this.brokerListeners	= new Array();
	}
	
	this.statusFeedback = function(mode,objid){
		var jkloop=null;
		if(document.getElementById(objid+"_jkloop")){
			jkloop = document.getElementById(objid+"_jkloop");
		}else{
			jkloop = document.createElement("div");
			jkloop.id = objid+"_jkloop";
			document.body.appendChild(jkloop);
		}
		if (mode=="run"){
			var obj = document.getElementById(objid);
			document.body.style.cursor = "wait";
			jkloop.className="jkloop";
			jkloop.style.position="absolute";
			jkloop.style.left = this.findPos(obj)[0]+"px";
			jkloop.style.top = this.findPos(obj)[1]+"px";
			jkloop.style.width = obj.offsetWidth+"px";
			jkloop.style.height = obj.offsetHeight+"px";
			jkloop.zIndex= 5000;
			jkloop.innerHTML='<img src="ElementImages/ajax-loader.gif" style="position:absolute;top:'+(parseInt(Number(obj.offsetHeight)/2)-12)+'px;left:'+(parseInt(Number(obj.offsetWidth)/2)-12)+'px;"/>';
			jkloop.style.display= "block";
		}
		if (mode=="stop"){
			document.body.style.cursor = "auto";
			if(jkloop){
				jkloop.style.display= "none";
			}

			//top.document.body.style.cursor = "auto";
			//top.document.title = this.originaltitle;
			//this.pistejono = ".";
			//this.originaltitle = "";

		}
	};


	this.StoreFrames =function(){
		if(document.getElementById("f_outliner").width){
			var f_outliner_width = document.getElementById("f_outliner").width;
			var f_list_width = document.getElementById("f_list").width;
			var frameset2_p = Math.round(100*f_outliner_width/(f_outliner_width+f_list_width));
			var f_list_height = document.getElementById("f_list").height;
			var f_form_height = document.getElementById("f_form").height;
			var frameset3_p = Math.round(100*f_list_height/(f_list_height+f_form_height));
			Stato.SetCookie("frameset2",frameset2_p+"%,"+(100-frameset2_p)+"%");
			Stato.SetCookie("frameset3",frameset3_p+"%,"+(100-frameset3_p)+"%");
		}else{
			Stato.SetCookie("frameset2",document.getElementById("frameset2").cols);
			Stato.SetCookie("frameset3",document.getElementById("frameset3").rows);
		}
	};


	this.GetRequest = function(){
		if(window.XMLHttpRequest) {
   		    this.GetRequest = function(){
   		      return new XMLHttpRequest();
   		    };
   		   return new XMLHttpRequest();
   		} else if(window.ActiveXObject) {
   		  var msxml = ['MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'];
   		  for (var i=0, len = msxml.length; i < len; ++i) {
   		    try {
   		      this.GetRequest = function() {
   		       	return new ActiveXObject(msxml[i]);
   		      };
   		      return new ActiveXObject(msxml[i]);
   		    }
   		    catch(e) {}
   		  }
   		}
   		return null;
	};


	this.HandleClick = function(e){
		try{
			var targ;
			if (!e)
				var e = window.event;
			if (e.target)
				targ = e.target;
			else if (e.srcElement)
				targ = e.srcElement;
			if (targ.nodeType == 3)
				targ = targ.parentNode;
			Stato.eventNode = targ;
		}catch(ex){

		}
	};


	this.setPosition = function(id){
		var next = document.getElementById(id).nextSibling;
		while(next.nodeType!=1){
			next = next.nextSibling;
		}
		
		if(next){
			document.getElementById(id).style.left = Stato.findPos(next)[0]+'px';
		}
	};

	this.setValue = function(path,key,value){
		path=this.brokerpath+"/"+path;
		this.loadXMLDoc(this.brokerURL+"?path="+path+"&key="+key+"&value="+value,this.done);
	};

	this.searchDOMChildren = function( pnode , attribute , notattribute , returnArray ) {
		if (pnode.hasChildNodes()) {
			var children = pnode.childNodes;
			var tnode = "";
			for (var i=0 ; i<children.length ; i++ ){
				tnode = children[i];
				if (tnode.nodeType=="1") {
					if (tnode.getAttribute(attribute) == "true") {
						returnArray[returnArray.length] = tnode;
					}
					if (!(tnode.getAttribute(notattribute) == "true")) {
						this.searchDOMChildren( tnode , attribute , notattribute , returnArray );
					}
				}
			}
		}
	};



	/*
	this.getValue = function(path,key){
		path=this.brokerpath+"/"+path;
		this.loaderDiv = document.createElement("DIV");
		this.loaderDiv.id = "tmploader";
		this.loadContent("jep",this.brokerURL+"?path="+path+"&key="+key+"&mode=getvalue");
	};
	*/

	
	this.ReadBroker = function(){
		//path=this.brokerpath+"/"+path;
		path=this.brokerpath;
		
		var tmp = this.JSONParse(this.loadURL(this.brokerURL+"?path="+path+"&mode=listfield"));
		var str = "";
		for(var key in tmp){
			str += key +" = "+ tmp[key] +"\n"; 
		}
		window.status = new Date().getTime()+" "+str;
	};	

	this.SynchronizeBroker = function(){
		path=this.brokerpath;
		
		var tmp = this.JSONParse(this.loadURL(this.brokerURL+"?path="+path+"&mode=synchronize&testi2=joo"));
		var str = "";
		for(var key in tmp){
			str += key +" = "+ tmp[key] +"\n"; 
		}
		alert(str);
	};	

	this.JSONParse = function(text){
		if(JSON){
			return JSON.parse(text);
		}else{
			var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(text.replace(/"(\\.|[^"\\])*"/g, ''))) && eval('(' + text + ')');
			return eval(my_JSON_object);		
		}
	};

	this.Add = function(editor,addpath){
		this.addContainer = document.getElementById(editor);
		this.loaderDiv = document.createElement("DIV");
		this.loadXMLDoc(this.addURL+"?AddPath="+addpath,this.processAddReqChange);
	};

	this.Remove = function(blockID,removepath){
		if(confirm(this.confirmStr)==true){
			block = document.getElementById(blockID);
			var	editor = block.parentNode;
			this.removeblock = block;
			Stato.loadXMLDoc(this.removeURL+"?StatoRemove=true&RemovePath="+removepath,this.processRemoveReqChange);
		}
	};

	this.ClearContent = function(blockID){
		document.getElementById(blockID).innerHTML="";
	};

	this.processRemoveReqChange = function(req){
		if(req.readyState == 4) {
			if (req.status == 200) {
				if(req.responseText=="OK"){
					if(selectedId){
						if(selectedId==Stato.removeblock.id)
							selectedId = "";
					}
					if(selectedId2==Stato.removeblock.id)
						selectedId2 = "";
					var	editor = Stato.removeblock.parentNode;
					editor.removeChild(Stato.removeblock);
				}
			} else {
				alert("There was a problem retrieving the XML data:\n" + req.statusText);
			}
		}
	};

	this.processAddReqChange = function(req){
		if(req.readyState == 4) {
			if (req.status == 200) {
					Stato.loaderDiv.innerHTML = req.responseText;
					//alert(Stato.loaderDiv.firstChild.nodeName);
					if( Stato.loaderDiv.firstChild.nodeName == "#text")
						Stato.addContainer.appendChild(Stato.loaderDiv.firstChild.nextSibling);
					else
						Stato.addContainer.appendChild(Stato.loaderDiv.firstChild);
					Stato.loaderDiv = null;
			} else {
				alert("There was a problem retrieving the XML data:\n" + req.statusText);
			}
		}
	};


	this.done = function() {};

	this.GetNodeList = function(block){
		var nodelist = new Array();
		var	editor = block.parentNode;
		for(var i=0;i< editor.childNodes.length;i++){
			var childN = editor.childNodes[i];
			if(childN.nodeType=="1"){
				if (childN.getAttribute("id") != "" && childN.getAttribute("id") != null){
					nodelist.push(childN.id);
				}
			}
		}
		return nodelist;
	};


	this.loadURL = function(urli){
		var req = Stato.GetRequest();
		req.open("GET",urli,false);
		req.send("");
		return req.responseText;
	};

	this.loadXMLDoc = function(url,handler){
		var req = Stato.GetRequest();
		req.onreadystatechange = function(){ handler(req) };
		req.open("GET", url, true);
		req.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset="+this.charset);
		req.send(null);
	};

	this.postXMLDoc = function(url,query,handler) {
		//var loader = new Stato.AjaxLoader();
		//loader.postXMLDoc(url,query,handler);
		var req = Stato.GetRequest();
		req.onreadystatechange = function(){ handler(req) };
		req.open("POST", url, true);
		req.setRequestHeader("Content-type","application/x-www-form-urlencoded;charset="+this.charset);
		req.send(query);
	};

	this.setQueryString = function(element){
		var queryString="";
		var root = document.getElementById(element);
		var inputs = root.getElementsByTagName("INPUT");
		var textareas = root.getElementsByTagName("TEXTAREA");
		var selects = root.getElementsByTagName("SELECT");
		for(var i = 0; i <  inputs.length; i++) {
			if( inputs[i].name != '' ){
				if (inputs[i].type == "text" | inputs[i].type == "hidden") {
		            	queryString += inputs[i].name + "=" + this.encodePostValue(inputs[i].value) + "&";
		         	}
				if (inputs[i].type == "checkbox") {
					if (inputs[i].checked) {
		                  queryString += inputs[i].name + "=" + this.encodePostValue(inputs[i].value) + "&";
		               } else {
		                  //queryString += inputs[i].name + "=&";
		               }
				}
				if (inputs[i].type == "radio") {
					if (inputs[i].checked) {
						queryString += inputs[i].name + "=" + this.encodePostValue(inputs[i].value) + "&";

					}
				}
			}
			// vanha - queryString += inputs[i].name+"="+encodeURIComponent(inputs[i].value)+"&";
		}
		for(var i = 0; i <  textareas.length; i++){
			if(textareas[i].getAttribute("cmstextarea")=="true"){
				kentat[textareas[i].id.replace("source_","")].tallenna();
			}
			if(  textareas[i].name != ''  ){
				queryString += textareas[i].name+"="+this.encodePostValue(textareas[i].value)+"&";
			}
		}
		for(var i = 0; i <  selects.length; i++){
			if( selects[i].name != ''  ){
				queryString += selects[i].name+"="+this.encodePostValue(selects[i].options[selects[i].selectedIndex].value)+"&";
			}
		}
		return queryString;
	};

	this.encodeValue = function(value){
		//return(this.charset == "UTF-8")?encodeURIComponent(value):escape(value).replace(/\+/g,'%2B');
			return escape(value).replace(/\+/g,'%2B');

	};

	this.encodePostValue = function(value){
		return(this.charset == "UTF-8")?encodeURIComponent(value):escape(value).replace(/\+/g,'%2B');
	};

	/*
	this.NewReqObj = function(){
		if(window.XMLHttpRequest) {
    	    this.NewReqObj = function(){
    	      return new XMLHttpRequest();
    	    };
    	   return new XMLHttpRequest();
    	} else if(window.ActiveXObject) {
    	  var msxml = ['MSXML2.XMLHTTP.3.0','MSXML2.XMLHTTP','Microsoft.XMLHTTP'];
    	  for (var i=0, len = msxml.length; i < len; ++i) {
    	    try {
    	      this.NewReqObj = function() {
    	       	return new ActiveXObject(msxml[i]);
    	      };
    	      return new ActiveXObject(msxml[i]);
    	    }
    	    catch(e) {}
    	  }
    	}
    	return null;
	};
	*/

	this.setParam = function(path,key,value){
		if(!this.DBTree[path])
			this.DBTree[path] = new Array();
		this.DBTree[path][key]= value;
	};



	this.getCurrentNotify = function( key ){
		 if( this.element.refreshedNotifyPath ){
		 	returnvalue = this.getNotify( this.element.refreshedNotifyPath, key );
		 	if( returnvalue ){
		 		return returnvalue;
		 	}
		 	return null;
		 }
	}

	this.getNotify = function(param1,param2){
		if(arguments.length==1){
			key = param1;
			element = this.brokerListenerPath;
			var tmp = this.brokerListenerPath.split(",");
			var returnvalue ="";
			for(var i=0;i<tmp.length;i++){
				if(this.DBTree[tmp[i]] && this.DBTree[tmp[i]][key]!=undefined){
					returnvalue = this.DBTree[tmp[i]][key];
				}
			}
			return returnvalue;
		}else{
			element = param1;
			key = param2;
			return (this.DBTree[element][key])?this.DBTree[element][key]:"";
		}
		
		
	};

	this.getParam = function(param1,param2){	
		if(arguments.length==1){
			return this.getNotify(param1);
		}else if(arguments.length==2){
			return this.getNotify(param1,param2);
		}
	};

	this.getParams = function(element){
		var str = "";
			str +="?element="+element;
			str +="&StoreParams="+this.storeparams;
			str +="&path="+document.getElementById(element).getAttribute("element");
			str +="&BrokerPath="+this.brokerpath;


		var tmpArray = new Array();
		if(this.DBTree["common"] instanceof Array){
			for(key in this.DBTree["common"]){
				if(typeof this.DBTree["common"][key] != "function"){
					tmpArray[key] = this.DBTree["common"][key];
				}
			}
		}
		for(key in this.DBTree[element]){
			if(this.DBTree[element][key]!=null)
				if(typeof this.DBTree[element][key] != "function"){
					tmpArray[key] = this.DBTree[element][key];
				}
		}
		for(key in tmpArray){
			if(tmpArray[key]!=null){
				if(typeof tmpArray[key] != "function"){
					str += "&"+key+"="+tmpArray[key];
				}
			}
		}
		delete tmpArray;
		return str;
	};

	this.loadContent = function(element,url){
		//this.jkloops[element] = setTimeout("Stato.statusFeedback('run','"+element+"')",this.jkloopwait);
		this.loadXMLDoc(url,function(req){Stato.processReqChange(req,element)});
	};

	this.loadXMLHeaders = function(url,handler){
		var req = Stato.GetRequest();
		req.onreadystatechange = function(){ handler(req) };
		req.open("HEAD", url, true);
		req.send(null);
	};


	this.LastModified = function(element,url,handler){
		if(arguments.length==2)
			handler=Stato.LastModifiedReqChange;
		this.loadXMLHeaders(url,function(req){handler(req,element)});
	};

	this.LastModifiedReqChange = function(req,element) {
		try{
			var rootNodeObj = document.getElementById(element);
			if (req.readyState == 4) {
				if (req.status == 200) {
					rootNodeObj.innerHTML =  new Date(req.getResponseHeader("Last-Modified")).getTime();
				}
			}
		}catch(e){
			//alert(rootNodeObj.id+e.message);
		}
	};




	this.replaceContent = function(element,url){
		var loaderDiv = document.createElement("DIV");
		this.loadXMLDoc(url,function(req){Stato.processReqChange2(req,loaderDiv,element)});
	};


	this.LoadElement = function(container,element){
		if(arguments.length==0)
			container = this.element;
		if( container.refreshedNotifyPath ){
			var params = container.card.toString();			
			if( container.refreshedNotifyPath ){ for( var i in top.Stato.DBTree[ container.refreshedNotifyPath ]  ){ params += "&"+ i + "=" +  top.Stato.DBTree[container.refreshedNotifyPath][i]; } }			
			Stato.loadContent( container.get('Element.Broker.Id'),container.URL+'?'+params);
		} else {
			this.loadXMLDoc(this.elementeditURL+"?path="+element,function(req){Stato.processReqChange(req,container)});
		}
		
	};


	this.postContent = function(element,url){
		var query = this.setQueryString(element);
		query += this.ReadGetParamsToPost(url);
		url = url.replace(/\?.*$/,'');
		this.postXMLDoc(url,query,function(req){Stato.processReqChange(req,element)});
	};

	this.ReadGetParams = function(url){
		var query = "";
		var  tmp =  url.split("?");
		if(tmp.length==2){
			var getparams = tmp[1];
			var params = getparams.split("&");
			for(var i=0;i<params.length;i++){
				var param = params[i].split("=");
				var key=param[0];
				var value=param[1];
				query +=key + "=" + this.encodeValue(value) + "&";
			}
		}
		return query;

	};

	this.ReadGetParamsToPost = function(url){
		var query = "";
		var  tmp =  url.split("?");
		if(tmp.length==2){
			var getparams = tmp[1];
			var params = getparams.split("&");
			for(var i=0;i<params.length;i++){
				var param = params[i].split("=");
				var key=param[0];
				var value=param[1];
				query +=key + "=" + this.encodePostValue(value) + "&";
			}
		}
		return query;

	};


	this.showElement = function(element){
		document.getElementById(element).style.display = "";
	};

	this.hideElement = function(element){
		document.getElementById(element).style.display = "none";
	};

	this.openElement = function(element){
		this.refreshContent(element);
		document.getElementById(element).style.display = "";
	};

	this.closeElement = function(element){
		document.getElementById(element).style.display = "none";
		document.getElementById(element).innerHTML = "";
	};

	this.refreshElement = function(element){
		var el = document.getElementById(element).getAttribute("element");
		if(el){
			this.loadContent(element,this.elementlinkURL+Stato.getParams(el));
		}
		else if(document.getElementById(element).getAttribute("url")){
			this.loadContent(element,document.getElementById(element).getAttribute("url"));
		}


	};

	this.sendParams = function(element){
		var el = document.getElementById(element).getAttribute("element");
		if(el){
			this.loadXMLDoc(this.storeParamsURL+Stato.getParams(el),IE6Null);
			/*
			this.loadXL(element,this.elementlinkURL+Stato.getParams(el));
			*/
		}
	};


	this.editElement = function(element){
		var el = document.getElementById(element).getAttribute("element");
		if(el){
			this.loadContent(element,this.elementeditURL+Stato.getParams(el));
		}
		else if(document.getElementById(element).getAttribute("url")){
			this.loadContent(element,document.getElementById(element).getAttribute("url"));
		}
	};

	this.postElement = function(element){
		var el = document.getElementById(element).getAttribute("element");
		if(el){
			var elementlink = (document.getElementById(element).getAttribute("elementlink"))?document.getElementById(element).getAttribute("elementlink"):this.elementeditURL;
			this.postContent(element,elementlink+Stato.getParams(el));
		}
		else if(document.getElementById(element).getAttribute("url")){
			this.postContent(element,document.getElementById(element).getAttribute("url"));
		}
	};

	this.processReqChange = function(req,elemString) {
		try{
			//Stato.statusFeedback("run",elemString);
			if (req.readyState == 4) {
				if (req.status == 200) {
					document.getElementById(elemString).innerHTML = req.responseText;
					var tmp_divi = document.createElement("DIV");
					tmp_divi.innerHTML = "&nbsp;"+req.responseText;
					var scriptit = tmp_divi.getElementsByTagName("script");
					
					for(var eval_i=0;eval_i<scriptit.length;eval_i++){
						try {
						eval(scriptit[eval_i].innerHTML);
						}catch(e){
						Stato.Debug("Stato.js: content js eval: " + document.getElementById(elemString) + e);
						}
					}
					if (document.getElementById(elemString).parentNode.getAttribute("dragable"))
						initBoxHeader(document.getElementById(elemString));
					if(document.getElementById(elemString).getAttribute("onrefresh")){
						thissi.refreshElement(document.getElementById(elemString).getAttribute("onrefresh"));
					}
				} else {
					alert("There was a problem retrieving the XML data:\n" + req.statusText);
				}
				clearTimeout(Stato.jkloops[elemString]);
				//Stato.statusFeedback("stop",elemString);
			}
		}catch(e){
				//Stato.Debug("Stato.js: processReqChange: element: " +elemString["node"].id );
			 
				Stato.Debug("Stato.js: processReqChange: " + elemString + document.getElementById(elemString) + e);
			 
		
			Stato.statusFeedback("stop",document.getElementById(elemString));
			Stato.Debug("Stato.js: processReqChange: " + elemString + document.getElementById(elemString) + e);
			//alert(rootNodeObj.id+e.message);
		}
	};

	this.processReqChange2 = function(req,loaderDiv,element) {
		try{
			var rootNodeObj = document.getElementById(element);
			//Stato.statusFeedback("run",element);
			if (req.readyState == 4) {
				if (req.status == 200) {
					loaderDiv.innerHTML = req.responseText;
					// Firefox tulkitsee whitespacen ensimmaiseksi ja talla peipalla saadaan systeemi toimimaan myos IE:ssa 
					
					var newNode = loaderDiv.firstChild.nextSibling;
					if( !newNode){
						var newNode = loaderDiv.firstChild;
					}
					
					var parentNode = document.getElementById(element).parentNode;
					parentNode.replaceChild(newNode,document.getElementById(element));
					
					var scriptit = newNode.getElementsByTagName("script");
					for(var eval_i=0;eval_i<scriptit.length;eval_i++){
						try {
						eval(scriptit[eval_i].innerHTML);
						}catch(e){
						Stato.Debug("Stato.js: content js eval: " + document.getElementById(element) + e);
						}
					}
					
					/*
					var tmp_divi = document.createElement("DIV");
					tmp_divi.innerHTML = "&nbsp;"+req.responseText;
					var scriptit = tmp_divi.getElementsByTagName("script");
					for(var eval_i=0;eval_i<scriptit.length;eval_i++){
						eval(scriptit[eval_i].innerHTML);
					}
					if (rootNodeObj.parentNode.getAttribute("dragable"))
						initBoxHeader(rootNodeObj);
					if(rootNodeObj.getAttribute("onrefresh")){
						thissi.refreshElement(rootNodeObj.getAttribute("onrefresh"));
					}
					*/
				} else {
					alert("There was a problem retrieving the XML data:\n" + req.statusText);
				}
				//Stato.statusFeedback("stop",element);
			}
		}catch(e){
			Stato.Debug("Stato.js: processReqChange: " + e);
			//Stato.statusFeedback("stop",element);
			alert(rootNodeObj.id+e.message);
		}
	};


	this.swapNodes = function(node1,node2){
			var ekku = null;
			var tokku = null;
			var tmp = node1.parentNode.childNodes;

			for(var i =0;i< tmp.length;i++){
				if(tmp[i]==node1){
					ekku = node1;
					break;
				}
				if(tmp[i]==node2){
					ekku = node2;
					break;
				}
			}
			if(ekku==node1){
				node2.swapNode(node1);
			}else{
				node1.swapNode(node2);
			}

		//node1.swapNode(node2);
	};

/*
	this.swapNodes = function(node1,node2){
		if(!node1.swapNode){
			var parentNode = node1.parentNode;
			var tmp = parentNode.childNodes;
			var ekku = null;
			for(var i =0;i< tmp.length;i++){
				if(tmp[i]==node1){
					ekku = node1;
					break;
				}
				if(tmp[i]==node2){
					ekku = node2;
					break;
				}
			}
			if(ekku==node1){
				parentNode.insertBefore(node2, node1);
			}else{
				parentNode.insertBefore(node1, node2);
			}
		}
		else
			node1.swapNode(node2);
	};
*/

	this.getNodeIndex = function(nodelist,node){
		for(var i=0;i<nodelist.length;i++){
			if(nodelist[i]==node.id){
				return i;
			}
		}
		return null;
	};

	this.getPrevious = function(node){
		var nodelist = this.GetNodeList(node);
		index = this.getNodeIndex(nodelist,node);
		if(index!=null && index>0)
			return nodelist[index-1];
		else
			return null;
	};

	this.getNext = function(node){
		var nodelist = this.GetNodeList(node);
		index = this.getNodeIndex(nodelist,node);
		if(index!=null && index<nodelist.length-1)
			return nodelist[index+1];
		else
			return null;
	};

	 this.findPos = function(obj) {
		var curleft = curtop = 0;
		if (obj.offsetParent) {
			curleft = obj.offsetLeft;
			curtop = obj.offsetTop;
			while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft;
				curtop += obj.offsetTop;
			}
		}
		return [curleft,curtop];
	};

	this.SetCookie = function(name,value){
		var exp = new Date();
		exp.setYear(exp.getFullYear()+1);
		document.cookie = name + "=" + value + ";path=/;expires=" + exp.toGMTString();
	};

	this.GetCookie = function(name){
		var dc = document.cookie;
		var prefix = name + "=";
		var begin = dc.indexOf("; " + prefix);
		if (begin == -1) {
			begin = dc.indexOf(prefix);
			if (begin != 0) return null;
		} else {
			begin += 2;
		}
		var end = document.cookie.indexOf(";", begin);
		if (end == -1) {end = dc.length;}
		return unescape(dc.substring(begin + prefix.length, end));
	};


	 this.getPageSize = function(){
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}

		var windowWidth, windowHeight;
		if (self.innerHeight) {
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth;
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) {
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = yScroll;
		}
		if(xScroll < windowWidth){
			pageWidth = xScroll;
		} else {
			pageWidth = windowWidth;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
	};

	this.LoadDialog = function(url,mode,containerID,width,height,left,paramObj){
		if(!paramObj){ paramObj = {}; }
		if(!mode) mode="div";
		var pagesize = this.getPageSize();
		var dimmer = document.createElement("div");
		dimmer.setAttribute("id","addpage_dimmer");
		dimmer.style.width="100%";
		//dimmer.style.width=pagesize[0]+"px";
		dimmer.style.height=pagesize[1]+"px";
		dimmer.innerHTML = " ";
		dimmer.style.display="block";
		dimmer.setAttribute("onclick","Stato.CancelDialog()");
		var placement_bg = document.createElement("div");


		placement_bg.setAttribute("id","addpage_placement_bg");
		placement_bg.innerHTML = " ";
		var spacer = document.createElement("div");
		spacer.setAttribute("class","spacer");

		var addpage = document.createElement(mode);
		addpage.setAttribute("id","addpage");
		if(mode=="iframe"){
			addpage.setAttribute("src",url);
			addpage.setAttribute("frameborder","0");
			addpage.style.width=  ( paramObj.iframe_width )?paramObj.iframe_width:"90%";
			addpage.style.height= ( paramObj.iframe_height )?paramObj.iframe_height:"90%";
		}

		var header = document.createElement("div");
		header.setAttribute("id","addpage_header");
		header.setAttribute("align","right");
		header.innerHTML = '<a href="javascript:Stato.CancelDialog()"><img src="ElementImages/cms_close.gif"></a>';

		var placement = document.createElement("div");

		if(arguments.length>3){
			placement_bg.style.width	= width+"px";
			placement.style.width		= width+"px";
			placement_bg.style.height	= height+"px";
			placement.style.height		= height+"px";
		}

		placement.setAttribute("id","addpage_placement");
		placement.appendChild(header);
		placement.appendChild(addpage);
		placement.appendChild(spacer);
		var container;
		if(!containerID){
			container = document.body;
		}else{
			container = document.getElementById(containerID);
		}

		var dombody = (document.documentElement)?document.documentElement:document.body;
		//placement_bg.style.top = (dombody.scrollTop+25)+"px";
		placement_bg.style.top = (dombody.scrollTop+25)+"px";
		if(arguments.length>5){
			placement_bg.style.left = arguments[5]+"px";
			placement.style.left = arguments[5]+"px";
		}
		placement_bg.style.marginTop="0px";
		placement.style.top = (dombody.scrollTop+25)+"px";

		placement.style.marginTop="0px";
		container.appendChild(dimmer);
		container.appendChild(placement_bg);
		container.appendChild(placement);

		if(mode=="div"){
			this.loadContent("addpage",url);
		}
	};

	this.CancelDialog = function(){
		container1 = document.getElementById("addpage_dimmer").parentNode;
		container1.removeChild(document.getElementById("addpage_dimmer"));
		container1.removeChild(document.getElementById("addpage_placement_bg"));
		container1.removeChild(document.getElementById("addpage_placement"));
	};

	this.Writelog = function(message){
		this.loadXMLDoc(this.debugURL+"?message="+message,IE6Null);
	};

	this.Debug = function(message){
		this.Writelog(message);
		//this.loadXMLDoc(this.debugURL+"?message="+message,IE6Null);
	};

	this.childNodeOrder = new Array();

	this.orderChildNodes = function(headerObj,container,numeric){
		var orderlista = new Array();
		var field= headerObj.id;
		var node =document.getElementById(container).firstChild;
		while(node.nodeName=="#text"){
			node = node.nextSibling;
		}

		var tmp = document.getElementById(container).getElementsByTagName(node.nodeName);
		for(var i =0;i< tmp.length;i++){
			if(!tmp[i].getAttribute("headerrow"))
			orderlista.push(tmp[i]);
		}
		if(field.endsWith(".numeric")|numeric){
			orderlista = orderlista.sort(function(a,b){return a.getAttribute(field.replace(".numeric","")) - b.getAttribute(field.replace(".numeric",""))});
		}else{
			var arvot = new Array();
			var orderlista2 = new Array();

			for(var i =0;i< orderlista.length;i++){
				arvot[i] = orderlista[i].getAttribute(field)+"|"+i;
			}
			arvot.sort();
			for(var i =0;i< arvot.length;i++){
				orderlista2[i]=orderlista[arvot[i].split("|")[1]];
			}
			orderlista	= orderlista2;

			/*
			orderlista = orderlista.sort(function(a,b){
				var arr = new Array();
				arr.push(a.getAttribute(field));
				arr.push(b.getAttribute(field));
				return arr[0]!=arr.sort()[0];
			});
			*/
		}

		//alert(field+" "+oldfield);
		if(field==this.childNodeOrder[container]){
			orderlista.reverse();
			this.childNodeOrder[container] = null;
		}
		else{
			this.childNodeOrder[container] = field;
		}
		for(var i =0;i< orderlista.length;i++){
			document.getElementById(container).appendChild(orderlista[i]);
		}
		this.SelectHeaderColumn(headerObj,"#eee","#cddbde");
	};

	this.SelectHeaderColumn = function(selectedCol,color1,color2){
		var tmp = selectedCol.parentNode.getElementsByTagName(selectedCol.nodeName);
		for(var i =0;i< tmp.length;i++){
			tmp[i].style.background=color1;
		}
		selectedCol.style.background=color2;
	};
	
	this.addClass = function(celement,cclass){
		if( celement && cclass ){
			var re = new RegExp(cclass,"g");
			if( !celement.className.match(re) ){
				celement.className += " " + cclass;
			}
			
		}
	};

	this.removeClass = function( celement, cclass ){
		if( celement && cclass ){
			var re = new RegExp(cclass,"g");
			celement.className = celement.className.replace(re,'');
		}
	};

	//this.publishPoolRefreshTime = 3000;

	this.RefreshPublishPool = function(){
		this.loadContent("publishpoolcounter",this.elementeditURL+"?path=PublishPool&Mode=Counter");
	};
	

	this.addListener = function(paths, element ){
		
		if( paths && element ){
			paths = paths.split(",");
			for( var path in paths  ){
				var listeners = this.brokerListeners[ paths[path] ];
				var newElement = true;
				if(!listeners){ listeners = new Array(); }
				for( var li in listeners){
					if( listeners[li].get('Element.Broker.Id') == element.get('Element.Broker.Id') ){
						listeners[li] = element;
						newElement = false;								
					}
				}
				if( newElement ){
					listeners.push( element );
				}
				this.brokerListeners[ paths[path] ] = listeners;
			}
		}
	};	
	
	this.Notify =  function (param1, param2){
		var paths = null;
		var keyvalues = new Array();
		var keyvalue = null;
		
		if(arguments.length==2){
			paths =  param1.split(',');
			keyvalues = param2;
		}
		else{
			var node = this.eventNode;		
			var root = this.findElement(node);
			var element = root["elementobj"];
			if(element){
				if(element.get("Element.Broker.Notify.Path")){				
					paths = element.get("Element.Broker.Notify.Path").split(",");
					if(arguments.length==1){
						keyvalues = param1;
					}
					else if(arguments.length==0){
					
						var fields=element.get("Element.Broker.Notify.Fields").split(",");
						var inputs = root.getElementsByTagName("INPUT");
						var textareas = root.getElementsByTagName("TEXTAREA");
						var selects = root.getElementsByTagName("SELECT");
						for( var f=0;f<fields.length;f++){
							if( fields[f] && element.get(fields[f])){
								keyvalues.push(fields[f]+"="+element.get(fields[f]));
							} 
						}
						for( var i=0;i<inputs.length;i++){
							if((inputs[i].type=="text" ||inputs[i].type=="hidden") && inputs[i].name){
								if(element.get("Element.Broker.Notify.Fields").indexOf(inputs[i].name)>-1){	
									keyvalues.push(inputs[i].name+"="+inputs[i].value);
								}
							}
						}
					}					
				}
			}
		}
		for( var path in paths){
			for( var kv=0;kv<keyvalues.length;kv++){
				keyvalue =  keyvalues[kv].split('=');				
				this.setParam( paths[path], keyvalue[0], keyvalue[1]);
			}
			var listeners = this.brokerListeners[paths[path]]; 
			
			this.Writelog("Notify: paths="+paths);
			this.Writelog("Notify: keyvalue="+keyvalue);
			
			if( listeners ){
				for( var i  in listeners ){
				
					listeners[i].refreshedNotifyPath = paths[path];
					listeners[i].refresh();
				}
			}
		}
		
		if(this.notifyOnce){
			for( var path in paths){
				for( var kv=0;kv<keyvalues.length;kv++){
					keyvalue =  keyvalues[kv].split('=') ;
					this.setParam( paths[path], keyvalue[0], "");
				}
			}
		}
		
	};

	this.NotifyOnce = function(param1,param2){
		this.notifyOnce = true;
		if(arguments.length==2){
			this.Notify(param1,param2);
		}else if(arguments.length==1){
			this.Notify(param1);
		}else{
			this.Notify();
		}
		this.notifyOnce=false;
	}


	this.isNotifyPath = function( polku ){
		if( this.element ){
			if( this.element.refreshedNotifyPath == polku ){
				return true;
			}
		}
		return false;
	}
	
	this.getCurrentNotifyPath = function(){
		return (this.element.refreshedNotifyPath)?this.element.refreshedNotifyPath:null;
	}

	this.NextPage = function(){
		this.NotifyOnce(['Action=NextPage']);
	};
	this.PrevPage = function(){
		this.NotifyOnce(['Action=PrevPage']);
	};

	this.Add = function(){
		this.NotifyOnce(['Action=Add']);
	};
	
	this.Remove = function(){
		this.NotifyOnce(['Action=Remove']);
	};

	this.Save = function(){
		this.NotifyOnce(['Action=Save']);
	};

	this.Cancel = function(){
		this.NotifyOnce(['Action=Cancel']);
	};

// Notify etsii alla olevalla funkitolla contekstin

	
	this.findAttribute = function ( node,attribute ){
		var value = null;
		do{
			if( node.nodeName == 'BODY'){ break; }
			if(node[attribute]){ return node[attribute]; }
			node = node.parentNode;
		}while( node != null && value == null );
		return null;
	};	
	
	this.findElement = function ( node ){
		while( node.nodeName != 'BODY'){
			if(node.nodeName=="STATOELEMENT"){ return node; }
			node = node.parentNode;
		};
		return null;
	};		
	
	this.getElements = function(){
		return document.getElementsByTagName("statoelement");
	};	
	

	this.FormatText = function(command, option, classi, targetti){
		selectedTextarea.FormatText(command, option, classi, targetti);
	};
	
	
}

// Card

	function CardObj(){
		this.fields = new Array();
	
		this.get = function( key ){
			return this.fields[key];
		} 
		this.put = function( key,value ){		
			if( key ){
				this.fields[key] = value;
			}			
		}
		this.getFields = function(){
			var out = "";
			for( var i in this.fields ){
				out += (out != '')?","+i:i;
			}
			return out;			
		}	
		this.toString = function( delim,equals ){
			delim = (delim)?delim:"&";
			equals = (equals)?equals:"=";
			var out = "";
			for( var i in this.fields ){
				out += (out != '')?delim+i+equals+this.fields[i] : i+equals+this.fields[i];
			}
			return out;
		}
	}

// Brokerin kayttama elementti.

	function ElementObj(statoelementObj, url,element_path){
		//ElementBrokerID
		
		this.node = statoelementObj;
		//(document.getElementById(ElementBrokerID))?document.getElementById(ElementBrokerID):null;
		if(this.node){this.node.elementobj = this;}
		this.URL = url;
		this.refreshedNotifyPath = null;
		this.init = function(){};
		this.refresh =  function(){};
		this.card = new CardObj();
		this.get = function(key){ return this.card.get( key) };
		this.put = function(key, value){ this.card.put( key, value) };
		this.brokerPath = Stato.brokerpath;
		var	elparams = statoelementObj.getAttribute("elparams").split(",");
		for(var i=0;i<elparams.length;i++){
			var key = elparams[i];
			var value = statoelementObj.getAttribute(key);
			//Stato.Debug("-----param:  "+key+"="+value);
			this.put(key,value);
		}
		this.put('Element.Path',element_path);
		this.put('element',element_path);
		this.put('elementlink',this.URL);
		
		this.put('path',element_path);
	}


/*
	
	Elementin js:ssa näillä pyydetään ja asetetetaan elementtiparametrin arvo

	Stato.setElement( avain, arvo )
	Stato.getElement( avain ) = String

	Elementin js:ssa näillä pyydetään NotifyPathissa oleva arvo

	Stato.getNotify( avain ) = String
	Stato.getNotify( polku, avain ) = String

	Pyydetään dom viittaus statoelement tagiin.
	Stato.getStatoElement() = statoelement

	Testataan onko tämä polku virkistänyt refreshin.
	Stato.isNotifyPath( polku ) = true | false


	Debugia kehitetään keräämään logia viestiliikenteestä
		- Mihin polkuun kirjoitetaan
		- Mitä kirjoitetaan
		- Ketkä virkistetään



*/



function IE6Null(){}
var jkluuppi = null;
//var req = null;
var rootNodeObj = null;
var selectedId = null;
var selectedId2 = null;
var Stato = new StatoObj();
var stato = Stato;

if(typeof window.addEventListener != 'undefined'){
	window.addEventListener('mousedown', Stato.HandleClick, false);
}
else if(typeof document.addEventListener != 'undefined'){
	document.addEventListener('mousedown', Stato.HandleClick, false);
}
else if(typeof window.attachEvent != 'undefined'){
	window.attachEvent('onmousedown', Stato.HandleClick);
}


// window.addEventListener('mousedown',Stato.HandleClick,false);