var Ajax = {
	state : "idle",
	item : {url:null, callback:null, canvas:null, message:null},
	queu : new Array(),
	loadingMsg : "<center>Loading...</center>"
};


/*   CREATE THE HTTPREQUEST   */
Ajax.call = function(script, callback, canvas, message)
{
	var url = (script.indexOf("www.") > -1 || script.indexOf("scripts/") > -1) ? script : "scripts/"+script;

	if(message != false)
	{
		document.getElementById(canvas).innerHTML = message ? message : Ajax.loadingMsg;
	}

	/*
	    Check if the engine is busy with another item
	    If it is, then queu this new item and wait...
	*/
	if(Ajax.state == "busy")
	{
		Ajax.queu.push({url:url, callback:callback, canvas:canvas, message:message});
		return;
	}
	else
	{
		Ajax.item = {url:url, callback:callback, canvas:canvas, message:message};
	}

	if(window.XMLHttpRequest)
	{
		Ajax.xmlHttp = new XMLHttpRequest();
	}
	else if(window.ActiveXObject)
	{
		Ajax.xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	if(Ajax.xmlHttp != null)
	{
		var myCall = (Ajax.item.url.indexOf("?") > -1) ? Ajax.item.url : Ajax.item.url + "?=";
		myCall = myCall + "&rand=" + Math.random();

		var xmlHttp = Ajax.xmlHttp;
		xmlHttp.onreadystatechange = Ajax.item.callback;
		xmlHttp.open("GET", myCall, true);
		xmlHttp.send(null);

		// Set the engine state to "busy" i.e. "DO NOT DISTURB"
		Ajax.state = "busy";
	}
}


/*   CALLBACK FUNCTION TO PRINT THE RESPONSE TEXT   */
Ajax.print = function()
{
	var xmlHttp = Ajax.xmlHttp;

	if(xmlHttp.readyState == 4)
	{
		try
		{
			if(xmlHttp.status == 200)
			{
				Ajax.response = xmlHttp.responseText;
			}
			else
			{
				Ajax.response = "<p><center><div class='feedback0'>Error</div></center></p>";
			}

		}
		catch(e)
		{
			Ajax.rotate();
		}

		var canvas = document.getElementById(Ajax.item.canvas);

		try
		{
			canvas.innerHTML = Ajax.response;
		}
		catch(e)
		{
			Ajax.rotate();
		}

		Ajax.rotate();
	}
}


Ajax.rotate = function()
{
	Ajax.state = "idle";

	if(Ajax.queu.length > 0)
	{
		var A = Ajax.queu[0];
		Ajax.call(A.url, A.callback, A.canvas, A.message);
		Ajax.queu.splice(0,1);
	}
}