 
// Aditya's little AJAX "library"

function AjaxObject(owner)
{
	this.Parameters = new Array();
	this.Callback = null;
	this.SendResponseToCallback = true;
	this.Owner = owner;
	this.ClassName = "AjaxObject";
	this.Mode = "xml";
}

function AjaxConnection(url)
{
	this.XmlHttpObject = false;
	this.IsBusy = false;
	this.CurrentProcess = false;
	this.ProcessQueue = new Array();
	this.Url = url;
	this.ClassName = "AjaxConnection";
	
	// Creates and returns an AJAX object for the 
	// current browser.
	this.GetAjaxObject = function()
	{
		var x;
		var browser = navigator.appName;
		if(window.ActiveXObject)
		{
			x = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else
		{
			x = new XMLHttpRequest();
		}
		return x;
	}	
	
	// Handles state changes in the request object
	this.HandleStateChange = function()
	{
		if(this.XmlHttpObject.readyState == 4)
		{
			var response = null;
			if(this.CurrentProcess.Mode == "xml")
			{
				response = this.XmlHttpObject.responseXML.documentElement;
			}
			else
			{
				response = this.XmlHttpObject.responseText;
			}
			if(this.CurrentProcess.Callback != null)
			{
				if(this.CurrentProcess.SendResponseToCallback)
				{
					this.CurrentProcess.Callback(response);
				}
				else
				{
					this.CurrentProcess.Callback();
				}
			}
			this.IsBusy = false;
			
			// check if there are any items in the queue
			if(this.ProcessQueue.length > 0)
			{
				this.DoAjax(this.ProcessQueue.shift());
				
				// we dont have to do a for loop on the doAction
				// because each doAction will check 
				// for items in the action queue
			}
			else
			{
				this.CurrentProcess = null;
			}
		}
	}
	
	// Sends an ajax request
	this.DoAjax = function(dataObj)
	{
		if(this.IsBusy)
		{
			this.ProcessQueue.push(dataObj);
			return;
		}
		
		var _this = this;
		
		var date = new Date();
		dataObj.Parameters.push("dummy_param=" + date.getTime());
		var params = dataObj.Parameters.join("&");
		var url = this.Url + "?" + params;
		this.XmlHttpObject = this.GetAjaxObject();
		this.XmlHttpObject.onreadystatechange = function(){_this.HandleStateChange()};
		this.XmlHttpObject.open("GET", url, true);
		this.CurrentProcess = dataObj;
		this.IsBusy = true;	
		this.XmlHttpObject.send(null);
	}
	
}
