var aReq = new Array();

function Broker(lock) {
	this.locked=lock;
	this.reqtext='';
	if(window.XMLHttpRequest){
		this.oReq=new XMLHttpRequest();
	}
	if(window.ActiveXObject){
		this.oReq=new ActiveXObject("Microsoft.XMLHTTP");
	}
}
function AjaxCall(module, action, Sysobj) {
	var u, dat;
//alert(Sysobj);
	if (!Sysobj) {
		Sysobj = new Object;
//		alert(Sysobj);
	}
	Sysobj.module = module;
	Sysobj.action = action;

	u="/main/php/objcalls.php";
//    settext("curr_info",Sysobj.nm);
// For a Post use this 
//	dat="obj="+JSON.stringify(Sysobj);
// For a Get use this
	var dat=JSON.stringify(Sysobj);
	u=u+"?obj="+dat;
	if (isobj("debugtxt")) {
		appendtext("debugtxt",dat);
	}

//	u="cmd.php?obj="+dat;
	//Let's look for an empty request
	var pos = -1;
	// search the array for an unlocked object
	for (var i=0; i<aReq.length; i++) {
		if (aReq[i].locked == 1) {
			pos = i;
			break;
		}
	}
	// if we couldnt find a spare one
	if (pos == -1) {
		// create a new one, passing in the unlock code = 1
		pos = aReq.length;
		aReq[pos] = new Broker(1);
		if (aReq[pos].oReq==null) {
		   alert ("Browser does not support HTTP Request");
		   return;
		}
	}
	if (aReq[pos].oReq) {
		// set the lock
		aReq[pos].locked = 0;
		// type, url, asynchronous
		aReq[pos].oReq.open("GET", u, true);
//		aReq[pos].oReq.open("POST", u, true);
		// assign an event handler to watch for state changes
		aReq[pos].oReq.onreadystatechange = function() {
			// check if the response is ready to be dealt with

			if (REQ_change(pos)) {
//alert(aReq[pos].oReq.responseText);
				doResponse(aReq[pos].oReq.responseText);
				// unlock the request
				aReq[pos].locked = 1;
			}
		}
//	Bobj = new Object;
//	Bobj.module = "back";
//	Bobj.action = "";

// For a Post use this 
//	dat="obj="+JSON.stringify(Sysobj);
// For a Get use this
//	var d=JSON.stringify(Bobj);
//	u2="../psd/psd.php#back";
//	alert(u2);
//document.getElementById("link_back").src = u;
//		This is for a GET it includes the data as part of the URL
		aReq[pos].oReq.send(null);
//		This is for a POST it seperates the url from the data
		// send it all off and let the event handler do its work
//		aReq[pos].oReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
//		aReq[pos].oReq.send(dat);
	} else {
		alert("Your browser doesn't support HTTP get requests.");
	}
}

function REQ_change(pos) {

	if (typeof(aReq[pos]) != 'undefined' && aReq[pos].locked == 0 && aReq[pos].oReq.readyState == 4 ) {
		// check the headers status : 200 =  OK || 304 = Not Modified
		// some advanced browsers such as opera actually use an http mechanism called "conditional get"
		// which returns a code 304
		try {
			if (aReq[pos].oReq.status == 200 || aReq[pos].oReq.status == 304 || aReq[pos].oReq.status == 0 ) {
				return true;
			} else {
				alert("ERROR: connectivity problems! (State:"+aReq[pos].oReq.status+")");
			}
		}catch(e){
			return false;
		}
	}
	return false;
}


