/* Main Ajax request script
 * 
 * 
 */
var httpRequest = getXmlHttpRequestObject();
httpRequest.onreadystatechange = nextRequest;
var requests = new Array();
var countRequest = 0;

function getXmlHttpRequestObject() {
	var xmlHttp=null;
	try {
	  	// Firefox, Opera 8.0+, Safari, IE7
	  	xmlHttp=new XMLHttpRequest();
	} catch (e) {
		// Internet Explorer 6.0-
		try {
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	if (xmlHttp==null) { alert("Your browser is too old to support AJAX"); }
	return xmlHttp;
}
function doNothing(){}

function AJAXRequest(uri,params,stateChangeFunc,obj) {
	
	//process this ajax request
	requests.push(new Array(uri,params,stateChangeFunc,obj,0));
	if (httpRequest.readyState == 4 || httpRequest.readyState == 0) {
		if(requests.length == 1){
			nextRequest();
		}
	}
}
var ReqCount=0;
function nextRequest(){
	ReqCount++;
    if (httpRequest.readyState == 4 || httpRequest.readyState == 0) { 
//if we're ready to send a request and/or we've recieved a response
    	
    	if (requests[0][4] == 1 && httpRequest.readyState == 4  && httpRequest.status==200){  
//if the request was sent for the current element in the queue array, and we have a response (readystate =  4)
    		if (requests[0][3]==null) {
 //if the specified object in the array is null then call it like a function 
    			requests[0][2]();
                        		} else {
                        			requests[0][2].call(requests[0][3]); 
//otherwise call it as a method of an object using .call()
		              }
    		requests.shift(); 
//delete the first element of requests, and shift the rest up

		               if(requests.length > 0){ 
//if there are more requests
				nextRequest(); 
				
//run the next request (the next item in the queue)
		               }
		               
	     }else{
	    	 
	                httpRequest.open("POST", requests[0][0], true); 
	                httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      				httpRequest.setRequestHeader("Content-length", requests[0][1].length);
      				httpRequest.setRequestHeader("Connection", "close");	                	
	 				
//specifies the next request as the 'current' (requests[0]) item in the queue 
                        	httpRequest.send(requests[0][1]);
//sends the request
                  httpRequest.onreadystatechange = nextRequest;
	    
//if the readystate changes then changes then call this function again
              	requests[0][4] = 1;  
              	 	
//set the state to ready for the next request
              	
              	//debug
              	//if(requests[0]){ document.getElementById('debug').innerHTML+=ReqCount+': '+requests[0][1]+'; queue:'+requests.length+'<br/>'; }
		}
     
     }
   
}
