var loadingTimeout = null;

var Ajax = {
	url: "",
	setURL: function(url) {
		this.url = url;
	},
	getXMLHttpRequestObject: function() {
		// Browser-nonspecific function to get an XMLHttpRequest object.
		var req = null;
		if (typeof XMLHttpRequest != "undefined")
			req = new XMLHttpRequest();
		if (!req && typeof ActiveXObject != "undefined")
		{
			try
			{
				req=new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (e)
			{
				try
				{
					req=new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (e2)
				{
					try {
						req=new ActiveXObject("Msxml2.XMLHTTP.4.0");
					}
					catch (e3)
					{
						req=null;
					}
				}
			}
		}
		if(!req && window.createRequest)
			req = window.createRequest();
	
		if (!req) alert("Request object instantiation failed.");
		
		return req;
	},

	loadingFunction: function() {},
	doneLoadingFunction: function() {},
	responseFunction: function(sResponse) {},

	callServer: function(ajaxargs) {
		// Sends a XMLHttpRequest to call the ajax command processor
		// on the server.

		var i,r,postData;
		var value;

		if (loadingTimeout)
			clearTimeout(loadingTimeout);
		loadingTimeout = setTimeout("Ajax.loadingFunction();",400);
		postData = "ajax=ajax";
		if (ajaxargs) {
			postData += "&ajaxargs="+encodeURIComponent(ajaxargs);
		}

		r = this.getXMLHttpRequestObject();
		if (!r) return false;
		r.open("POST", this.url, true);
		try
		{
			r.setRequestHeader("Method", "POST " + this.url + " HTTP/1.1");
			r.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		}
		catch(e)
		{
			alert("Your browser does not appear to support asynchronous requests using POST.");
			return false;
		}

		r.onreadystatechange = function() {
			if (r.readyState != 4)
				return "notReady";
			
			if (r.status==200)
			{
				if (r.responseText)
				{
					clearTimeout(loadingTimeout);
					Ajax.doneLoadingFunction();
					Ajax.responseFunction(r.responseText);
					return true;
				} else {
					var errorString = "Error: the response that was returned from the server is invalid.";
					errorString += "\nReceived:\n" + r.responseText;
					alert(errorString);
				}
			}
			else {
				var errorString = "Error: the server returned the following HTTP status: " + r.status;
				errorString += "\nReceived:\n" + r.responseText;
				alert(errorString);
			}
			
			delete r;
			r = null;
			return false;
		}

		r.send(postData);
		delete r;
		return true;
	}
}
