
// **** XMLHttpRequest utilities ***
var ajax={};	// namespace

ajax.READY_STATE_UNINITIALISED=0;
ajax.READY_STATE_LOADING=1;
ajax.READY_STATE_LOADED=2;
ajax.READY_STATE_INTERACTIVE=3;
ajax.READY_STATE_COMPLETE=4;

// create a new XMLHttpRequest object, and link it to a wrapper object.
// (otherwise, the onreadystatechange function can't access the wrapping object)
ajax.initXMLHTTPRequest = function (obj) {
	var xRequest=null;
	if (window.XMLHttpRequest) {
		xRequest=new XMLHttpRequest();
	} else {
		xRequest=new ActiveXObject ("Microsoft.XMLHTTP");
	}
	xRequest.onreadystatechange=function () { 
		obj.onReadyState() ;
	};
	return xRequest;
}

// **** XMLHttpRequest wrapper ****
function xhr(url) {
	this.url=url;
	this.HttpMethod="GET";
	this.params="";		// mainly for POST requests
	this.httpStatus=null;
	this.async=true;
	this.xhr=ajax.initXMLHTTPRequest(this);
}

// event handler for asynchronous handling of the request
xhr.prototype.onReadyState=function () {
	// on successful completion, store result in this.data.
	// depending on http return code, call processData() or httpError()
	var xhr=this.xhr;
	var ready=xhr.readyState;
	// report.say( "ready state is "+ready);
	var data=null;
	if (ready==ajax.READY_STATE_COMPLETE) {
		var status = xhr.status;
		this.httpStatus=status;
		this.data=xhr.responseText;
		if ( status >= 200 && status < 300 ) {
			this.processData();
		} else {
			this.httpError();	
		}
	}
}

// initiate an asynchronous request to the server (url)
xhr.prototype.send=function () {
	// report.say("sending event, async="+this.async);
	this.xhr.open(this.HttpMethod,this.url,this.async);
	this.xhr.setRequestHeader
		("Content-Type", "application/x-www-form-urlencoded");
	this.xhr.send(this.params);
}

// display debugging data on the web-page "consol"
xhr.prototype.report=function () {
	report.say ( "Dump of xhr object: ","purple" );
	for ( key in this ) {
		report.say(key, "green");
		report.say(this[key],"blue");
	}
	report.say( "  dump of XMLHttpRequest object: ","magenta" );
	for ( key in this.xhr ) {
		report.say(key, "green");
	//	report.say(this.xhr[key],"blue"); // you will get an error if you try 
	}
	report.say ( " end dump of XMLHttpRequest object: ","magenta" );
	report.say ( "End dump of xhr object: ","purple" );
}

// process data if successfully retrieved from server
xhr.prototype.processData=function () {
	report.say (" processing data ");
	report.say(this.data);
}

// respond to http error condition
xhr.prototype.httpError=function () {
	report.say (" processing http error ");
}



