// object is the backend for AJAX requests

// --- AJAXRequest ----
// Use a single instance of this object on your page to perform as many simultaneous
// requests as you wish.  They will be processed in parallell.
function AJAXRequest ()
{
	this.xmlhttparray = new Array(null);
}


// --- doPost ---
// Posts the provided data to the provided URL.  Calls the provided function when finished
// callback - The function to call when finished.
// URL - The URL to use to make the post.
// data - Data to send.
AJAXRequest.prototype.doPost = function(callback, URL, data)
{
	var i = this.getIdleRequest();
	
	if (this.xmlhttparray[i] != null)
	{
		var ajaxRequest = this;
		
		this.xmlhttparray[i].onreadystatechange = function() { ajaxRequest.processStateChange(i, callback); };
		
	
		this.xmlhttparray[i].open("POST", URL, true);

		this.xmlhttparray[i].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		this.xmlhttparray[i].setRequestHeader("Content-length", data.length);
		this.xmlhttparray[i].setRequestHeader("Connection", "close");
		
		this.xmlhttparray[i].send(data);
	}
}

// --- doGet ---
// Gets the provided URL.  Calls the provided function when finished
// callback - The function to call when finished.
// URL - The URL to use to make the GET.
AJAXRequest.prototype.doGet = function(callback, URL)
{
	var i = this.getIdleRequest();
	
	if (this.xmlhttparray[i] != null)
	{
		var ajaxRequest = this;
		
		this.xmlhttparray[i].onreadystatechange = function() { ajaxRequest.processStateChange(i, callback); };
		
		this.xmlhttparray[i].open("GET", URL, true);
		this.xmlhttparray[i].send(null);
	}
	
}

// --- getIdleRequest ---
// Gets an idle HTTP request object.  This should not be used independantly.
// returns - An index into the xmlhttparray of the request that is safe to use.
AJAXRequest.prototype.getIdleRequest = function()
{
	// find an inactive request object
	for(var i = 0; i < this.xmlhttparray.length && this.xmlhttparray[i] != null; ++i)
	{}

	if ( this.xmlhttparray[i] != null )
	{
		// no idle requests, push a new one onto the array
		i = this.xmlhttparray.push(null) - 1;
	}

	// code for Mozilla, etc.
	if (window.XMLHttpRequest)
	{
		this.xmlhttparray[i] = new XMLHttpRequest();
	}
	// code for IE
	else if (window.ActiveXObject)
	{
		this.xmlhttparray[i] = new ActiveXObject("Microsoft.XMLHTTP");
	}

	return i;
}

AJAXRequest.prototype.processStateChange = function(i, callback)
{
	if(this.xmlhttparray[i].readyState == 4 && this.xmlhttparray[i].status == 200)
	{
		if (this.xmlhttparray[i].responseXML != null && this.xmlhttparray[i].responseXML.hasChildNodes())
		{
			// return as XML
			callback(this.xmlhttparray[i].responseXML);
		}
		else
		{
			// return as text
			callback(this.xmlhttparray[i].responseText);			
		}

		this.xmlhttparray[i] = null;
	}
}
