

;HOST = location.href.split("?")[0].replace(/(\/\/[^\/]*)\/.*$/, "$1");
HOST_PATH = location.href.split("?")[0].replace(/\/[^\/]*$/, "") + "/";
CWD = location.href.split("?")[0].replace(/^(.*\/)[^\/]*$/, "$1") + "/";
PACKAGED = false;
DEBUG = false;
DEBUG_TYPE = "";
DEBUG_FILTER = "!teleport";
WARNINGS = false;

IS_OPERA = navigator.userAgent.toLowerCase().indexOf("opera") != -1;

IS_KONQUEROR = navigator.userAgent.toLowerCase().indexOf("konqueror") != -1;
IS_SAFARI = !IS_OPERA && ((navigator.vendor && navigator.vendor.match(/Apple/) ? true : false) || navigator.userAgent.toLowerCase().indexOf("safari") != -1 || IS_KONQUEROR);
IS_SAFARI_OLD = false;
if(IS_SAFARI){
	var matches = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
	if(matches) IS_SAFARI_OLD = parseInt(matches[1]) < 420;
}

IS_GECKO = !IS_OPERA && !IS_SAFARI && navigator.userAgent.toLowerCase().indexOf("gecko") != -1;
IS_IE = document.all && !IS_OPERA && !IS_SAFARI;
IS_IE50 = IS_IE && navigator.userAgent.toLowerCase().indexOf("5.0") != -1;
IS_IE55 = IS_IE && navigator.userAgent.toLowerCase().indexOf("5.5") != -1;
IS_IE6 = IS_IE && navigator.userAgent.toLowerCase().indexOf("6.") != -1;
IS_IE7 = IS_IE && navigator.userAgent.toLowerCase().indexOf("7.") != -1;;
//temp
MAX_JAV_RETRIES = IS_OPERA ? 0 : 3;

HAS_DESKRUN = HAS_WEBRUN = false;

TAGNAME = IS_IE ? "baseName" : "localName";

//mozilla root detection
//try{ISROOT = !window.opener || !window.opener.Kernel}catch(e){ISROOT = true}
ISROOT = true;

function include(sourceFile, doBase){
	setStatus("including js file: " + sourceFile);
	
	//Safari Special Case
	/*if(IS_SAFARI){
		document.write("<script src='" + (doBase ? BASEPATH + sourceFile : sourceFile) + "' defer='true'></script>");
	}
	//Other browsers
	else{*/
		var head = $("head")[0];
		var elScript = document.createElement("script");
		elScript.defer = true;
		elScript.src = doBase ? BASEPATH + sourceFile : sourceFile;
		head.appendChild(elScript);
	//}
}

if(IS_OPERA){
	var $ = function(tag, doc, prefix, force){
		// || doc && (doc.nodeType == 9 ? doc : doc.ownerDocument) != document
		if(!prefix) 
			return (doc || document).getElementsByTagName(tag);

		return (doc || document).getElementsByTagName(prefix + ":" + tag);
	}
}
else
	var $ = function(tag, doc, prefix, force){
		// || IS_SAFARI
		return (doc || document).getElementsByTagName((prefix && (force || IS_GECKO) ? prefix + ":" : "") + tag);
	}

var $j = function(xmlNode, tag){
	if(IS_IE){
		if(xmlNode.style)
			return xmlNode.getElementsByTagName(tag)
		else{
			xmlNode.ownerDocument.setProperty("SelectionNamespaces", "xmlns:j='http://www.javeline.net/j'");
			return xmlNode.selectNodes(".//" + tag + "|.//j:" + tag)
		}
	}
	else
		return xmlNode.getElementsByTagNameNS("http://www.javeline.net/j", tag);
}

function setStatus(str){
	if(!DEBUG) return;
	
	if(false && IS_OPERA) status = str;
	else if(HAS_DESKRUN || HAS_WEBRUN)	lp.Write("STATUS",str);
	else if(self.Kernel){
		var dt = new Date();
		var date = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds() + ":" + dt.getMilliseconds();	
		Kernel.debugMsg("[" + date + "] " + str.replace(/\n/g, "<br />").replace(/\t/g,"&nbsp;&nbsp;&nbsp;") + "<br />", "status");
	}
	else document.title = str;
}

Init = {
	queue : [],
	cond : {
		combined : []	
	},
	done : {},
	
	add : function(func, o){
		if(this.inited) func.call(o);
		else if(func) this.queue.push([func, o]);
	},
	
	addConditional : function(func, o, strObj){
		if(typeof strObj != "string"){
			if(this.checkCombined(strObj)) return func.call(o);
			this.cond.combined.push([func, o, strObj]);
		}
		else if(self[strObj]) func.call(o);
		else{
			if(!this.cond[strObj]) this.cond[strObj] = [];
			this.cond[strObj].push([func, o]);
			
			this.checkAllCombined();
		}
	},
	
	checkAllCombined : function(){
		for(var i=0;i<this.cond.combined.length;i++){
			if(!this.cond.combined[i]) continue;
			
			if(this.checkCombined(this.cond.combined[i][2])){
				this.cond.combined[i][0].call(this.cond.combined[i][1])
				this.cond.combined[i] = null;
			}
		}
	},
	
	checkCombined : function(arr){
		for(var i=0;i<arr.length;i++){
			if(!this.done[arr[i]]) return false;
		}

		return true;
	},
	
	run : function(strObj){
		this.inited = true;
		this.done[strObj] = true;
		
		this.checkAllCombined();
		
		var data = strObj ? this.cond[strObj] : this.queue;
		if(!data) return;
		for(var i=0;i<data.length;i++) data[i][0].call(data[i][1]);
	}
};;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;/** 
* @projectDescription 	Javeline Platform
*
* @author	Ruben Daniels ruben@javeline.nl
* @version	1.0
*/

VERSION 			= 0x000900;

NOGUI_NODE 		= 101;
GUI_NODE 		= 102;
KERNEL_MODULE	= 103;
MF_NODE 		= 104;

if(!self.DEBUG) DEBUG = false;
//NAMESPACE = document.all ? "scopeName" : "prefix";

//CGI VARS
var HTTP_GET_VARS={}, vars = location.href.split(/[\?\&\=]/);
for(var k=1;k<vars.length;k+=2) HTTP_GET_VARS[vars[k]] = vars[k+1] || "";

Array.prototype.dataType = "array";
Number.prototype.dataType = "number";
Date.prototype.dataType = "date";
Boolean.prototype.dataType = "boolean";
String.prototype.dataType = "string";
RegExp.prototype.dataType = "regexp";
Function.prototype.dataType = "function";

/**
 * @moduleDescription 	Javeline Platform Kernel
 */

//Initalizing Kernel
Kernel = {
	/**
	* This method returns a string representation of the object
	* @return {String}	Returns a string representing the object.
	* @method
	*/
	toString : function(){
		return "[Javeline (Kernel)]";
	},
	
	emptyf : function(){},
	
	all : [],
	hasContentEditable : IS_IE || IS_SAFARI,
	
	getElement : function(parent, nr){
		var nodes = parent.childNodes;
		for(var j=0,i=0;i<nodes.length;i++){
			if(nodes[i].nodeType != 1) continue;
			if(j++ == nr) return nodes[i];
		}
	},
	
	/**
	* This method inherit all properties and methods to this object from another class
	* @param {Function}	classRef	Required Class reference 
	* @method
	*/
	inherit : function(classRef){classRef.call(this);},
	
	/**
	* This method transforms an object into a Javeline Class
	* @param {Object}	oBlank Required Object to be transformed into a Javeline Class
	* @method
	*/
	makeClass : function(oBlank){oBlank.inherit = this.inherit;oBlank.inherit(Class);},
	
	XSLTPrefix : IS_IE ? "xsl:" : "",
	
	/********* BROWSER FEATURES ***********
		Compatibility Methods and functions
	**************************************/
	root : true,
	named : {},

	Init : function(){
		try{
			//if(window.opener && window.opener.Kernel) this.all = window.opener.Kernel.all;
			if(IS_IE) document.execCommand("BackgroundImageCache", false, true);
		}catch(e){}
	},

	cancelBubble : function(e, o){
		e.cancelBubble = true;
		if(o.focussable && !o.disabled) me.__focus(o);
	},

	/**
	* This method sets a single CSS rule 
	* @param {String}	name Required CSS name of the rule (i.e. '.cls' or '#id')
	* @param {String}	type Required CSS property to change
	* @param {String}	value Required CSS value of the property
	* @param {String}	stylesheet Optional Name of the stylesheet to change 
	* @method
	*/	
	setStyleRule : function(name, type, value, stylesheet){
		var rules = document.styleSheets[stylesheet || 0][IS_IE ? "rules" : "cssRules"] ;
		for(var i=0;i<rules.length;i++){
			if(rules.item(i).selectorText == name){
				rules.item(i).style[type] = value;
				return;
			}
		}
	},

	/**
	* This method imports a stylesheet defined in a multidimensional array 
	* @param {Array}	def Required Multidimensional array specifying 
	* @param {Object}	win Optional Reference to a window
	* @method
	* @deprecated
	*/	
	importStylesheet : function(def, win){
		//if(IS_OPERA) return; //maybe version check here 9.21 it works, below might not
		for(var i=0;i<def.length;i++){
			if(def[i][1]){
				if(IS_IE)
					(win || window).document.styleSheets[0].addRule(def[i][0], def[i][1]);
				else
					(win || window).document.styleSheets[0].insertRule(def[i][0] + " {" + def[i][1] + "}", 0);
			}
		}
	},

	/**
	* This method imports a CSS stylesheet from a string 
	* @param {Object}	doc Required Reference to the document where the CSS is applied on
	* @param {String}	cssString Required String containing the CSS definition 
	* @param {String}	media Optional The media to which this CSS applies (i.e. 'print' or 'screen')
	* @method
	*/
	importCssString : function(doc, cssString, media){
		var htmlNode = doc.getElementsByTagName("head")[0];//doc.documentElement.getElementsByTagName("head")[0]
		if(htmlNode.insertAdjacentHTML){
			htmlNode.insertAdjacentHTML("beforeend", ".<style media='" + (media || "all") + "'>" + cssString + "</style>");

			//IE bug fix
			if(document.body && IS_IE6 && Application.IE6Fix){
				//document.body.style.height = "100%";
				//setTimeout('document.body.style.height = "auto"');
			}
		}
		else{
			var r = htmlNode.ownerDocument.createRange();
			r.setStartBefore(htmlNode);
			var parsedHTML = r.createContextualFragment("<style media='" + (media || "all") + "'>" + cssString + "</style>");
			htmlNode.appendChild(parsedHTML);
		}
	},

	/**
	* This method loads a stylesheet from a url
	* @param {String}	filename Required The url to load the stylesheet from
	* @param {String}	title Optional Title of the stylesheet to load
	* @method
	*/
	loadStylesheet : function(filename, title){
		with(o = document.getElementsByTagName("head")[0].appendChild(document.createElement("LINK"))){
			rel = "stylesheet";
			type = "text/css";
			href = filename;
			title = title;
		}

		return o;
	},

	/**
	* This method retrieves the current value of a property on a HTML element
	* @param {HTMLElement}	el Required The element to read the property from
	* @param {String}	prop Required The property to read 
	* @method
	*/
	getStyle : function(el, prop) {
		if(typeof document.defaultView != "undefined"
		   && typeof document.defaultView.getComputedStyle != "undefined")
			return document.defaultView.getComputedStyle(el,'').getPropertyValue(prop);
		return el.currentStyle[prop];
	},
	
	addEventListener : function(oHtml, eventName, method){
		if(IS_IE) oHtml["on" + eventName] = method;
		else oHtml.addEventListener(eventName, method, false);
	},
	
	removeNode : function (element) {
		if(!element) return;
		
		if(!IS_IE){
			if(element.parentNode) element.parentNode.removeChild(element);
			return;
		}
		
		var garbageBin = document.getElementById('IELeakGarbageBin');
		if (!garbageBin) {
			garbageBin = document.createElement('DIV');
			garbageBin.id = 'IELeakGarbageBin';
			garbageBin.style.display = 'none';
			document.body.appendChild(garbageBin);
		}
	
		// move the element to the garbage bin
		garbageBin.appendChild(element);
		garbageBin.innerHTML = '';
	},
	
	uniqueHtmlIds : 0,
	setUniqueHtmlId : function(oHtml){
		oHtml.setAttribute("id", "q" + this.uniqueHtmlIds++)
	},
	
	getUniqueId : function(oHtml){return this.uniqueHtmlIds++;},

	/********* NODE METHODS ***********
		Methods to help Javeline Nodes
	**********************************/

	local : [],
	locals : {},

	getRoot : function(){
		return this.root ? this : window.opener.Kernel;
	},

	getActiveWindow : function(){
		return this.getRoot().activeWindow;
	},

	getPath : function(path){
		return (path.match(/http\:\/\/|file\:\/\//) ? path : HOST_PATH + path);
	},

	register : function(o, tagName, nodeType){
		o.tagName = tagName;
		o.nodeType = nodeType || NOGUI_NODE;
		//o.kernel = this;
		o.uniqueId = this.all.push(o)-1;
		
		this.makeClass(o);


		if(!this.root){
			this.local.push(o);
			this.locals[o.uniqueId] = true;
		}
	},
	
	lookup : function(uniqueId){
		return this.all[uniqueId];
	},

	localLookup : function(uniqueId){
		if(this.locals.length && !this.locals[uniqueId]) return;
		return this.all[uniqueId];
	},

	findHost : function(o){
		var node = o;
		while(o && !o.host && o.parentNode) o = o.parentNode;
		return o && o.host ? o.host : false;
	},

	sleep : function(ms){
		if(IS_IE) window.showModalDialog('javascript:document.writeln("<script>window.setTimeout(function () { window.close(); }, ' + ms + ');</script>")');
	},
	
	availHTTP : [],
	
	releaseHTTP : function(http){
		if(self.XMLHttpRequestUnSafe && http.constructor == XMLHttpRequestUnSafe) return;
		
		http.onreadystatechange = this.emptyf;
		http.abort();
		this.availHTTP.push(http);
	},

	/********* SETREFERENCE ***********
		Set Reference to an object by name
	
		INTERFACE:
		this.setReference(name, o, global);
	****************************/
	setReference : function(name, o, global){
		if(self[name] && self[name].hasFeature) return;
		return (self[name] = o);
	},
	
	getRules : function(node){
		var rules = {};
		
		for(var w = node.firstChild;w;w=w.nextSibling){
			if(w.nodeType != 1) continue;
			else{
				if(!rules[w[TAGNAME]]) rules[w[TAGNAME]] = [];
				rules[w[TAGNAME]].push(w);
			}
		}
		
		return rules;
	},

	/********* NODE METHODS ***********
		Debug functions
	**********************************/

	warnings : {},
	DEBUG_INFO : "",

	debugMsg : function(msg, type, forceWin){
		if(!DEBUG) return;

		if(DEBUG_FILTER.match(new RegExp("!" + type + "(\||$)", "i"))) return;
		if(DEBUG_TYPE.toLowerCase() == "window" || this.win && !this.win.closed || forceWin){
			this.win = window.open("", "debug");
			if(!this.win){
				if(!this.haspopupkiller) alert("Could not open debug window, please check your popupkiller");
				this.haspopupkiller = true;
			}
			else this.win.document.write(msg);
		}
		
		this.DEBUG_INFO += msg;

		if(this.ondebug) this.ondebug(msg);
	},

	showDebug : function(){
		this.win = window.open("", "debug");
		this.win.document.write(this.DEBUG_INFO);
	},
	
	formErrorString : function(number, control, process, message, jmlContext, outputname, output){
		var str = ["---- Javeline Error ----"];
		if(jmlContext){
			var c = jmlContext.ownerDocument.outerHTML || jmlContext.ownerDocument.xml || "";
			var jmlStr = (jmlContext.outerHTML || jmlContext.xml || jmlContext.serialize()).replace(/\<\?xml\:namespace prefix = j ns = "http\:\/\/www.javeline.net\/j" \/\>/g, "").replace(/xmlns:j="[^"]*"\s*/g, "");
			var linenr = c.substr(0, c.indexOf(jmlStr)).split("\n").length;
			str.push("jml file: [line: " + linenr + "] " + removePathContext(HOST_PATH, jmlContext.ownerDocument.documentElement.getAttribute("filename")));
		}
		if(control) str.push("Control: '" + (control.name||control.jml.getAttribute("id")||"{Anonymous}") + "' [" + control.tagName + "]");
		if(process) str.push("Process: " + process);
		if(message) str.push("Message: [" + number + "] " + message);
		if(outputname) str.push(outputname+ ": " + output);
		if(jmlContext) str.push("\n===\n" + jmlStr);

		return str.join("\n");
	},
	
	//throw new Error(1101, Kernel.formErrorString(1101, this, null, "A dropdown with a bind='' attribute needs a bindclass='' attribute or have <j:Item /> children.", "JML", this.jml.outerHTML));
	

	destroy : function(exclude){
		this.Popup.destroy();
		
		for(var i=0;i<this.all.length;i++)
			if(this.all[i] && this.all[i] != exclude && this.all[i].destroy)
				this.all[i].destroy();
		
		document.oncontextmenu = null;
		document.onmousedown = null;
		document.onselectstart = null;
		document.onkeyup = null;
		document.onkeydown = null;
		
		for(var i=0;i<this.availHTTP.length;i++){
			this.availHTTP[i] = null;
		}
	}
};
//try{Kernel.root = !window.opener || !window.opener.Kernel;}
//catch(e){Kernel.root = false}
Kernel.root = true;

Init.run('Kernel');


/********* COOKIE METHODS *********
	Cookie Handling Methods
**********************************/

function setcookie(name, value, expire, path, domain, secure){
	var ck = name + "=" + escape(value) + ";";
	if(expire) ck += "expires=" + new Date(expire + new Date().getTimezoneOffset()*60).toGMTString() + ";";
	if(path) ck += "path=" + path + ";";
	if(domain) ck += "domain=" + domain;
	if(secure) ck += "secure";

	document.cookie = ck;
	return true
}

function getcookie(name){
  var aCookie = document.cookie.split("; ");
  for (var i=0; i < aCookie.length; i++){
	var aCrumb = aCookie[i].split("=");
	if (name == aCrumb[0])
	  return unescape(aCrumb[1]);
  }

  return "";
}

function delcookie(name,domain){
  	document.cookie = name + "=blah; expires=Fri, 31 Dec 1999 23:59:59 GMT;"+domain?'domain='+domain:'';
}


/********* HELPER FUNCTIONS *********
**********************************/


function removeParts(str){
	q = str.replace(/^\s*function\s*\w*\s*\([^\)]*\)\s*\{/, "");
	q = q.replace(/\}\s*$/, "");
	return q;
}

function importClass(ref, strip, win){
	if(!ref) throw new Error(1018, Kernel.formErrorString(1018, null, "importing class", "Could not load reference. Reference is null"));

	if(!IS_IE) return ref();//.call(self);

	if(!strip) return (win.execScript ? win.execScript(ref.toString()) : eval(ref.toString()));
	var q = removeParts(ref.toString());

	//var q = ref.toString().split("\n");q.shift();q.pop();
	//if(!win.execScript) q.shift();q.pop();

	return win.execScript ? win.execScript(q) : eval(q);
};__HTTP_SUCCESS__ = 1;
__HTTP_TIMEOUT__ = 2;
__HTTP_ERROR__ = 3;

__RPC_SUCCESS__ = 1;
__RPC_TIMEOUT__ = 2;
__RPC_ERROR__ = 3;


Kernel.TelePort = {
	modules : new Array(),
	named : {},

	register : function(obj){
		var id = false, data = {
			name : obj.SmartBindingHook[0],
			args : obj.SmartBindingHook[1],
			obj : obj
		};

		this.named[obj.SmartBindingHook[0]] = data;
		return this.modules.push(data) - 1;
	},

	getModules : function(){
		return this.modules;
	},

	getModuleByName : function(defname){
		return this.named[defname]
	},

	hasLoadRule : function(xmlNode){
		for(mod in this.named){
			if(!this.named[mod] || !this.named[mod].args) continue;

			if(xmlNode.getAttribute(this.named[mod].name)){
				this.lastRuleFound = this.named[mod];
				return true;
			}
		}
		
		this.lastRuleFound = {};
		return false;
	},
	
	removeLoadRule : function(xmlNode){
		if(!this.hasLoadRule(xmlNode));
		
		// Could go wrong because one of the two doesn't exist... just a precaution
		try{
			xmlNode.removeAttribute(xmlNode.getAttributeNode(this.lastRuleFound.name));
			xmlNode.removeAttribute(xmlNode.getAttributeNode(this.lastRuleFound.args));
		}catch(e){}
	},

	// Set Communication
	Init : function(){
		this.inited = true;

		var comdef = document.documentElement.getElementsByTagName("head")[0].getElementsByTagName(IS_IE ? "teleport" : "j:teleport")[0];
		if(!comdef && document.documentElement.getElementsByTagNameNS) comdef = document.documentElement.getElementsByTagNameNS("http://javeline.nl/j", "j:teleport")[0];
		if(!comdef){
			this.isInited = true;
			return issueWarning(1006, "Could not find Javeline TelePort Definition")
		}
		if(comdef.getAttribute("src")){
			new HTTP().getXML(HOST_PATH + comdef.getAttribute("src"), function(xmlNode, state, extra){
				if(state != __RPC_SUCCESS__){
					if(extra.retries < MAX_RETRIES) return HTTP.retry(extra.id);
					else throw new Error(1021, Kernel.formErrrorString(1021, null, "Application", "Could not load Javeline TelePort Definition:\n\n" + extra.message));
				}

				Kernel.TelePort.xml = xmlNode;
				Kernel.TelePort.isInited = true;

				//if(self.PACKAGED) Kernel.TelePort.load();
			}, true);
		}
		else{
			var xmlNode = comdef.firstChild ? XMLDatabase.getDataIsland(comdef.firstChild) : null

			Kernel.TelePort.xml = xmlNode;
			Kernel.TelePort.isInited = true;

			//if(self.PACKAGED) Kernel.TelePort.load();
		}
	},

	// Load TelePort Definition
	load : function(xml){
		if(xml) this.xml = xml;
		if(!this.xml) return;

		var nodes = this.xml.childNodes;
		if(!nodes.length) return;

		for(var i=0;i<nodes.length;i++)
			this.initComm(nodes[i]);

		this.loaded = true;
		if(this.onload) this.onload();
	},

	/********* INITCOMM ***********
		Initialize Communication Protocols

		INTERFACE:
		this.initComm(xmlNode);
	****************************/
	initComm : function(x){
		if(x.nodeType != 1) return;

		//Socket Communication
		if(x[TAGNAME] == "Socket"){
			var o = new Socket();
			Kernel.setReference(x.getAttribute("id"), o);
			o.load(x);
		}

		//Polling Engine
		else if(x[TAGNAME] == "Poll")
			Kernel.setReference(x.getAttribute("id"), new Poll().load(x));

		//Initialize Communication Component
		else Kernel.setReference(x.getAttribute("id"), new CommBaseClass(x));
	},

	/********* CALLMETHODFROMNODE ***********
		Call method by the definition in an Xml Node

		INTERFACE:
		this.callMethodFromNode(xmlCommNode, xmlNode, receive, multicall);
	****************************/
	callMethodFromNode : function(xmlCommNode, xmlNode, receive, multicall, userdata, arg){
		var commRule = xmlCommNode.getAttribute(this.lastRuleFound.name);
		if(!commRule){
			if(xmlCommNode.getAttribute("src")){
				var commRule = new HTTP().instantiate(xmlCommNode);
				xmlCommNode.setAttribute("http", commRule);
				xmlCommNode.removeAttributeNode(xmlCommNode.getAttributeNode("src"));
			}
			
			if(!commRule){
				if(!this.hasLoadRule(xmlCommNode)) throw new Error(1022, Kernel.formErrorString(1022, null, "TelePort load from xmlNode", "Could not load method from node :" + (xmlRPCNode ? xmlRPCNode.xml : "")));
				commRule = xmlCommNode.getAttribute(this.lastRuleFound.name);
			}
		}

		var q = commRule.split(";");
		var obj = eval(q[0]);
		var method = q[1];
		if(!arg && this.lastRuleFound.args){
			arg = xmlCommNode.getAttribute(this.lastRuleFound.args);
			arg = arg ? arg.split(";") : [];
		}

		//force multicall if needed;
		if(multicall) obj.force_multicall = true;
		
		//Get values from dynamic args
		if(arg) arg = this.processArguments(arg, xmlNode, xmlCommNode);
		
		//Set information later neeed
		if(userdata) obj[method].userdata = userdata;
		if(!obj.multicall) obj.callbacks[method] = receive; //&& obj[method].async
		
		//Call method
		var data = obj.call(method, arg ? obj.fArgs(arg, obj.names[method], (obj.vartype != "cgi" && obj.vexport == "cgi")) : null);//obj.named ? obj.names[method] : []));

		if(obj.multicall) return obj.purge(receive, "&@^%!@");
		else if(multicall){
			obj.force_multicall = false;
			return obj;
		}

		if(data && !obj.multicall && !obj[method].async) return receive(data);
	},
	
	processArguments : function(arg, xmlNode, xmlCommNode){
		for(var i=0;i<arg.length;i++){
			if(typeof arg[i] == "object") continue;
			
			if(typeof arg[i] == "string"){
				//this could be optimized if needed
				if(arg[i].match(/^xpath\:(.*)$/)){
					var o = xmlNode.selectSingleNode(RegExp.$1);
	
					if(!o) arg[i] = "";
					else if(o.nodeType >= 2 && o.nodeType <= 4) arg[i] = o.nodeValue;
					//else if(o.firstChild) arg[i] = o.firstChild.nodeValue;// && (o.firstChild.nodeType == 3 || o.firstChild.nodeType == 4)
					//else arg[i] = "";
					else arg[i] = o.serialize ? o.serialize() : o.xml;
				}
				else if(arg[i].match(/^method\:(.*)$/)){
					arg[i] = self[RegExp.$1](xmlNode, xmlCommNode);
				}
				else if(arg[i].match(/^eval\:(.*)$/)){
					arg[i] = eval(RegExp.$1);
				}
				else if(arg[i].match(/^\((.*)\)$/)){
					arg[i] = this.processArguments(RegExp.$1.split(","), xmlNode, xmlCommNode);
				}
				else arg[i] = arg[i] || "";
			}
			else arg[i] = arg[i] || "";
		}
		
		return arg;
	}
}

function CommBaseClass(xml){
	this.xml = xml;
	this.uniqueId = Kernel.all.push(this) - 1;
	Kernel.makeClass(this);

	this.toString = function(){
		return "[Javeline TelePort Component : " + (this.name || "") + " (" + this.type + ")]";
	}

	if(this.xml){
		this.name = xml.getAttribute("id");
		this.type = xml[TAGNAME];

		// Inherit from the specified baseclass
		if(!self[this.type]) throw new Error(1023, Kernel.formErrorString(1023, null, "TelePort baseclass", "Could not find Javeline TelePort Component '" + this.type + "'", this.xml));
		this.inherit(self[this.type]);

		if(this.useHTTP){
			// Inherit from HTTP Module
			if(!self.HTTP) throw new Error(1024, Kernel.formErrorString(1024, null, "Teleport baseclass", "Could not find Javeline TelePort HTTP Component", this.xml));
			this.inherit(HTTP);
		}

		if(this.xml.getAttribute("protocol")){
			// Inherit from Module
			if(!self[this.xml.getAttribute("protocol")]) throw new Error(1025, Kernel.formErrorString(1025, null, "Teleport baseclass", "Could not find Javeline TelePort RPC Component '" + this.xml.getAttribute("protocol") + "'", this.xml));
			this.inherit(self[this.xml.getAttribute("protocol")]);
		}
	}

	// Load Comm definition
	if(this.xml) this.load(this.xml);
}


Init.run('TelePort');;;__JMLNODE__ = 1<<15;
__VALIDATION__ = 1<<6;



document.onkeydown = function(e){
	if(!e) e = event;


	//HOTKEY
	if(Kernel.onhotkey && Kernel.onhotkey(e.keyCode, e.ctrlKey, e.shiftKey, e.altKey, e) == false){
		e.returnValue = false;e.cancelBubble = true; if(IS_IE) e.keyCode = 0;
		return false;
	}
	
	//HOTKEY QUICKFIX.. please fix using addeventlistener
	if(Kernel.ondebugkey && Kernel.ondebugkey(e.keyCode, e.ctrlKey, e.shiftKey, e.altKey, e) == false){
		e.returnValue = false;e.cancelBubble = true; if(IS_IE) try{e.keyCode = 0;}catch(e){}
		return false;
	}
	
}
;
Application = {
	xml : null,
	xmlForms : null,
	
	
	stateStack : [],

	/********* INIT ***********
		Initialize Application
	
		INTERFACE:
		this.Init();
	****************************/
	Init : function(jml){
		setStatus("Start parsing main application");
		Profiler.start();
		this.xml = jml;
		
		if(!this.xml) return;
		
		if(!this.xml.childNodes.length) throw new Error(1014, Kernel.formErrorString(1014, null, "Application", "Init\nMessage : Got invalid JML"));
		
		//THIS NEED OPTIMIZATION
		this.preLoadNonRef(jml);
		for(var i=0;i<IncludeStack.length;i++) if(IncludeStack[i].nodeType) this.preLoadNonRef(IncludeStack[i]);
		this.preLoadRef(jml);
		for(var i=0;i<IncludeStack.length;i++) if(IncludeStack[i].nodeType) this.preLoadRef(IncludeStack[i]);

		
		if(this.oninit) this.oninit();
		this.inited = true;
		
		//Profiler.end();
		//setStatus("[TIME] Total load time: " + Profiler.totalTime + "ms");
		//Profiler.start(true);
	},
	
	preLoadNonRef : function(xmlNode){
		//BUG: IE document handling bugs
		if(IS_IE){
			if(xmlNode.style) return;
			xmlNode.ownerDocument.setProperty("SelectionNamespaces", "xmlns:j='http://www.javeline.net/j'");
		}
		
		setStatus("Preloading Non Referencing nodes...");
		
		//Hack to support non NS defined documents - there must be a better way
		try{
			var nodes = xmlNode.selectNodes("//teleport|//j:teleport|//presentation|//j:presentation|//settings|//j:settings|//skin|//j:skin|//bindings[@id]|//actions[@id]|//dragdrop[@id]|//j:bindings[@id]|//j:actions[@id]|//j:dragdrop[@id]");
		}
		catch(e){
			var nodes = xmlNode.selectNodes("//teleport|//presentation|//settings|//skin|//bindings[@id]|//actions[@id]|//dragdrop[@id]");
		}

		this.preLoadNodes(nodes);
	},
	
	preLoadRef : function(xmlNode){
		setStatus("Preloading Referencing nodes...");
		
		//Hack to support non NS defined documents - there must be a better way
		try{
			var nodes = xmlNode.selectNodes("//style|//j:style|//model[@id]|//smartbinding[@id]|//j:smartbinding[@id]|//j:model[@id]");
		}
		catch(e){
			var nodes = xmlNode.selectNodes("//style|//model[@id]");
		}
		
		this.preLoadNodes(nodes);
	},
	
	preLoadNodes : function(nodes){
		//for(var i=nodes.length-1;i>=0;i--){
		for(var i=0;i<nodes.length;i++){

			if(this.handler[nodes[i][TAGNAME]]){
				setStatus("Processing [preload] '" + nodes[i][TAGNAME] + "' node");
				
				this.handler[nodes[i][TAGNAME]](nodes[i]);
			}
				
			if(nodes[i][TAGNAME] != "presentation" && nodes[i].parentNode)
				nodes[i].parentNode.removeChild(nodes[i]);
		}
	},

	loadIncludeFile : function(filename){
		//loadJMLInclude(null, new Http(), false, getAbsolutePath(HOST_PATH, filename));
	},
	
	
	handler : {
		"script" : function(q){
			//if(IS_SAFARI) return;
			if(q.getAttribute("src")){
				//temp solution
				if(IS_OPERA) setTimeout(function(){me.loadCodeFile(HOST_PATH + q.getAttribute("src"));},1000);
				else me.loadCodeFile(HOST_PATH + q.getAttribute("src"));
			}
			else if(q.firstChild){
				var scode = q.firstChild.nodeValue;// + ";\nvar __LoadedScript = true;"
				if(IS_IE) 
					window.execScript(scode);
				else if(IS_GECKO)
					document.body.insertAdjacentHTML("beforeend", "<script>" + scode + "</script>");
				else
					eval(scode);
					
				//if(!__LoadedScript)
				//	throw new Error(0, Kernel.formErrorString(0, null, "Inserting Code Block", "An Error has occurred inserting the javascript code block", q));
			}
		},
		
		
		
			
		"socket" : function(q){
			var o = new Socket();
			Kernel.setReference(x.getAttribute("id"), o);
			o.load(q);
		},

		"poll" : function(q){
			Kernel.setReference(x.getAttribute("id"), new Poll().load(q));
		},
		
		//problem:
		"teleport" : function(q){
			//Initialize Communication Component
			//Kernel.setReference(x.getAttribute("id"), new CommBaseClass(x));
			Kernel.TelePort.load(q);
		},
		
		
		
		"settings" : function(q, jmlParent){
			Application.foundSettings = true;
			Application.lastSettings = q;
			
			//if(!jmlParent.tagName == "Window")
			//	throw new Error(0, Kernel.formErrorString(0, null, "Initialization", "Could not apply settings to window"));
			
			//Set Globals
			//this.iconPath = q.getAttribute("icon-path") || "Icons/";
			//this.mediaPath = q.getAttribute("media-path") || "images/";
			SKIN_PATH = q.getAttribute("skin-path") || "Skins/";
			if(!self.DEBUG) DEBUG = isTrue(q.getAttribute("debug"));
			if(q.getAttribute("debug-type")) DEBUG_TYPE = q.getAttribute("debug-type");
			//if(q.getAttribute("debug-filter")) 
			DEBUG_FILTER = isTrue(q.getAttribute("debug-teleport")) ? "" : "!teleport";
			
			if(!isTrue(q.getAttribute("enable-rightclick")))
				document.oncontextmenu = function(){return false;}
			
			Application.allowSelect = isTrue(q.getAttribute("allow-select"));
				
			Application.autoDisableActions = isTrue(q.getAttribute("auto-disable-actions"));
			Application.autoDisable = !isFalse(q.getAttribute("auto-disable"));
			Application.disableF5 = isTrue(q.getAttribute("disable-f5"));
			
			//_Window.getForm(jmlParent.tagName == "Window" ? jmlParent.getAttribute("id") : "main").loadSettings(q);
		}
		
		
	},
	
	
	
	
	/********* PROCESSDATABINDING ***********
		Process Databinding Rules of all objects set
	
		INTERFACE:
		this.processDatabinding();
	****************************/
	processDatabinding : function(){
		
		if(!this.loaded){
			
			//Call the onload event
			if(this.onload) this.onload();
			//Reset the Smart Bindings load stack
			
			// Set the default selected element
			me.moveNext();
			
			this.loaded = true;
		}

		this.sbInit = {};
		this.modelInit = [];
		this.stateStack = [];
		// END OF ENTIRE APPLICATION STARTUP
		
		setStatus("Initialization finished");
		Profiler.end();
		setStatus("[TIME] Total time for SmartBindings: " + Profiler.totalTime + "ms");
	}
	
}


Init.run('Application');;;;;;
function _JSLT(){

	//------------------------------------------------------------------------------------
	// compile functions
	function isString() {
		if (typeof arguments[0] == 'string') return true;
		if (typeof arguments[0] == 'object' && arguments[0].constructor) return (arguments[0].constructor.toString().match(/string/i) != null);
		return false;
	}
	function jesc(s,esc){
		if(esc.toLowerCase()=='q')return s.replace(/\'/g,"\\\'").replace(/\"/g,"\\\"");
		return s;
	}
	function jcpy(s,n,p){if(!n)return;if(p){var t = n.selectNodes(p);if(!t || t.length==0)return;for(var i = 0;i<t.length;i++)s[s.length]=t[i].xml;}else s[s.length]=n.xml;}
	function jxml(n,p){if(!n)return;if(p){var o = [];var t = n.selectNodes(p);if(!t || t.length==0)return;for(var i = 0;i<t.length;i++)o[o.length]=t[i].xml;}else return n.xml;return o.join('');}
	function jval(n,p){
		if(!n)return '';if(p)n = n.selectSingleNode(p);if(!n)return '';if(n.nodeType == 1) n=n.firstChild;
		return n?n.nodeValue:'';
	}
	function jloc(n,f,p){if(!n)return;n = isString(p)?n.selectSingleNode(p):p;if(!n)return;f(n);};
	function jdbg(a){setStatus(a)};
	function jnod(n,p){if(!n)return '';if(p)n = n.selectSingleNode(p);if(!n)return null;return n;}
	function jnds(n,p){if(!n)return '';if(p)n = n.selectNodes(p);if(!n)return null;return n;}
	function jexs(n,p){if(!n)return false;if(p)n = n.selectSingleNode(p);return n!=null;}
	function jemp(n,p){if(!n)return false;if(p)n = n.selectSingleNode(p);if(!n)return true;if(n.nodeType == 1) n=n.firstChild;return (n?n.nodeValue:'').match(/^[\s\r\n\t]*$/)!=null;}
	function jcnt(n,p){if(!n)return 0; var t= n.selectNodes(p);return t?t.length:0;}
	function jpak(n,f,p){
		var s=[];f(s,n);return s.join('');
	}
	function jstore(n,pk,f,p){
		if(!p)p='def';
		if(!pk[p])pk[p]=[];
		f(pk[p],n);return;
	}
	function jfetch(pk,p){
		if(!p)p='def';
		if(pk[p])return pk[p].join('');
		return '';
	}
	
	function jfra(f,t,sp,ep){if(!t)return;var end = ep==null?t.length:Math.min(t.length,(sp+ep));for(var i = (sp==null)?0:sp;i<end;i++)f(i,end,t[i]);}
	function jvls(n,p){
		var r=[];
		if(!n)return r; var t = n.selectNodes(p);if(!t)return r;
		for(var i = 0;i<t.length;i++){ 
			n = t[i];if(n.nodeType == 1) n=n.firstChild;r[i]=n?n.nodeValue:'';
		}
		return r;
	}
	function jpar(f,str){var n = parseXML(str).documentElement;f(n);}
	function jfor(n,f,p,sp,ep){
		if(!n)return;
		var t = n.selectNodes(p);
		var end = ep==null?t.length:Math.min(t.length,(sp+ep));
		for(var i = (sp==null)?0:sp;i<end;i++)f(i,end,t[i]);
	}
	
	// Sorting helpers
	var sort_intmask = ["", "0", "00", "000", "0000", "00000", "000000", "0000000", "00000000", "000000000", "0000000000", "00000000000", "000000000000", "0000000000000", "00000000000000" ];
	var sort_dateFmtStr;
	var sort_dateFormat;
	var sort_dateReplace; 
	function sort_dateFmt(str){
		sort_dateFmtStr = str;
		var result = str.match(/(D+|Y+|M+|h+|m+|s+)/g);
		if(!result)return;
		for(var pos={},i=0;i<result.length;i++) pos[result[i].substr(0,1)] = i+1;
		sort_dateFormat = new RegExp(str.replace(/[^\sDYMhms]/g,'\\$1').replace(/YYYY/, "(\\d\\d\\d\\d)").replace(/(DD|YY|MM|hh|mm|ss)/g, "(\\d\\d)"));
		sort_dateReplace = "$" + pos["M"] + "/$" + pos["D"] + "/$" + pos["Y"];
		if(pos["h"])sort_dateReplace += " - $"+pos["h"]+":$"+pos["m"]+":$"+pos["s"];
	}

	// Sorting methods for sort()
  	function sort_alpha(n)  { if(!n)return '';if(n.nodeType == 1) n=n.firstChild;return n?n.nodeValue:''; }
	function sort_number(n){
		var t = sort_alpha(n);
	  	return (t.length < sort_intmask.length ? sort_intmask[sort_intmask.length - t.length] : "") + t;
	}
	function sort_date(n,args){
		if(!sort_dateFormat || (args && sort_dateFmtStr!=args[0]))sort_dateFmt(args?args[0]:"*");
		var t = sort_alpha(n),d;
		if(sort_dateFmtStr=='*')d = Date.parse(t);
		else d = (new Date(t.replace(sort_dateFormat, sort_dateReplace))).getTime();
		t = ""+parseInt(d); if(t=="NaN")t="0";
		return (t.length < sort_intmask.length ? sort_intmask[sort_intmask.length - t.length] : "") + t;
	}
	
	function jsort(n,f,p,ps,sm,desc,sp,ep){
		sm = sm?sm:sort_alpha;
		var sa = [], t = n.selectNodes(p), i = t.length, args = null;
		if(typeof sm != "function"){var m = sm.shift();args = sm; sm = m;}		

		// build string-sortable list with sort method
		while(i--){
			var n = t[i].selectSingleNode(ps);
			if(n) sa[sa.length] = {toString:function(){return this.v;}, pn:t[i], v:sm(n,args)};
			else  sa[sa.length] = {toString:function(){return this.v;}, pn:t[i], v:''};
		}
		// sort it
		sa.sort();
		
		//iterate like foreach
		var end = ep==null?sa.length:Math.min(sa.length,(sp+ep));
		var start = (sp==null)?0:sp;
		if(desc){
			for(var i = end-1;i>=start;i--)f(end-i-1,end,sa[i].pn,sa[i].v);
		}else{
			for(var i = start;i<end;i++)f(i,end,sa[i].pn,sa[i].v);
		}
	}
	
	
	function japl(s,n,ma,p){
		if(!n)return;
		var m = n.selectNodes(p||'node()');
		for(var i=0;i<m.length;i++){
			var n = m[i];
			var f = ma[0][n.tagName];
			if(f)f(s,n);
			else{
				for(var k=1;k<ma.length;k++){
					var sn = n.selectSingleNode(ma[k][0]);
					if(sn){ma[k][1](s,sn);break;}
				}
			}
		}
	}
	
	function jmat(ma,f,p){	
		var s = p.split(/\|/), all = true;
		for(var i = 0;i<s.length;i++){
			if(!s[i].match(/^[\w_]+$/))all=false;
			ma[0][s[i]]=f;
		}
		if(!all){
			p = "self::"+p.replace(/\|/g,"|self::");
			ma[ma.length]=[p,f];
		}
	}
	

	//------------------------------------------------------------------------------------

	var types=['[','{','(','text','xpath','word','sep','ws','semi','sh','op','col','str','regex'];
	var closes=[']','}',')'];

	var func={'last':[0,'(i==len-1)'],
			    'first':[0,'(i==0)'],
				 'out':[0,'s[s.length]'],
				 'apply':[1,';japl(s,n,ma,',');'],
				 'copy':[1,';jcpy(s,n,',');'],
				 'xml':[1,'jxml(n,',')'],
				 'value':[1,'jval(n,',')'],
				 'exists':[1,'jexs(n,',')'],
				 'empty':[1,'jemp(n,',')'],
				 'values':[1,'jvls(n,',')'],
				 'node':[1,'jnod(n,',')'],
				 'nodes':[1,'jnds(n,',')'],
				 'count':[1,'jcnt(n,',')'],
				 'context':[1,'(n=n.selectSingleNode(','))'],
				 'foreach':[2,';jfor(n,function(i,len,n){','},',');'],
				 'sort':[2,';jsort(n,function(i,len,n,sv){','},',');'],
				 'local':[2,';jloc(n,function(n){','},',');'],	
				 'match':[2,';jmat(ma,function(s,n){','},',');'],
				 'pack':[2,'jpak(n,function(s,n){','},',')'],
				 'store':[2,'jstore(n,os,function(s,n){','},',');'],
				 'fetch':[1,'jfetch(os,',')'],

				 'parse':[2,'jpar(function(n){','},',');'],
				 'forarray':[3],
				 'macro':[4],
				 'pragma':[5],
				 '_':[6]};
	// s,n,i,len
		
	var short_0={'%':'s[s.length]='};
	var short_1={'$':['jval(n,',')'],
					 '&':['jnod(n,',')'],
					 '@':['(n=n.selectSingleNode(','))'],
					 '~':['jexs(n,',')'],
					 '!':['!jexs(n,',')'],
					 '#':['jcnt(n,',')'],
					 '^':[';japl(s,n,ma,',');']};
	var short_2={'*':[';jfor(n,function(i,len,n){','},',')']};
	
	//------------------------------------------------------------------------------------
	
	function dump_tree(n,s,w){
		for(var i =0;i<n.length;i++){
			var m=n[i], t  = m[0];
			if(t<3){
				s.push(w+types[t]);dump_tree(m[1],s,'&nbsp;&nbsp;'+w);s.push(closes[t]);s.push('\n');
			}else{
				s.push(w+types[t]+': '+m[1]+'\n');					
			}
		}
	}
				
	this.compile =function(str, trim_startspace){

		var err		=[];	// error list
		var tree		=[];  // parse tree
		var stack	=[];  // scopestack
		var node 	= tree;
		var blevel=0, tpos=0;
		var istr = 0, icc = 0;
		var lm = 0;
		var macros={};
		//tokenize
		str = str.replace(/\/\*[\s\S]*?\*\//gm,"");
		str.replace(/([\w_\.]+)|([\s]*,[\s]*)|([\s]*;[\s]*)|((?:[\s]*)[\$\@\#\%\^\&\*\?\!](?:[\s]*))|([\s]*[\+\-\<\>\|\=]+[\s]*)|(\s*\:\s*)|(\s+)|(\\[\\\{\}\[\]\"\'\/])|(\[)|(\])|([\s]*\([\s]*)|([\s]*\)[\s]*)|([\s]*\{[\s]*)|([\s]*\}[\s]*)|(\')|(\")|(\/)/g,function(m,word,sep,semi,sh,op,col,ws,bs1,bo,bc,po,pc,co,cc,q1,q2,re,pos){
			// stack helper functions
			function add_track(t)		{
				var txt = trim_startspace?str.substr( tpos, pos-tpos).replace(/[\r\n]\s*/,'').replace(/^\s*[\r\n]/,'').replace(/\\s/g,' ').replace(/[\r\n\t]/g,''):str.substr( tpos, pos-tpos).replace(/[\r\n\t]/g,'');
				if(txt.length>0){ node[node.length]=[t,txt,tpos,pos];}
			}
			function add_node(t,data)	{node[node.length]=[t,data,pos];}
			function add_sub(t)			{var n = [];node[node.length]=[t,n,pos];stack[stack.length] = node;node = n;}
			function pop_sub(t)			{if(stack.length==0){err[err.length] = ["extra "+closes[t],pos];}else{node = stack.pop();var ot = node[node.length-1][0];if(ot!=t){err[err.length]=["scope mismatch "+types[ot]+" with "+types[t],pos];}}}

			// are we in textmode or entering textmode?
			if(blevel==0 || (bc && blevel==1 && !istr )){
				if(icc==0){
					if(bo){add_track(3);blevel++;} // begin codeblock
					if(bc){if(blevel==0)err[err.length] = ["extra ]",pos];else {blevel--;tpos = pos+1;}} // end codeblock
				}
				if(co){add_track(3);tpos = pos+1;icc++;} // add last text chunk
				if(cc){add_track(4);tpos = pos+1;icc--;if(icc<0)err[err.length]=["extra }",pos];} // xpath chunk
			}else{
				if(!istr){
					if(word){add_node(5,m);if(m=='macro')lm=1;else if(lm)macros[m]=1,lm=0;}
					if(sep)add_node(6,',');
					if(ws)add_node(7,m);
					if(semi)add_node(8,m);
					if(sh)add_node(9,m);
					if(op)add_node(10,m);
					if(col)add_node(11,m);
					if(bo){blevel++;add_sub(0);}
					if(bc){blevel--;pop_sub(0);}
					if(co)add_sub(1);
					if(cc)pop_sub(1);
					if(po)add_sub(2);
					if(pc)pop_sub(2);
				}		
				if(q1){ if(istr==0){istr=1;tpos=pos;}else if(istr==1){istr=0;pos+=1;add_track(12);} }	
				if(q2){ if(istr==0){istr=2;tpos=pos;}else if(istr==2){istr=0;pos+=1;add_track(12);} }
				if(re){ 
					if(istr==0){
						// only allow regex mode if we have no previous siblings or we have a , before us
						if(node.length==0 || node[node.length-1][0]==6){
							istr=3;tpos=pos;
						}else add_node(10,m);
					}
					else if(istr==3){istr=0;pos+=1;add_track(13);}
				}
			}
			return m;
		});
		if(blevel==0){
			var txt = str.substr( tpos, str.length-tpos).replace(/[\r\n\t]/g,'');
			if(txt.length>0){ node[node.length]=[3,txt,tpos,str.length];}}
		if( stack.length > 0 )for(var i = stack.length-1;i>=0;i--){
			var j = stack[i][stack[i].length-1];
			err[err.length] = ["unclosed tag "+types[j[0]],j[2]]; 
		}

		var s		=['var s=[],ma=[{}],os={};'];				
		
		var pragma_trace = 0;
		function line_pos(cpos){
			var l=0;str.replace(/\n/g,function(m,pos){if(pos<cpos)l++;return m;});
			return l;
		}
		
		//recursive compile
		function compile_recur(s,n,offset){

			var k=n.length;
			var d,e;
		//	var lt=14;
			for(var i = ((offset==null)?0:offset);i<k;i++){
				var t = n[i][0];
				// function expansion
				if(t==5){
					var nt1=(i<k-1)?n[i+1][0]:-1,nt2=(i<k-2)?n[i+2][0]:-1;
					var m = n[i][1];
					var d = func[m];
					// also dont insert ;'s
					if(d){
						
						switch(d[0]){
							case 0: s[s.length] = d[1]; break;
							case 1: // () type function
								if(nt1!=2){
									err[err.length]=["Function "+m+" syntax error",n[i][2]];	
								}else{
									s[s.length] = d[1];if(!compile_recur(s,n[i+1][1]))s[s.length]='null';s[s.length] = d[2];
									i++;
								}
								break; 
							case 2: // () {} type function
								if(nt1!=2 || nt2!=1){
									err[err.length]=["Function "+m+" syntax error",n[i][2]];	
								}else{							
									s[s.length] = d[1];compile_recur(s,n[i+2][1]);s[s.length] = d[2];
									if( !compile_recur(s, n[i+1][1] ) )s[s.length]='null';
									s[s.length] = d[3];
									i+=2;		
								}
								break;
							case 3://forarray
								//we should have ( word ws in .... , .. , ..  ) {}
								var o,ok;
								if( i>k-3 || n[i+1][0]!=2 || n[i+2][0]!=1 || (o=n[i+1][1])[0][0]!=5 ||
									(ok=o.length)<5 || o[1][0]!=7 || o[2][0]!=5 || o[2][1]!='in' ){
									err[err.length]=["forarray syntax error",n[i][2]];	
								}else{
									s[s.length]=';jfra(function(i,len,'+o[0][1]+'){';
									compile_recur(s,n[i+2][1]);
									s[s.length]='},';
									compile_recur(s,o, 3);
									s[s.length]=');';i+=2;
								}break; 
							case 4://macro
								//we should have ws, word, quote, code
								if( i>=k-4 || n[i+1][0]!=7 || n[i+2][0]!=5 || n[i+3][0]!=2 || n[i+4][0] != 1){
									err[err.length]=["macro syntax error at",n[0][2]];
								}else{	
									s[s.length] = 'function '+n[i+2][1]+'(s,n,';
									if(!compile_recur(s,n[i+3][1]))s[s.length]='null';
									s[s.length]='){';compile_recur(s,n[i+4][1]);s[s.length]='}';
									i+=4;
								}
								break;
							case 5://pragma
							{
								if( i>=k-3 || n[i+1][0]!=7 || n[i+2][0]!=5 || n[i+3][0]!=2){
									err[err.length]=["macro syntax error at",n[0][2]];
								}else{	
									switch(n[i+2][1]){
										case 'trace':{
											var ts =[];
											compile_recur(ts,n[i+3][1]);
											pragma_trace = eval(ts.join(''));
										}break;
									}
								}
								i+=3;
							}
							case 6://trace
							{
								s[s.length]=';alert("Trace: '+line_pos(n[i][2])+'");';
							}
						}							
					}else{
						if(macros[m] && nt1 == 2){
							s[s.length] = m+'(s,n,';if(!compile_recur(s,n[i+1][1]))s[s.length]='null';s[s.length] = ')';
							i++;
						}else s[s.length] = m;
					}
					// check our type
				}
				//shorthand expansion
				else if(t==9){
					var nt1=(i<k-1)?n[i+1][0]:-1,nt2=(i<k-2)?n[i+2][0]:-1;
					var m = n[i][1];
					
					if(nt1==12){
						if(nt2==1){
							if(d=short_2[m]){
								s[s.length] = d[0];compile_recur(s,n[i+2][1]);s[s.length] = d[1]+n[i+1][1]+d[2];
								i+=2;lt=1;
							}
							else s[s.length]=m;
						}
						else{
							if(d=short_1[m]){
								if(nt2==11)s[s.length]=m;
								else{
									s[s.length] = d[0]+n[i+1][1]+d[1];
									i++;
								}
							}
							else {
								if( d=short_0[m] )s[s.length]=d;
								else s[s.length]=m;
							}		
						}	
					}else{
						if( d=short_0[m] )s[s.length]=d;
						else s[s.length]=m;
					}		
				}
				// normal add
				else{
					if(t<3){
						s[s.length] = types[t];compile_recur(s,n[i][1]);s[s.length]=closes[t];

						// ; insertion code
						if( (t==1 && i<k-1 && n[i+1][0]==5 && n[i+1][1]!='else') ||  // }word
							 ( t==2 && i<k-1 && n[i+1][0]==5 && !n[i+1][1].match(/^\./) && // )word
							   (i==0 || n[i-1][0]!=5 || !n[i-1][1].match(/^(if|for)$/) ) ) )
						{
							s[s.length] = ';';
						}

					}
					else{
						
						if(t==3)s[s.length]=';s[s.length]="'+n[i][1].replace(/\"/g,"\\\"").replace(/\n/g,"\\n")+'";';
						else if(t==4){
							var m = n[i][1].match(/^\^([\w])\s?/);
							if(m){
								s[s.length]=';s[s.length]=jesc(jval(n,"'+n[i][1].substr(2).replace(/"/g,"\\\"")+'"),"'+m[1]+'");';
							}else{
								s[s.length]=';s[s.length]=jval(n,"'+n[i][1].replace(/"/g,"\\\"")+'");';
							}
						}
						else s[s.length]=n[i][1];
					}
				}
				//lt = n[i][0];
			}
			return k;
		}	
		if(err.length==0)compile_recur(s,tree);
						
		// return all parse errors
		if(err.length>0){
			var e=[];
			for(var i = 0;i<err.length;i++){
				e[e.length]='Parse error('+line_pos(err[i][1])+'): '+err[i][0]+'\n';


			}
			// lets spit out our parse tree

			//var out=[];
			//dump_tree(tree,out,'');
						
			throw new Error(0, "Could not parse JSLT with: " + e.join('') +"\n" );
		}

		s[s.length]=";return s.join('');";
		var strJS = s.join('');

		try{eval("var f = function(n){" + strJS + "};");}catch(e){
			//var treedump=[];
			//dump_tree(tree,treedump,'');	
			setStatus(formatJS(strJS));
			throw new Error(0, "Could not parse JSLT with: " + e.message /*+ "\n" + treedump.join('')*/);
		}
	
		return [f, strJS];
	};
	
	/************************************************
		//you can interchange nodes and strings
		apply(jsltStr, xmlStr);
		apply(jsltNode, xmlNode);
		
		returns string or false
	************************************************/
	this.cache = [];
	
	this.apply = function(jsltNode, xmlNode){
		var jsltFunc, cacheId, jsltStr, doTest;
		
		//Type detection xmlNode
		var xmlNode = XMLDatabase.getBindXmlNode(xmlNode);
		
		//Type detection jsltNode
		if(typeof jsltNode == "object"){
			
			//check the jslt node for cache setting
			cacheId = jsltNode.getAttribute("cache");
			jsltFunc = this.cache[cacheId];
			if(!jsltFunc) jsltStr = jsltNode.selectSingleNode('text()').nodeValue
		}
		else{
			cacheId = jsltNode;
			jsltFunc = this.cache[cacheId];
			if(!jsltFunc) jsltStr = jsltNode;
		}
		
		//Compile string
		if(!jsltFunc)
			jsltFunc = this.compile(jsltStr);
		
		this.lastJslt = jsltStr;
		this.lastJs = jsltFunc[0]; //if it crashes here there is something seriously wrong
		
		//Invalid code - Syntax Error
		if(!jsltFunc[0]) return false;
		
		//Caching
		if(!cacheId){
			if(typeof jsltNode == "object"){
				cacheId = this.cache.push(jsltFunc) - 1
				jsltNode.setAttribute("cache", cacheId);
			}
			else this.cache[jsltStr] = jsltFunc;
		}
		
		//Execute JSLT
		try{
			if(!xmlNode) return '';
			
			return jsltFunc[0](xmlNode);
		}
		catch(e){
			setStatus(formatJS(jsltFunc[1]));
			throw new Error(0, Kernel.formErrorString(0, null, "JSLT parsing", "Could not execute JSLT with: " + e.message));
		}
	}
}
var JSLT = new _JSLT();;
function Class(){
	this.__jmlLoaders = [];
	this.__addJmlLoader = function(func){
		if(!this.__jmlLoaders) func.call(this, this.jml);
		else this.__jmlLoaders.push(func);
	}
	
	this.__jmlDestroyers = [];
	this.__addJmlDestroyer = function(func){this.__jmlDestroyers.push(func);}
	
	this.__regbase = 0;
	this.hasFeature = function(test){return this.__regbase&test}

	/************************
		PROPERTY BINDING
	************************/
	
	
	this.setProperty = function(prop, value, reqValue, forceOnMe){
		if(reqValue && !value) return;

		if(this[prop] !== value)
			this.handlePropSet(prop, value, forceOnMe);
		
	}
	
	this.getProperty = function(prop){
		return this[prop];
	}
	
	/************************
		EVENT HANDLING
	************************/
	
	var events_stack = {};
	this.dispatchEvent = function(eventName){
		if(this.disabled) return false;
		
		
		var result, arr = events_stack[eventName];
		if((!arr || !arr.length) && !this[eventName]) return;
		
		for(var args=[],i=1;i<arguments.length;i++) args.push(arguments[i]);
		if(this[eventName]) result = this[eventName].apply(this, args); //Backwards compatibility
		if(!arr) return result;
		
		for(var retValue, i=0;i<arr.length;i++){
			retValue = arr[i].apply(this, args);
			if(retValue != undefined) result = retValue;
		}
		
		return result;
	}
	this.addEventListener = function(eventName, func){
		if(!events_stack[eventName]) events_stack[eventName] = [];
		events_stack[eventName].pushUnique(func);
	}
	this.removeEventListener = function(eventName, func){
		if(events_stack[eventName]) events_stack[eventName].remove(func);
	}
	this.hasEventListener = function(eventName){
		return events_stack[eventName] && events_stack[eventName].length > 0;
	}
	
	this.destroy = function(){
		if(!this.uniqueId) return;
		
		if(this.__destroy) this.__destroy();
		
		for(var i=this.__jmlDestroyers.length-1;i>=0;i--)
			this.__jmlDestroyers[i].call(this);
		this.__jmlDestroyers = undefined;
		
		if(this.oExt && !this.oExt.isNative && this.oExt.nodeType == 1) this.oExt.host = null;
		if(this.oInt && !this.oExt.isNative && this.oInt.nodeType == 1) this.oInt.host = null;
		
		this.jml = null;
		
		// Remove from Kernel.all
		Kernel.all[this.uniqueId] = null;
		this.uniqueId = null;
	}
	
	
	this.destroySelf = function(){
		if(!this.hasFeature) return;
		
		//Update JMLDOMApi as well
		
		// Remove id from global js space
		if(this.name) self[this.name] = null;
	
		// Remove from window.onresize - Should be in Anchoring or Alignment
		if(this.hasFeature(__ANCHORING__)) this.disableAnchoring();
		if(this.hasFeature(__ALIGNMENT__)) this.disableAlignment();
		
		// Remove dynamic properties - Should be in Class (clear events???)
		this.unbindAllProperties();
		
		// Remove data connections - Should be in DataBinding
		if(this.dataParent) this.dataParent.parent.disconnect(this);
		if(this.hasFeature(__DATABINDING__)){
			this.unloadBindings();
			this.unloadActions();
		}
		if(this.hasFeature(__DRAGDROP__))
			this.unloadDragDrop();
		
		// Remove from focus list - Should be in JmlNode
		if(this.focussable) me.__removeFocus(this);
		
		// Remove from multilang list listener (also on skin switching) - Should be in MultiLang
		if(this.hasFeature(__MULTILANG__)) this.__removeEditable();
		
		//Remove all cached Items - Should be in Cache
		if(this.hasFeature(__CACHE__)) this.clearAllCache();
		
		if(this.childNodes){
			for(var i=0;i<this.childNodes.length;i++){
				if(this.childNodes[i].destroySelf)
					this.childNodes[i].destroySelf();
				else
					Kernel.removeNode(this.childNodes[i].oExt);
			}
		}
		
		if(this.destroy) this.destroy();
	}
}
;;;
function issueWarning(nr, msg){
	if(!self.DEBUG) return;
	
	//needs implementation
	if(Kernel.warnings[msg]) return;

	//var seeAgain = confirm("Javelin Notification\nA warning has been issued\n\nNumber: " + nr + "\nWarning: " + msg + "\n\nPress OK to see this warning again.");
	//if(!seeAgain) Kernel.warnings[msg] = true;
	
	setStatus("[Warning - " + nr + "]:<br />" + msg.replace(/\n/g, "<br />") + "<br />");
	Kernel.warnings[msg] = true;
}

function vardump(obj, depth, recur){
	if(!obj) return obj + "";
	if(!depth) depth = 0;

	switch(obj.dataType){
		case "string":	return "\"" + obj + "\"";
		case "number":	return obj;
		case "boolean": return obj ? "true" : "false";
		case "date": return "Date[" + new Date() + "]";
		case "array":
			var str = "{\n";
			for(var i=0;i<obj.length;i++){
				str += "     ".repeat(depth+1) + i + " => " + (!recur && depth > 0 ? typeof obj[i] : vardump(obj[i], depth+1, !recur)) + "\n";
			}
			str += "     ".repeat(depth) + "}";
			
			return str;
		default:
			if(typeof obj == "function") return "function";
			if(obj.xml) return depth==0 ? "[ " + obj.xml + " ]" : "XML Element";
			if(!recur && depth>0) return "object";
		
			//((typeof obj[prop]).match(/(function|object)/) ? RegExp.$1 : obj[prop])
			var str = "{\n";
			for(prop in obj){
				try{
					str += "     ".repeat(depth+1) + prop + " => " + (!recur && depth > 0? typeof obj[prop] : vardump(obj[prop], depth+1, !recur)) + "\n";
				}catch(e){
					str += "     ".repeat(depth+1) + prop + " => [ERROR]\n";
				}
			}
			str += "     ".repeat(depth) + "}";
			
			return str;
	}
}

function alert_r(obj, recur){
	alert(vardump(obj, null, !recur));
}

Profiler = {
	totalTime : 0,
	start : function(clear){
		if(clear) this.totalTime = 0;
		this.startTime = new Date();
		
		this.isStarted = true;
	},
	end : function(){
		if(!this.startTime) return;
		var startTime = this.startTime;
		var endTime = new Date();
		this.totalTime += (endTime.getMinutes()-startTime.getMinutes())*60000+(endTime.getSeconds()-startTime.getSeconds())*1000+(endTime.getMilliseconds()-startTime.getMilliseconds());
		
		this.isStarted = false;
	},
	addPoint : function(msg){
		this.end();
		setStatus("[TIME] " + msg + ": " + this.totalTime + "ms");
		this.start(true);
	}
}
         
var DEBUG_SCREEN;
function setDebug(value){
	if(!DEBUG_SCREEN){
		DEBUG_SCREEN = top.document.body.appendChild(document.createElement("DIV"));
		with(DEBUG_SCREEN.style){
			backgroundColor = "white";
			fontFamily = "Arial";
			fontSize  = "8pt";
			color = "black";
			border = "2px inset white";
			width = "500px";
			height = "200px";
			overflow = "auto";
			position = "absolute";
			left = "0px";
			bottom = "0px";
			zIndex = 100000;
		}  
	}     
	      
	DEBUG_SCREEN.innerHTML = value.replace(/\n/, "<br>");
}        
         
function analyzeObject(o){
	str = "<table>";
	for(prop in o) str += "<tr><td vAlign='top' style='font-family:Arial;font-size:8pt'>" + prop + "</td><td style='font-family:Arial;font-size:8pt'>" + (typeof o[prop] == "function" ? "<b>function</b>" : (prop == "innerHTML" || prop == "outerHTML" || prop == "innerText" || prop == "outerText" || prop == "altHTML"  ? "<b>CONTENTS</b>" : o[prop])) + "</td></tr>";
	setDebug(str + "</table>");
}

/**************** DEBUGGER ********************/

TYPE_OBJECT = "object";
TYPE_NUMBER = "number";
TYPE_STRING = "string";
TYPE_ARRAY = "array";
TYPE_DATE = "date";
TYPE_REGEXP = "regexp";
TYPE_BOOLEAN = "boolean";
TYPE_FUNCTION = "function";
TYPE_DOMNODE = "dom node";
TYPE_JAVNODE = "Javeline Component";

STATE_UNDEFINED = "undefined";
STATE_NULL = "null";
STATE_NAN = "nan";
STATE_INFINITE = "infinite";

function getType(variable){
	if(variable === null) return STATE_NULL;
	if(variable === undefined) return STATE_UNDEFINED;
	if(typeof variable == "number" && isNaN(variable)) return STATE_NAN;
	if(typeof variable == "number" && !isFinite(variable)) return STATE_INFINITE;

	if(typeof variable == "object"){
		if(variable.hasFeature) return TYPE_JAVNODE;
		if(variable.tagName || variable.nodeValue) return TYPE_DOMNODE;
	}
	
	if(variable.dataType == undefined) return TYPE_OBJECT;
	
	return variable.dataType;
}

function isType(variable){
	if(variable == null) return false;
	if(variable == undefined) return false;
	if(variable.type == TYPE_NUMBER && isNaN(variable)) return false;
	
	return true;
}

var DebugInfoStack = [];
Function.prototype.toHTMLNode = function(highlight){
	var code, line1, line2;
	
	//anonymous
	code = this.toString();
	endLine1 = code.indexOf("\n"); 
	line1 = code.slice(0, endLine1);
	line2 = code.slice(endLine1+1);
	
	res = /^function(\s+(.*?)\s*|\s*?)\((.*)\)(.*)$/.exec(line1);
	if(res){
		var name = res[1];
		var args = res[3];
		var last = res[4];

		if(this.arguments){
			var argName, namedArgs = args.split(",");
			args = [];

			for(i=0;i<this.arguments.length;i++){
				//if(i != 0 && arr[i]) args += ", ";
				argName = (namedArgs[i].trim() || "__NOT_NAMED__");// args += "<b>" + arr[i] + "</b>";
				
				var info = ["Name: " + argName];
				var id = DebugInfoStack.push(info) - 1;
				
				args.push("<a href='javascript:void(0)' onclick='alert(DebugInfoStack[" + id + "].join(\"\\n\"));event.cancelBubble=true;'>" + argName + "</a>");
				info.push("Type: " + getType(this.arguments[i]));
				info.push("Value: " + vardump(this.arguments[i], null, true));
			}	
		}

		line2 = line2.replace(/\{/ , "");
		line2 = line2.substr(0, line2.length-2);

		if(!highlight){
			line2 = line2.replace(/ /g, "&nbsp;");
			line2 = line2.replace(/\t/g, "&nbsp;&nbsp;&nbsp;");
			line2 = line2.replace(/\n/g, "</nobr><br><nobr>&nbsp;&nbsp;&nbsp;");
			line2 = "{<br><nobr>&nbsp;&nbsp;&nbsp;" + line2 + "</nobr><br>}";
		}
		else{
			line2 = "{\n" + line2 + "\n}\n";
			var div = dp.SyntaxHighlighter.HighlightString(line2, false, false);
		}
		
		var d = document.createElement("div");
		res = "<div><div style='padding:0px 0px 2px 0px;cursor:default;' onclick='obj = this.lastChild.style;if(obj.display == \"block\"){obj.display = \"none\";this.firstChild.firstChild.src=\"images/debug_arrow_right.gif\"}else{obj.display = \"block\";this.firstChild.firstChild.src=\"images/debug_arrow_down.gif\"};event.cancelBubble=true'><nobr><img width='9' height='9' src='images/debug_arrow_right.gif' style='margin:0 3px 0 2px;' />"+(name.trim()||"function")+"("+args.join(", ")+")&nbsp;</nobr><div onclick='event.cancelBubble=true' onselectstart='event.cancelBubble=true' style='cursor:text;display:none;padding:0px;background-color:#EAEAEA;color:#222222;overflow:auto;margin-top:2px;'><blockquote></blockquote></div></div></div>";
		d.innerHTML = res;
		var b = d.getElementsByTagName("blockquote")[0];
		
		if(highlight){
			b.replaceNode(div);
		}
		else{
			b.insertAdjacentHTML("beforeBegin", line2);
			b.parentNode.removeChild(b);
		}

		return d.firstChild;
	}
	else{
		return this.toString();
	}
}

/******************
** Error Handler **
******************/
if(getcookie("highlight") != "false" && self.BASEPATH){
	//<script class="javascript" src="../Library/Core/Highlighter/shCore.uncompressed.js"></script>
	//<script class="javascript" src="../Library/Core/Highlighter/shBrushJScript.js"></script>
	include(BASEPATH + "Library/Core/Highlighter/shCore.uncompressed.js");	
	include(BASEPATH + "Library/Core/Highlighter/shBrushJScript.js");	
	//<link type="text/css" rel="stylesheet" href="../Library/Core/Highlighter/SyntaxHighlighter.css" />
	Kernel.loadStylesheet(BASEPATH + "Library/Core/Highlighter/SyntaxHighlighter.css");
}
else if(self.SyntaxHighlighterCSS){
	Kernel.importCssString(document, SyntaxHighlighterCSS);	
}
else{
	setcookie("highlight", false)
}

function __DEBUGERR(e, filename, linenr){
	var list = [], seen = {};
	
	//Opera doesnt support caller... weird...
	try{
		var loop = end = IS_IE ? __DEBUGERR.caller.caller : __DEBUGERR.caller.caller ? __DEBUGERR.caller.caller.caller : __DEBUGERR.caller.caller;
		if(loop){
			try{
				do{
					if(seen[loop.toString()]) break; //recursion checker
					seen[loop.toString()] = true;
					//str += loop.toHTML();
					list.push(loop.toHTMLNode(getcookie("highlight") != "false"));
					loop = loop.caller;
				}while(list.length < 30 && loop && loop.caller && loop.caller.caller != loop);
			}catch(a){
				list=[];	
			}
		}
	}
	catch(e){}
	
	errorInfo = "Exception caught on line " + linenr + " in file " + filename + "<br>Message: " + e.message;
		
	e.lineNr = linenr;
	e.fileName = filename;

	__JavDispError(e, list, errorInfo);//str
	
	//window.onerror = function(){window.onerror=null;return true}
	//throw new Error(0, "Stopping Error Prosecution");
}

var winError, USE_DEBUGGER = getcookie("debugger") == "true";
function __JavDispError(e, stackTrace, errorInfo){;
	if(!winError){
		var elError = document.getElementById("javerror");
		if(!elError){
			if(document.body){
				elError = document.body.appendChild(document.createElement("div"));
				elError.id = "javerror";
			}
			else{
				document.write("<div id='javerror'></div>");
				elError = document.getElementById("javerror");
			}
			
			elError.style.position = "absolute";
	 		elError.style.zIndex = 10000000;
			elError.style.right = "10px";
			elError.style.top = "10px";
			elError.style.border = "2px outset";
			elError.style.MozBorderBottomColors = "black gray";
			elError.style.MozBorderRightColors = "black gray";
			elError.style.MozBorderTopColors = "#C0C0C0 #FFFFFF";
			elError.style.MozBorderLeftColors = "#C0C0C0 #FFFFFF";
			elError.style.padding = "10px";
			elError.style.width = "600px";
			elError.style.background = "#D4D0C8 url(images/appbg.gif)";
		}
		
		document.body.style.display = "block";
		
		elError.style.display = "block";
		var parse = e.message.split(/\n===\n/);
		var errorMessage = parse[0].replace(/---- Javeline Error ----\n/g, "").replace(/</g, "&lt;").replace(/Message: \[(\d+)\]/g, "Message: [<a title='Visit the manual on error code $1' style='color:blue;text-decoration:none;' target='_blank' href='http://developer.javeline.net/projects/platform/wiki/ErrorCodes#$1'>$1</a>]").replace(/(\n|^)([\w ]+:)/gm, "$1<strong>$2</strong>").replace(/\n/g, "<br />");
		var jmlContext = formatXML(parse[1] ? parse[1].trim(true) : "").replace(/</g, "&lt;").replace(/\n/g, "<br />").replace(/\t/g, "&nbsp;&nbsp;&nbsp;");;

		elError.innerHTML = 
			"<span onclick='this.parentNode.style.display=\"none\"' style='cursor:hand;cursor:pointer;float:right;margin:0px;font-size:8pt;font-family:Verdana;width:14px;text-align:center;height:14px;overflow:hidden;border:1px solid gray;color:gray;background-color:#EEEEEE;padding:0'>X</span><h1 style='font-size:14pt;font-family:Arial;margin-bottom:10px;margin-top:0;color:black;'><strong>An error has occurred in this application:</strong></h1>" +
			"<div onselectstart='event.cancelBubble=true' style='border:1px solid black;padding:4px;font-family:Arial;font-size:10pt;background-color:white;margin-bottom:5px;'>" + errorMessage + "</div>" + 
			(jmlContext ? "<div style='cursor:default;border:1px solid gray;padding:4px;font-family:MS Sans Serif;font-size:8pt;background-color:#DDDDDD;margin-bottom:1px;' onclick='obj = this.lastChild.style;if(obj.display == \"block\"){obj.display = \"none\";this.firstChild.src=\"images/debug_arrow_right.gif\"}else{obj.display = \"block\";this.firstChild.src=\"images/debug_arrow_down.gif\"}'><img width='9' height='9' src='images/debug_arrow_down.gif' />&nbsp;<strong>Javeline Markup Language</strong><br /><div onclick='event.cancelBubble=true' onselectstart='event.cancelBubble=true' style='border:1px solid red;cursor:text;background-color:white;padding:4px 4px 20px 4px;font-size:9pt;font-family:Courier New;margin:3px;border:1px solid gray;max-height:200px;white-space:nowrap;overflow:auto;'>" + jmlContext + "</div></div>" : "") +
			"<div style='cursor:default;border:1px solid gray;padding:4px;font-family:MS Sans Serif;font-size:8pt;background-color:#DDDDDD;margin-bottom:1px;' onclick='obj = this.lastChild.style;if(obj.display == \"block\"){obj.display = \"none\";this.firstChild.src=\"images/debug_arrow_right.gif\"}else{obj.display = \"block\";this.firstChild.src=\"images/debug_arrow_down.gif\"};'><div style='margin-right:5px;float:right;margin-top:-4px;'><input id='cbHighlight' type='checkbox' onclick='toggleHighlighting(this.checked);event.cancelBubble = true;' " + (getcookie("highlight") != "false" ? "checked='checked'" : "") + "/><label for='cbHighlight' style='top:-2px;position:relative;' onclick='event.cancelBubble=true'>Enable Syntax Coloring</label></div><img width='9' height='9' src='images/debug_arrow_right.gif' />&nbsp;<strong>Stack Trace</strong><br /><div style='display:none;background-color:white;padding:4px;font-size:9pt;font-family:Courier New;margin:3px;border:1px solid gray;'><blockquote></blockquote></div></div>" +
			"<div style='cursor:default;border:1px solid gray;padding:4px;font-family:MS Sans Serif;font-size:8pt;background-color:#DDDDDD;margin-bottom:1px;' onclick='obj = this.lastChild.style;if(obj.display == \"block\"){obj.display = \"none\";this.firstChild.nextSibling.src=\"images/debug_arrow_right.gif\"}else{obj.display = \"block\";this.firstChild.nextSibling.src=\"images/debug_arrow_down.gif\";this.lastChild.scrollTop=this.lastChild.scrollHeight};'><div style='margin-right:5px;float:right;margin-top:-4px;'><input id='cbTW' type='checkbox' onclick='toggleLogInWindow(this.checked);event.cancelBubble = true;' " + (getcookie("viewinwindow") == "true" ? "checked='checked'" : "") + "/><label for='cbTW' style='top:-2px;position:relative;' onclick='event.cancelBubble=true'>View in window</label></div><img width='9' height='9' src='images/debug_arrow_right.gif' />&nbsp;<strong>Log Viewer</strong><br /><div id='jvlnviewlog' onclick='event.cancelBubble=true' onselectstart='event.cancelBubble=true' style='display:none;height:150px;overflow:auto;cursor:text;background-color:white;padding:4px;font-size:9pt;font-family:Courier New;margin:3px;border:1px solid gray;'>" + Kernel.DEBUG_INFO.replace(/\n/g, "<br />") + "</div></div>" +
			"<div style='cursor:default;border:1px solid gray;padding:4px;font-family:MS Sans Serif;font-size:8pt;background-color:#DDDDDD;margin-bottom:1px;' onclick='obj = this.lastChild.style;if(obj.display == \"block\"){obj.display = \"none\";this.firstChild.src=\"images/debug_arrow_right.gif\"}else{obj.display = \"block\";this.firstChild.src=\"images/debug_arrow_down.gif\";this.lastChild.firstChild.focus()};'><img width='9' height='9' src='images/debug_arrow_right.gif' />&nbsp;<strong>Javascript console</strong><br /><div style='display:none' onclick='event.cancelBubble=true'><textarea onkeydown='if(event.keyCode == 9){this.nextSibling.focus();event.cancelBubble=true;return false;}' onselectstart='event.cancelBubble=true' style='background-color:white;padding:4px;font-size:9pt;font-family:Courier New;margin:3px;border:1px solid gray;width:575px;height:100px;'>" + getcookie("jsexec") + "</textarea><button onclick='jRunCode(this.previousSibling.value)' style='font-family:MS Sans Serif;font-size:8pt;margin:0 0 0 3px;' onkeydown='if(event.shiftKey && event.keyCode == 9){this.previousSibling.focus();event.cancelBubble=true;return false;}'>Execute</button></div></div>" +
			"<br style='line-height:5px'/><input id='toggledebug' type='checkbox' onclick='toggleDebugger(this.checked)' /><label for='toggledebug' style='font-family:MS Sans Serif;font-size:8pt;'>Use browser's debugger</label>"
		var b = elError.getElementsByTagName("blockquote")[0];
		//" || "No stacktrace possible").replace(/\n/g, "<br />") + "
		if(stackTrace.length){
			for(var i=0;i<stackTrace.length;i++)
				b.parentNode.insertBefore(stackTrace[i], b);
			b.parentNode.removeChild(b);
		}
		else b.replaceNode(document.createTextNode("No stacktrace possible"));
		
		Kernel.ondebug = function(str){
			var logView = document.getElementById("jvlnviewlog");
			if(!logView) return;
			
			logView.insertAdjacentHTML("beforeend", str);
			logView.style.display = "block";
			logView.scrollTop = logView.scrollHeight;
		}
		
		clearInterval(Init.interval);
		ERROR_HAS_OCCURRED = true;
	}
}

function jRunCode(code){
	setcookie("jsexec", code);
	
	if(USE_DEBUGGER){
		var x = eval(code) || "";
		try{setStatus(x.toString().replace(/</g, "&lt;").replace(/\n/g, "<br />"));}catch(e){setStatus(x ? "Could not serialize object" : x)}
	}
	else{
		try{
			var x = eval(code) || "";
			try{setStatus(x.toString().replace(/</g, "&lt;").replace(/\n/g, "<br />"));}catch(e){setStatus(x ? "Could not serialize object" : x)}
		}
		catch(e){setStatus("[ERROR] " + e.message)}
	}
}

function toggleLogInWindow(checked){
	if(checked){
		DEBUG_TYPE = "window";
		Kernel.win = window.open("", "debug");
		Kernel.win.document.write(Kernel.DEBUG_INFO);
	}
	else DEBUG_TYPE = "memory";
	
	if(self.setcookie) setcookie("viewinwindow", checked)
}
DEBUG_TYPE = "memory";//getcookie("viewinwindow") == "true" ? "window" : "memory";

function toggleHighlighting(checked){
	setcookie("highlight", checked);
}

function toggleDebugger(checked){
	USE_DEBUGGER = checked;

	if(self.setcookie) setcookie("debugger", checked)
	
	if(!checked) window.onerror = __ErrorHandler;
	else window.onerror = null; 
}

function __ErrorHandler(message, filename, linenr){
	if(!message) message = "";
	e = {
		message : "js file: [line: " + linenr + "] " + removePathContext(HOST_PATH, filename) + "\n" + message
	}
	
	setStatus("[ERROR on line " + linenr + "]:<br />" + message.split(/\n\n===\n/)[0].replace(/</g, "&lt;").replace(/\n/g, "<br />") + "<br />");
	__DEBUGERR(e, filename, linenr);
	return true;
}
if(!USE_DEBUGGER) window.onerror = __ErrorHandler

if(!USE_DEBUGGER && (IS_OPERA || IS_SAFARI)){
	Error = function(nr, msg){
		__ErrorHandler(msg, location.href, 0);
	}
}

Kernel.ondebugkey = function(keyCode, ctrlKey, shiftKey, altKey){
	//ctrlKey && keyCode == 71 || ctrlKey && altKey && keyCode == 68
	if(keyCode == 120 || ctrlKey && altKey && keyCode == 68){
		toggleDebugger(false);

		if(document.getElementById("javerror")) document.getElementById("javerror").style.display = "block";
		else __ErrorHandler("User initiated error", location.href, 0);//setTimeout('throw new Error(0, "User initiated error");');
	}
}

/**************** END DEBUGGER ********************/

;;/********* OBJECT EXTENSIONS *********
	Fix Browser Incompatibility and
	implement extra functionalities
	like inheritence etc
*************************************/

/*Function.prototype.inherit = function(classRef){
	this.prototype = (classRef instanceof Function ? new classRef() : classRef);
}*/

function parseUri(sourceUri){
    var uriPartNames = ["source","protocol","authority","domain","port","path","directoryPath","fileName","query","anchor"];
    var uriParts = new RegExp("^(?:([^:/?#.]+):)?(?://)?(([^:/?#]*)(?::(\\d*))?)?((/(?:[^?#](?![^?#/]*\\.[^?#/.]+(?:[\\?#]|$)))*/?)?([^?#/]*))?(?:\\?([^#]*))?(?:#(.*))?").exec(sourceUri);
    var uri = {};
    
    for(var i = 0; i < 10; i++){
        uri[uriPartNames[i]] = (uriParts[i] ? uriParts[i] : "");
    }
    
    // Always end directoryPath with a trailing backslash if a path was present in the source URI
    // Note that a trailing backslash is NOT automatically inserted within or appended to the "path" key
    if(uri.directoryPath.length > 0){
        uri.directoryPath = uri.directoryPath.replace(/\/?$/, "/");
    }
    
    return uri;
}

function extend(dest){
	for(var i=1;i<arguments.length;i++){
		var src = arguments[i];
		for(var prop in src) dest[prop] = src[prop];
	}
	return dest;
}

/*function serialize(data){
	return new JSON().getSerialized("test", data)
}*/

function unserialize(str){
	if(!str) return str;
	eval("var data = " + str);
	return data;
}


function isNull(value){
	if(value) return false;
	return (value == null || !String(value).length);
}

function isArray(o){
	return (o && typeof o == "object" && o.length);
}

function isTrue(c){
	return c === true || c === "true" || c === "on" || typeof c == "number" && c > 0 || c === "1";
}

function isFalse(c){
	return c === false || c === "false" || c === "off" || c === 0 || c === "0";
}

function isNot(c){
	// a var that is null, false, undefined, Infinity, NaN and c isn't a string
	return (!c && typeof c != "string" && c !== 0 || (typeof c == "number" && !isFinite(c)));
}

if(!self.isFinite){
	function isFinite(val){
		return val+1!=val;
	}
}

function copyObject(o){
	var rv = new Object();
	for(prop in o) rv[prop] = o[prop];
	return rv;
}

Array.prototype.copy = function(){
	var ar = new Array();
	for(var i=0;i<this.length;i++)
		ar[i] = this[i] && this[i].copy ? this[i].copy() : this[i];

	return ar;
}

function copyArray(ar, Type){
	if(!ar) return ar;
	for(var car=[], i=0;i<ar.length;i++)
		car[i] = Type ? new Type(ar[i]) : ar[i];

	return car;
}

Array.prototype.arrayAdd = function(){
	var s = this.copy();
	for(var i=0;i<arguments.length;i++){
		for(var j=0;j<s.length;j++){
			s[j] += arguments[i][j];
		}
	}

	return s;
}

//equals??
Array.prototype.isEqual = function(obj){
	for(var i=0;i<this.length;i++) if(this[i] != obj[i]) return false;
	return true;
}

Array.prototype.makeUnique = function(){
	var newArr = [];
	for(var i=0;i<this.length;i++)
		if(!newArr.contains(this[i])) newArr.push(this[i]);

	this.length = 0;
	for(var i=0;i<newArr.length;i++)
		this.push(newArr[i]);
}

Array.prototype.makeUnique = function(){
	var newArr = [];
	for(var i=0;i<this.length;i++)
		if(!newArr.contains(this[i])) newArr.push(this[i]);

	this.length = 0;
	for(var i=0;i<newArr.length;i++)
		this.push(newArr[i]);
}

Array.prototype.contains = function(obj){
	for(var i=0;i<this.length;i++) if(this[i] == obj) return true;
	return false;
}

Array.prototype.indexOf = function(obj){
	for(var i=0;i<this.length;i++) if(this[i] == obj) return i;
	return -1;
}

Array.prototype.pushUnique = function(item){
	if(!this.contains(item)) this.push(item);
}

Array.prototype.search = function(){
	for(var i=0;i<arguments.length;i++){
		if(typeof this[i] != "array") continue;
		for(var j=0;j<arguments.length;j++){
			if(this[i][j] != arguments[j]) break;
			else if(j == arguments.length-1) return this[i];
		}
	}
}

//Mac workaround...
if(!Function.prototype.call){
	Function.prototype.call = function(obj, arg1, arg2, arg3){
		obj.tf = this;
		var rv = obj.tf(arg1, arg2, arg3);
		obj.tf = null;
		return rv;
	}
}

/*Object.prototype.runEvent = function(eventname, arg1, arg2, arg3){
	if(this[eventname]) this[eventname](arg1, arg2, arg3);
}*/

Array.prototype.remove = function(obj){
	for(var i=0;i<this.length;i++){
		if(this[i] != obj) continue;

		for(var j=i;j<this.length;j++)
			this[j] = this[j+1];
		this.length--;
		i--;
	}
}

Array.prototype.removeIndex = function(i){
	for(var j=i;j<this.length;j++)
		this[j] = this[j+1];
	this.length--;
}

Array.prototype.insertIndex = function(obj, i){
	for(var j=this.length;j>=i;j--)
		this[j] = this[j-1];
	
	this[i] = obj;
}

Array.prototype.invert = function(){
	var l = this.length-1;
	for(var temp,i=0;i<Math.ceil(0.5*l);i++){
		temp = this[i];
		this[i] = this[l-i]
		this[l-i] = temp;
	}
	
	return this;
}

if(!Array.prototype.push){
	Array.prototype.push = function(item){
		this[this.length] = item;
		return this.length;
	}
}

if(!Array.prototype.pop){
	Array.prototype.pop = function(item){
		var item = this[this.length-1];
		delete this[this.length-1];
		this.length--;
		return item;
	}
}

if(!Array.prototype.shift){
	Array.prototype.shift = function(){
		var item = this[0];
		for(var i=0;i<this.length;i++) this[i] = this[i+1];
		this.length--;
		return item;
	}
}

if(!Array.prototype.join){
	Array.prototype.join = function(connect){
		for (var str = "", i=0;i<this.length;i++)
			str += this[i] + (i < this.length-1 ? connect : "");
		return str;
	}
}

Math.hexlist = "0123456789ABCDEF";
Math.decToHex = function(value){
	var hex = this.floor(value/16);
	hex = (hex >15 ? this.decToHex(hex) : this.hexlist.charAt(hex));

	return hex + "" + this.hexlist.charAt(this.floor(value%16));
}
Math.hexToDec = function(value){
	if(!/(.)(.)/.exec(value.toUpperCase())) return false;
	return this.hexlist.indexOf(RegExp.$1) * 16 + this.hexlist.indexOf(RegExp.$2);
}

String.prototype.uCaseFirst = function (str){return this.substr(0,1).toUpperCase() + this.substr(1)};
String.prototype.trim = function (){return this.replace(/\s*$/, "").replace(/^\s*/, "");}
String.prototype.repeat = function (times){for(var out="",i=0;i<times;i++) out += this;return out;}
String.prototype.count = function(str){return this.split(str).length-1;}
String.prototype.pad = function(l, s, t){
	return s || (s = " "), (l -= this.length) > 0 ? (s = new Array(Math.ceil(l / s.length)
		+ 1).join(s)).substr(0, t = !t ? l : t == 1 ? 0 : Math.ceil(l / 2))
		+ this + s.substr(0, l - t) : this;
};
PAD_LEFT = 0;
PAD_RIGHT = 1;
PAD_BOTH = 2;

function trim(str){return str.replace(/^\s*(.*)\s*$/, "$1");}
function repeat(str, times){for(var out="",i=0;i<times;i++) out += str;return out;}
function formatXML(output){
	output = trim(output);

	var lines = output.split("\n");
	for(var i=0;i<lines.length;i++) lines[i] = trim(lines[i]);
	lines = lines.join("\n").replace(/\>\r\n/g, ">").replace(/\>/g, ">\n").replace(/\n\</g, "<").replace(/\</g, "\n<").split("\n");
	lines.remove(0);//test if this is actually always fine
	lines.remove(lines.length);
	
	for(var depth=0,i=0;i<lines.length;i++)
		lines[i] = repeat("\t", (lines[i].match(/^\s*\<\//) ? --depth :  (lines[i].match(/^\s*\<[^\?][^>]+[^\/]\>/) ? depth++ : depth))) + lines[i];

	return lines.join("\n");
}

function formatJS(x){
	var d=0;
	return x.replace(/;+/g,';').replace(/;}/g,'}').replace(/{;/g,'{').replace(/({)|(})|(;)/g,function(m,a,b,c){
		if(a)d++;if(b)d--;
		var o='';for(var i=0;i<d;i++)o+='\t\t';
		if(a)return '{\n'+o; if(b)return '\n'+o+'}';if(c)return ';\n'+o;
	}).replace(/\>/g,'&gt;').replace(/\</g,'&lt;');
}

function pasteWindow(str){
	var win = window.open("about:blank");	
	win.document.write(str);
}

function htmlentities(str){
	return str.replace(/</g, "&lt;");
}

function html_entity_decode(str){
	return str.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&nbsp;/g, " ");
}

function htmlentitiesdecode(str){
	str = str.replace(/\&\#38;/g, "&");
	return str;
}

;;;;;;;;;function runIE(){
	
/********* XML Compatibility ************************************************
	Extensions to the XMLDatabase
****************************************************************************/

var hasIE7Security = hasIESecurity = false;
if(IS_IE7) try{new XLMHttpRequest()}catch(e){hasIE7Security=true}
try{new ActiveXObject("microsoft.XMLHTTP")}catch(e){hasIESecurity=true}

function fixIESecurity(){
	__CONTENT_IFRAME
}
if(hasIESecurity) importClass(fixIESecurity, true, self);

Kernel.getObject = hasIESecurity ? 
function(type, message, no_error, isDataIsland){
	if(type == "HTTP"){
		if(Kernel.availHTTP.length) return Kernel.availHTTP.pop();
		
		return new XMLHttpRequest();
	}
	else if(type == "XMLDOM"){
		xmlParser = getDOMParser(message, no_error);
		return xmlParser;
	}
} :
function(type, message, no_error, isDataIsland){
	if(type == "HTTP"){
		if(Kernel.availHTTP.length) return Kernel.availHTTP.pop();

		//if(IS_IE7 && !hasIE7Security) return new XMLHttpRequest();
		return new ActiveXObject("microsoft.XMLHTTP");
	}
	else if(type == "XMLDOM"){
		xmlParser = new ActiveXObject("microsoft.XMLDOM");
		
		xmlParser.setProperty("SelectionLanguage", "XPath");
		//xmlParser.setProperty("SelectionNamespaces", "xmlns:j='http://www.javeline.nl/j'");
		
		//if(!isDataIsland) xmlParser.preserveWhiteSpace = true;
		if(message){
			if(IS_IE50) message = message.replace(/\] \]/g, "] ]").replace(/^<\?[^>]*\?>/, "");//replace xml definition <?xml .* ?> for IE5.0 
			
			xmlParser.loadXML(message);
		}
		if(!no_error) this.xmlParseError(xmlParser);
		
		return xmlParser;
	}
};

Kernel.xmlParseError = function(xml){
	var xmlParseError = xml.parseError;
	if(xmlParseError != 0){
		/*
			http://msdn.microsoft.com/library/en-us/xmlsdk30/htm/xmobjpmexmldomparseerror.asp?frame=true
		
			errorCode 	Contains the error code of the last parse error. Read-only. 
			filepos 		Contains the absolute file position where the error occurred. Read-only. 
			line 			Specifies the line number that contains the error. Read-only. 
			linepos 		Contains the character position within the line where the error occurred. Read-only. 
			reason 		Explains the reason for the error. Read-only. 
			srcText 		Returns the full text of the line containing the error. Read-only. 
			url 			Contains the URL of the XML document containing the last error. Read-only. 
		*/
		
		throw new Error(1050, Kernel.formErrorString(1050, null, "XML Parse error on line " +  xmlParseError.line, xmlParseError.reason + "Source Text:\n" + xmlParseError.srcText.replace(/\t/gi, " ")));
	}
	
	return xml;
}

function extendXmlDb(){

}

Init.addConditional(extendXmlDb, self, '_XMLDatabase');
if(!hasIESecurity) Init.run('XMLDatabase');



	
}

function runSafari(){
	setTimeoutSafari = setTimeout;
lookupSafariCall = [];
setTimeout = function(call, time){
	if(typeof call == "string") return setTimeoutSafari(call, time);
	return setTimeoutSafari("lookupSafariCall[" + (lookupSafariCall.push(call)-1) + "]()", time);
}

if(IS_SAFARI_OLD){
	HTMLHtmlElement = document.createElement("html").constructor;
	Node = HTMLElement = {};
	HTMLElement.prototype = HTMLHtmlElement.__proto__.__proto__;
	HTMLDocument = Document = document.constructor;
	var x = new DOMParser();
	XMLDocument = x.constructor;
	Element = x.parseFromString("<Single />", "text/xml").documentElement.constructor;
	x = null;
}

/****************************************************************************
	XML Serialization
****************************************************************************/

//XMLDocument.xml
Document.prototype.serialize = 
Node.prototype.serialize = 
XMLDocument.prototype.serialize = function(){
	return (new XMLSerializer()).serializeToString(this);
}
//Node.xml
/*Node.prototype.serialize = function(){
	return (new XMLSerializer()).serializeToString(this);
}*/
//Node.xml


if(IS_SAFARI_OLD || IS_SAFARI){
	//XMLDocument.selectNodes
	HTMLDocument.prototype.selectNodes = 
	XMLDocument.prototype.selectNodes = function(sExpr, contextNode){
		return XPath.selectNodes(sExpr, contextNode || this);
	}
	
	//Element.selectNodes
	Element.prototype.selectNodes = function(sExpr, contextNode){
		return XPath.selectNodes(sExpr, contextNode || this);
	};
	
	//XMLDocument.selectSingleNode
	HTMLDocument.prototype.selectSingleNode = 
	XMLDocument.prototype.selectSingleNode = function(sExpr, contextNode){
		return XPath.selectNodes(sExpr, contextNode || this)[0];
	}
	
	//Element.selectSingleNode
	Element.prototype.selectSingleNode = function(sExpr, contextNode){
		return XPath.selectNodes(sExpr, contextNode || this)[0];
	};
	
	importClass(runXpath, true, self);
	importClass(runXslt, true, self);
}
/*else{
	//XMLDocument.selectNodes
	HTMLDocument.prototype.selectNodes = 
	XMLDocument.prototype.selectNodes = function(sExpr, contextNode){
		var oResult = this.evaluate(sExpr, (contextNode?contextNode:this), this.createNSResolver(this.documentElement), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
		var nodeList = new Array(oResult.snapshotLength);
		nodeList.expr = sExpr;
		for(i=0;i<nodeList.length;i++) nodeList[i] = oResult.snapshotItem(i);
		return nodeList;
	
	}
	
	//Element.selectNodes
	Element.prototype.selectNodes = function(sExpr){
		var doc = this.ownerDocument;
		if(doc.selectNodes)
			return doc.selectNodes(sExpr, this);
		else
			throw new Error(1047, Kernel.formErrorString(1047, null, "xPath selection", "Method selectNodes is only supported by XML Nodes"));
	};
	
	//XMLDocument.selectSingleNode
	HTMLDocument.prototype.selectSingleNode = 
	XMLDocument.prototype.selectSingleNode = function(sExpr, contextNode){
		var nodeList = this.selectNodes(sExpr + "[1]", contextNode?contextNode:null);
		return nodeList.length > 0 ? nodeList[0] : null;
	}
	
	//Element.selectSingleNode
	Element.prototype.selectSingleNode = function(sExpr){
		var doc = this.ownerDocument;
		if(doc.selectSingleNode)
			return doc.selectSingleNode(sExpr, this);
		else
			throw new Error(1048, Kernel.formErrorString(1048, null, "XPath Selection", "Method selectSingleNode is only supported by XML Nodes. \nInfo : " + e));
	};
}*/



	importClass(runNonIe, true, self);
}

function runGecko(){
	importClass(runNonIe, true, self);
	
DocumentFragment.prototype.getElementById = function(id){
	return this.childNodes.length ? this.childNodes[0].ownerDocument.getElementById(id) : null;
}

/****************************************************************************
	XML Serialization
****************************************************************************/

//XMLDocument.xml
XMLDocument.prototype.__defineGetter__("xml", function(){
	return (new XMLSerializer()).serializeToString(this);
});
XMLDocument.prototype.__defineSetter__("xml", function(){
	throw new Error(1042, Kernel.formErrorString(1042, null, "XML serializer", "Invalid assignment on read-only property 'xml'."));
});

//Node.xml
Node.prototype.__defineGetter__("xml", function(){
	if(this.nodeType == 3 || this.nodeType == 4 || this.nodeType == 2) return this.nodeValue;
	return (new XMLSerializer()).serializeToString(this);
});

//Node.xml
Element.prototype.__defineGetter__("xml", function(){
	return (new XMLSerializer()).serializeToString(this);
});

/****************************************************************************
	XSLT
****************************************************************************/


//XMLDocument.selectNodes
HTMLDocument.prototype.selectNodes = 
XMLDocument.prototype.selectNodes = function(sExpr, contextNode){
	var oResult = this.evaluate(sExpr, (contextNode?contextNode:this), this.createNSResolver(this.documentElement), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var nodeList = new Array(oResult.snapshotLength);
	nodeList.expr = sExpr;
	for(i=0;i<nodeList.length;i++) nodeList[i] = oResult.snapshotItem(i);
	return nodeList;
}

//Element.selectNodes
Element.prototype.selectNodes = function(sExpr){
	var doc = this.ownerDocument;
	if(doc.selectNodes)
		return doc.selectNodes(sExpr, this);
	else
		throw new Error(1047, Kernel.formErrorString(1047, null, "xPath selection", "Method selectNodes is only supported by XML Nodes"));
};

//XMLDocument.selectSingleNode
HTMLDocument.prototype.selectSingleNode = 
XMLDocument.prototype.selectSingleNode = function(sExpr, contextNode){
	var nodeList = this.selectNodes(sExpr + "[1]", contextNode?contextNode:null);
	return nodeList.length > 0 ? nodeList[0] : null;
}

//Element.selectSingleNode
Element.prototype.selectSingleNode = function(sExpr){
	var doc = this.ownerDocument;
	if(doc.selectSingleNode)
		return doc.selectSingleNode(sExpr, this);
	else
		throw new Error(1048, Kernel.formErrorString(1048, null, "XPath Selection", "Method selectSingleNode is only supported by XML Nodes. \nInfo : " + e));
};


/********* Error Compatibility **********************************************
	Error Object like IE
****************************************************************************/

function Error(nr, msg){
	if(!USE_DEBUGGER) __ErrorHandler(msg, "", 0);
	
	this.message = msg;
	this.nr = nr;
}

/********* XML Compatibility ************************************************
	Extensions to the XMLDatabase
****************************************************************************/

}

function runOpera(){
	setTimeoutOpera = setTimeout;
lookupOperaCall = [];
setTimeout = function(call, time){
	if(typeof call == "string") return setTimeoutOpera(call, time);
	return setTimeoutOpera("lookupOperaCall[" + (lookupOperaCall.push(call)-1) + "]()", time);
}

//HTMLHtmlElement = document.createElement("html").constructor;
//HTMLElement = {};
//HTMLElement.prototype = HTMLHtmlElement.__proto__.__proto__;
//HTMLDocument = Document = document.constructor;
var x = new DOMParser();
XMLDocument = DOMParser.constructor;
//Element = x.parseFromString("<Single />", "text/xml").documentElement.constructor;
x = null;

/****************************************************************************
	XML Serialization
****************************************************************************/

//XMLDocument.xml

//Node.xml
/*Node.prototype.serialize = function(){
	return (new XMLSerializer()).serializeToString(this);
}*/
//Node.xml

Node.prototype.serialize = 
XMLDocument.prototype.serialize = 
Element.prototype.serialize = function(){
	return (new XMLSerializer()).serializeToString(this);
}


//XMLDocument.selectNodes
Document.prototype.selectNodes = 
XMLDocument.prototype.selectNodes = 
HTMLDocument.prototype.selectNodes = function(sExpr, contextNode){
	var oResult = this.evaluate(sExpr, (contextNode?contextNode:this), this.createNSResolver(this.documentElement), XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
	var nodeList = new Array(oResult.snapshotLength);
	nodeList.expr = sExpr;
	for(i=0;i<nodeList.length;i++) nodeList[i] = oResult.snapshotItem(i);
	return nodeList;
}

//Element.selectNodes
Element.prototype.selectNodes = function(sExpr){
	var doc = this.ownerDocument;
	if(!doc.selectSingleNode){
		doc.selectSingleNode = HTMLDocument.prototype.selectSingleNode;
		doc.selectNodes = HTMLDocument.prototype.selectNodes;
	}
	
	if(doc.selectNodes)
		return doc.selectNodes(sExpr, this);
	else
		throw new Error(1047, Kernel.formErrorString(1047, null, "XPath Selection", "Method selectNodes is only supported by XML Nodes"));
};

//XMLDocument.selectSingleNode
Document.prototype.selectSingleNode = 
XMLDocument.prototype.selectSingleNode = 
HTMLDocument.prototype.selectSingleNode = function(sExpr, contextNode){
	var nodeList = this.selectNodes(sExpr + "[1]", contextNode?contextNode:null);
	return nodeList.length > 0 ? nodeList[0] : null;
}

//Element.selectSingleNode
Element.prototype.selectSingleNode = function(sExpr){
	var doc = this.ownerDocument;
	if(!doc.selectSingleNode){
		doc.selectSingleNode = HTMLDocument.prototype.selectSingleNode;
		doc.selectNodes = HTMLDocument.prototype.selectNodes;
	}
	
	if(doc.selectSingleNode)
		return doc.selectSingleNode(sExpr, this);
	else
		throw new Error(1048, Kernel.formErrorString(1048, null, "XPath Selection", "Method selectSingleNode is only supported by XML Nodes. \nInfo : " + e));
};




	importClass(runNonIe, true, self);
}

function runNonIe(){
	

/********* HTML Interfaces **************************************************
	insertAdjacentHTML(), insertAdjacentText() and insertAdjacentElement()
****************************************************************************/
if(typeof HTMLElement!="undefined"){
	if(!HTMLElement.prototype.insertAdjacentElement){
		HTMLElement.prototype.insertAdjacentElement = function(where,parsedNode){
			switch(where.toLowerCase()){
				case "beforebegin":
					this.parentNode.insertBefore(parsedNode,this);
					break;
				case "afterbegin":
					this.insertBefore(parsedNode,this.firstChild);
					break;
				case "beforeend":
					this.appendChild(parsedNode);
					break;
				case "afterend":
					if (this.nextSibling) this.parentNode.insertBefore(parsedNode,this.nextSibling);
					else this.parentNode.appendChild(parsedNode);
					break;
			}
		};
	}

	if(!HTMLElement.prototype.insertAdjacentHTML){
		HTMLElement.prototype.insertAdjacentHTML = function(where,htmlStr){
			var r = this.ownerDocument.createRange();
			r.setStartBefore(IS_SAFARI ? document.body : this);
			var parsedHTML = r.createContextualFragment(htmlStr);
			this.insertAdjacentElement(where,parsedHTML);
		}
	}

	if(!HTMLElement.prototype.insertAdjacentText){
		HTMLElement.prototype.insertAdjacentText = function(where,txtStr){
			var parsedText = document.createTextNode(txtStr);
			this.insertAdjacentElement(where,parsedText);
		}
	}
	
	//HTMLElement.removeNode
	HTMLElement.prototype.removeNode = function(){
		if(!this.parentNode) return;
		this.parentNode.removeChild(this);
	}
	
	//Currently only supported by Gecko
	if(HTMLElement.prototype.__defineSetter__){
		//HTMLElement.innerText
		HTMLElement.prototype.__defineSetter__("innerText", function(sText){
			var s = "" + sText;
			this.innerHTML = s.replace(/\&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
		});
	
		HTMLElement.prototype.__defineGetter__("innerText", function(){
			return this.innerHTML.replace(/<[^>]+>/g,"").replace(/\s\s+/g, " ").replace(/^\s*|\s*$/g, " ")
		});
		
		HTMLElement.prototype.__defineGetter__("outerHTML", function(){
			return (new XMLSerializer()).serializeToString(this);
		});
	}
}

/********* XML Compatibility ************************************************
	Giving the Mozilla XML Parser the same interface as IE's Parser
****************************************************************************/
var IEPREFIX4XSLPARAM = "";
var ASYNCNOTSUPPORTED = false;

//Test if Async is supported
try{
	XMLDocument.prototype.async = true;
	ASYNCNOTSUPPORTED = true;
}catch(e){/*trap*/} 

Document.prototype.onreadystatechange = null;
Document.prototype.parseError = 0;

Array.prototype.item = function(i){return this[i];};
Array.prototype.expr = "";

XMLDocument.prototype.readyState = 0;

XMLDocument.prototype.__clearDOM = function(){
	while(this.hasChildNodes())
		this.removeChild(this.firstChild);
}

XMLDocument.prototype.__copyDOM = function(oDoc){
	this.__clearDOM();
	
	if(oDoc.nodeType == 9 || oDoc.nodeType == 11){
	   var oNodes = oDoc.childNodes;

	   for(i=0;i<oNodes.length;i++)
			this.appendChild(this.importNode(oNodes[i], true));
	}
	else if(oDoc.nodeType == 1)
   	this.appendChild(this.importNode(oDoc, true));
}

//XMLDocument.loadXML();
XMLDocument.prototype.loadXML = function(strXML){
	XMLDatabase.setReadyState(this, 1);
	var sOldXML = this.xml || this.serialize();
	var oDoc = (new DOMParser()).parseFromString(strXML, "text/xml");
	XMLDatabase.setReadyState(this, 2);
	this.__copyDOM(oDoc);
	XMLDatabase.setReadyState(this, 3);
	XMLDatabase.loadHandler(this);
	return sOldXML;
};

Node.prototype.getElementById = function(id){}

HTMLElement.prototype.replaceNode = 
Element.prototype.replaceNode = function(xmlNode){
	if(!this.parentNode) return;
	this.parentNode.insertBefore(xmlNode, this);
	this.parentNode.removeChild(this);
}

//XMLDocument.load
XMLDocument.prototype.__load = XMLDocument.prototype.load;
XMLDocument.prototype.load = function(sURI){
	var oDoc = document.implementation.createDocument("", "", null);
	oDoc.__copyDOM(this);
	this.parseError = 0;
	XMLDatabase.setReadyState(this, 1);

	try{
		if(this.async == false && ASYNCNOTSUPPORTED){
			var tmp = new XMLHttpRequest();
			tmp.open("GET", sURI, false);
			tmp.overrideMimeType("text/xml");
			tmp.send(null);
			XMLDatabase.setReadyState(this, 2);
			this.__copyDOM(tmp.responseXML);
			XMLDatabase.setReadyState(this, 3);
		}
		else this.__load(sURI);
	}
	catch(objException){this.parseError = -1;}
	finally{XMLDatabase.loadHandler(this);}

	return oDoc;
}




//XMLDocument.setProperty
HTMLDocument.prototype.setProperty = 
XMLDocument.prototype.setProperty = function(x,y){};

/********* XML Compatibility ************************************************
	Extensions to the XMLDatabase
****************************************************************************/
Kernel.getObject = function(type, message, no_error){
	if(type == "HTTP"){
		if(Kernel.availHTTP.length) return Kernel.availHTTP.pop();
		return new XMLHttpRequest();
	}
	else if(type == "XMLDOM"){
		xmlParser = new DOMParser();
		if(message) xmlParser = xmlParser.parseFromString(message, "text/xml");
		if(!no_error) this.xmlParseError(xmlParser);
		return xmlParser;
	}
}

Kernel.xmlParseError = function(xml){
	if(xml.documentElement.tagName == "parsererror"){
		var str = xml.documentElement.firstChild.nodeValue.split("\n");
		var linenr = str[2].match(/\w+ (\d+)/)[1];
		var message = str[0].replace(/\w+ \w+ \w+: (.*)/, "$1");
		
		var srcText = xml.documentElement.lastChild.firstChild.nodeValue.split("\n")[0];
		throw new Error(1050, Kernel.formErrorString(1050, null, "XML Parse Error on line " +  linenr, message + "\nSource Text : " + srcText.replace(/\t/gi, " ")));
	}
	
	return xml;
}


//Fix XML Data-Island Support Problem with Form Tag
Init.add(function(){
	var nodes = document.getElementsByTagName("form");
	for(var i=0;i<nodes.length;i++) nodes[i].removeNode();
	var nodes = document.getElementsByTagName("xml");
	for(var i=0;i<nodes.length;i++) nodes[i].removeNode();
	nodes = null;
});

//IE Like Error Handling
MAXMSG = 3;
ERROR_COUNT = 0;

/*window.onerror = function(message, filename, linenr){
	if(++ERROR_COUNT > MAXMSG) return;
	filename = filename ? filename.match(/\/([^\/]*)$/)[1] : "[Mozilla Library]";
	new Error(0, "---- Javeline Error ----\nProcess : Javascript code in '" + filename +  "'\nLine : " + linenr + "\nMessage : " + message);
	return false;
}*/

if(document.body) document.body.focus = function(){}

/*
//CurIndex = 0;
//CurValue is []
//FoundValue is []
//FoundNode is null
//Loop through childNodes
//if(Child is position absolute/relative and overflow == "hidden" && !inSpace) continue;

//if (Child is position absolute/relative and has zIndex) or overflow == "hidden"
	//if(!is position absolute/relative) zIndex = 0
	//if zIndex >= FoundValue[CurIndex] 
		//if zIndex > CurValue[CurIndex];
			//clear all CurValue values after CurIndex
			//set CurValue[CurIndex] = zIndex
		//CurIndex++
		//if(inSpace && CurIndex >= FoundValue.length)
			//Set FoundNode is currentNode
			//Set FoundValue is CurValue
	//else continue; //Ignore this treedepth
//else if CurValue[CurIndex] continue; //Ignore this treedepth

//loop through childnodes recursively
*/

if(!document.elementFromPoint){
	Document.prototype.elementFromPointRemove = function(el){
		if(!this.RegElements) return;
		this.RegElements.remove(el);
	}
	
	Document.prototype.elementFromPointAdd = function(el){
		if(!this.RegElements) this.RegElements = [];
		this.RegElements.push(el);
	}
	
	Document.prototype.elementFromPointReset = function(RegElements){
		//define globals
		FoundValue = [];
		FoundNode = null;
		LastFoundAbs = document.documentElement;
	}
	
	Document.prototype.elementFromPoint = function(x, y){
		// Optimization, Keeping last found node makes it ignore all lower levels 
		// when there is no possibility of changing positions and zIndexes
		/*if(self.FoundNode){
			var sx = getElementPosX(FoundNode); 
			var sy = getElementPosY(FoundNode);
			var ex = sx + FoundNode.offsetWidth; var ey = sy + FoundNode.offsetHeight;
		}
		if(!self.FoundNode || !(x > sx && x < ex && y > sy && y < ey))*/
			document.elementFromPointReset();
	
		// Optimization only looking at registered nodes
		if(this.RegElements){
			for(var calc_z=-1,calc,i=0;i<this.RegElements.length;i++){
				var n = this.RegElements[i];
				if(getStyle(n, "display") == "none") continue;
	
				var sx = getElementPosX(n); 
				var sy = getElementPosY(n);
				var ex = sx + n.offsetWidth; var ey = sy + n.offsetHeight;
				
				if(x > sx && x < ex && y > sy && y < ey){
					var z = getElementZindex(n);
					if(z > calc_z){ //equal z-indexes not supported
						calc = [n, x, y, sx, sy];
						calc_z = z;
					}
				}
			}
			
			if(calc){
				efpi(calc[0], calc[1], calc[2], 0, FoundValue, calc[3], calc[4]);
				if(!FoundNode){
					FoundNode = calc[0];
					LastFoundAbs = calc[0];
					FoundValue = [calc_z];
				}
			}
		}
		
		if(!this.RegElements || !this.RegElements.length)
			efpi(document.body, x, y, 0, [], getElementPosX(document.body), getElementPosY(document.body));
			
		return FoundNode;
	}
	
	function getStyle(el, prop) {
		return document.defaultView.getComputedStyle(el,'').getPropertyValue(prop);
	}
	
	function efpi(from, x, y, CurIndex, CurValue, px, py){
		var StartValue = CurValue;
		var StartIndex = CurIndex;
		
		//Loop through childNodes
		var nodes = from.childNodes;
		for(var n,i=0;i<from.childNodes.length;i++){
			n = from.childNodes[i];
			if( n.nodeType != Node.TEXT_NODE && getStyle(n, 'display') != 'none' ){
				var sx = px + n.offsetLeft - (IS_GECKO ? n.offsetParent.scrollLeft : 0);//getElementPosX(n); 
				var sy = py + n.offsetTop - (IS_GECKO ? n.offsetParent.scrollTop : 0);//getElementPosY(n);
				var ex = sx + n.offsetWidth; var ey = sy + n.offsetHeight;
				
				//if(Child is position absolute/relative and overflow == "hidden" && !inSpace) continue;
				var isAbs = getStyle(n, "position");
				isAbs = isAbs == "absolute" || isAbs == "relative";
				var isHidden = getStyle(n, "overflow") == "hidden";
				var inSpace = (x > sx && x < ex && y > sy && y < ey);
				if(isAbs && isHidden && !inSpace) continue;
		
				CurIndex = StartIndex;
				CurValue = StartValue.copy();
		
				//if (Child is position absolute/relative and has zIndex) or overflow == "hidden"
				var z = parseInt(getStyle(n, "z-index"));
				if(isAbs && (z || z == 0) || isHidden){
					//if(!is position absolute/relative) zIndex = 0
					if(!isAbs) z = 0;
					
					//if zIndex >= FoundValue[CurIndex] 
					if(z >= (FoundValue[CurIndex] || 0)){
						//if zIndex > CurValue[CurIndex];
						if(z > (CurValue[CurIndex] || 0)){
							//CurValue = StartValue.copy();
							
							//set CurValue[CurIndex] = zIndex
							CurValue[CurIndex] = z;
						}
						
						CurIndex++
						
						//if(inSpace && CurIndex >= FoundValue.length)
						if(inSpace && CurIndex >= FoundValue.length){
							//Set FoundNode is currentNode
							FoundNode = n;
							//Set FoundValue is CurValue
							FoundValue = CurValue;//.copy();
							
							LastFoundAbs = n;
						}
					}
					//else continue; //Ignore this treedepth
					else continue;
				}
				//else if CurValue[CurIndex] continue; //Ignore this treedepth
				//else if(CurValue[CurIndex]) continue;
				else if(inSpace && CurIndex >= FoundValue.length){
					//Set FoundNode is currentNode
					FoundNode = n;
					//Set FoundValue is CurValue
					FoundValue = CurValue;//.copy();
				}
				
				//loop through childnodes recursively
				efpi(n, x, y, CurIndex, CurValue, isAbs ? sx : px, isAbs ? sy : py)
			}
		}
	}
	
	function getElementPosY(myObj){return myObj.offsetTop + parseInt(Kernel.compat.getStyle(myObj, "border-top-width")) + (myObj.offsetParent ? getElementPosY(myObj.offsetParent) : 0)}
	function getElementPosX(myObj){return myObj.offsetLeft + parseInt(Kernel.compat.getStyle(myObj, "border-left-width")) + (myObj.offsetParent ? getElementPosX(myObj.offsetParent) : 0)}
	function getElementZindex(myObj){
		//This is not quite sufficient and should be changed
		var z = 0, n, p = myObj;
		while(p && p.nodeType == 1){
			z = Math.max(z, parseInt(getStyle(p, "z-index")) || -1);
			p = p.parentNode;
		}
		return z;
	}
}

Init.run('XMLDatabase');


}

function runXpath(){
	
/********* IE XPath Object ************************************************
	Workaround for the lack of having an XPath parser on safari
	It works on Safari's document and XMLDocument object.
	
	It doesn't support the full XPath spec, but just enought for
	the skinning engine which needs XPath on the HTML document.
	
	Supports:
	- Compilation of xpath statements
	- Caching of XPath statements
****************************************************************************/
XPath = {
	cache : {},
	
	getChildNode : function(htmlNode, tagName, info, count, num, sResult){
		var numfound = 0, result = null, data = info[count];

		var nodes = htmlNode.childNodes;
		if(!nodes) return; //Weird bug in Safari
		for(var i=0;i<nodes.length;i++){
			if(tagName && (nodes[i].style ? nodes[i].tagName.toLowerCase() : nodes[i].tagName) != tagName) continue;// || numsearch && ++numfound != numsearch

			if(data) data[0](nodes[i], data[1], info, count+1, numfound++ , sResult);
			else sResult.push(nodes[i]);
		}
		
		//commented out :  && (!numsearch || numsearch == numfound)
	},
	
	doQuery : function(htmlNode, qData, info, count, num, sResult){
		var result = null, data = info[count];
		var query = qData[0];
		var returnResult = qData[1];
		try{var qResult = eval(query);}catch(e){return;}
		
		if(returnResult) return sResult.push(qResult);
		if(!qResult) return;
		
		if(data) data[0](htmlNode, data[1], info, count+1, 0, sResult);
		else sResult.push(htmlNode);
	},
	
	getTextNode : function(htmlNode, empty, info, count, num, sResult){
		var result = null, data = info[count];

		var nodes = htmlNode.childNodes;
		for(var i=0;i<nodes.length;i++){
			if(nodes[i].nodeType != 3 && nodes[i].nodeType != 4) continue;
			
			if(data) data[0](nodes[i], data[1], info, count+1, i, sResult);
			else sResult.push(nodes[i]);
		}
	},
	
	getAnyNode : function(htmlNode, empty, info, count, num, sResult){
		var result = null, data = info[count];

		var sel = [], nodes = htmlNode.childNodes;
		for(var i=0;i<nodes.length;i++){
			if(data) data[0](nodes[i], data[1], info, count+1, i, sResult);
			else sResult.push(nodes[i]);
		}
	},
	
	getAttributeNode : function(htmlNode, attrName, info, count, num, sResult){
		if(!htmlNode || htmlNode.nodeType != 1) return;
		
		var result = null, data = info[count];
		var value = htmlNode.getAttributeNode(attrName);//htmlNode.attributes[attrName];//

		if(data) data[0](value, data[1], info, count+1, 0, sResult);
		else if(value) sResult.push(value);
	},
	
	getAllNodes : function(htmlNode, x, info, count, num, sResult){
		var result = null, data = info[count];
		var tagName = x[0];
		var inclSelf = x[1];
		var prefix = x[2];

		if(inclSelf && (htmlNode.tagName == tagName || tagName == "*")){
			if(data) data[0](htmlNode, data[1], info, count+1, 0, sResult);
			else sResult.push(htmlNode);
		}

		var nodes = $(tagName, htmlNode, tagName==prefix?"":prefix);//htmlNode.getElementsByTagName(tagName);
		for(var i=0;i<nodes.length;i++){
			if(data) data[0](nodes[i], data[1], info, count+1, i, sResult);
			else sResult.push(nodes[i]);
		}
	},
	
	getAllAncestorNodes : function(htmlNode, x, info, count, num, sResult){
		var result = null, data = info[count];
		var tagName = x[0];
		var inclSelf = x[1];
		var prefix = x[2];
		
		var i = 0, s = inclSelf ? htmlNode : htmlNode.parentNode;
		while(s && s.nodeType == 1){
			if(s.tagName == tagName || tagName == "*" || tagName == "node()"){
				if(data) data[0](s, data[1], info, count+1, ++i, sResult);
				else sResult.push(s);
			}
			s = s.parentNode
		}
	},
	
	getParentNode : function(htmlNode, empty, info, count, num, sResult){
		var result = null, data = info[count];
		var node = htmlNode.parentNode;
		
		if(data) data[0](node, data[1], info, count+1, 0, sResult);
		else if(node) sResult.push(node);
	},
	
	//precsiblg[3] might not be conform spec
	getPrecedingSibling : function(htmlNode, tagName, info, count, num, sResult){
		var result = null, data = info[count];
		
		var node = htmlNode.previousSibling;
		while(node){
			if(tagName != "node()" && (node.style ? node.tagName.toLowerCase() : node.tagName) != tagName){
				node = node.previousSibling;
				continue;
			}
			
			if(data) data[0](node, data[1], info, count+1, 0, sResult);
			else if(node){
				sResult.push(node);
				break;
			}
		}
	},
	
	//flwsiblg[3] might not be conform spec
	getFollowingSibling : function(htmlNode, tagName, info, count, num, sResult){
		var result = null, data = info[count];
		
		var node = htmlNode.nextSibling;
		while(node){
			if(tagName != "node()" && (node.style ? node.tagName.toLowerCase() : node.tagName) != tagName){
				node = node.nextSibling;
				continue;
			}
			
			if(data) data[0](node, data[1], info, count+1, 0, sResult);
			else if(node){
				sResult.push(node);
				break;
			}
		}
	},
	
	multiXpaths : function(contextNode, list, info, count, num, sResult){
		for(var i=0;i<list.length;i++){
			var info = list[i][0];
			var rootNode = (info[3] ? contextNode.ownerDocument.documentElement : contextNode);//document.body
			info[0](rootNode, info[1], list[i], 1, 0, sResult);
		}
		
		sResult.makeUnique();
	},
	
	compile : function(sExpr){
		sExpr = sExpr.replace(/\[(\d+)\]/g, "/##$1");
		sExpr = sExpr.replace(/\|\|(\d+)\|\|\d+/g, "##$1");
		sExpr = sExpr.replace(/\.\|\|\d+/g, ".");
		sExpr = sExpr.replace(/\[([^\]]*)\]/g, function(match, m1){
			return "/##" + m1.replace(/\|/g, "_@_");
		}); //wrong assumption think of |

		if(sExpr == "/" || sExpr == ".") return sExpr;
		
		//Mark // elements
		//sExpr = sExpr.replace(/\/\//g, "/[]/self::");
		sExpr = sExpr.replace(/\/\//g, "descendant::");
		
		//Check if this is an absolute query
		return this.processXpath(sExpr);
	},
	
	processXpath : function(sExpr){
		var results = new Array();
		sExpr = sExpr.replace(/('[^']*)\|([^']*')/g, "$1_@_$2");
		sExpr = sExpr.split("\|");
		for(var i=0;i<sExpr.length;i++)
			sExpr[i] = sExpr[i].replace(/_\@\_/g, "|");//replace(/('[^']*)\_\@\_([^']*')/g, "$1|$2");
		
		if(sExpr.length == 1) sExpr = sExpr[0];
		else{
			for(var i=0;i<sExpr.length;i++) sExpr[i] = this.processXpath(sExpr[i]);
			results.push([this.multiXpaths, sExpr]);
			return results;
		}
		
		var isAbsolute = sExpr.match(/^\/[^\/]/);
		var sections = sExpr.split("/");
		for(var i=0;i<sections.length;i++){
			if(sections[i] == "." || sections[i] == "") continue;
			else if(sections[i].match(/^[\w-_\.]+(?:\:[\w-_\.]+){0,1}$/)) results.push([this.getChildNode, sections[i]]);//.toUpperCase()
			else if(sections[i].match(/^\#\#(\d+)$/)) results.push([this.doQuery, ["num+1 == " + parseInt(RegExp.$1)]]);
			else if(sections[i].match(/^\#\#(.*)$/)){
				
				//FIX THIS CODE
				var query = RegExp.$1;
				var m = [query.match(/\(/g), query.match(/\)/g)];
				if(m[0] || m[1]){
					while(!m[0] && m[1] || m[0] && !m[1] || m[0].length != m[1].length){
						if(!sections[++i]) break;
						query += "/" + sections[i];
						m = [query.match(/\(/g), query.match(/\)/g)];
					}
				}
				
				results.push([this.doQuery, [this.compileQuery(query)]]);
			}
			else if(sections[i] == "*") results.push([this.getChildNode, null]); //FIX - put in def function
			else if(sections[i].substr(0,2) == "[]") results.push([this.getAllNodes, ["*", false]]);//sections[i].substr(2) || 
			else if(sections[i].match(/descendant-or-self::node\(\)$/)) results.push([this.getAllNodes, ["*", true]]);
			else if(sections[i].match(/descendant-or-self::([^\:]*)(?:\:(.*)){0,1}$/)) results.push([this.getAllNodes, [RegExp.$2 || RegExp.$1, true, RegExp.$1]]);
			else if(sections[i].match(/descendant::([^\:]*)(?:\:(.*)){0,1}$/)) results.push([this.getAllNodes, [RegExp.$2 || RegExp.$1, false, RegExp.$1]]);
			else if(sections[i].match(/ancestor-or-self::([^\:]*)(?:\:(.*)){0,1}$/)) results.push([this.getAllAncestorNodes, [RegExp.$2 || RegExp.$1, true, RegExp.$1]]);
			else if(sections[i].match(/ancestor::([^\:]*)(?:\:(.*)){0,1}$/)) results.push([this.getAllAncestorNodes, [RegExp.$2 || RegExp.$1, false, RegExp.$1]]);
			else if(sections[i].match(/^\@(.*)$/)) results.push([this.getAttributeNode, RegExp.$1]);
			else if(sections[i] == "text()") results.push([this.getTextNode, null]);
			else if(sections[i] == "node()") results.push([this.getAnyNode, null]);//FIX - put in def function
			else if(sections[i] == "..") results.push([this.getParentNode, null]);
			else if(sections[i].match(/following-sibling::(.*)$/)) results.push([this.getFollowingSibling, RegExp.$1.toLowerCase()]);
			else if(sections[i].match(/preceding-sibling::(.*)$/)) results.push([this.getPrecedingSibling, RegExp.$1.toLowerCase()]);
			else if(sections[i].match(/self::(.*)$/)) results.push([this.doQuery, ["XPath.doXpathFunc('local-name', htmlNode) == '" + RegExp.$1 + "'"]]);
			else{
				var query = sections[i];
			
				//FIX THIS CODE
				//add some checking here
				var m = [query.match(/\(/g), query.match(/\)/g)];
				if(m[0] || m[1]){
					while(!m[0] && m[1] || m[0] && !m[1] || m[0].length != m[1].length){
						if(!sections[++i]) break;
						query += "/" + sections[i];
						m = [query.match(/\(/g), query.match(/\)/g)];
					}
				}

				results.push([this.doQuery, [this.compileQuery(query), true]])
			
				//throw new Error(1503, "---- Javeline Error ----\nMessage : Could not match XPath statement: '" + sections[i] + "' in '" + sExpr + "'");
			}
		}

		results[0][3] = isAbsolute;
		return results;
	},
	
	compileQuery : function(code){
		var c = new CodeCompilation(code);
		return c.compile();
	},
	
	doXpathFunc : function(type, arg1, arg2, arg3){
		switch(type){
			case "not": return !arg1;
			case "position()": return num == arg1;
			case "format-number": return new String(Math.round(parseFloat(arg1)*100)/100).replace(/(\.\d?\d?)$/, function(m1){return m1.pad(3, "0", PAD_RIGHT)});; //this should actually do something
			case "floor": return Math.floor(arg1);
			case "ceiling": return Math.ceil(arg1);
			case "starts-with": return arg1 ? arg1.substr(0, arg2.length) == arg2 : false;
			case "string-length": return arg1 ? arg1.length : 0;
			case "count": return arg1 ? arg1.length : 0;
			case "last": return arg1 ? arg1[arg1.length-1] : null;
			case "local-name": return arg1 ? arg1.tagName : "";//[TAGNAME]
			case "substring": return arg1 && arg2 ? arg1.substring(arg2, arg3 || 0) : "";
			case "contains": return arg1 && arg2 ? arg1.indexOf(arg2) > -1 : false;
			case "concat": 
				for(var str="",i=1;i<arguments.length;i++){
					if(typeof arguments[i] == "object"){
						str += getNodeValue(arguments[i][0]);
						continue;
					}
					str += arguments[i];
				}
			return str;
		}
	},
	
	selectNodeExtended : function(sExpr, contextNode, match){
		var sResult = this.selectNodes(sExpr, contextNode);

		if(sResult.length == 0) return null;
		if(!match) return sResult[0];
		
		for(var i=0;i<sResult.length;i++){
			if(getNodeValue(sResult[i]) == match) return sResult[i];
		}
		
		return null;
	},
	
	selectNodes : function(sExpr, contextNode){
		if(!this.cache[sExpr]) this.cache[sExpr] = this.compile(sExpr);
		
		//setStatus("Processing custom XPath: " + sExpr + ":" + contextNode.serialize().replace(/</g, "&lt;"));
		
		if(typeof this.cache[sExpr] == "string"){
			if(this.cache[sExpr] == ".") return [contextNode];
			if(this.cache[sExpr] == "/") return [contextNode.nodeType == 9 ? contextNode : contextNode.ownerDocument.documentElement];
		}

		if(typeof this.cache[sExpr] == "string" && this.cache[sExpr] == ".") return [contextNode];
		
		var info = this.cache[sExpr][0];
		var rootNode = (info[3] && !contextNode.nodeType == 9 ? contextNode.ownerDocument.documentElement : contextNode);//document.body
		var sResult = [];

		info[0](rootNode, info[1], this.cache[sExpr], 1, 0, sResult);
		
		return sResult;
	}
}

function getNodeValue(sResult){
	if(sResult.nodeType == 1) return sResult.firstChild ? sResult.firstChild.nodeValue : "";
	if(sResult.nodeType > 1 || sResult.nodeType < 5) return sResult.nodeValue;
	return sResult;
}

function CodeCompilation(code){
	this.data = {
		F : [],
		S : [],
		I : [],
		X : []
	};
	
	this.compile = function(){
		code = code.replace(/ or /g, " || ");
		code = code.replace(/ and /g, " && ");
		code = code.replace(/!=/g, "{}");
		code = code.replace(/=/g, "==");
		code = code.replace(/\{\}/g, "!=");
		
		// Tokenize
		this.tokenize();
		
		// Insert
		this.insert();

		return code;
	}
	
	this.tokenize = function(){
		//Functions
		var data = this.data.F;
		code = code.replace(/(format-number|contains|substring|local-name|last|node|position|round|starts-with|string|string-length|sum|floor|ceiling|concat|count|not)\s*\(/g, function(d, match){return (data.push(match) - 1) + "F_";});

		//Strings
		var data = this.data.S;
		code = code.replace(/'([^']*)'/g, function(d, match){return (data.push(match) - 1) + "S_";});
		code = code.replace(/"([^"]*)"/g, function(d, match){return (data.push(match) - 1) + "S_";});

		//Xpath
		var data = this.data.X;
		code = code.replace(/(^|\W|\_)([\@\.\/A-Za-z][\.\@\/\w]*(?:\(\)){0,1})/g, function(d, m1, m2){return m1 + (data.push(m2) - 1) + "X_";});
		code = code.replace(/(\.[\.\@\/\w]*)/g, function(d, m1, m2){return (data.push(m1) - 1) + "X_";});
		
		//Ints
		var data = this.data.I; 
		code = code.replace(/(\d+)(\W)/g, function(d, m1, m2){return (data.push(m1) - 1) + "I_" + m2;});
	}
	
	this.insert = function(){
		var data = this.data;
		code = code.replace(/(\d+)X_\s*==\s*(\d+S_)/g, function(d, nr, str){
			return "XPath.selectNodeExtended('" +  data.X[nr].replace(/'/g, "\\'") + "', htmlNode, " + str + ")";
		});
		
		code = code.replace(/(\d+)([FISX])_/g, function(d, nr, type){
			var value = data[type][nr];
			
			if(type == "F"){
				return "XPath.doXpathFunc('" + value + "', ";
			}
			else if(type == "S"){
				return "'" + value + "'";	
			}
			else if(type == "I"){
				return value;
			}
			else if(type == "X"){
				return "XPath.selectNodeExtended('" + value.replace(/'/g, "\\'") + "', htmlNode)";
			}
		});
	}
}

self.XPath = XPath;


}

function runXslt(){
	
function XSLTProcessor(){
	this.templates = {};
	this.p = {
		"value-of" : function(context, xslNode, childStack, result){
			var xmlNode = XPath.selectNodes(xslNode.getAttribute("select"), context)[0];// + "[0]"

			if(!xmlNode) value = "";
			else if(xmlNode.nodeType == 1) value = xmlNode.firstChild ? xmlNode.firstChild.nodeValue : "";
			else value = typeof xmlNode == "object" ? xmlNode.nodeValue : xmlNode;
			
			result.appendChild(this.xmlDoc.createTextNode(value));
		},
		
		"copy-of" : function(context, xslNode, childStack, result){
			var xmlNode = XPath.selectNodes(xslNode.getAttribute("select"), context)[0];// + "[0]"
			if(xmlNode) result.appendChild(!IS_IE ? result.ownerDocument.importNode(xmlNode, true) : xmlNode.cloneNode(true));
		},
		
		"if" : function(context, xslNode, childStack, result){
			if(XPath.selectNodes(xslNode.getAttribute("test"), context)[0]){// + "[0]"
				this.parseChildren(context, xslNode, childStack, result);
			}
		},
		
		"for-each" : function(context, xslNode, childStack, result){
			var nodes = XPath.selectNodes(xslNode.getAttribute("select"), context);
			for(var i=0;i<nodes.length;i++){
				this.parseChildren(nodes[i], xslNode, childStack, result);
			}
		},
		
		"choose" : function(context, xslNode, childStack, result){
			var nodes = xslNode.childNodes;
			for(var i=0;i<nodes.length;i++){
				if(!nodes[i].tagName) continue;
				
				if(nodes[i][TAGNAME] == "otherwise" || nodes[i][TAGNAME] == "when" && XPath.selectNodes(nodes[i].getAttribute("test"), context)[0])
					return this.parseChildren(context, nodes[i], childStack[i][2], result);
			}
		},
		
		"output" : function(context, xslNode, childStack, result){
			
		},
		
		"param" : function(context, xslNode, childStack, result){
			
		},
		
		"attribute" : function(context, xslNode, childStack, result){
			var nres = this.xmlDoc.createDocumentFragment();
			this.parseChildren(context, xslNode, childStack, nres);
			
			result.setAttribute(xslNode.getAttribute("name"), nres.xml);
		},
		
		"apply-templates" : function(context, xslNode, childStack, result){
			if(!xslNode){
				var t = this.templates["/"] || this.templates[context.tagName];
				if(t) this.p["apply-templates"].call(this, context, t[0], t[1], result);
			}
			else if(xslNode.getAttribute("select")){
				var t = this.templates[xslNode.getAttribute("select")];
				if(t){
					if(xslNode.getAttribute("select") == "/") return alert("Something went wrong. The / template was executed as a normal template");
					
					var nodes = context.selectNodes(xslNode.getAttribute("select"));
					for(var i=0;i<nodes.length;i++){
						this.parseChildren(nodes[i], t[0], t[1], result);
					}
				}
			}
			//Named templates should be in a different hash
			else if(xslNode.getAttribute("name")){
				var t = this.templates[xslNode.getAttribute("name")];
				if(t) this.parseChildren(context, t[0], t[1], result);
			}
			else{
				//Copy context
				var ncontext = context.cloneNode(true); //importnode here??
				var nres = this.xmlDoc.createDocumentFragment();
				
				var nodes = ncontext.childNodes;
				for(var tName, i=nodes.length-1;i>=0;i--){
					if(nodes[i].nodeType == 3 || nodes[i].nodeType == 4){
						//result.appendChild(this.xmlDoc.createTextNode(nodes[i].nodeValue));
						continue;
					}
					if(!nodes[i].nodeType == 1) continue;
					var n = nodes[i];

					//Loop through all templates
					for(tName in this.templates){
						if(tName == "/") continue;
						var t = this.templates[tName];
						
						var snodes = n.selectNodes("self::" + tName);
						for(var j=snodes.length-1;j>=0;j--){
							var s = snodes[j], p = s.parentNode;
							this.parseChildren(s, t[0], t[1], nres);
							if(nres.childNodes){
								for(var k=nres.childNodes.length-1;k>=0;k--){
									p.insertBefore(nres.childNodes[k], s);
								}
							}
							p.removeChild(s);
						}
					}
					
					if(n.parentNode){
						var p = n.parentNode;
						this.p["apply-templates"].call(this, n, xslNode, childStack, nres);
						if(nres.childNodes){
							for(var k=nres.childNodes.length-1;k>=0;k--){
								p.insertBefore(nres.childNodes[k], n);
							}
						}
						p.removeChild(n);
					}
				}
				
				for(var i=ncontext.childNodes.length-1;i>=0;i--){
					result.insertBefore(ncontext.childNodes[i], result.firstChild);
				}
			}
		},
		
		cache : {},
		"import" : function(context, xslNode, childStack, result){
			var file = xslNode.getAttribute("href");
			if(!this.cache[file]){
				var data = new HTTP().get(file, false, true);
				this.cache[file] = data;
			}
			
			//compile
			//parseChildren
		},
		
		"include" : function(context, xslNode, childStack, result){
			
		},
		
		"when" : function(){},
		"otherwise" : function(){},
		
		"copy-clone" : function(context, xslNode, childStack, result){
			result = result.appendChild(!IS_IE ? result.ownerDocument.importNode(xslNode, false) : xslNode.cloneNode(false));
			if(result.nodeType == 1){
				for(var i=0;i<result.attributes.length;i++){
					var blah = result.attributes[i].nodeValue; //stupid Safari shit

					if(!IS_SAFARI_OLD && result.attributes[i].nodeName.match(/^xmlns/)) continue;
					result.attributes[i].nodeValue = result.attributes[i].nodeValue.replace(/\{([^\}]+)\}/g, function(m, xpath){
						var xmlNode = XPath.selectNodes(xpath, context)[0];
						
						if(!xmlNode) value = "";
						else if(xmlNode.nodeType == 1) value = xmlNode.firstChild ? xmlNode.firstChild.nodeValue : "";
						else value = typeof xmlNode == "object" ? xmlNode.nodeValue : xmlNode;
						
						return value;
					});
					
					result.attributes[i].nodeValue; //stupid Safari shit
				}
			}
			
			this.parseChildren(context, xslNode, childStack, result);
		}
	}
	
	this.parseChildren = function(context, xslNode, childStack, result){
		if(!childStack) return;
		for(var i=0;i<childStack.length;i++){
			childStack[i][0].call(this, context, childStack[i][1], childStack[i][2], result);
		}
	}
	
	this.compile = function(xslNode){
		var nodes = xslNode.childNodes;
		for(var stack=[],i=0;i<nodes.length;i++){
			if(nodes[i].nodeType != 1 && nodes[i].nodeType != 3 && nodes[i].nodeType != 4) continue;
			
			if(nodes[i][TAGNAME] == "template"){
				this.templates[nodes[i].getAttribute("match") || nodes[i].getAttribute("name")] = [nodes[i], this.compile(nodes[i])];
			}
			else if(nodes[i][TAGNAME] == "stylesheet"){
				this.compile(nodes[i])
			}
			else if(nodes[i].prefix == "xsl"){
				var func = this.p[nodes[i][TAGNAME]];
				if(!func) alert("xsl:" + nodes[i][TAGNAME] + " is not supported at this time on this platform");
				else stack.push([func, nodes[i], this.compile(nodes[i])]);
			}
			else{
				stack.push([this.p["copy-clone"], nodes[i], this.compile(nodes[i])]);
			}
		}
		return stack;
	}
	
	this.importStylesheet = function(xslDoc){
		this.xslDoc = xslDoc.nodeType == 9 ? xslDoc.documentElement : xslDoc;
		xslStack = this.compile(xslDoc);

		//var t = this.templates["/"] ? "/" : false;
		//if(!t) for(t in this.templates) if(typeof this.templates[t] == "array") break;
		this.xslStack = [[this.p["apply-templates"], null]];//{getAttribute : function(n){if(n=="name") return t}
	}
	
	//return nodes
	this.transformToFragment = function(doc, newDoc){
		this.xmlDoc = newDoc.nodeType != 9 ? newDoc.ownerDocument : newDoc;//new DOMParser().parseFromString("<xsltresult></xsltresult>", "text/xml");//
		var docfrag = this.xmlDoc.createDocumentFragment();

		if(!IS_SAFARI_OLD && doc.nodeType == 9) doc = doc.documentElement;
		var result = this.parseChildren(doc, this.xslDoc, this.xslStack, docfrag);
		return docfrag;
	}
}

self.XSLTProcessor = XSLTProcessor;


}

if(IS_IE) importClass(runIE, true, self);

if(IS_SAFARI) importClass(runSafari, true, self);

if(IS_OPERA) importClass(runOpera, true, self);

if(IS_GECKO || !IS_IE && !IS_SAFARI && !IS_OPERA) importClass(runGecko, true, self);
;__ALIGNMENT__ = 1<<12;

;__ANCHORING__ = 1<<13;

;__CACHE__ = 1<<2;

;/** 
* @projectDescription 	Javeline Platform
*
* @author	Ruben Daniels ruben@javeline.nl
* @version	1.0
*/

__DATABINDING__ = 1<<1;

;__DEFERREDUPDATE__ = 1<<3;
;__DELAYEDRENDER__ = 1<<11

;__DRAGDROP__ = 1<<5;

;__EDITMODE__ = 1<<15;
__MULTILANG__ = 1<<16;



;__VALIDATION__ = 1<<6;
;__JMLDOM__ = 1<<14;

;__MULTIBINDING__ = 1<<7;

;__MULTISELECT__ = 1<<8;

;__PRESENTATION__ = 1<<9;
;__RENAME__ = 1<<10;
;;
/*
*/;/*
	align="{align:left,edge:splitter,edge-margin:10,splitter-size:3,exec:single}"
	
	align='bottom'
	align-position='0-0';
	align-edge='sizer'
	align-margin='10'
	align-sizer='3'
	width='x'
	height='y'
	min-height='x'
	min-width='y'
	
	align-exec='single'
*/

;;;;;;;;;;;;
function HTTP(){
	this.queue = [null];
	this.callbacks = {};
	this.cache = {};
	this.timeout = 10000; //default 10 seconds
	if(!this.uniqueId) this.uniqueId = Kernel.all.push(this) - 1;
	
	// Register Communication Module
	this.SmartBindingHook = ["http", "variables"]
	Kernel.TelePort.register(this);
	
	if(!this.toString){
		this.toString = function(){
			return "[Javeline TelePort Component : (HTTP)]";
		}
	}
	
	
	this.loadCache = function(name){
			var strResult = this.get(CWD + name + ".txt");
			
		setStatus("[HTTP] Loading HTTP Cache", "steleport");
		
		if(!strResult) return false;

		eval("var data = " + strResult);
		this.cache = data.params;
		
		return true;
	}

	this.getXML = function(url, receive, async, userdata, nocache){
		return this.get(url, receive, async, userdata, nocache, "", true);
	}

	this.getString = function(url, receive, async, userdata, nocache){
		return this.get(url, receive, async, userdata, nocache, "");
	}

	this.get = function(url, receive, async, userdata, nocache, data, useXML, id, autoroute, useXSLT, caching){
		var tpModule = this;
		
		if(IS_OPERA) async = true; //opera doesnt support sync calls
		
		if(IS_SAFARI) url = htmlentitiesdecode(url);
		
		if(isNot(id)){
				var http = Kernel.getObject("HTTP");
			
			id = this.queue.push([http, receive, null, null, userdata, null, [url, async, data, nocache, useXSLT, caching], useXML, 0])-1;
			
		}
		else{
			var http = this.queue[id][0];
				http.abort();
		}

		if(async){
			if(IS_IE50){
				this.queue[id][3] = new Date();
				this.queue[id][2] = function(){
					var dt = new Date(new Date().getTime() - tpModule.queue[id][3].getTime());
					var diff = parseInt(dt.getSeconds()*1000 + dt.getMilliseconds());
					if(diff > tpModule.timeout){
						tpModule.dotimeout(id); 
						return
					};
					
					if(tpModule.queue[id][0].readyState == 4){
						tpModule.queue[id][0].onreadystatechange = function(){};
						tpModule.receive(id);
					}
				};
				this.queue[id][5] = setInterval(function(){tpModule.queue[id][2]()}, 20);
			}
			else{
				http.onreadystatechange = function(){
					if(!tpModule.queue[id] || http.readyState != 4) return;
					tpModule.receive(id);
				}
			}
		}

		if(!autoroute) autoroute = this.shouldAutoroute;
		if(this.autoroute && IS_OPERA) autoroute = true; //Bug in opera
		var srv = autoroute ? this.routeServer : url;

		Kernel.debugMsg("<strong>Making request[" + id + "] to " + url + (autoroute ? "<br /><span style='color:green'>[via: " + srv + (nocache ? (srv.match(/(\.asp|\.aspx|\.ashx)$/) ? "/" : (srv.match(/\?/) ? "&" : "?")) + Math.random() : "") + "]</span>" : "") + "</strong> with data:<br />" + new String(data && data.xml ? data.xml : data).replace(/\&/g, "&amp;").replace(/</g, "&lt;") + "<hr />", "teleport");
		
		setStatus("[HTTP] Making request[" + id + "] url: " + url, "steleport");

		try{
			//if(srv.match(/(\.asp|\.aspx|\.ashx)$/)) nocache = false;
			http.open(this.protocol || "GET", srv + (nocache ? (srv.match(/\?/) ? "&" : "?") + Math.random() : ""), async);
			
			//OPERA ERROR's here... on retry
			http.setRequestHeader("User-Agent", "Javeline TelePort 1.0.0");
			http.setRequestHeader("Content-type", this.contentType || (this.useXML || useXML ? "text/xml" : "text/plain"));
			
			if(autoroute){
				http.setRequestHeader("X-Route-Request", url);
				http.setRequestHeader("X-Proxy-Request", url);
				http.setRequestHeader("X-Compress-Response", "gzip");
			}
		}catch(e){
			var useOtherXH = false;
			
			if(self.XMLHttpRequestUnSafe){
				try{
					http = new XMLHttpRequestUnSafe();
					http.onreadystatechange = function(){
						if(!tpModule.queue[id] || http.readyState != 4) return;
						tpModule.receive(id);
					}
					http.open(this.protocol || "GET", srv + (nocache ? (srv.match(/\?/) ? "&" : "?") + Math.random() : ""), async);
					this.queue[id][0] = http;
					async = true; //force async
					useOtherXH = true;
				}
				catch(e){}
			}
			
			// Retry request by routing it
			if(!useOtherXH && this.autoroute && !autoroute){
				if(!isNot(id)){
					clearInterval(this.queue[id][5]);
					//this.queue[id] = null;
				}
				this.shouldAutoroute = true;
				return this.get(url, receive, async, userdata, nocache, data, useXML, id, true, useXSLT);
			}
			
			if(!useOtherXH){
				//Routing didn't work either... Throwing error
				var noClear = receive ? receive(null, __RPC_ERROR__, {
					userdata : userdata,
					http : http,
					url : url,
					tpModule : this,
					id : id,
					message : "Permission denied accessing remote resource: " + url
				}) : false;
				if(!noClear) this.clearQueueItem(id);
				
				return;
			}
		}

		if(this.__HeaderHook) this.__HeaderHook(http);

			http.send(data);

		if(!async) return this.receive(id);
	}

	this.receive = function(id){
		if(!this.queue[id]) return false;

		clearInterval(this.queue[id][5]);

		var data, message;
		var http = this.queue[id][0];

		// Test if HTTP object is ready
		try{if(http.status){}}catch(e){return setTimeout('Kernel.lookup(' + this.uniqueId + ').receive(' + id + ')', 10);}

		var callback = this.queue[id][1];
		var useXML = this.queue[id][7];
		var userdata = this.queue[id][4];
		var retries = this.queue[id][8];
		
		var a = this.queue[id][6];
		var from_url = a[0];
		var useXSLT = a[4];
		
		Kernel.debugMsg("<strong>Receiving [" + id + "]" + (http.isCaching ? "[<span style='color:orange'>cached</span>]" : "") + " from " + from_url + "<br /></strong>" + http.responseText.replace(/\&/g, "&amp;").replace(/\</g, "&lt;").replace(/\n/g, "<br />") + "<hr />", "teleport");
		
		setStatus("[HTTP] Receiving [" + id + "]" + (http.isCaching ? "[caching]" : "") + " from " + from_url, "steleport");

		try{
			var msg = "";

			// Check HTTP Status
			if(http.status != 200 && http.status != 0){
				if(this.isRPC && this.checkPermissions && this.checkPermissions(message, {id:id, http:http, tpModule:this, retries:retries}) === true) return;
				throw new Error(0, "HTTP error [" + id + "]:" + http.status + "\n" + http.responseText);
			}

			// Check for XML Errors
			if(useXML || this.useXML){
				if(http.responseText.replace(/^[\s\n\r]+|[\s\n\r]+$/g, "") == "") throw new Error("Empty Document");
				
				msg = "Received invalid XML\n\n";
				//var lines = http.responseText.split("\n");
				//if(lines[22] && lines[22].match(/Cafco /)) lines[22] = "";
				//lines.join("\n")
				var xmlDoc = http.responseXML && http.responseXML.documentElement ? Kernel.xmlParseError(http.responseXML) : Kernel.getObject("XMLDOM", http.responseText);
				if(IS_IE) xmlDoc.setProperty("SelectionLanguage", "XPath");
				var xmlNode = xmlDoc.documentElement;
			}

			// Get content
			var data = useXML || this.useXML ? xmlNode : http.responseText;

			// Check RPC specific Error messages
			if(this.isRPC){
				msg = "RPC result did not validate: ";
				message = this.checkErrors(data, http, {id:id, http:http, tpModule:this});
				if(this.checkPermissions && this.checkPermissions(message, {id:id, http:http, tpModule:this, retries:retries}) === true) return;
				data = this.unserialize(message);
			}
			
			//Use XSLT to transform xml node if needed
			if(useXML && useXSLT){
				var xmlNode = data;
				this.getXML(useXSLT, function(data, state, extra){
					if(state != __HTTP_SUCCESS__){
						if(state == __HTTP_TIMEOUT__ && extra.retries < MAX_JAV_RETRIES) return extra.tpModule.retry(extra.id);
						else{
							extra.userdata.message = "Could not load XSLT from external resource :\n\n" + extra.message;
							extra.userdata.callback(data, state, extra.userdata);
						}
					}

					var result = xmlNode.transformNode(data);
					
					var noClear = extra.userdata.callback ? extra.userdata.callback([result, xmlNode], __RPC_SUCCESS__, extra.userdata) : false;
					if(!noClear) extra.tpModule.queue[id] = null;
				}, true, {
					callback : callback,
					userdata : userdata,
					http : http,
					url : from_url,
					tpModule : this,
					id : id,
					retries : retries
				});
				
				return;
			}
		}
		catch(e){
			// Send callback error state
			var noClear = callback ? callback(data, __RPC_ERROR__, {
				userdata : userdata,
				http : http,
				url : from_url,
				tpModule : this,
				id : id,
				message : msg + e.message,
				retries : retries
			}) : false;
			if(!noClear){
				http.abort();
				this.clearQueueItem(id);
			}

			return;
		}
		

		var noClear = callback ? callback(data, __RPC_SUCCESS__, {
			userdata : userdata,
			http : http,
			url : from_url,
			tpModule : this,
			id : id,
			retries : retries
		}) : false;
		if(!noClear) this.clearQueueItem(id);

		return data;
	}

	this.dotimeout = function(id){
		if(!this.queue[id]) return false;

		clearInterval(this.queue[id][5]);
		var http = this.queue[id][0];

		// Test if HTTP object is ready
		try{if(http.status){}}catch(e){return setTimeout('HTTP.dotimeout(' + id + ')', 10);}

		var callback = this.queue[id][1];
		var useXML = this.queue[id][7];
		var userdata = this.queue[id][4];

		http.abort();

		Kernel.debugMsg("<strong>HTTP Timeout [" + id + "]<br /></strong><hr />", "teleport");
		
		setStatus("[HTTP] Timeout [" + id + "]", "steleport");

		var noClear = callback ? callback(null, __RPC_TIMEOUT__, {
			userdata : userdata,
			http : http,
			url : this.queue[id][6][0],
			tpModule : this,
			id : id,
			message : "HTTP Call timed out",
			retries : this.queue[id][8]
		}) : false;
		if(!noClear) this.clearQueueItem(id);
	}
	
	this.clearQueueItem = function(id){
		if(IS_IE50) clearInterval(this.queue[id][5]);
		Kernel.releaseHTTP(this.queue[id][0]);
		this.queue[id] = null;
		delete this.queue[id];
		return true;
	}

	this.retry = function(id){
		if(!this.queue[id]) return false;

		clearInterval(this.queue[id][5]);
		var q = this.queue[id];
		var a = q[6];

		Kernel.debugMsg("<strong>Retrying request...<br /></strong><hr />", "teleport");
		
		setStatus("[HTTP] Retrying request [" + id + "]", "steleport");

		q[8]++;
		this.get(a[0], q[1], a[1], q[4], a[3], a[2], q[7], id, null, null, a[5]);
		
		return true;
	}

	this.cancel = function(id){
		if(id === null) id = this.queue.length-1;
		if(!this.queue[id]) return false;
		
		//this.queue[id][0].abort();
		this.clearQueueItem(id);
	}

	if(!this.load){
		this.load = function(x){
			var receive = x.getAttribute("receive");
			
			for(var i=0;i<x.childNodes.length;i++){
				if(x.childNodes[i].nodeType != 1) continue;
				
				var useXML = x.childNodes[i].getAttribute("type") == "XML";
				var url = x.childNodes[i].getAttribute("url");
				var receive = x.childNodes[i].getAttribute("receive") || receive;
				var async = x.childNodes[i].getAttribute("async") != "false";
				
				this[x.childNodes[i].getAttribute("name")] = function(data, userdata){
					return this.get(url, self[receive], async, userdata, false, data, useXML);
				}
			}
		}
		
		this.instantiate = function(x){
			var url = x.getAttribute("src");
			var useXSLT = x.getAttribute("xslt");
			var async = x.getAttribute("async") != "false";

			this.getURL = function(data, userdata){
				return this.get(url, this.callbacks.getURL, async, userdata, false, data, true, null, null, useXSLT);
			}
			
			var name = "http" + Math.round(Math.random()*100000);
			Kernel.setReference(name, this);
			
			return name + ";getURL";
		}
		
		this.call = function(method, args){
			this[method].call(this, args);
		}
	}
}

//Init.addConditional(function(){Kernel.Comm.register("http", "variables", HTTP);}, null, ['Kernel']);
Init.run('HTTP');
;Init.run('XMLDatabase');;;
function HEADER(){
	this.supportMulticall = false;
	this.protocol = "GET";
	this.vartype = "header";
	this.isXML = true;
	this.namedArguments = true;

	// Register Communication Module
	this.SmartBindingHook = ["rpc", "arguments"];
	Kernel.TelePort.register(this);

	// Stand Alone
	if(!this.uniqueId){
		Kernel.makeClass(this);
		this.inherit(CommBaseClass);
		this.inherit(HTTP);
		this.inherit(RPC);
	}

	this.unserialize = function(str){
		return str;
	}

	// Create message to send
	this.serialize = function(functionName, args){
		for(var hFunc=[],i=0;i<args.length;i++){
	   	if(!args[i][0] || !args[i][1]) continue;

			Kernel.debugMsg("<strong>" + args[i][0] + ":</strong> " + args[i][1] + "<br />", "teleport");

   		http.setRequestHeader(args[i][0], args[i][1]);
	   }
	   
	   this.__HeaderHook = new Function('http', hFunc.join("\n"));

		return "";
	}

	// Check Received Data for errors
	this.checkErrors = function(data, http){
		return data;
	}

	this.__load = function(x){
		if(x.getAttribute("method-name")){
			var mName = x.getAttribute("method-name");
			var nodes = x.childNodes;

			for(var i=0;i<nodes.length;i++){
				var y = nodes[i];
				var v = y.insertBefore(x.ownerDocument.createElement("variable"), y.firstChild);
				v.setAttribute("name", mName);
				v.setAttribute("value", y.getAttribute("name"));
			}
		}
	}
}

;
function JPHP(){
	this.supportMulticall = true;
	this.multicall = false;
	this.mcallname = "multicall";
	this.protocol = "POST";
	this.useXML = true;
	this.namedArguments = false;

	// Register Communication Module
	this.SmartBindingHook = ["rpc", "arguments"]
	Kernel.TelePort.register(this);

	// Stand Alone
	if(!this.uniqueId){
		Kernel.makeClass(this);
		this.inherit(CommBaseClass);
		this.inherit(HTTP);
		this.inherit(RPC);
	}

	// Serialize Objects
	var serialize = {
		host : this,
		
		object : function(ob){
			var ob = ob.valueOf();

			var length = 0, x = "";
			for(prop in ob){
				if(typeof this[prop] != "function"){
					length++;
					//WEIRD FUCKED UP INTERNET EXPLORER BUG
					var r = prop;
					x += this.host.doSerialize(r) + ";" + this.host.doSerialize(ob[r]) + (typeof ob[r] == "object" || typeof ob[r] == "array" ? "" : ";");
				}
			}

			if(ob.className) return "O:" + ob.className.length + ":\"" + ob.className + "\":" + length + ":{" + x.substr(0, x.length) + "}";
			return "a:" + length + ":{" + x.substr(0, x.length) + "}";
		},

		string : function(str){
			var str = str.replace(/[\r]/g, "");
			str = str.replace(/\]\]/g, "\]-\]-\]").replace(/\]\]/g, "\]-\]-\]");
			return "s:" + str.length + ":\"" + str + "\"";
		},

		number : function(nr){
			if(nr == parseInt(nr))
				return "i:" + nr;
			else if(nr == parseFloat(nr))
				return "d:" + nr;
			else
				return this["boolean"](false);
		},

		"boolean" : function(b){
			return "b:" + (b == true ? 1 : 0);
		},

		array : function(ar){
			var x = "a:" + ar.length + ":{";
			for(var i=0;i<ar.length;i++)
				x += "i:" + i + ";" + this.host.doSerialize(ar[i]) + (i < ar.length && typeof ar[i] != "object" && typeof ar[i] != "array" ? ";" : "");

			return x + "}";
		}
	}

	this.unserialize = function(str){
		return eval(str.replace(/\|-\|-\|/g, "]]").replace(/\|\|\|/g, "\\n"));
	}

	this.doSerialize = function(args){
		if(typeof args == "function"){
			throw new Error(0, "Cannot Parse functions");
		}
		else if(isNot(args))
			return serialize["boolean"](false);

		return serialize[args.dataType || "object"](args);
	}

	// Create message to send
	this.serialize = function(functionName, args){
  		//Construct the XML-RPC message
  		var message = "<?xml version='1.0' encoding='UTF-16'?><run m='" + functionName + "'><![CDATA[";
  		//for(i=0;i<args.length;i++){
  			message += this.doSerialize(args);
  		//}

  		return message + "]]></run>";
  	}

	// Check Received Data for errors
	this.checkErrors = function(data, http){
   	//handle method result
      if(data && data.tagName == "data"){
      	data = data.firstChild.nodeValue;

			//error handling
			if(data && data[0] == "error") throw new Error(10, data[1]);
		}
		else throw new Error(1083, Kernel.formErrorString(1083, null, "Checking for errors", "Malformed RPC Message: Parse Error\n\n:'" + http.responseText + "'"));

		return data;
	}
}

;
// Serialize Objects
var __JSONSerialize = {
	object : function(o){
		var str = [];
		for(var prop in o){
			str.push('"' + prop.replace(/(["\\])/g, '\\$1') + '": ' + serialize(o[prop]));
		}

		return "{" + str.join(", ") + "}";
	},

	string : function(s){
		s = '"' + s.replace(/(["\\])/g, '\\$1') + '"';
		return s.replace(/(\n)/g, "\\n").replace(/\r/g, "");
	},

	number : function(i){
		return i.toString();
	},

	"boolean" : function(b){
		return b.toString();
	},

	date : function(d){
		var padd = function(s, p){
			s=p+s;
			return s.substring(s.length - p.length);
		};
		var y = padd(d.getUTCFullYear(), "0000");
		var m = padd(d.getUTCMonth() + 1, "00");
		var d = padd(d.getUTCDate(), "00");
		var h = padd(d.getUTCHours(), "00");
		var min = padd(d.getUTCMinutes(), "00");
		var s = padd(d.getUTCSeconds(), "00");

		var isodate = y +  m  + d + "T" + h +  ":" + min + ":" + s;

		return '{"jsonclass":["sys.ISODate", ["' + isodate + '"]]}';
	},

	array : function(a){
		for(var q=[],i=0;i<a.length;i++)
			q.push(serialize(a[i]));

		return "[" + q.join(", ") + "]";
	}
}

function serialize(args){
	if(typeof args == "function" || isNot(args))
		return "null";
	return __JSONSerialize[args.dataType || "object"](args);
}

function JSON(){
	this.supportMulticall = false;
	this.multicall = false;

	this.protocol = "POST";
	this.useXML = false;
	this.id = 0;
	this.namedArguments = false;

	// Register Communication Module
	this.SmartBindingHook = ["rpc", "arguments"]
	Kernel.TelePort.register(this);

	// Stand Alone
	if(!this.uniqueId){
		Kernel.makeClass(this);
		this.inherit(CommBaseClass);
		this.inherit(HTTP);
		this.inherit(RPC);
	}
	
	this.getSingleCall = function(name, args, obj){
		obj.push({method: name, params: args});
	}

	// Create message to send
	this.serialize = function(functionName, args){
		this.fName = functionName;
		this.id++;

  		//Construct the XML-RPC message
  		var message = '{"method":"' + functionName + '","params":' + serialize(args) + ',"id":' + this.id + '}';
  		return message;
  	}

  	this.__HeaderHook = function(http){
  		http.setRequestHeader('X-JSON-RPC', this.fName);
  	}

	this.unserialize = function(str){
		var obj = eval('obj=' + str);
		return obj.result;
	}

	// Check Received Data for errors
	this.checkErrors = function(data, http){
		return data;
	}
}

;;
function POST(){
	this.supportMulticall = true;
	this.mcallname = "multicall";
	this.multicall = false;
	this.protocol = "POST";
	this.vartype = "cgi";
	this.isXML = true;
	this.namedArguments = true;
	this.contentType = "application/x-www-form-urlencoded";

	// Register Communication Module
	this.SmartBindingHook = ["rpc", "arguments"];
	Kernel.TelePort.register(this);

	// Stand Alone
	if(!this.uniqueId){
		Kernel.makeClass(this);
		this.inherit(CommBaseClass);
		this.inherit(HTTP);
		this.inherit(RPC);
	}

	this.unserialize = function(str){
		return str;
	}
	
	this.__HeaderHook = function(http){
	}
	
	this.getSingleCall = function(name, args, obj){
		//var args2={};for(var i = 0;i<args.length;i++)args2[args[i][0]]=args[i][1];
		obj.push(args);
	}
	
	// Create message to send
	this.serialize = function(functionName, args){
		if(functionName == 'postform' && postVars){
			var v = postVars; postVars = null;
			this.URL = this.urls[functionName];
			return v;
		}
		
		var vars = [];

		function recur(o,stack){
			if(isArray(o)){
				for(var j=0;j<o.length;j++) recur(o[j],stack+"%5B"+j+"%5D");
			}
			else if(typeof o == "object"){
				for(prop in o){
					if(typeof o[prop] == "function") continue;
					recur(o[prop],stack+"%5B" + encodeURIComponent(prop) + "%5D");	
				}
			}
			else vars.push(stack+"="+o);
		};

		if(this.multicall){
			vars.push("func="+this.mcallname);
			for(var i=0; i < args[0].length; i++ )
				recur( args[0][i], "f%5B"+i+"%5D" );
		}
		else{
			for(prop in args)
				recur(args[prop], prop);
		}
				
		if( !this.BaseURL ) this.BaseURL = this.URL;
		this.URL = this.urls[functionName] ? this.urls[functionName] : this.BaseURL;

		return vars.join("&");
	}

	// Check Received Data for errors
	this.checkErrors = function(data, http){
		return data;
	}

	this.__load = function(x){
		if(x.getAttribute("method-name")){
			var mName = x.getAttribute("method-name");
			var nodes = x.childNodes;

			for(var i=0;i<nodes.length;i++){
				if(nodes[i].nodeType != 1) continue;
				var y = nodes[i];
				var v = y.insertBefore(x.ownerDocument.createElement("variable"), y.firstChild);
				v.setAttribute("name", mName);
				v.setAttribute("value", y.getAttribute("name"));
			}
		}
	}
	
	/**
	 * Submit a form with ajax (POST)
 	 *
 	 * @param form     form
 	 * @param function callback  Called when http result is received
	 */
	var postVars;
	this.submitForm = function(form, callback){
		if(!this['postform']) this.addMethod('postform', callback);

		var args = [];
		for (var i=0; i<form.elements.length; i++) {
            if (!form.elements[i].name) continue;
            if (form.elements[i].tagname = 'input' && (form.elements[i].type == 'checkbox' || form.elements[i].type == 'radio') && !form.elements[i].checked) continue;
            
            if (form.elements[i].tagname = 'select' && form.elements[i].multiple) {
                for (j=0; j<form.elements[i].options.length; j++) {
                    if (form.elements[i].options[j].selected) args.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
                }
            } else {
                args.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
            }
        }
		
		this.urls['postform'] = form.action || location.href;
		postVars = args.join("&");
		this['postform'].call(this);
		
		return false;
	}
}

;
function REST(){
	this.supportMulticall = false;
	this.protocol = "GET";
	this.vartype = "cgi";
	this.isXML = true;
	this.namedArguments = true;

	// Register Communication Module
	this.SmartBindingHook = ["rpc", "arguments"];
	Kernel.TelePort.register(this);

	// Stand Alone
	if(!this.uniqueId){
		Kernel.makeClass(this);
		this.inherit(CommBaseClass);
		this.inherit(HTTP);
		this.inherit(RPC);
	}

	this.unserialize = function(str){
		return str;
	}

	this.getSingleCall = function(name, args, obj){
		//var args2={};for(var i = 0;i<args.length;i++)args2[args[i][0]]=args[i][1];
		obj.push(args);
	}
	
	// Create message to send
	this.serialize = function(functionName, args){
		var vars = [];

		if(functionName == 'postform') {
			this.URL = this.urls[functionName];
			return "";
		}

		function recur(o,stack){
			if(isArray(o)){
				for(var j=0;j<o.length;j++) recur(o[j],stack+"%5B"+j+"%5D");
			}
			else if(typeof o == "object"){
				for(prop in o){
					if(typeof o[prop] == "function") continue;
					recur(o[prop],stack+"%5B" + encodeURIComponent(prop) + "%5D");	
				}
			}
			else vars.push(stack+"="+o);
		};

		if(this.multicall){
			vars.push("func="+this.mcallname);
			for(var i=0; i < args[0].length; i++ )
				recur( args[0][i], "f%5B"+i+"%5D" );
		}
		else{
			for(prop in args)
				recur(args[prop], prop);
		}
				
		if(!this.BaseURL) this.BaseURL = this.URL;
		var nUrl = this.urls[functionName] ? this.urls[functionName] : this.BaseURL;
		this.URL = nUrl + (nUrl.match(/\?/) ? "&" : "?") + vars.join("&");

		return "";
	}

	// Check Received Data for errors
	this.checkErrors = function(data, http){
		return data;
	}

	this.__load = function(x){
		if(x.getAttribute("method-name")){
			var mName = x.getAttribute("method-name");
			var nodes = x.childNodes;

			for(var i=0;i<nodes.length;i++){
				var y = nodes[i];
				var v = y.insertBefore(x.ownerDocument.createElement("variable"), y.firstChild);
				v.setAttribute("name", mName);
				v.setAttribute("value", y.getAttribute("name"));
			}
		}
	}
	
	/**
	 * Submit a form with ajax (GET)
 	 *
 	 * @param form     form
 	 * @param function callback  Called when http result is received
	 */
	this.submitForm = function(form, callback){
		if(!this['postform']) this.addMethod('postform', callback);

		var args = [];		
		for (var i=0; i<form.elements.length; i++) {
            if (!form.elements[i].name) continue;
            if (form.elements[i].tagname = 'input' && (form.elements[i].type == 'checkbox' || form.elements[i].type == 'radio') && !form.elements[i].checked) continue;
            
            if (form.elements[i].tagname = 'select' && form.elements[i].multiple) {
                for (j=0; j<form.elements[i].options.length; j++) {
                    if (form.elements[i].options[j].selected) args.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].options[j].value));
                }
            } else {
                args.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));
            }
        }
		
		var loc = (form.action || location.href);
		this.urls['postform'] = loc + (loc.indexOf("?") > -1 ? "&" : "?") + args.join("&");
		this['postform'].call(this);
		
		return false;
	}
}

;
function SOAP(){
	this.supportMulticall = false;
	this.protocol = "POST";
	this.useXML = true;

	this.nsName = "m";
	this.nsURL = "http://www.javeline.org";
	
	this.namedArguments = true;

	// Register Communication Module
	this.SmartBindingHook = ["rpc", "arguments"]
	Kernel.TelePort.register(this);

	// Stand Alone
	if(!this.uniqueId){
		Kernel.makeClass(this);
		this.inherit(CommBaseClass);
		this.inherit(HTTP);
		this.inherit(RPC);
	}

	// Serialize Objects
	var serialize = {
		host : this,

		object : function(o){
			var wo = o.valueOf();

			for(prop in wo){
				if(typeof wo[prop] != "function" && prop != "type"){
					retstr += this.host.doSerialize(wo[prop], prop);
				}
			}

			return retstr;
		},

		string : function(s){
			return s.replace(/\]\]/g, "] ]");//"<![CDATA[" + s.replace(/\]\]/g, "] ]") + "]]>";
		},

		number : function(i){
			return i;
		},

		"boolean" : function(b){
			return b == true ? 1 : 0;
		},

		date : function(d){
			//Could build in possibilities to express dates
			//in weeks or other iso8601 possibillities
			//hmmmm ????
			//19980717T14:08:55
			return doYear(d.getUTCYear()) + doZero(d.getMonth()) + doZero(d.getUTCDate()) + "T" + doZero(d.getHours()) + ":" + doZero(d.getMinutes()) + ":" + doZero(d.getSeconds());

			function doZero(nr) {
				nr = String("0" + nr);
				return nr.substr(nr.length-2, 2);
			}

			function doYear(year) {
				if(year > 9999 || year < 0)
					XMLRPC.handleError(new Error("Unsupported year: " + year));

				year = String("0000" + year)
				return year.substr(year.length-4, 4);
			}
		},

		array : function(a){
			var retstr = "";
			for(var i=0;i<a.length;i++)
				retstr += this.host.doSerialize(a[i], "item");

			return retstr;
		}
	}

	this.doSerialize = function(args, name){
		var c = name ? args : args[1];
		var name = name ? name : args[0];

		if(typeof c == "function") throw new Error(0, "Cannot Parse functions");

		if(c === false)
			return '<' + name + ' xsi:null="1"/>';
		else
			return '<' + name + ' ' + this.getXSIType(c) + '>' + serialize[c.dataType || "object"](c) + '</' + name + '>';
	}

	// get xsi:type
	this.getXSIType = function(c){
		if(!c.dataType) return '';
		else if(c.dataType == "array")
			return 'xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="xsd:ur-type[' + c.length + ']"';
		else if(c.dataType == "number")
			return 'xsi:type="' + (parseInt(c) == c ? "xsd:int" : "xsd:float") + '"';
		else if(c.dataType == "data")
			return 'xsi:type="xsd:timeInstant"';
		else
			return 'xsi:type="xsd:' + c.dataType + '"';
	}

	// Create message to send
	this.serialize = function(functionName, args){
  		//Construct the SOAP message

  		var message = '<?xml version="1.0"?>' +
		'<SOAP-ENV:Envelope SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/1999/XMLSchema" xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance">' +
		'<SOAP-ENV:Body>' +
		'<' + this.nsName + ':' + functionName + ' xmlns:' + this.nsName + '="' + this.nsURL + '">'

   	for(i=0;i<args.length;i++){
   		message += this.doSerialize(args[i]);
		}

		message += '</' + this.nsName + ':' + functionName + '></SOAP-ENV:Body></SOAP-ENV:Envelope>';

  		return message;
  	}

  	this.__HeaderHook = function(http){
  		http.setRequestHeader('SOAPAction', '"' + this.URL.replace(/http:\/\/.*\/([^\/]*)$/, "$1") + '"');
  	}

	this.unserialize = function(data){
		return data;
		var ret, i;

		//xsi:type
		var type = data.getAttribute("xsi:type");
		switch(type){
			case "xsd:string":
				return (data.firstChild) ? new String(data.firstChild.nodeValue) : "";
			break;
			case "xsd:int":
			case "xsd:double":
			case "xsd:float":
				return (data.firstChild) ? new Number(data.firstChild.nodeValue) : 0;
			break;
			case "xsd:timeInstant":
				/*
				Have to read the spec to be able to completely
				parse all the possibilities in iso8601
				07-17-1998 14:08:55
				19980717T14:08:55
				*/

				var sn = (IS_IE) ? "-" : "/";

				if(/^(\d{4})(\d{2})(\d{2})T(\d{2}):(\d{2}):(\d{2})/.test(data.firstChild.nodeValue)){;//data.text)){
	      		return new Date(RegExp.$2 + sn + RegExp.$3 + sn +
	      							RegExp.$1 + " " + RegExp.$4 + ":" +
	      							RegExp.$5 + ":" + RegExp.$6);
	      	}
	    		else{
	    			return new Date();
	    		}

			break;
			case "xsd:boolean":
				return Boolean(isNaN(parseInt(data.firstChild.nodeValue)) ? (data.firstChild.nodeValue == "true") : parseInt(data.firstChild.nodeValue))

			break;
			case "SOAP-ENC:base64":
				return Kernel.decodeBase64(data.firstChild.nodeValue);
			break;
			case "SOAP-ENC:Array":
				var nodes = data.childNodes;

				ret = new Array();
				for(var i=0;i<nodes.length;i++){
					if(nodes[i].nodeType != 1) continue;
     				ret.push(this.unserialize(nodes[i]));
     			}

				return ret;

			break;
			default:
				//Custom Type
				if(type && !self[type]) throw new Error(1084, Kernel.formErrorString(1084, null, "SOAP", "Invalid Object Specified in SOAP message: " + type));

				var nodes = data.childNodes;
				var o = type ? new self[type] : {};

				ret = new Array();
				for(var i=0;i<nodes.length;i++){
					if(nodes[i].nodeType != 1) continue;
     				ret[nodes[i].tagName] = this.unserialize(nodes[i]);
     			}

				return ret;
			break;
		}
	}

	// Check Received Data for errors
	this.checkErrors = function(data, http){
		/*var fault = data.selectSingleNode("Fault");
		if(fault){
			var nr = fault.selectSingleNode("faultcode/text()").nodeValue;
			var msg = "\n" + fault.selectSingleNode("faultstring/text()").nodeValue;
			throw new Error(nr, msg);
		}

		else if(data.getElementsByTagName("Errors")){
			var fault = data.getElementsByTagName("Errors")[0];
			var nr = fault.selectSingleNode("node()/node()/text()").nodeValue;
			var msg = "\n" + fault.selectSingleNode("node()/node()[2]/text()").nodeValue;
			throw new Error(nr, msg);
		}*/

		// IE Hack
		if(IS_IE)
			data.ownerDocument.setProperty("SelectionNamespaces", "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xds='http://www.w3.org/2001/XMLSchema' xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'");

		rvalue = data.getElementsByTagName("SOAP-ENV:Body")[0];///node()/node()[2]
		if(!rvalue && data.getElementsByTagNameNS) rvalue = data.getElementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/", "Body")[0]

		return rvalue;
	}

	this.__load = function(x){
		if(x.getAttribute("ns-name")) this.nsName = x.getAttribute("ns-name");
		if(x.getAttribute("ns-url")) this.nsURL = x.getAttribute("ns-url");
	}
}

;;
function XMLRPC(){
	this.supportMulticall = true;
	this.multicall = false;
	this.mcallname = "system.multicall";
	this.protocol = "POST";
	this.useXML = true;
	
	this.namedArguments = false;

	// Register Communication Module
	this.SmartBindingHook = ["rpc", "arguments"]
	Kernel.TelePort.register(this);

	// Stand Alone
	if(!this.uniqueId){
		Kernel.makeClass(this);
		this.inherit(CommBaseClass);
		this.inherit(HTTP);
		this.inherit(RPC);
	}

	// Serialize Objects
	var serialize = {
		host : this,

		object : function(o){
			var wo = o.valueOf();

			retstr = "<struct>";

			for(prop in wo){
				if(typeof wo[prop] != "function" && prop != "type"){
					retstr += "<member><name>" + prop + "</name><value>" + this.host.doSerialize(wo[prop]) + "</value></member>";
				}
			}
			retstr += "</struct>";

			return retstr;
		},

		string : function(s){
			//<![CDATA[***your text here***]]>
			//return "<string><![CDATA[" + s.replace(/\]\]\>/g, "").replace(/\<\!\[\CDATA\[/g, "") + "]]></string>";//.replace(/</g, "&lt;").replace(/&/g, "&amp;")
			return "<string><![CDATA[" + s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;") + "]]></string>";
			//var str = "<string>" + s.replace(/\&/g, "&amp;").replace(/\</g, "&lt;").replace(/\>/g, "&gt;") + "</string>";//.replace(/</g, "&lt;").replace(/&/g, "&amp;")
			return str;
		},

		number : function(i){
			if(i == parseInt(i)){
				return "<int>" + i + "</int>";
			}
			else if(i == parseFloat(i)){
				return "<double>" + i + "</double>";
			}
			else{
				return this["boolean"](false);
			}
		},

		"boolean" : function(b){
			if(b == true) return "<boolean>1</boolean>";
			else return "<boolean>0</boolean>";
		},

		date : function(d){
			//Could build in possibilities to express dates
			//in weeks or other iso8601 possibillities
			//hmmmm ????
			//19980717T14:08:55
			return "<dateTime.iso8601>" + doYear(d.getUTCYear()) + doZero(d.getMonth()) + doZero(d.getUTCDate()) + "T" + doZero(d.getHours()) + ":" + doZero(d.getMinutes()) + ":" + doZero(d.getSeconds()) + "</dateTime.iso8601>";

			function doZero(nr) {
				nr = String("0" + nr);
				return nr.substr(nr.length-2, 2);
			}

			function doYear(year) {
				if(year > 9999 || year < 0)
					XMLRPC.handleError(new Error(1085, Kernel.formErrorString(1085, null, "XMLRPC serialization", "Unsupported year: " + year)));

				year = String("0000" + year)
				return year.substr(year.length-4, 4);
			}
		},

		array : function(a){
			var retstr = "<array><data>";
			for(var i=0;i<a.length;i++){
				retstr += "<value>";
				retstr += this.host.doSerialize(a[i])
				retstr += "</value>";
			}
			return retstr + "</data></array>";
		}
	}

	this.getSingleCall = function(name, args, obj){
		obj.push({m: name, p: args});
	}

	this.doSerialize = function(args){
		if(typeof args == "function"){
			throw new Error(1086, Kernel.formErrorString(1086, null, "XMLRPC serialization", "Cannot Parse functions"));
		}
		else if(isNot(args))
			return serialize["boolean"](false);

		return serialize[args.dataType || "object"](args);
	}

	// Create message to send
	this.serialize = function(functionName, args){
  		//Construct the XML-RPC message
		var message = '<?xml version="1.0" encoding=\"UTF-8\"?><methodCall><methodName>' + functionName + '</methodName><params>';
   		for(i=0;i<args.length;i++){
   			message += '<param><value>' + this.doSerialize(args[i]) + '</value></param>';
		}
		message += '</params></methodCall>';

  		return message;
  	}

  	// Needs revision (still from vcXMLRPC)
	this.getNode = function(data, tree){
		var nc = 0;//nodeCount

		//node = 1
		if(data != null){
			for(i=0;i<data.childNodes.length;i++){
				if(data.childNodes[i].nodeType == 1){
					if(nc == tree[0]){
						data = data.childNodes[i];
						if(tree.length > 1){
							tree.shift();
							data = this.getNode(data, tree);
						}
						return data;
					}
					nc++
				}
			}
		}

		return false;
	}

	this.unserialize = function(data){
		var ret, i;

		switch(data.tagName){
			case "string":
				if(IS_GECKO){
					data = (new XMLSerializer()).serializeToString(data);
					data = data.replace(/^\<string\>/,'');
					data = data.replace(/\<\/string\>$/,'');
					data = data.replace(/\&lt;/g, "<");
					data = data.replace(/\&gt;/g, ">");

					return data;
				}

				return (data.firstChild) ? data.firstChild.nodeValue : "";
				break;
			case "int":
			case "i4":
			case "double":
				return (data.firstChild) ? new Number(data.firstChild.nodeValue) : 0;
				break;
			case "dateTime.iso8601":
				/*
				Have to read the spec to be able to completely
				parse all the possibilities in iso8601
				07-17-1998 14:08:55
				19980717T14:08:55
				*/

				var sn = (IS_IE) ? "-" : "/";

				if(/^(\d{4})(\d{2})(\d{2})T(\d{2}):(\d{2}):(\d{2})/.test(data.firstChild.nodeValue)){;//data.text)){
	      		return new Date(RegExp.$2 + sn + RegExp.$3 + sn +
	      							RegExp.$1 + " " + RegExp.$4 + ":" +
	      							RegExp.$5 + ":" + RegExp.$6);
	      	}
	    		else{
	    			return new Date();
	    		}

				break;
			case "array":
				data = this.getNode(data, [0]);

				if(data && data.tagName == "data"){
					ret = new Array();

					var i = 0;
					while(child = this.getNode(data, [i++])){
      				ret.push(this.unserialize(child));
					}

					return ret;
				}
				else{
					this.handleError(new Error(1087, Kernel.formErrorString(1087, null, "", "Malformed XMLRPC Message")));
					return false;
				}
				break;
			case "struct":
				ret = {};

				var i = 0;
				while(child = this.getNode(data, [i++])){
					if(child.tagName == "member"){
						ret[this.getNode(child, [0]).firstChild.nodeValue] = this.unserialize(this.getNode(child, [1]));
					}
					else{
						this.handleError(new Error(1087, Kernel.formErrorString(1087, null, "", "Malformed XMLRPC Message2")));
						return false;
					}
				}

				return ret;
				break;
			case "boolean":
				return Boolean(isNaN(parseInt(data.firstChild.nodeValue)) ? (data.firstChild.nodeValue == "true") : parseInt(data.firstChild.nodeValue))

				break;
			case "base64":
				return Kernel.decodeBase64(data.firstChild.nodeValue);
				break;
			case "value":
				child = this.getNode(data, [0]);
				return (!child) ? ((data.firstChild) ? new String(data.firstChild.nodeValue) : "") : this.unserialize(child);

				break;
			default:
				throw new Error(1088, Kernel.formErrorString(1088, null, "", "Malformed XMLRPC Message: " + data.tagName));
				return false;
				break;
		}
	}

	// Check Received Data for errors
	this.checkErrors = function(data, http){
		if(this.getNode(data, [0]).tagName == "fault"){
			if(!Kernel.isSafari){
				var nr = data.selectSingleNode("//member[name/text()='faultCode']/value/int/text()").nodeValue;
				var msg = "\n" + data.selectSingleNode("//member[name/text()='faultString']/value/string/text()").nodeValue;
			}else{nr = msg = ""}

			throw new Error(nr, msg);
		}

		data = this.getNode(data, [0,0,0]);

		return data;
	}
}

;
function RPC(){
	if(!this.supportMulticall) this.multicall = false;

	this.stack = {};
	this.globals = {};
	this.names = {};
	this.urls = {};

	this.isRPC = true;
	this.useHTTP = true;
	this.TelePortModule = true;

	this.routeServer = HOST + "/cgi-bin/rpcproxy.cgi";
	this.autoroute = false;

	this.namedArguments = false;

	/* ADD METHODS */

	this.addMethod = function(name, receive, names, async, vexport, is_global, global_name, global_lookup, caching){
		if(is_global) this.callbacks[name] = new Function('data', 'status', 'extra', 'Kernel.lookup(' + this.uniqueId + ').setGlobalVar("' + global_name + '"' + ', data, extra.http, "' + global_lookup + '", "' + receive + '", extra, status)');
		else if(receive) this.callbacks[name] = receive;

		this.setName(name, names);
		if(vexport) this.vexport = vexport;
		this[name] = new Function('return this.call("' + name + '"' + ', this.fArgs(arguments, this.names["' + name + '"], ' + (this.vartype != "cgi" && this.vexport == "cgi") + '));');
		this[name].async = async;
		this[name].caching = caching;

		return true;
	}

	this.setName = function(name, names){
		this.names[name] = names;
	}

	this.setCallback = function(name, func){
		this.callbacks[name] = func;
	}

	this.fArgs = function(a, nodes, no_globals){
		var args = this.namedArguments ? {} : [];
		if(!no_globals) for(var i=0;i<this.globals.length;i++) args[this.globals[i][0]] = this.globals[i][1];
		
		if(nodes && nodes.length){
			for(var value, j=0,i=0;i<nodes.length;i++){
				// Determine value
				var name = nodes[i].getAttribute("name");
				if(nodes[i].getAttribute("value")) value = nodes[i].getAttribute("value");
				else if(nodes[i].getAttribute("method")) value = self[nodes[i].getAttribute("method")](args);
				else{
					//Fugly Rik Hack				
					if ( a.length==1 && typeof a[0]=='object'){
					    //typeof(a[0][name]) != "undefined";
						value = a[0][name];
					}else{
						value = a[j];
						j++;
					}
					if(isNot(value)) value = nodes[i].getAttribute("default");
				}

				//Encode string optionally
				value = nodes[i].getAttribute("encoded") == "true" ? encodeURIComponent(value) : value;

				//Set arguments
				this.namedArguments ? (args[name] = value) : (args.push(value)); //isn't this only called for namedArguments = true (should)
			}
		}
		else
			for(var i=0;i<a.length;i++) args.push(a[i]);
		
		return args;
	}

	/* GLOBALS */

	this.setGlobalVar = function(name, data, http, lookup, receive, extra, status){
		if(status != __RPC_SUCCESS__){
			Kernel.debugMsg("Could not get Global Variable<br />", "teleport");

			if(receive) self[receive](data, status, extra);
			return;
		}

		if(this.vartype == "header" && lookup && http) data = http.getResponseHeader(lookup);
		if(lookup.split("\:", 2)[0] == "xpath"){

			try{
				var doc = Kernel.getObject("XMLDOM", data).documentElement;
			}
			catch(e){
				throw new Error(1083, Kernel.formErrorString(1083, null, "Receiving global", "Returned value is not XML (for global variable lookup with name '" + name + "')"));
			}

			var xmlNode = doc.selectSingleNode(lookup.split("\:", 2)[1]);
			var data = xmlNode.nodeValue();
		}

		for(var found=false,i=0;i<this.globals.length;i++){
			if(this.globals[i][0] == name){
				this.globals[i][1] = data;
				found = true;
			}
		}
		if(!found) this.globals.push([name, data]);

		if(receive) self[receive](data, __RPC_SUCCESS__, extra);
	}

	/* CALL */

	this.call = function(name, args){
		if(this.workOffline) return;
		
		if(this.oncall) this.oncall(name, args);

		var receive = typeof this.callbacks[name] == "string" ? self[this.callbacks[name]] : this.callbacks[name];
		if(!receive) receive = function(){}
		//if(!receive){throw new Error(1602, "---- Javeline Error ----\nProcess :  RPC Send\nMessage : Callback method is not declared: '" + this.callbacks[name] + "'")}

		// Set up multicall
		if(this.multicall){
			if(!this.stack[this.URL]) this.stack[this.URL] = this.getMulticallObject ? this.getMulticallObject() : new Array();
			//this.stack[this.URL].push();
			this.getSingleCall(name, args, this.stack[this.URL])
			return true;
		}

		// Get Data
		var data = this.serialize(name, args); //function of module

		// Sent the request
		var info = this.get(this.URL, receive, this[name].async, this[name].userdata, true, data, false, null, null, null, this[name].caching);

		return info;
	}

	/* PURGE MULTICALL */

	this.purge = function(receive, userdata, async){
		if(!this.stack[this.URL] || !this.stack[this.URL].length) throw new Error(0, Kernel.formErrorString(0, null, "Executing a multicall", "No RPC calls where executed before calling purge()."));
		
		// Get Data
		var data = this.serialize("multicall", [this.stack[this.URL]]); //function of module

		info = this.get(this.URL, receive, async, userdata, true, data, false);
		this.stack[this.URL] = this.getMulticallObject ? this.getMulticallObject() : [];

		//return info[1];
	}

	this.revert = function(modConst){
		this.stack[modConst.URL] = this.getMulticallObject ? this.getMulticallObject() : [];
	}

	/* Load XML Definitions */

	this.load = function(x){
		this.jml = x;
		this.timeout = parseInt(x.getAttribute("timeout")) || this.timeout;
		this.URL = x.getAttribute("url-eval") ? eval(x.getAttribute("url-eval")) : x.getAttribute("url");
		if(this.URL) this.server = this.URL.replace(/^(.*\/\/[^\/]*)\/.*$/, "$1") + "/";
		this.multicall = x.getAttribute("multicall") == "true";
		this.autoroute = x.getAttribute("autoroute") == "true";
		this.workOffline = x.getAttribute("offline") == "true";

		if(this.__load) this.__load(x);

		var q = x.childNodes;
		for(var url, i=0;i<q.length;i++){
			if(q[i].nodeType != 1) continue;

			if(q[i].tagName == "global"){
				this.globals.push([q[i].getAttribute("name"), q[i].getAttribute("value")]);
				continue;
			}

			if(IS_IE) var nodes = q[i].getElementsByTagName("j:variable|variable");
			else{
				var nodes = q[i].getElementsByTagNameNS("http://javeline.nl/j", "variable");
				if(!nodes.length) nodes = q[i].getElementsByTagName("variable");
			}

			url =q[i].getAttribute("url-eval") ? eval(q[i].getAttribute("url-eval")) : q[i].getAttribute("url");
			if(url) this.urls[q[i].getAttribute("name")] = url;

			//Add Method
			this.addMethod(
				q[i].getAttribute("name"),
				q[i].getAttribute("receive") || x.getAttribute("receive"),
				nodes,
				(q[i].getAttribute("async") == "false" ? false : true),
				q[i].getAttribute("export"),
				q[i].getAttribute("type") == "global",
				q[i].getAttribute("variable"),
				q[i].getAttribute("lookup"),
				q[i].getAttribute("caching") == "true"
			);
		}
	}
	
	/**
	 * Post a form with ajax
 	 *
 	 * @param form     form
 	 * @param function callback  Called when http result is received
	this.submitForm = function(form, callback, callName) {
		this.addMethod('postform', callback);
		this.urls['postform'] = form.action;

		var args = [];
		for (var i=0; i < form.elements.length; i++) {
			var name = form.elements[i].name.split("[");
			for(var j=0;j<name.length;j++){
				//Hmm problem with sequence of names... have to get that from the variable sequence...
			}
			args[] = form.elements[i].value;  
		}
		
		this['postform'].apply(this, args);
	}*/
}
;
//Depends on implementation of Javeline HTTP Socket on Server Side
function Socket(){
	this.uniqueId = Kernel.all.push(this) - 1;
	this.server = null;
	this.timeout = 10000;
	
	this.TelePortModule = true;
	
	/*************************************************************
				Receiving - Permanent Connection (HTTP-PUSH)
	*************************************************************/
	this.init = function(){
		this.iframe = document.createElement("IFRAME");
		document.body.appendChild(this.iframe);
		this.iframe.style.position = "absolute";

		//if(!IS_IE) importClass(MozillaCompat, true, this.iframe.contentWindow);
		
		/*if(self.DEBUG){
			this.iframe.style.left = "0px";
			this.iframe.style.top = "0px";
			this.iframe.style.zIndex = 100;
		}
		else */
		this.iframe.style.display = "none";
		this.timer = setInterval("var o = Kernel.lookup(" + this.uniqueId + ");if(o.iframe.contentWindow.document.readyState == 'complete') o.reconnect()", 1000);
		
		this.inited = true;
	}

	this.socketConnect = function(vars){
		if(!this.inited) this.init();
		
		if(!vars) vars = [["date", new Date().getTime()]];
		else vars.push(["date", new Date().getTime()]);

		for(var str="",i=0;i<vars.length;i++)
			vars[i] = vars[i][0] + "=" + escape(vars[i][1])

		this.iframe.src = this.server + "?connection_id=" + this.uniqueId + "&" + vars.join("&");
		return this;
	}

	this.reconnect = function(){
		this.iframe.contentWindow.location.reload();
	}

	this.socketDisconnect = function(){
		clearInterval(this.timer);
		this.iframe.src = "blank.html";this.iframe.src = "blank.html";
	}

	this.setConnectionId = function(listenId){
		this.connectionId = listenId;
	}

	this.receive = function(module, strdata){
		Kernel.debugMsg("<strong>HTTP Socket RCV: [" + module + "] - " + strdata.replace(/</g, "&lt;") + "</strong><hr />", "teleport");

		if(module == "LISTENER_ID") this.listenerId = strdata;
		else{
			var o = eval(strdata.replace(/\]-\]-\]/g, "]]").replace(/\|\|\|/g, "\\n"));
			//if(this.onreceive) this.onreceive(module, o);
			if(this.onreceive) self[this.onreceive](module, o);
		}
	}

	/*************************************************************
						Forward Communication (RPC)
	*************************************************************/

	this.send = function(module, data){
		Kernel.debugMsg("<strong>HTTP Socket SND: [" + module + "] - " + data.toString().replace(/</g, "&lt;") + "</strong><hr />", "teleport");

		this.forward.send(this.connectionId, module, data);
	}

	this.purge = function(){
		this.forward.purge();
	}

	this.load = function(x){
		this.server = x.getAttribute("url-eval") ? eval(x.getAttribute("url-eval")) : x.getAttribute("url");
		
		var fName = x.getAttribute("f-type") || "JPHP";
		
		this.forward = new self[fName]();
		this.forward.addMethod("send", null, null, true)
		
		this.forward.timeout = parseInt(x.getAttribute("timeout")) || this.timeout;
		this.forward.URL = this.server;
		this.forward.server = this.server.replace(/^(.*\/\/[^\/]*)\/.*$/, "$1") + "/";
		if(x.getAttribute("var-type")) this.forward.vartype = x.getAttribute("var-type");
		this.forward.multicall = x.getAttribute("multicall") == "true";
		
		if(x.getAttribute("mode") != "manual") this.socketConnect();
		if(x.getAttribute("receive")) this.onreceive = x.getAttribute("receive");
	}
}

;function loadIncludes(docElement){
	//Subwindow
	if(false && window.opener && window.opener.Application){
		if(document.all) document.body.innerHTML = window.opener.Application.xml.outerHTML;
		LoadData["interface"] = [window.opener.Application.xmlClass, document.all ? document.getElementsByTagName("Application")[0] : window.opener.Application.xml];
		
		/*if(LoadData[1].getElementsByTagName("LoadScreen").length){
			if(!document.all) document.body.innerHTML = "";
			loadScreen = XMLDatabase.htmlImport(Kernel.getElement(LoadData[1].getElementsByTagName("LoadScreen")[0], 0), document.body);
		}*/

		document.body.style.display = "block";
		return;
	}

	//Load current HTML document as 'second DOM'
	
	document.body.setAttribute("mode", "xml");
	
	if((!IS_IE || document.body.getAttribute("mode") == "xml") && !docElement){
		return new HTTP().getString((document.body.getAttribute("xml-url") || location.href).split(/#/)[0], function(xmlString, status, extra){
			if(status != __HTTP_SUCCESS__) throw new Error(extra.message);
			
			var str = xmlString.replace(/\<\!DOCTYPE[^>]*>/, "").replace(/&nbsp;/g, " ").replace(/xmlns\=\"[^"]*\"/g, "").replace(/&\w+;/, "").replace(/^[\r\n\s]*/, ""); 
			//var str = xmlString.replace(/xmlns\=\"[^"]*\"/g, "").split("\n"); str.shift(); str = str.join("\n");//.replace(/\<(\/?)j\:/g, "<$1").split("\n"); str.shift(); str = str.join("\n");
			var xmlNode = Kernel.getObject("XMLDOM", str);
			if(Kernel.xmlParseError) Kernel.xmlParseError(xmlNode);
			
			
			return loadIncludes(xmlNode);
		}, true);
	}
	else if(!docElement) docElement = document;
	
	//Check for docType

	//Parse the second DOM (add includes)
	
	AppData = docElement.body ? docElement.body : docElement.selectSingleNode("/html/body")

	loadJMLIncludes(AppData);
	
	
	if(!self.ERROR_HAS_OCCURRED)
		Init.interval = setInterval('if(checkLoaded()) initialize()', 20);
}

function loadJMLIncludes(xmlNode, oHttp, doSync){
	
	return true;
}

function loadJMLInclude(node, oHttp, doSync, path){
}

// Load user defined includes
var AppData, IncludeStack = [];
//loadIncludes();
Init.addConditional(loadIncludes, null, ['BODY', 'HTTP', 'XMLDatabase', 'TelePort']);

function checkLoaded(){
	for(var i=0;i<IncludeStack.length;i++){
		if(!IncludeStack[i]){
			setStatus("Waiting for: [" + i + "] " + IncludeStack[i]);
			return false;
		}
	}
	
	if(!document.body) return false;
	
	setStatus("Dependencies loaded");
	
	return true;
}

function initialize(){
	
	setStatus("Initializing...");
	clearInterval(Init.interval);
	
	//Initialize Form
	if(self._Window) _Window.Init();

	// Boot kernel
	if(Kernel.Init) Kernel.Init();

	// Run Init
	Init.run();

	// Start application
	if(self.Application) Application.Init(AppData);

	if(self.loadScreen) loadScreen.style.display = "none";
}

function getAbsolutePath(base, src){
	return src.match(/^\w+\:\/\//) ? src : base + src;
}

function removePathContext(base, src){
	if(!src) return "";
	if(src.indexOf(base) > -1) return src.substr(base.length);
	return src;
}

if(document.body) Init.run('BODY');
else window.onload = function(){Init.run('BODY');};;
