/*
CLASSIC CAJAX CLASS
*/
function CAjax() {
	this.ReadyState = {
		Uninitialized: 0,
		Loading: 1,
		Loaded:2,
		Interactive:3,
		Complete: 4
	}
		
	this.Status = {
		OK: 200,
		
		Created: 201,
		Accepted: 202,
		NoContent: 204,
		
		BadRequest: 400,
		Forbidden: 403,
		NotFound: 404,
		Gone: 410,
		
		ServerError: 500
	}
		
	this.Cache = {
		Get: 1,
		GetCache: 2,
		GetNoCache: 3,
		FromCache: 4
	},
	
	this.Method = {Get: "GET", Post: "POST", Put: "PUT", Delete: "DELETE"},
	
	this.enabled = false;
	this.logging = false;
	this._get = null;	// Reference to the XmlHttpRequest object
	this._cache = new Object();
	this._callback_args = null;
	this._callback = null;
	
	this.Init = function(){
		this._get = this._getXmlHttp()
		this.enabled = (this._get != null)
		this.logging = (window.Logging != null);
	}
	
	this._getXmlHttp = function(){
	/*@cc_on @*//*@if (@_jscript_version >= 5)
		try { return new ActiveXObject("Msxml2.XMLHTTP"); } 
		catch (e) {} 
		try { return new ActiveXObject("Microsoft.XMLHTTP"); } 
		catch (e) {} 
	@end @*/
		try { return new XMLHttpRequest();}
		catch (e) {}

		return null;
	}

/*
	Params:
		url: The URL to request. Required.
		cache: Cache control. Defaults to Cache.Get.
		callback: onreadystatechange function, called when request is completed. Optional.
		method: HTTP method. Defaults to Method.Get.
*/
	this.get = function(params, callback_args)
	{	
		this.Init();
		
		if (!this.enabled) throw "AJAX: XmlHttpRequest not available.";
		
		this._callback_args = callback_args;
		
		var url = params.url;
		if (!url) throw "AJAX: A URL must be specified";
				
		var cache = params.cache || this.Cache.Get;
		var method = params.method || this.Method.Get;

		if (!params.body)
		    method = this.Method.Get;

		this._callback = params.callback;
		
		if ((cache == this.Cache.FromCache) || (cache == this.Cache.GetCache))
		{
			var in_cache = this.from_cache(url)

			if (this.logging){
				Logging.log(["AJAX: URL in cache: " + in_cache]);
			}

			if (in_cache || (cache == this.Cache.FromCache)) return in_cache;
		}
		
		if (cache == this.Cache.GetNoCache)
		{
			var sep = (-1 < url.indexOf("?")) ? "&" : "?"	
			url = url + sep + "__=" + encodeURIComponent((new Date()).getTime());
		}
				
		// Only one request at a time, please
		if ((this._get.readyState != this.ReadyState.Uninitialized) && 
			(this._get.readyState != this.ReadyState.Complete)){
			this._get.abort();
			
			if (this.logging){
				Logging.log(["AJAX: Aborted request in progress."]);
			}
		}
		
		var parent = this;
		this._get.onreadystatechange = function()
		{			
			if (parent._get.readyState != parent.ReadyState.Complete) return;
			
			if (parent.logging){
				Logging.log(["AJAX: Returned, status: " + parent._get.status]);
			}

			if ((cache == parent.Cache.GetCache) && (parent._get.status == parent.Status.OK)){
				parent._cache[url] = parent._get.responseText;
			}
			
			if (parent._callback_args == null) parent._callback_args = new Array();

			var cb_params = new Array();
			cb_params.push(parent._get);
			for(var i=0;i<parent._callback_args.length;i++)
				cb_params.push(parent._callback_args[i]);
				
			parent._callback.apply(null, cb_params);
		};
		
		this._get.open(method, url, true);

		if(this.logging){
			Logging.log(["AJAX: Started\n\tURL: " + url + "\n\tMethod: " + method + "; Cache: " + Hash.keyName(this.Cache,cache)])
		}
		
		this._get.send(params.body || null);
	}
	
	
	this.toDocument = function(text) {
		var xmlDoc;
		
		if(window.ActiveXObject) /* IE */
		{
			// Load XML 
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM")
			xmlDoc.loadXML(text);
		}
		else if(window.XSLTProcessor) /* fire fox */
		{
			var xmlParser = new DOMParser();
				
			// Load XML 
			xmlDoc = xmlParser.parseFromString(text, "text/xml");
		}
		
		return xmlDoc;
	}
	
	this.from_cache = function(url){
		var result = this._cache[url];
		
		if (result != null) {
			var response = new this.CachedResponse(result)
			
			var cb_params = new Array();
			cb_params.push(response);
			for(var i=0;i<this._callback_args.length;i++)
				cb_params.push(this._callback_args[i]);
							
			this._callback.apply(null, cb_params);
				
			return true
		}
		else
			return false
	}
	
	this.clear_cache = function(){
		this._cache = new Object();
	}
	
	this.is_cached = function(url){
		return this._cache[url]!=null;
	}
	
	this.CachedResponse = function(response) {
		this.readyState = this.ReadyState.Complete
		this.status = this.Status.OK
		this.responseText = response
	}
	
} // end class CAjax

CAjax.json_response = function(response){
	var js = response.responseText;
	try{
		return eval(js); 
	} catch(e){
		if (this.logging){
			Logging.logError(["json_response: " + e]);
		}
		else{
			//alert("Error: " + e + "\n" + js);
			ShowAlertBox('', '', '', 'Error', 'Error', e + '\n' + js);
		}
		return null;
	}
}

CAjax.getResponseProps = function(response, header){
	try {
		var s = response.getResponseHeader(header || 'X-Ajax-Props');
		if (s==null || s=="")
			return new Object()
		else
			return eval("o="+s)
	} catch (e) { return new Object() }
}


CAjax.runRequest = function(url, fnt, parameters)
{
	var ajax = new CAjax();
	
	ajax.get({
				url: url,
				callback: (function(funcPtr)
					{ return function(result, ajax)
						{
							if(funcPtr)
								funcPtr(result.responseText);
						}
					})(fnt),
				cache: ajax.Cache.GetNoCache,
				body: parameters
				}, [ajax]);
}

CAjax.getXMLDocument = function(xml)
{
	var ajax = new CAjax();
	return ajax.toDocument(xml);	
}


/*
NEW AJAX
*/
var nextURLElement=0; //IE caches the AJAX request, so add a change element to the querystring
var ie=window.ActiveXObject;

function runRequest(url, fnt, parameters, async)
{
    var xmlhttp
    var async;
    var result;
    if (fnt == null && async == null) { async = false; }
    
    if(async == undefined)
        async = true;

    nextURLElement += 1;
    if (url.lastIndexOf("?") == -1)
    { url += "?qqq=" + + new Date().getTime(); }
    else
    { url += "&qqq=" + + new Date().getTime(); }
    if (ie)
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")
    }
    else
    {
        xmlhttp = new XMLHttpRequest()
    }

    if (xmlhttp != null)
    {
        var method = "POST";
        if (!parameters)
            method = "GET";

        xmlhttp.open(method, url, async); //open first before onreadystatechange or second time will fail!
        xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        
        if (parameters != null)
        {
            xmlhttp.setRequestHeader("Content-length", parameters.length);
        }
        
        xmlhttp.setRequestHeader("Connection", "close");
        
        if(async)
        {
            xmlhttp.onreadystatechange = function()
            {
                if (xmlhttp.readyState == 4)
                {
                    if (fnt != null) { fnt(xmlhttp.responseText); }
                }
            }
        }
        
        xmlhttp.send(parameters)
        
        if(!async && fnt != null)
            fnt(xmlhttp.responseText);
    }
    if(!async)
    { return xmlhttp.responseText };
}

function getXMLDocumentFromRequest(url, parameters)
	{
		return getXMLDocument(runRequest(url, null, parameters));
	}
function getXMLDocument(xml)
	{
		if (ie)
		  {
			  newDoc=new ActiveXObject("Microsoft.XMLDOM");
			  newDoc.async="false";
			  newDoc.loadXML(xml);
		  }
		else
		  {
			  var parser=new DOMParser();
			  newDoc=parser.parseFromString(xml,"text/xml");
		  }
		return newDoc;
	}

function EncodeString(string) 
		{
			if (window.encodeURIComponent) 
			   string = encodeURIComponent(string); 
			else if (window.escape) 
			   string = escape(string);
			return string;
		}	
	
function loadListBoxByNodes(listBox, xml, valueTagName, displayTagName)
	{
	try {
	  var listDoc=getXMLDocument(xml);
	  var root=listDoc.documentElement;
	  var valueNodes=root.getElementsByTagName(valueTagName);
	  var displayNodes=root.getElementsByTagName(displayTagName);
	  for (i=0;i<root.childNodes.length;i++) 
		{
			listBox.options[listBox.options.length]= new Option(displayNodes[i].childNodes[0].nodeValue,valueNodes[i].childNodes[0].nodeValue);
		}
	}
	catch (error) {}
	}
function selectListBoxValue(listBox, value)
	{
		var index=null;
		for (i=0;i<listBox.options.length;i++) 
			{
				if (listBox.options[i].value==value) {index=i;}
			}
		if (index!=null) {listBox.selectedIndex=index;} else {listBox.selectedIndex=0;}
	}