
/* 
	Async Request support 

		after "Ajax in Action", p74-75 

	usage:
	
	var loader = new asyncRequest.ContentLoader('mydata.xml', parseMyData [,myErrorHandler])


see also:

http://www-128.ibm.com/developerworks/webservices/library/j-ajax1/

for a dumb parser...
		
*/
var asyncRequest=new Object();

// load events
asyncRequest.READY_STATE_UNITIALIZED=0;
asyncRequest.READY_STATE_LOADING=1;
asyncRequest.READY_STATE_LOADED=2;
asyncRequest.READY_STATE_INTERACTIVE=3;
asyncRequest.READY_STATE_COMPLETE=4;

// constructor (invokes request)
asyncRequest.ContentLoader = function(url, onload, onerror){
	this.url = url;
	this.req=null;
	this.onload=onload;
	this.onerror=(onerror) ? onerror : this.defaultError;
	this.LoadXMLDoc(url);
}

//
asyncRequest.ContentLoader.prototype = {
	LoadXMLDoc:function(url) {


		this.req = null;

		if (window.XMLHttpRequest) {
			this.req = new XMLHttpRequest();
		}
		else {
			if (window.ActiveXObject) {
				try {
					/* newer IE */
					this.req = new ActiveXObject("Msxml2.XMLHTTP")
				}
				catch (e1) {	
					this.req = null;
				}
				if (!this.req) {
					try {
						/* older IE */
						this.req = new ActiveXObject("Microsoft.XMLHttp");
					}
					catch (e2) {
						this.req = null;
					}	
				}	
			}
		}
		

		if (this.req) {
			try {
				// is this a copy, or a reference? 
				var loader = this;
				
				this.req.onreadystatechange = function () {
					loader.onReadyState.call(loader);
				}
				
				this.req.open('GET', url, true);
				this.req.send(null);
			}
			catch (e3) {
				this.onerror.call(this);
			}
		}
	},
	
	//Callbacks 
	
	onReadyState:function () {
		
		var req = this.req;
		var ready = req.readyState;
		
		if (ready == asyncRequest.READY_STATE_COMPLETE) {
			var httpStatus = req.status;
			if (httpStatus == 200 || httpStatus == 0) {
				this.onload.call(this);	
			}
			else {
				this.onerror.call(this);
			}
		}
	},
	
	
	// this really isn't an acceptable production intent implementation 
	defaultError:function() {
		
		alert("error fetching data."
			+"\n\nreadyState:" + this.req.readyState
			+"\nstatus:" + this.req.status
			+"\nheaders:" + this.req.getAllResponseHeaders());
	}
}