function Mob_XMLHTTP_RequestList(max)
{
	this.maxRequests = max;
	this.requestList = new Array(max);
	this.readPos = 0;
	this.writePos = 0;
	for (var i=0; i<max; i++)
		this.requestList[i] = null;
	
	this.get = function()
	{
		if (this.requestList[this.readPos] != null)
		{
			var req = this.requestList[this.readPos];
			this.requestList[this.readPos++] = null;
			if (this.readPos >= this.maxRequests)
				this.readPos = 0;
			return req;
		}
		return null;
	}

	this.set = function(params, URL, handler)
	{
		this.requestList[this.writePos++] = new Array(params, URL, handler);
		if (this.writePos >= this.maxRequests)
			this.writePos = 0;
	}
}

function Mob_XMLHTTP_Request(xmlhttp)
{
	this.requestList = new Mob_XMLHTTP_RequestList(5);
	this.xmlhttp = xmlhttp;
	this.requestPending = false;
	// current handler callback
	this.currentHandler = null;
	
	this.request = function(params, URL, handler)
	{
		if (this.xmlhttp != null)
		{
			// Queue the request
			if (params != null)
				this.requestList.set(params, URL, handler);
			if (this.requestPending == false)
			{
				// No requests are being processed
				var r = this.requestList.get();
				if (r != null)
				{
					this.requestPending = true;
					// Process the request, or the queued one
					this.currentHandler = r[2];
					this.xmlhttp.open("POST", r[1], true);
					// Use a closure
					var helper = this;
					this.xmlhttp.onreadystatechange = function()
					{
						if (helper.xmlhttp.readyState == 4)
						{
							if (helper.currentHandler != null)
								helper.currentHandler(helper.xmlhttp.responseXML, helper.xmlhttp.responseText);
							helper.currentHandler = null;
							helper.requestPending = false;
							// Process the next queued request.
							var fncref = function() { helper.request(null, null, null); }
							window.setTimeout(fncref, 10);
						}
					}
					this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
					this.xmlhttp.send(r[0]);
				}
			}
		}
	}
	
	this.clearQueue = function()
	{
		var r;
		do
		{
			r = this.requestList.get();
		} while (r != null);
	}
}

function Mob_XMLHTTP()
{
	this.init = function()
	{
		this.xmlhttp = null;
		try
		{
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (a)
		{
			try
			{
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (b)
			{
			}
		}
		if (!this.xmlhttp && (typeof XMLHttpRequest != 'undefined'))
		{
			this.xmlhttp = new XMLHttpRequest();
		}
	}
	
	this.init();
	this.requestHandler = new Mob_XMLHTTP_Request(this.xmlhttp);
}

