/*==============================================================================
Name: 		AJAX Client Engine (ACE) 
Version: 	1.0
Author:		Li Shen
Created: 	Auguest 24, 2005
Updated:	September 21, 2005 
License:	The MIT License
================================================================================
Copyright (c) 2005 Li Shen (email: li.shen@lishen.name)
      
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
==============================================================================*/

Ace = function()
{
};

Ace.Engine = function(eng, tra)
{
	var requester;
	var request;
	var expiration;
	var interval;
	var intervalId;
	
	var engineId = eng;
	var tracerId = tra;
		
	function trace(info)
	{		
		if (engineId)
		{
			if (!Ace.Tracer)
			{
				if (tracerId)
				{
					Ace.Tracer = window.open("", tracerId, "menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
				}
				else
				{
					Ace.Tracer = window.open("", Ace.Constant.DefaultTracerId, "menubar=no,resizable=yes,scrollbars=yes,status=no,toolbar=no");
				}
				
				Ace.Tracer.document.write('<html><body style="margin:0px;font-family:courier new,arial;font-size:6pt"><textarea id="traceText" style="width:100%;height:100%;border:none;overflow:visible">[' + engineId + '] The engine is added to the tracer.\r\n</textarea></body></html>');
			}
			
			var traceText = Ace.Tracer.document.getElementById("traceText");
			traceText.value = traceText.value + "[" + engineId + "] " + info + "\r\n";
			Ace.Tracer.scrollTo(0, Ace.Tracer.document.body.scrollHeight);
		} 
	};
	
	function Requester()
	{
		var requester;
		
		if (window.XMLHttpRequest)
		{
			requester = new window.XMLHttpRequest(); 
		}
		else if (window.ActiveXObject)
		{
			requester = new ActiveXObject("Msxml2.XMLHTTP");

			if (!requester)
			{
				requester = new ActiveXObject("Microsoft.XMLHTTP");

				if (!requester)
				{	
					trace("Error occurred: " + Ace.Exception.XmlHttpNotSupported);
					throw Ace.Exception.XmlHttpNotSupported;
				}
			}
		}
		else
		{
			trace("Error occurred: " + Ace.Exception.XmlHttpNotSupported);
			throw Ace.Exception.XmlHttpNotSupported;
		}
		
		return requester;
	};

	function headersFromString(s)
	{
		var h = new Object();
		
		var a = s.split("\r\n");
					
		for (var i = 0; i < a.length; i++)
		{
			var a2 = a[i].split(": ");
			
			if (a2.length == 2 && a2[1] != "-")
			{
				h[a2[0]] = a2[1];
			}	
		}
		
		return h;
	};
		
	function headersToString(h)
	{
		var s = "";
		
		for (var k in h)
		{
			s = s + k + ": " + h[k] + "\r\n";
		}
		
		if (s.length > 0)
		{
			s.substring(0, s.length - 2);
		}
		
		return s;
	}; 
	
	function getCache(request, expiration)
	{
		if (expiration)
		{		
			if (Ace.Cache)
			{
				var key = request.url + "&&" + request.content;

				if (Ace.Cache[key])
				{
					if (Ace.Cache[key][0] > (new Date()))
					{
						trace("Cached response '" + key + "' is fetched.");
						return Ace.Cache[key][1];
					}
					else
					{
						delete Ace.Cache[key];
						trace("Cached response '" + key + "' is expired.");
						return Ace.Constant.NotFoundInCache;
					}	 
				}  
				else
				{
					return Ace.Constant.NotFoundInCache;
				}
			}
			else
			{
				Ace.Cache = new Object();
				return Ace.Constant.NotFoundInCache;
			}
		}
		else
		{
			return Ace.Constant.NotFoundInCache;
		}
	};
	
	function setCache(request, expiration, response)
	{
		var key = request.url + "&&" + request.content;
			
		if (expiration)
		{
			if (!Ace.Cache[key] || Ace.Cache[key][0] <= (new Date()))
			{  
				Ace.Cache[key] = [new Date((new Date()).getTime() + expiration * 1000), response];
				trace("Response '" + key + "' is added to the cache.");
			}
		}
		else
		{	
			if (Ace.Cache && Ace.Cache[key])
			{
				Ace.Cache[key][1] = response;
				trace("Response '" + key + "' is updated in the cache.");
			}											
		}
	};

	function validateRequest()
	{		
		if (request.method != Ace.Method.Get && request.method != Ace.Method.Post && request.method != Ace.Method.Head)
		{
			trace("Error occurred: " + Ace.Exception.InvalidMethod);
			throw Ace.Exception.InvalidMethod;
		}
		
		if (!request.url)
		{
			trace("Error occurred: " + Ace.Exception.MissingUrl);
			throw Ace.Exception.MissingUrl;
		} 
		
		if (request.headers && typeof(request.headers) != "object") 
		{
			trace("Error occurred: " + Ace.Exception.InvalidHeaders);
			throw Ace.Exception.InvalidHeaders;
		}
		
		if (request.method != Ace.Method.Post && request.content)
		{
			trace("Error occurred: " + Ace.Exception.IllegalContent);
			throw Ace.Exception.IllegalContent;
		}

		if (request.method == Ace.Method.Post && request.content)
		{			
			if (request.content.search(/^(\w+\=\w+)(&\w+\=\w+)*$/) != 0)
			{
//				trace("Error occurred: " + Ace.Exception.InvalidContent);
//				throw Ace.Exception.InvalidContent;
			}
		}
	}
		
	function beginRequest() 
	{	
		requester = new Requester();
		
		var response = getCache(request, expiration);
		
		if (response == Ace.Constant.NotFoundInCache)
		{
			if (request.callback)
			{
				requester.onreadystatechange = readystatechangeHandler;
	
				requester.open(request.method, request.url, true);
				
				if (request.method == Ace.Method.Post)
				{
					requester.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				}
			
				if (request.headers)
				{
					for (header in request.headers)
					{
						requester.setRequestHeader(header, request.headers[header]);		
					} 
				}
				
				trace("An asynchrounous request is sent to '" + request.url + "'.");
				requester.send(request.content);
			}
			else
			{
				requester.open(request.method, request.url, false);
				
				if (request.method == Ace.Method.Post)
				{
					requester.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
				}
			
				if (request.headers)
				{
					for (header in request.headers)
					{
						requester.setRequestHeader(header, request.headers[header]);		
					} 
				}
				
				trace("A synchrounous request is sent to '" + url + "'.");
				requester.send(request.content);
				trace("The requester's status is " + requester.status + ".");
		
				if (requester.status == Ace.Status.OK)
				{
					trace("The requester's response text is '" + requester.responseText + "'.");
					
					response = new Ace.Response(requester.readyState, requester.status, headersFromString(requester.getAllResponseHeaders()), requester.responseText, requester.responseXML);
					setCache(request, expiration, response);
					return response;
				}
				else
				{
					return new Ace.Response(requester.readyState, requester.staus, headersFromString(requester.getAllResponseHeaders()));
				}
			}	
		}			
		else
		{	
			if (request.callback)
			{
				request.callback.apply(null, [response, request.callbackArgs]);
			}
			else
			{
				return response;
			}
		}	
	};
	
	function endRequest()
	{
		if (requester && requester.readyState != Ace.ReadyState.Uninitialized && requester.readyState != Ace.ReadyState.Complete)
		{
			requester.abort();
			trace("The current request is aborted.");
		}

		if (intervalId)
		{
			window.clearInterval(intervalId);
			trace("The polling service is stopped.");
		}
	};	
	
	function readystatechangeHandler()
	{
		var response;

		trace("The requester's ready state is " + requester.readyState + ".");

		if (requester.readyState == Ace.ReadyState.Complete)
		{
			trace("The requester's status is " + requester.status + ".");

			if (requester.status == Ace.Status.OK)
			{
				trace("The requester's response text is '" + requester.responseText + "'.");

				response = new Ace.Response(requester.readyState, requester.status, headersFromString(requester.getAllResponseHeaders()), requester.responseText, requester.responseXML);
				setCache(request, expiration, response);
				request.callback.apply(null, [response, request.callbackArgs]);
			}
			else
			{
				if (request.callbackOption != Ace.CallbackOption.StatusOK)
				{
					response = new Ace.Response(requester.readyState, requester.staus, headersFromString(requester.getAllResponseHeaders()));
					request.callback.apply(null, [response, request.callbackArgs]);
				}
			}
		}
		else
		{
			if (request.callbackOption == Ace.CallbackOption.Always)
			{
				response = new Ace.Response(requester.readyState);
				request.callback.apply(null, [response, request.callbackArgs]);
			}
		}
	};
	
	this.ready = (!requester) || (requester.readyState == Ace.ReadyState.Uninitialized) || (requester.readyState == Ace.ReadyState.Complete);
		
	this.invoke = function(req, exp, inv)
	{
		trace("invoke() method is called.");

		endRequest();

		request = req;
		expiration = exp;
		interval = inv;

		validateRequest();

		if (interval)
		{
			if (request.callback)
			{
				intervalId = window.setInterval(beginRequest, interval * 1000);
				trace("The polling service is started for an interval of " + interval + " seconds.");
			}
			else
			{
				trace("Error occurred: " + Ace.Exception.IllegalInterval);
				throw Ace.Exception.IllegalInterval;
			}	
		}
		else
		{
			if (request.callback)
			{
				beginRequest(); 
			}
			else
			{	
				return beginRequest(); 
			}
		}
	};
	
	this.cancel = function()
	{	
		trace("cancel() method is called.");
		endRequest();
	};
};

Ace.Method = 
{
	Get: "GET",
	Post: "POST", 
	Head: "HEAD"
};

Ace.ReadyState = 
{
	Uninitialized: 0,
	Loading: 1,
	Loaded: 2,
	Interactive: 3,
	Complete: 4
};

Ace.Status = 
{
	OK: 200,
	Created: 201,
	Accepted: 202,
	NoContent: 204,
	BadRequest: 400,
	Unauthorized: 401,
	Forbidden: 403,
	NotFound: 404,
	MethodNotAllowed: 405,
	RequestTimeout: 408,
	Gone: 410,
	ServerError: 500
};

Ace.CallbackOption = 
{
	StatusOK: 1,
	ReadyStateComplete: 2,
	Always: 3
};

Ace.Exception = 
{
	XmlHttpNotSupported: "XMLHTTPRequest is not supported by the browser.",
	XmlDomNotSupported: "XML DOM is not supported by the browser.",
	XmlIslandNotSupported: "XML Data Island is not supported by the browser.",
	InvalidMethod: "'method' must be 'GET', 'POST', or 'HEAD'.",
	MissingUrl: "'url' must be specified.",
	InvalidHeaders: "'headers' must be an object.",
	InvalidContent: "'content' must be a string of the format 'name1=value1&name2=value2'.",
	IllegalContent: "'content' must be null when 'method' is 'GET' or 'HEAD'.",
	IllegalInterval: "'interval' can be set only if 'callback' of 'request' is set.",
	InvalidCallbackArgs: "'args' for the callback function misses certain properties."
};
		
Ace.Constant = 
{
	DefaultTracerId: "Ace_Default_Tracer",
	NotFoundInCache: "Ace_Not_Found_In_Cache"
};

Ace.Request = function(method, url, headers, content, callback, callbackArgs, callbackOption)
{
	this.method = method || Ace.Method.Get;
	this.url = url;
	this.headers = headers;
	this.content = content;
	this.callback = callback;
	this.callbackArgs = callbackArgs;
	this.callbackOption = callbackOption || Ace.CallbackOption.Always;  
};

Ace.Response = function(readyState, status, headers, text, xml)
{	
	this.readyState = readyState;
	this.status = status;
	this.headers = headers;
	this.text = text;
	this.xml = xml;
};

Ace.HtmlCallback = function(response, args)
{
	if (args.id && args.attr)
	{
		document.getElementById(args.id)[args.attr] = response.text;
	}
	else if (args.id && args.style)
	{
		document.getElementById(args.id).style[args.style] = response.text;
	}
	else
	{
		trace("Error occurred: " + Ace.Exception.InvalidCallbackArgs);
		throw Ace.Exception.InvalidCallbackArgs;
	}
};

Ace.ScriptCallback = function(response, args)
{
	if (args.id && args.attr)
	{
		document.getElementById(args.id)[args.attr] = eval(response.text);
	}
	else if (args.id && args.style)
	{
		document.getElementById(args.id).style[args.style] = eval(response.text);
	}
	else
	{
		trace("Error occurred: " + Ace.Exception.InvalidCallbackArgs);
		throw Ace.Exception.InvalidCallbackArgs;
	}
};

Ace.XmlCallback = function(response, args)
{
	var xmldom, xsldom, result;	

	if (document.implementation && document.implementation.createDocument)
	{
		var parser = new DOMParser();
		xmldom = parser.parseFromString(response.text, "text/xml");

		if (args.xslString)
		{
			xsldom = parser.parseFromString(args.xslString, "text/xml");
		}
		else if (args.xslId)
		{
			trace("Error occurred: " + Ace.Exception.InvalidCallbackArgs);
			throw Ace.Exception.XmlIslandNotSupported;
		} 
		else
		{
			trace("Error occurred: " + Ace.Exception.InvalidCallbackArgs);
			throw Ace.Exception.InvalidCallbackArgs;
		}

		var xsltProcessor = new XSLTProcessor();
		xsltProcessor.importStylesheet(xsldom);
		var xmldom2 = xsltProcessor.transformToDocument(xmldom);

		var xmlSerializer = new XMLSerializer();
		var result = xmlSerializer.serializeToString(xmldom2);
	}
	else if (window.ActiveXObject)
	{		
		xmldom = new ActiveXObject("MSXML2.DOMDocument");
		xmldom.validateOnParse = true;
		xmldom.async = false;
		xmldom.resolveExternals = false;
		xmldom.loadXML(response.text);

		if (args.xslString)
		{
			xsldom = new ActiveXObject("MSXML2.DOMDocument");
			xsldom.validateOnParse = true;
			xsldom.async = false;
			xsldom.resolveExternals = false;
			xsldom.loadXML(args.xslString)
		}	
		else if (args.xslId)
		{
			xsldom = document.all[args.xslId].XMLDocument; 
		}
		else
		{
			trace("Error occurred: " + Ace.Exception.InvalidCallbackArgs);
			throw Ace.Exception.InvalidCallbackArgs;
		}

		result = xmldom.transformNode(xsldom);
	}
	else
	{
		trace("Error occurred: " + Ace.Exception.XmlDomNotSupported);
		throw Ace.Exception.XmlDomNotSupported;
	}

	if (args.id && args.attr)
	{
		document.getElementById(args.id)[args.attr] = result;
	}
	else if (args.id && args.style)
	{
		document.getElementById(args.id).style[args.style] = result;
	}
	else
	{
		trace("Error occurred: " + Ace.Exception.InvalidCallbackArgs);
		throw Ace.Exception.InvalidCallbackArgs;
	}
};







