
/**
 * GUID生成工具
 * 
 * @type UUID
 * @class UUID
 */
var UUID =
{
	S4			: function()
	{
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	},
	/**
	 * 生成32位GUID,速度慢
	 * 
	 * @return {}
	 */
	randomUUID	: function()
	{
		return(UUID.S4() + UUID.S4() + "-" + UUID.S4() + "-" + UUID.S4() + "-" + UUID.S4() + "-" + UUID.S4() + UUID.S4() + UUID.S4());
	},
	d			: new Date().getTime() + "_" + Math.random().toString().replace('.', '_') + "_",
	c			: 0,
	/**
	 * 生成客户端唯一ID,速度快
	 * 
	 * @return {}
	 */
	cID			: function()
	{
		++UUID.c;
		return 'cid_' + UUID.d + UUID.c;
	}
};

/**
 * array对象,该对象为JS Array在特定情况下的替换品 该对象查找value的速度优于 JS Array,避免了JS
 * Array查找对象必需循环的缺点
 * 
 * @constructor
 * @class array
 * @type array
 */
var array = function()
{
	this.k = UUID.cID();
	/**
	 * keys
	 */
	this.keys = {};
}
/**
 * @type Number
 */
array.prototype.length = 0;
array.prototype.n = 'number';
array.prototype.b = 'boolean';
array.prototype.s = 'string';
array.prototype.nn = "n_";
/**
 * @param {}
 *            value
 */
array.prototype.add = function(value)
{
	if (value == null)
		return;
	var t = typeof(value)
	var ii = t == this.n || t == this.b || t == this.s;
	var key;
	if (ii)
	{
		key = this.k + this.nn + value;
		if (this.keys[key] != null)
			return;
	}
	else
	{
		key = this.k + this.length;
		if (value[this.k] > -1)
			return;
		else value[this.k] = this.length;
	}
	this.keys[key] = value;

	++this.length;
}
/**
 * @param {}
 *            idx
 * @return {}
 */
array.prototype.getindex = function(idx)
{
	return this.getValue(this.keys[idx]);
}
/**
 * @param {}
 *            value
 */
array.prototype.getkey = function(value)
{
	if (value == null)
		return;

	var t = typeof(value)
	var ii = t == this.n || t == this.b || t == this.s;

	if (ii)
	{
		var k = this.k + this.nn + value;
		if (this.keys[k] != null)
			return k;
	}
	else
	{
		var ret = value[this.k];
		if (ret > -1)
			return this.k + ret;
	}
}
/**
 * @param {}
 *            value
 * @return {}
 */
array.prototype.contains = function(value)
{
	return this.getkey(value) != null;
}
/**
 * @param {}
 *            key
 * @return {}
 */
array.prototype.getvalue = function(key)
{
	return this.keys[key];
}
/**
 * @param {}
 *            value
 */
array.prototype.remove = function(value)
{
	var key = this.getkey(value);
	if (key == null)
		return;

	delete this.keys[key];
	--this.length;
}
/**
 * 
 */
array.prototype.clear = function()
{
	this.keys = null;
	this.keys = {};
	this.length = 0;
}

if(!window.leapdefaultcallservice)
{
	window.leapdefaultcallservice = "leap";
}

//var scanner = null;
var leapconfig =
{
	server				: 'http://192.168.0.174:8080/LEAPClient',
	_rpcurl				: null,
	loginHTML			: null,
	rpcurl				: function()
	{
		return this._rpcurl;
	},
	resurl				: function()
	{
		return this.server;
	},
	rpcservice			: window.leapdefaultcallservice,
	defaultCallService	: window.leapdefaultcallservice,
	ReturnJSON			: true
};

var PublishServerConfig =
{
	URL			: 'http://192.168.0.174:8080/LEAPClient',
	ImagesPath	: this.URL + 'Images',
	UploadURL	: this.URL + 'Upload.jsp'
};

PublishServerConfig.getURL = function(url)
{
	if (url.indexOf('http://') == 0 || url.indexOf('https://') == 0) { return url; }

	if (this.URL.charAt(this.URL.length - 1) == '/')
	{
		if (url.charAt(0) == '/')
		{
			return this.URL + url.substring(1, url.length);
		}
		else
		{
			return this.URL + url;
		}
	}
	else
	{
		if (url.charAt(0) == '/')
		{
			return this.URL + url.substring(1, url.length);
		}
		else
		{
			return this.URL + "/" + url;
		}
	}
};

var leapscripttype =
{
	js			: 0,
	css			: 1,
	template	: 2
};
var ___logout = function()
{
//	var url = document.URL;
//	url = url.substring(0, url.indexOf("/HTML/")) + "/HTML/Login.html";
//	if (leapconfig.loginHTML == null)
//	{
//		window.location.replace(url);
//	}
//	else
//	{
//		window.location.replace(leapconfig.server + leapconfig.loginHTML);
//	}
	if(window.event != null && LEAP != null)
		LEAP.stopEvent(window.event);
	
	window.history.back();
}

var leaprpcclientasyncactivelist = new array();
var asyncount = 0;
var leaprpcclient = function()
{
	this.URL = leapconfig.rpcurl();
	this.Service = leapconfig.rpcservice;
	this.CallService = leapconfig.defaultCallService;
	this.IsReturnJSON = leapconfig.ReturnJSON;
	var loadedscripts;

	var loadedfiles;

	this.isSuccess = null;
	this.lastError = null;
	this.lastErrorCode = null;
	this.lastWarring = null;
	this.extendResult = null;
	this.version = null;
	this.initVersion = null;

	this.ID = "";

	this.sid = null;

	this.getVersion = function()
	{
		if (this.initVersion == null)
		{
//			this.initVersion = true;
//			var str = XmlHttpHelper.GetTextByPost(leapconfig.server + 'LEAP/Service/RPC/RPC.DO?gv=1&rid');
//			if (str != null && str.length > 0)
				this.version = window.leapversion;
		}
		return this.version;
	}

	this.getLastWarring = function()
	{
		return this.lastWarring;
	}

	this.getLastExtendResult = function()
	{
		return this.extendResult;
	}

	this.setLastExtendResult = function(result)
	{
		this.extendResult = result;
	}

	this.getLastError = function()
	{
		var error = this.lastError;
		var errorcode = this.lastErrorCode;
		var success = this.isSuccess;

		this.isSuccess = 1;
		this.lastError = null;
		this.lastErrorCode = null;

		if (error == null && errorcode == null && success == 1)
			return;
		var ret =
		{
			error	: error,
			code	: errorcode,
			success	: success
		};
		return ret;
	}

	this.___buildResult = function(str, istojson)
	{
		this.isSuccess = 1;
		this.lastError = null;
		this.lastErrorCode = null;

		if (str == null || str == "" || str == "null")
		{
			this.isSuccess = 0;
			this.lastError = "request result is null";
			this.lastErrorCode = "-9999";
			return null;
		}
		if (istojson == null)
		{
			istojson = true;
		}
		else
		{
			var result = null;
			try
			{
				result = JSON.parse(str);//JSON.parse(str);
				if (result != null && result.javaClass)
				{
					this.isSuccess = result.isSuccess;
					this.lastError = result.lastError;
					this.lastErrorCode = result.lastErrorCode;
					this.lastWarring = result.lastWarring;
					this.extendResult = result.extendResult;

					if (this.isSuccess == 0)
					{
						if (this.lastErrorCode == "88888" || this.lastErrorCode == "-1")
						{
							setTimeout(___logout, 1000);
						}
						return null;
					}

					var ret = result.result;
					if (ret == null || ret == "" || ret == "null")
						return null;
					if (result.dataType != null && result.dataType == 12)
					{
						istojson = false;
					}
					if (istojson)
					{
						var _jo = null;
						try
						{
							_jo = JSON.parse(ret);
						}
						catch(ex)
						{
						}

						if (_jo != null)
							return _jo;
						return ret;
					}
					else
					{
						return ret;
					}
				}
			}
			catch(err)
			{
				this.isSuccess = 0;
				this.lastError = "deserialize server return result error";
				this.lastErrorCode = "-9998";
			}
		}
	}

	this.getsid = function()
	{
		if (this.sid == null)
		{
			if (document.cookie.indexOf('JSESSIONID=') > -1)
			{
				var str = document.cookie.substring(document.cookie.indexOf('JSESSIONID='));
				str = str.split(';')[0];
				this.sid = str.substring(11);
				return this.sid;
			}
			else
			{
				var ret = XmlHttpHelper.GetTextByPost(leapconfig.rpcurl(), "type=997");
				this.sid = ret;
				return this.sid;
			}
		}
		else return this.sid;
	}

	this.initsafe = false;
	this.safe = null;

	/**
	 * def.name 方法名称<br>
	 * def.par 参数<br>
	 * this.extendPar 扩展参数<br>
	 * def.callback 回调方法<br>
	 * def.service 调用服务名称<br>
	 * def.callService 调用服务名称<br>
	 * def.requestType 请求类型<br>
	 * def.isreturnjson 是否返回json对象<br>
	 * def.useGet 是否使用get请求<br>
	 * def.domain 回调作用域<br>
	 * def.arg 回调参数
	 */
	this.request2 = function(def)
	{
		if (def.requestGroup != null)
		{
			def.requestGroup.add(def);
			return;
		}
		else
		{
			return this.request(def.name, def.par, this.extendPar, def.callback, def.service, def.callService, def.requestType, def.isreturnjson, def.useGet, def.domain, def.arg);
		}
	}
	this.request = function(_methodName, _JSONObject, extendParameters, callback, serviceName, callService, requestType, isreturnjson, useGet, _domain, _args)
	{
		var _serviceName = null;
		var _callService = null;
		if (serviceName == null)
			_serviceName = this.Service;
		else _serviceName = serviceName;
		if (callService == null)
			_callService = this.CallService;
		else _callService = callService;
		var rj = this.IsReturnJSON;
		if (isreturnjson != null && isreturnjson != rj)
			rj = isreturnjson;

		var uri = "service=" + _serviceName + "&method=" + _methodName + "&callService=" + _callService + "&returnJSON=" + rj + "&clientID=" + this.ID + "&sid=" + this.getsid();
		if (extendParameters != null)
		{
			uri += "&extend=" + encodeURIComponent(encodeURIComponent(escape(extendParameters)));
		}
		if (!this.initsafe)
		{
			this.safe = document.getElementById('safecontrol');
			this.initsafe = true;
		}
		if (this.safe != null)
		{
			var ran = (Math.round(Math.random() * 10000)) + "";
			while(ran.length < 4)
				ran += "0";
			uri += "&zz=" + (ran);
			try
			{
				uri += this.safe.a(ran);
			}
			catch(e)
			{
			}
		}
		if (requestType != null)
		{
			uri += "&type=" + requestType
		}
		var parData = null;
		if (_JSONObject != null && typeof(_JSONObject) == "object" && _JSONObject != "")
		{
			try
			{
				var parDatas = [];
				var tempcount = 0;
				for(var key in _JSONObject)
				{
					if (typeof(_JSONObject[key]) != "function")
					{
						var v = _JSONObject[key];
						if (v == null)
							parDatas[tempcount] = null;
						else if (typeof(_JSONObject[key]) != "string")
							parDatas[tempcount] = JSON.stringify(v);
						else parDatas[tempcount] = v;
						tempcount++;
					}
				}
				uri += "&requestData=" + encodeURIComponent(encodeURIComponent(escape(JSON.stringify(parDatas))));// "requestData="+escape(
				// JSON.stringify(_JSONObject)
				// );
			}
			catch(err)
			{
				parexp = null;
			}
		}
		try
		{
			if (uri != null && uri != '')
				uri += '&'
			uri += "requestURL=" + document.URL;

			if (callback == null)
			{
				var str = null;
				if (useGet == true)
					str = XmlHttpHelper.GetTextByGet(_methodName);
				else str = XmlHttpHelper.GetTextByPost(leapconfig.rpcurl(), uri);
				if (rj)
					return this.___buildResult(str, true);
				else return str;
			}
			else
			{
				++asyncount;
				var instance = asyncount;
				if (useGet == true)
					XmlHttpHelper.GetTextByGet(_methodName, this.callbackfunction, this,
					{
						callback	: callback,
						domain		: _domain,
						args		: _args,
						instance	: instance
					});
				else XmlHttpHelper.GetTextByPost(leapconfig.rpcurl(), uri, this.callbackfunction, this,
				{
					callback	: callback,
					domain		: _domain,
					args		: _args,
					instance	: instance
				});
				leaprpcclientasyncactivelist.add(instance);
				return instance;
			}
		}
		catch(err)
		{
			if (callback != null)
				return null;
		}
	};

	this.asynrequest = function(_methodName, _JSONObject, extendParameters, _callback, _domain)
	{
		return this.request(_methodName, _JSONObject, extendParameters, _callback, null, null, null, null, null, _domain);
	}
	this.callbackfunction = function(text, arg)
	{
		try
		{
			var result = this.___buildResult(text, true);

			if (arg.callback != null)
			{
				var fn = function()
				{
					try
					{
						var app = arg.domain;
						if (app == null)
							app = this;
						arg.callback.call(app, result, arg.args);
						app = callobject = null;
					}
					catch(e)
					{

					}
					finally
					{
						app = arg = null;
					}
				};
				setTimeout(fn, 1);
			}
		}
		catch(ex)
		{
		}
	};

	this.load = function(fileName)
	{
		var filefirst = fileName.charAt(0);
		if (filefirst == '/' || filefirst == '\\')
		{
			fileName = fileName.substring(1);
		}
		if (fileName.indexOf('?') == -1 && this.getVersion() != null)
			fileName += '?gv=' + this.getVersion();
		return this.request(leapconfig.resurl() + fileName, null, null, null, null, null, 2, false, true);
	};

	this.loadjs = function(fileName, targetDocument, useDefer)
	{
		return this.loadscript(fileName, leapscripttype.js, targetDocument, useDefer);
	};

	this.loadcss = function(fileName, targetDocument)
	{
		return this.loadscript(fileName, leapscripttype.css, targetDocument);
	};

	this.loadtl = function(fileName, targetDocument)
	{
		return this.loadscript(fileName, leapscripttype.template, targetDocument);
	};

	this._s = null;
	this._c = null;
	this.loadscript = function(fileName, scriptType, targetDocument, useDefer)
	{
		var filefirst = fileName.charAt(0);
		if (filefirst == '/' || filefirst == '\\')
		{
			fileName = fileName.substring(1);
		}
		if (fileName.indexOf('?') == -1 && this.getVersion() != null)
			fileName += '?gv=' + this.getVersion();

		if (targetDocument == null)
			targetDocument = document;

		var comFile = fileName;
		if (fileName.indexOf('?') != -1)
		{
			comFile = fileName.substring(0, fileName.indexOf('?'));
		}

		if (this._s == null)
		{
			this._s = [];
			var ss = targetDocument.getElementsByTagName('SCRIPT');
			if (ss != null)
			{
				for(var i = 0;i < ss.length;i++)
				{
					var p = ss[i].getAttribute('path');

					if (p != null)
					{
						if (p.indexOf('?') != -1)
						{
							p = p.substring(0, p.indexOf('?'));
						}

						this._s.push(p.toLowerCase());
					}
					p = null;
				}
			}
		}

		if (this._c == null)
		{
			this._c = [];
			var cs = targetDocument.getElementsByTagName('LINK');
			if (cs != null)
			{
				for(var i = 0;i < cs.length;i++)
				{
					var p = cs[i].getAttribute('path');
					if (p != null)
					{

						if (p.indexOf('?') != -1)
						{
							p = p.substring(0, p.indexOf('?'));
						}

						this._c.push(p.toLowerCase());
					}
					p = null;
				}
			}
		}

		if (scriptType == null)
			scriptType = leapscripttype.js;

		if (scriptType == leapscripttype.js)
		{
			var l = this._s.length;
			var __t = comFile.toLowerCase();
			for(var i = 0;i < l;i++)
			{
				if (__t == this._s[i])
					return;
			}
			this._s.push(__t);
		}
		else if (scriptType == leapscripttype.css)
		{
			var l = this._c.length;
			var __t = comFile.toLowerCase();
			for(var i = 0;i < l;i++)
			{
				if (__t == this._c[i])
					return;
			}
			this._c.push(__t);
		}

		var str = this.load(fileName);
		if (str == null)
			return;
		if (scriptType == leapscripttype.js || scriptType == leapscripttype.css)
		{
			addScript(str, targetDocument, scriptType, useDefer, fileName);
		}
		else
		{
			try
			{
				return str;
			}
			finally
			{
				str = null;
			}
		}
	};

	var addScript = function(source, targetDocument, type, useDefer, path)
	{
		try
		{
			if (source != null)
			{
				var oHead = targetDocument.getElementsByTagName('HEAD').item(0);
				var oScript;
				if (type == leapscripttype.js)
				{
					oScript = targetDocument.createElement("script");
					oScript.language = "javascript";
					oScript.type = "text/javascript";
					oScript.charset = 'UTF-8';
					oScript.defer = 'defer';
					oScript.text = source;
					oScript.path = path;
				}
				else if (type == leapscripttype.css)
				{
					var oScript = targetDocument.createElement("link")
					oScript.setAttribute("rel", "stylesheet")
					oScript.setAttribute("type", "text/css")
					oScript.setAttribute("href", leapconfig.server + path);
					oScript.text = source;
					oScript.path = path;
				}
				oHead.appendChild(oScript);
				source = targetDocument = type = useDefer = oHead = oScript = null;
				return true;
			}
		}
		catch(err)
		{
		}
	};

	this.init = function()
	{
		var url = window.location.href;
		var nodes = document.getElementsByTagName('HEAD').item(0).childNodes;
		for(var i = 0;i < nodes.length;i++)
		{
			if (nodes[i].tagName == 'SCRIPT' && nodes[i].src != null && (nodes[i].src.indexOf('Base.js') > -1 || nodes[i].src.indexOf('Net.js') > -1))
			{
				var s = nodes[i].src;
				if (s.charAt(0) == '/')
				{
					while(url.indexOf('//') > -1)
						url = url.replace('//', '_');
					url = url.replace('http:_', "http://").replace('https:_', "https://");
					while(url.lastIndexOf('/') > -1 && url.charAt(url.lastIndexOf('/') - 1) != '/')
					{
						url = url.substring(0, url.lastIndexOf("/"));
					}
					if (nodes[i].src.indexOf('Base.js') > -1)
						url += s.replace('LEAP/Resource/JavaScript/Base.js', '');
					else url += s.replace('LEAP/Resource/JavaScript/Base/Net.js', '');
				}
				else
				{
					if (s.indexOf('http://') > -1 || s.indexOf('https://') > -1)
					{
						if (nodes[i].src.indexOf('Base.js') > -1)
							url = s.replace('LEAP/Resource/JavaScript/Base.js', '');
						else url = s.replace('LEAP/Resource/JavaScript/Base/Net.js', '');
					}
					else
					{
						var c = 0;
						while(s.indexOf('../') > -1)
						{
							c += 1;
							s = s.replace("../", "");
						}
						while(s.indexOf('./') > -1)
						{
							c += 1;
							s = s.replace("./", "");
						}
						while(url.indexOf('//') > -1)
							url = url.replace('//', '_');
						url = url.replace('http:_', "http://").replace('https:_', "https://").substring(0, url.lastIndexOf("/"));
						if (c > 0)
						{
							while(c > 0)
							{
								c--;
								url = url.substring(0, url.lastIndexOf("/"));
							}
						}
						url = url + '/' + s;
						if (nodes[i].src.indexOf('Base.js') > -1)
						{
							if (url.indexOf('LEAP/Resource/JavaScript/Base.js') > -1)
								url = url.replace('LEAP/Resource/JavaScript/Base.js', '');
							else if (url.indexOf('Resource/JavaScript/Base.js') > -1)
								url = url.replace('Resource/JavaScript/Base.js', '');
						}
						else url = url.replace('LEAP/Resource/JavaScript/Base/Net.js', '');
					}
				}
				break;
			}
		}

		var urlpre = url;
		leapconfig.server = urlpre;
		leapconfig._rpcurl = urlpre + "LEAP/Service/RPC/RPC.DO";
		PublishServerConfig.URL = urlpre;
		PublishServerConfig.ImagesPath = PublishServerConfig.URL + 'Images';
		PublishServerConfig.UploadURL = PublishServerConfig.URL + 'Upload.jsp';
	}
};

var leapclient = new leaprpcclient();
function XmlHttpHelper()
{
}

//"MSXML2.XMLHTTP.4.0",
var arr_t = new Array("MSXML2.XMLHTTP.3.0","MSXML2.XMLHTTP.2.6","MSXML2.XMLHTTP","Microsoft.XMLHTTP","MSXML.XMLHTTP");
var arr_t_indx = -1;
XmlHttpHelper._getXmlHttpObj = function()
{
	var _xh = null;
	if (window.ActiveXObject)
	{
		if (arr_t_indx == -1)
		{
			for(var i = 0;i < arr_t.length;i++)
			{
				try
				{
					_xh = new ActiveXObject(arr_t[i]);
					arr_t_indx = i;
				}
				catch(e)
				{
				}
				if (_xh != null)
					break;
			}
		}
		else _xh = new ActiveXObject(arr_t[arr_t_indx]);
	}
	if (_xh == null)
	{
		if (window.XMLHttpRequest)
		{
			try
			{
				_xh = new XMLHttpRequest();
				if (_xh.overrideMimeType)
				{
					_xh.overrideMimeType('text/xml');
				}
			}
			catch(ex)
			{
			}
		}
	}
	if (_xh == null)
	{
		alert('con not create XMLHTTP object');
		throw(new Error(-1,'con not create XMLHTTP object'));
	}
	return _xh;
};

XmlHttpHelper.GetTextByPost = function(url, postData, callback, callbackdomain, callargs)
{
	var d = null;
	try
	{
		if (arguments.length > 2)
		{
			if (arguments.length > 3)
				d = arguments[3];
			return XmlHttpHelper.transmit(arguments[0], "POST", arguments[1], "text", true, arguments[2], d, callargs);
		}
		else return XmlHttpHelper.transmit(arguments[0], "POST", arguments[1], "text", false, null);
	}
	finally
	{
		d = null;
	}
};

XmlHttpHelper.GetTextByGet = function(url, callback, callbackdomain, callargs)
{
	var d = null;
	try
	{
		if (arguments.length > 1)
		{
			if (arguments.length > 3)
				d = arguments[2];
			return XmlHttpHelper.transmit(arguments[0], "GET", null, "text", true, arguments[1], d, callargs);
		}
		else return XmlHttpHelper.transmit(arguments[0], "GET", null, "text", false, null);
	}
	finally
	{
		d = null;
	}
};
/*
 * XmlHttpHelper.GetXmlByPost = function(url,postData,callback) {
 * if(arguments.length == 3) return
 * XmlHttpHelper.transmit(arguments[0],"POST",arguments[1],"xml",true,arguments[2]);
 * else return
 * XmlHttpHelper.transmit(arguments[0],"POST",arguments[1],"xml",false,null); };
 * XmlHttpHelper.GetXmlByGet = function(url,callback) { if(arguments.length ==
 * 2) return
 * XmlHttpHelper.transmit(arguments[0],"GET",null,"xml",true,arguments[1]); else
 * return XmlHttpHelper.transmit(arguments[0],"GET",null,"xml",false,null); };
 */

XmlHttpHelper.transmit = function(url, httpMethod, postData, responseType, async, callback, callbackdomain, callargs)
{
	// if(Debug) alert("go to XmlHttpHelper.transmit");
	var instance = null;
	var xmlhttp = this._getXmlHttpObj();
	try
	{
		xmlhttp.open(httpMethod, url, async);

		xmlhttp.setRequestHeader('connection', 'keep-alive');

		if (httpMethod.toLowerCase() == "post")
		{
			var _length = 0;
			if (postData != null)
			{
				_length = postData.length;
			}
			xmlhttp.setRequestHeader('Content-Length', '"' + _length + '"');
			xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		}

		if (async)
		{
			if (callargs != null && callargs.instance != null)
				instance = callargs.instance;

			xmlhttp.onreadystatechange = function()
			{
				if (xmlhttp.readyState == 4)
				{
					try
					{
						if (responseType != null)
						{
							if (responseType.toLowerCase() == "text")
							{
								if (callback != null)
								{
									if (callbackdomain != null)
									{
										if (instance == null || (instance != null && leaprpcclientasyncactivelist.contains(instance)))
											callback.call(callbackdomain, xmlhttp.responseText, callargs);
										else callback = callargs = null;
										if (instance != null)
											leaprpcclientasyncactivelist.remove(instance);
									}
									else
									{
										callback.call(xmlhttp.responseText);
									}
								}
								// else
								// {
								// callback(xmlhttp.responseText, callback);
								// }
							}
							else if (responseType.toLowerCase() == "xml")
							{
								if (callbackdomain != null)
								{
									if (instance == null || (instance != null && leaprpcclientasyncactivelist.contains(instance)))
										callback.call(callbackdomain, xmlhttp.responseXML, callargs);
									else callback = callargs = null;
									if (instance != null)
										leaprpcclientasyncactivelist.remove(instance);
								}
								else
								{
									callback.call(xmlhttp.responseXML);
								}

								// if (callback.callbackmethod != null)
								// {
								// callback.callbackmethod(xmlhttp.responseXML,
								// callback);
								// }
								// else
								// {
								// callback(xmlhttp.responseXML, callback);
								// }
							}
						}
						else
						{
							if (callbackdomain != null)
							{
								if (callargs != null)
									callback.call(callbackdomain, null, callargs);
								else callback.call(callbackdomain);
							}
							else
							{
								callback.call();
							}
							// if (callback.callbackmethod != null)
							// {
							// callback.callbackmethod(null, callback);
							// }
							// else
							// {
							// callback(null, callback);
							// }
						}
					}
					finally
					{
						// xmlhttp = null;
					}
				}
			};
			if (postData == null)
				postData = '';
			xmlhttp.send(postData);
		}
		else
		{
			if (postData == null)
				postData = '';
			xmlhttp.send(postData);
			if (xmlhttp.status == 200)
			{
				if (responseType != null)
				{
					if (responseType.toLowerCase() == "text")
						return xmlhttp.responseText;
					else if (responseType.toLowerCase() == "xml")
						return xmlhttp.responseXML;
				}
				else
				{
					return null;
				}
			}
			return null;
		}
	}
	catch(errmsg)
	{
		if (instance != null)
		{
			leaprpcclientasyncactivelist.remove(instance);
		}
	}
	finally
	{
		if (xmlhttp != null)
		{
			try
			{
				// delete xmlhttp;
			}
			catch(oooo)
			{
			}
			// xmlhttp = null;
		}
	}
};

RegExp.prototype.toJSON = function()
{
	return this.toString();
}

if (!this.JSON)
{
	this.JSON = {};
}

(function()
{

	function f(n)
	{
		// Format integers to have at least two digits.
		return n < 10 ? '0' + n : n;
	}

	if (typeof Date.prototype.toJSON !== 'function')
	{

		Date.prototype.toJSON = function(key)
		{
			return isFinite(this.valueOf()) ? this.getUTCFullYear() + '-' + f(this.getUTCMonth() + 1) + '-' + f(this.getUTCDate()) + 'T' + f(this.getUTCHours()) + ':' + f(this.getUTCMinutes()) + ':' + f(this.getUTCSeconds()) + 'Z' : null;
		};

		String.prototype.toJSON = Number.prototype.toJSON = Boolean.prototype.toJSON = function(key)
		{
			return this.valueOf();
		};
	}

	var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta =
	{ // table of character substitutions
		'\b'	: '\\b',
		'\t'	: '\\t',
		'\n'	: '\\n',
		'\f'	: '\\f',
		'\r'	: '\\r',
		'"'		: '\\"',
		'\\'	: '\\\\'
	},rep;

	function quote(string)
	{

		// If the string contains no control characters, no quote characters, and no
		// backslash characters, then we can safely slap some quotes around it.
		// Otherwise we must also replace the offending characters with safe escape
		// sequences.

		escapable.lastIndex = 0;
		return escapable.test(string) ? '"' + string.replace(escapable, function(a)
		{
			var c = meta[a];
			return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
		}) + '"' : '"' + string + '"';
	}

	function str(key, holder)
	{

		// Produce a string from holder[key].

		var i, // The loop counter.
		k, // The member key.
		v, // The member value.
		length,mind = gap,partial,value = holder[key];

		// If the value has a toJSON method, call it to obtain a replacement value.

		if (value && typeof value === 'object' && typeof value.toJSON === 'function')
		{
			value = value.toJSON(key);
		}

		// If we were called with a replacer function, then call the replacer to
		// obtain a replacement value.

		if (typeof rep === 'function')
		{
			value = rep.call(holder, key, value);
		}

		// What happens next depends on the value's type.

		switch(typeof value)
		{
			case 'string':
				return quote(value);

			case 'number':

				// JSON numbers must be finite. Encode non-finite numbers as null.

				return isFinite(value) ? String(value) : 'null';

			case 'boolean':
			case 'null':

				// If the value is a boolean or null, convert it to a string. Note:
				// typeof null does not produce 'null'. The case is included here in
				// the remote chance that this gets fixed someday.

				return String(value);

				// If the type is 'object', we might be dealing with an object or an array or
				// null.

			case 'object':

				// Due to a specification blunder in ECMAScript, typeof null is 'object',
				// so watch out for that case.

				if (!value) { return 'null'; }

				// Make an array to hold the partial results of stringifying this object value.

				gap += indent;
				partial = [];

				// Is the value an array?

				if (Object.prototype.toString.apply(value) === '[object Array]')
				{

					// The value is an array. Stringify every element. Use null as a placeholder
					// for non-JSON values.

					length = value.length;
					for(i = 0;i < length;i += 1)
					{
						partial[i] = str(i, value) || 'null';
					}

					// Join all of the elements together, separated with commas, and wrap them in
					// brackets.

					v = partial.length === 0 ? '[]' : gap ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' : '[' + partial.join(',') + ']';
					gap = mind;
					return v;
				}

				// If the replacer is an array, use it to select the members to be stringified.

				if (rep && typeof rep === 'object')
				{
					length = rep.length;
					for(i = 0;i < length;i += 1)
					{
						k = rep[i];
						if (typeof k === 'string')
						{
							v = str(k, value);
							if (v)
							{
								partial.push(quote(k) + (gap ? ': ' : ':') + v);
							}
						}
					}
				}
				else
				{

					// Otherwise, iterate through all of the keys in the object.

					for(k in value)
					{
						if (Object.hasOwnProperty.call(value, k))
						{
							v = str(k, value);
							if (v)
							{
								partial.push(quote(k) + (gap ? ': ' : ':') + v);
							}
						}
					}
				}

				// Join all of the member texts together, separated with commas,
				// and wrap them in braces.

				v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}';
				gap = mind;
				return v;
		}
	}

	// If the JSON object does not yet have a stringify method, give it one.

	if (typeof JSON.stringify !== 'function')
	{
		JSON.stringify = function(value, replacer, space)
		{

			// The stringify method takes a value and an optional replacer, and an optional
			// space parameter, and returns a JSON text. The replacer can be a function
			// that can replace values, or an array of strings that will select the keys.
			// A default replacer method can be provided. Use of the space parameter can
			// produce text that is more easily readable.

			var i;
			gap = '';
			indent = '';

			// If the space parameter is a number, make an indent string containing that
			// many spaces.

			if (typeof space === 'number')
			{
				for(i = 0;i < space;i += 1)
				{
					indent += ' ';
				}

				// If the space parameter is a string, it will be used as the indent string.

			}
			else if (typeof space === 'string')
			{
				indent = space;
			}

			// If there is a replacer, it must be a function or an array.
			// Otherwise, throw an error.

			rep = replacer;
			if (replacer && typeof replacer !== 'function' && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); }

			// Make a fake root object containing our value under the key of ''.
			// Return the result of stringifying the value.

			return str('',
			{
				''	: value
			});
		};
	}

	// If the JSON object does not yet have a parse method, give it one.

	if (typeof JSON.parse !== 'function')
	{
		JSON.parse = function(text, reviver)
		{

			// The parse method takes a text and an optional reviver function, and returns
			// a JavaScript value if the text is a valid JSON text.

			var j;

			function walk(holder, key)
			{

				// The walk method is used to recursively walk the resulting structure so
				// that modifications can be made.

				var k,v,value = holder[key];
				if (value && typeof value === 'object')
				{
					for(k in value)
					{
						if (Object.hasOwnProperty.call(value, k))
						{
							v = walk(value, k);
							if (v !== undefined)
							{
								value[k] = v;
							}
							else
							{
								delete value[k];
							}
						}
					}
				}
				return reviver.call(holder, key, value);
			}

			// Parsing happens in four stages. In the first stage, we replace certain
			// Unicode characters with escape sequences. JavaScript handles many characters
			// incorrectly, either silently deleting them, or treating them as line endings.

			cx.lastIndex = 0;
			if (cx.test(text))
			{
				text = text.replace(cx, function(a)
				{
					return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
				});
			}

			// In the second stage, we run the text against regular expressions that look
			// for non-JSON patterns. We are especially concerned with '()' and 'new'
			// because they can cause invocation, and '=' because it can cause mutation.
			// But just to be safe, we want to reject all unexpected forms.

			// We split the second stage into 4 regexp operations in order to work around
			// crippling inefficiencies in IE's and Safari's regexp engines. First we
			// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
			// replace all simple value tokens with ']' characters. Third, we delete all
			// open brackets that follow a colon or comma or that begin the text. Finally,
			// we look to see that the remaining characters are only whitespace or ']' or
			// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

			if (/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, '')))
			{

				// In the third stage we use the eval function to compile the text into a
				// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
				// in JavaScript: it can begin a block or an object literal. We wrap the text
				// in parens to eliminate the ambiguity.

				j = eval('(' + text + ')');

				// In the optional fourth stage, we recursively walk the new structure, passing
				// each name/value pair to a reviver function for possible transformation.

				return typeof reviver === 'function' ? walk(
				{
					''	: j
				}, '') : j;
			}

			// If the text is not JSON parseable, then a SyntaxError is thrown.

			throw new SyntaxError('JSON.parse');
		};
	}
}());

var json_parse = (function()
{

	// This is a function that can parse a JSON text, producing a JavaScript
	// data structure. It is a simple, recursive descent parser. It does not use
	// eval or regular expressions, so it can be used as a model for implementing
	// a JSON parser in other languages.

	// We are defining the function inside of another function to avoid creating
	// global variables.

	var at, // The index of the current character
	ch, // The current character
	escapee =
	{
		'"'		: '"',
		'\\'	: '\\',
		'/'		: '/',
		b		: '\b',
		f		: '\f',
		n		: '\n',
		r		: '\r',
		t		: '\t'
	},text,

	error = function(m)
	{

		// Call error when something is wrong.

		var err =
		{
			name	: 'SyntaxError',
			message	: m,
			at		: at,
			text	: text
		};
		throw err;
	},

	next = function(c)
	{

		// If a c parameter is provided, verify that it matches the current character.

		if (c && c !== ch)
		{
			error("Expected '" + c + "' instead of '" + ch + "'");
		}

		// Get the next character. When there are no more characters,
		// return the empty string.

		ch = text.charAt(at);
		at += 1;
		return ch;
	},

	number = function()
	{

		// Parse a number value.

		var number,string = '';

		if (ch === '-')
		{
			string = '-';
			next('-');
		}
		while(ch >= '0' && ch <= '9')
		{
			string += ch;
			next();
		}
		if (ch === '.')
		{
			string += '.';
			while(next() && ch >= '0' && ch <= '9')
			{
				string += ch;
			}
		}
		if (ch === 'e' || ch === 'E')
		{
			string += ch;
			next();
			if (ch === '-' || ch === '+')
			{
				string += ch;
				next();
			}
			while(ch >= '0' && ch <= '9')
			{
				string += ch;
				next();
			}
		}
		number = +string;
		if (isNaN(number))
		{
			error("Bad number");
		}
		else
		{
			return number;
		}
	},

	string = function()
	{

		// Parse a string value.

		var hex,i,string = '',uffff;

		// When parsing for string values, we must look for " and \ characters.

		if (ch === '"')
		{
			while(next())
			{
				if (ch === '"')
				{
					next();
					return string;
				}
				else if (ch === '\\')
				{
					next();
					if (ch === 'u')
					{
						uffff = 0;
						for(i = 0;i < 4;i += 1)
						{
							hex = parseInt(next(), 16);
							if (!isFinite(hex))
							{
								break;
							}
							uffff = uffff * 16 + hex;
						}
						string += String.fromCharCode(uffff);
					}
					else if (typeof escapee[ch] === 'string')
					{
						string += escapee[ch];
					}
					else
					{
						break;
					}
				}
				else
				{
					string += ch;
				}
			}
		}
		error("Bad string");
	},

	white = function()
	{

		// Skip whitespace.

		while(ch && ch <= ' ')
		{
			next();
		}
	},

	word = function()
	{

		// true, false, or null.

		switch(ch)
		{
			case 't':
				next('t');
				next('r');
				next('u');
				next('e');
				return true;
			case 'f':
				next('f');
				next('a');
				next('l');
				next('s');
				next('e');
				return false;
			case 'n':
				next('n');
				next('u');
				next('l');
				next('l');
				return null;
		}
		error("Unexpected '" + ch + "'");
	},

	value, // Place holder for the value function.

	array = function()
	{

		// Parse an array value.

		var array = [];

		if (ch === '[')
		{
			next('[');
			white();
			if (ch === ']')
			{
				next(']');
				return array; // empty array
			}
			while(ch)
			{
				array.push(value());
				white();
				if (ch === ']')
				{
					next(']');
					return array;
				}
				next(',');
				white();
			}
		}
		error("Bad array");
	},

	object = function()
	{

		// Parse an object value.

		var key,object = {};

		if (ch === '{')
		{
			next('{');
			white();
			if (ch === '}')
			{
				next('}');
				return object; // empty object
			}
			while(ch)
			{
				key = string();
				white();
				next(':');
				if (Object.hasOwnProperty.call(object, key))
				{
					error('Duplicate key "' + key + '"');
				}
				object[key] = value();
				white();
				if (ch === '}')
				{
					next('}');
					return object;
				}
				next(',');
				white();
			}
		}
		error("Bad object");
	};

	value = function()
	{

		// Parse a JSON value. It could be an object, an array, a string, a number,
		// or a word.

		white();
		switch(ch)
		{
			case '{':
				return object();
			case '[':
				return array();
			case '"':
				return string();
			case '-':
				return number();
			default:
				return ch >= '0' && ch <= '9' ? number() : word();
		}
	};

	// Return the json_parse function. It will have access to all of the above
	// functions and variables.

	return function(source, reviver)
	{
		var result;

		text = source;
		at = 0;
		ch = ' ';
		result = value();
		white();
		if (ch)
		{
			error("Syntax error");
		}

		// If there is a reviver function, we recursively walk the new structure,
		// passing each name/value pair to the reviver function for possible
		// transformation, starting with a temporary root object that holds the result
		// in an empty key. If there is not a reviver function, we simply return the
		// result.

		return typeof reviver === 'function' ? (function walk(holder, key)
		{
			var k,v,value = holder[key];
			if (value && typeof value === 'object')
			{
				for(k in value)
				{
					if (Object.hasOwnProperty.call(value, k))
					{
						v = walk(value, k);
						if (v !== undefined)
						{
							value[k] = v;
						}
						else
						{
							delete value[k];
						}
					}
				}
			}
			return reviver.call(holder, key, value);
		}(
		{
			''	: result
		}, '')) : result;
	};
}());

if (this.JSON && !window.ActiveXObject)
{
	if (this.JSON.parse && this.json_parse)
	{
		this.JSON.innerParse = this.JSON.parse;
		this.JSON.parse = function(text, reviver)
		{
			if (text != null)
			{
				if (text.length >= 327680)
				{
					return json_parse(text, reviver);
				}
				else
				{
					return JSON.innerParse(text, reviver);
				}
			}
		}
	}
}

function leap_common_init()
{
	leapclient.init();
}
leap_common_init();
leapclient.ID = UUID.randomUUID();

/*
var RequestGroupTask = function(sequence, requestDef)
{
	this.sequence = sequence;
	this.requestDef = requestDef;
};
RequestGroupTask.prototype.clear = function()
{
	this.sequence = this.requestDef = null;
};
RequestGroupTask.prototype.apply = function(ret, type)
{
	if (this.requestDef.callback != null)
	{
		var domain = this.requestDef.domain;
		if (domain == null)
			domain = window;

		if (type == 1)
		{
			if (ret == null && this.args == null)
				this.requestDef.callback.call(domain);
			else this.requestDef.callback.call(domain, ret, this.requestDef.arg);
		}
		else if (type == 2)
		{
			if (this.args == null)
			{
				this.requestDef.callback.call(domain);
			}
			else
			{
				this.requestDef.callback.apply(domain, this.requestDef.arg);
			}
		}
	}
};

var _clone = function(o, r)
{
	if (o && o.clone != null) { return o.clone(); }

	if (r == null)
		r = {};
	for(var k in o)
	{
		r[k] = o[k];
	}
	return r;
}

var RequestGroup = function(complateFunction, domain, args)
{
	this.complateFunction = complateFunction;
	this.domain = domain;
	this.arg = args;
};
RequestGroup.prototype.requestTaskList = [];
RequestGroup.prototype.lastSequence = 1;
RequestGroup.prototype.add = function(requestDef)
{
	this.requestTaskList.add(new RequestGroupTask(this.lastSequence,requestDef));
	this.lastSequence++;
};
RequestGroup.prototype.addTask = function(fn, domain)
{
	var args = null;
	if (arguments != null && arguments.length > 2)
	{
		args = [];
		var arguments_len = arguments.length;
		for(var i = 2;i < arguments_len;i++)
		{
			var cur = arguments[i];
			args.add(cur);
		}
	}
	this.requestTaskList.add(new RequestGroupTask(this.lastSequence,
	{
		callbal	: fn,
		arg		: args,
		domain	: domain
	}));
	this.lastSequence++;
};
RequestGroup.prototype.callBack = function(ret, task)
{
	task.apply(ret, 1);
	task.clear();
	task = null;
	this.execute();
};
RequestGroup.prototype.callBack2 = function(task)
{
	task.apply(null, 2);
	task.clear();
	task = null;
	this.execute();
};
RequestGroup.prototype.execute = function()
{
	if (this.requestTaskList.length > 0)
	{
		var task = this.requestTaskList[0];
		this.requestTaskList.removeindex(0);
		if (task.requestDef.name != null)
		{
			var def = _clone(task.requestDef);
			def.requestGroup = null;
			def.callback = this.callBack;
			def.arg = task;
			def.domain = this;
			leapclient.request2(def);
		}
		else
		{
			this.callBack2(task);
		}
		task = null;
	}
	else
	{
		if (this.complateFunction != null)
		{
			var domain = this.domain;
			if (domain == null)
				domain = window;

			if (this.args == null)
				this.complateFunction.call(domain);
			else this.complateFunction.call(domain, this.args);
		}
	}
};
*/
