/**
 * @author Reto Bisang
 */
function PAjax()
{
	var me = this;
	this._xmlhttp = this.getXmlHttpObject();
	this._loading = false;
	this._enableQueue = false;
	this._queue = [];
	this._currentCallback = null;
	
	this.onreadystatechange = function()
	{
		if (this.readyState == 4 && this.status == 200) {
			me._currentCallback(this.responseText);
			me._loading = false;
			me.processQueue();
		}
	};
}

PAjax.prototype.enableQueue=function enableQueue(enable) {
	this._enableQueue = enable;
};

PAjax.prototype.getXmlHttpObject=function getXmlHttpObject()
{
	if (window.XMLHttpRequest)
	{
		// code for IE7+, Firefox, Chrome, Opera, Safari
		return new XMLHttpRequest();
	}
	if (window.ActiveXObject)
	{
		// code for IE6, IE5
		return new ActiveXObject("Microsoft.XMLHTTP");
	}

	return null;
};

PAjax.prototype.processQueue=function processQueue()
{
	if (this._enableQueue == true && this._queue.length > 0) {
		var currentElement = this._queue[0];
		this._queue.shift();
		
		if (currentElement.t == 1) {
			this.sendGetRequest(currentElement.url, currentElement.cf);
		} else {
			this.sendPostRequest(currentElement.url, currentElement.cf);
		}
	}
};

PAjax.prototype.sendGetRequest=function sendGetRequest(url,callbackFunction)
{
	if (!url) {
		return;	
	}
	
	if (this._xmlhttp)
	{
		if (this._enableQueue == true && this._loading == true) {
			this._queue.push({t:1,url:url, cf:callbackFunction});
			return;
		}

		this._currentCallback = callbackFunction;
		this._loading = true;
		this._xmlhttp.open("GET",url,true);
		this._xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this._xmlhttp.onreadystatechange = this.onreadystatechange;
		this._xmlhttp.send(null);
	}
};

PAjax.prototype.sendPostRequest=function sendPostRequest(url,callbackFunction)
{
	if (!url) {
		return;	
	}
	
	if (this._xmlhttp)
	{
		if (this._enableQueue == true && this._loading == true) {
			this._queue.push({t:2,url:url, cf:callbackFunction});
			return;
		}

		this._currentCallback = callbackFunction;
		this._loading = true;
		this._xmlhttp.open("POST",url,true);
		this._xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		this._xmlhttp.onreadystatechange = this.onreadystatechange;
		this._xmlhttp.send(null);
	}
};