// JavaScript Document
function ajaxConnection( caller, url ){
	this.xmlRequestObj = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	this.connection_parameters = new Object();
	this.url = url;
	this.handler = caller;
}

ajaxConnection.prototype.initRequestObject = function(){
	var _this = this;
	this.xmlRequestObj = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
	this.xmlRequestObj.onreadystatechange = function(){ _this.parseResponse() };
	this.connection_parameters = new Object();
}

ajaxConnection.prototype.addVariable = function( name, value ){
	this.connection_parameters[name] = value;
}

ajaxConnection.prototype.execute = function(){
	var reqID = Math.floor(Math.random()*1000001);
	var params = "reqID=" + reqID ;
	for( var key in this.connection_parameters ){
		params += "&" + key + "=" + this.connection_parameters[key];
	}
	
	this.xmlRequestObj.open( "POST", this.url, true );
	
	this.xmlRequestObj.setRequestHeader("DatPiff-Ajax", "true");
	this.xmlRequestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	this.xmlRequestObj.setRequestHeader("Content-length", params.length);
	this.xmlRequestObj.setRequestHeader("Connection", "close");

	
	this.xmlRequestObj.send(params);
}

ajaxConnection.prototype.parseResponse = function(){
	if ( this.xmlRequestObj.readyState == 4 ){
		if( this.xmlRequestObj.status == 200 || this.xmlRequestObj.status == 304 ){
			var resultXML = this.xmlRequestObj.responseXML;
			//alert( this.xmlRequestObj.responseText );
			
			// TODO - we need to see if the node returned is an error (due to not being logged in or some other error)
			// TODO - parse for server comments like redirect, alert?
			try{
				var node = resultXML.getElementsByTagName( "DatPiff-Response" )[0];
				//var node = resultXML.firstChild;
				var action = node.getAttribute( "action" );
				var status = node.getAttribute( "status" );
				
				this.handler.processXMLResponse( resultXML, action, status );
			}catch( err ){
			}
		}else if( this.xmlRequestObj.status == 408 ){
			//10.4.9 408 Request Timeout
			//The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time. 
			this.execute();
			// We may want to notify the caller
		}
	}
}
