var g_xmlHttpRequester = new xmlHttpRequester();

function xmlHttpRequester()
{
	this.classname="xmlHttpRequester";
	this.elements = new Array();
	this.nextFree = false;
}

xmlHttpRequester.contentType = 
{
		XML : "text/xml",
		TEXT: "text/text"
}

xmlHttpRequester.message = 
{
	OK 		: "#OK",
	TIMEOUT : "#SESSION_TIMEOUT",
	ERR		: "#ERROR:"
}

xmlHttpRequester.prototype.getFreeElement = function()
{
	var res;
	for(var i=0; i<this.elements.length && !res;i++)
		res = this.elements[i].busy ? null : this.elements[i];
	return res;
}

xmlHttpRequester.prototype.getElement = function()
{
	var elm = this.getFreeElement();
	if(!elm)
	{
		elm = new xmlHttprequesterElement(this.elements.length);
		this.elements[this.elements.length] = elm;
	}
	return elm;
}

xmlHttpRequester.prototype.load = function (url,fct,elmlnk,sync)
{
	var elm  = this.getElement();
	return elm.load(url,fct,elmlnk,sync);	
}

xmlHttpRequester.prototype.post = function (url,type,doc,fct,elmlnk,sync)
{
	var elm  = this.getElement();
	elm.post(url,type,doc,fct,elmlnk,sync);	
}

function xmlHttprequesterElement(idx)
{
	this.classname="xmlHttprequesterElement";
	this.busy = false;
	this.idx = idx;
	this.onLoadFct = eval("fct = function(){g_xmlHttpRequester.elements["+ idx +"].getResponse();}");
}

xmlHttprequesterElement.prototype.checkResponse = function(dom)
{
	var ret = false;
	var txt = this.xmldoc.responseText;
	if(txt == xmlHttpRequester.message.TIMEOUT)
		window.location.reload(true);
	else if(txt == xmlHttpRequester.message.ERR)
		alert(txt);
	else if(this.fct)
		ret = true;
		
	if(ret)
		this.fct(txt,dom,this.elm);
}

		

xmlHttprequesterElement.prototype.load = function(url,fct,elmlnk,sync)
{
	this.url = url;
	this.fct = fct;
	this.elm = elmlnk;
	this.busy = true;
	this.initXmlDoc(sync);
	//to force the reload (IE put the XML in the cache)
	if(url.indexOf("?")<0)
		url+="?_date_="+new Date();
	else
		url+="&_date_="+new Date();
	this.xmldoc.open("GET", url , sync ? false : true);
	this.xmldoc.send(null);
	
	if(sync) this.getResponse();
}

xmlHttprequesterElement.prototype.post = function(url,type,doc,fct,elmlnk,sync)
{
	this.url = url;
	this.fct = fct;
	this.elm = elmlnk;
	this.busy = true;
	this.initXmlDoc(sync);
	//to force the reload (IE put the XML in the cache)
	if(url.indexOf("?")<0)
		url+="?_date_="+new Date();
	else
		url+="&_date_="+new Date();
	this.xmldoc.open("POST", url , true);
	this.xmldoc.setRequestHeader("Content-Type",type);
	try{this.xmldoc.send("<?xml version='1.0' encoding='UTF-8'?>"+doc);}catch(e){alert(e.toString());}
	if(sync) this.getResponse();
}
