/********************************************************************/
/* AJAX OBJECT : Simple static object to use ajax features          */
/* Copyright   : MyWebSolutions Inc. 2006 (MyXpass)                 */
/* Date        : 18/08/2006                                         */
/* Features    : Timeout, post/get support                          */
/********************************************************************/

Ajax = new Object();

Ajax._init = function()
{
	xmlhttp = false;
	
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		try {
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){}
		}
	}
	if(!xmlhttp) throw "Can't initiate XmlHttpRequest";
	return xmlhttp;
}

Ajax.query = function(method, url, args, async, callback_complete, callback_error, timeout) {
	if(timeout == null) timeout =3000;
	try {
		var xmlhttp = Ajax._init();
	} catch(e) {
		callback_error('Ajax not found', xmlhttp);
		return;
	}
	var timeouted = false;
	var reqtimeout = setTimeout(function()
	{
		timeouted = true;
		if(xmlhttp.state != 4) {
			xmlhttp.abort();
		}
		callback_error('Time out', xmlhttp);
	}
	, timeout);
	
	xmlhttp.onreadystatechange = function()
	{
		if (!timeouted && xmlhttp && xmlhttp.readyState == 4) {
			clearTimeout(reqtimeout);
			if (xmlhttp.status == 200) {
				callback_complete(xmlhttp);
			} else if(callback_error != null) {
				callback_error('Bad status', xmlhttp);
			}
		}
	}

	if(method == "GET") {
		if(args != "") url += "?" + args;
		xmlhttp.open("GET", url, async);
		xmlhttp.send(null);
	} else {
		xmlhttp.open("POST", url, async);
		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlhttp.send(args);
	}
}

Ajax.urlencode = function(str) {
	return encodeURIComponent(str);	
}


