/* ----------------------------------------------------------------------------
	AJAX
---------------------------------------------------------------------------- */
var DeepAJAX;

Deepend.AJAX = function () {
	var RS_COMPLETE = 4;
	
	// sPath needs to be set
	var sPath; this.sPath = sPath;
	
	// oLoader is the gloabl function to receive the xml
	// only reason for defining the loader as a global variable, is because sOnComplete needs params and it gets overwritten
	var oLoader; this.oLoader;
	
	/*
	Load
	@sScript: Name of the server side script. (Mandatory)
	@sMethod: Defined as "GET" or "POST". (Mandatory)
	@sOnComplete: Destination function when request is completed. (Mandatory)
	@sParam: Param for sOnComplete. TODO - make it possible to do multiple params. (Optional)
	@sSource: Raw XML, JSON or Post Vars. Only needed if sMethod is "POST". (Optional)
	@sOnError: Destination function when request errors. (Optional)
	*/
	this.Load = function(sScript, sMethod, sOnComplete, sParam, sSource, sOnError) {
		var sURL = this.sPath + sScript;
		this.sURL = sURL;
		var sContentType = (sMethod == "POST") ? "application/x-www-form-urlencoded" : null;
		this.sContentType = sContentType;
		this.sOnComplete = (sOnComplete) ? sOnComplete : null;
		this.sParam = (sParam) ? sParam : null;
		this.sSource = (sSource) ? sSource : null;
		this.sOnError = (sOnError) ? sOnError : this.DefaultError;
		
		if (BrowserDetect.browser == "Explorer")
			this.oLoader = new ActiveXObject("Microsoft.XMLHTTP")
		else 
			this.oLoader = new XMLHttpRequest();
		//this.oLoader = new ActiveXObject("Microsoft.XMLHTTP");
		
		
		if (this.oLoader) {
			try {
				var loading = this;
				this.oLoader.onreadystatechange = function() { loading.ReadyState.call(loading); }
				this.oLoader.open(sMethod, sURL, true);
				if (sContentType) this.oLoader.setRequestHeader("Content-Type", sContentType);
				this.oLoader.send(sSource);
			} catch (e) {
				this.sOnError.call(this);
			}
		}
	};
	this.ReadyState = function() {
		var oReq = this.oLoader;
		if (oReq.readyState == RS_COMPLETE)
			if (oReq.status == 200) {
				// TODO - multi params - huge problems
				//DeepAJAX.oLoader = this.oLoader;
				//this.sOnComplete.apply(this, arguments);
				//this.sOnComplete = new Function("return " + this.sOnComplete + ".apply(this, arguments)");
				//this.sOnComplete.call(this, new Function("return " + this.sOnComplete + ".call(null, 1)"));
				if (this.sOnComplete != null) {
					this.sOnComplete.call(this, this.sParam);
				}
			} else
				this.sOnError.call(this);
	};
	this.DefaultError = function() {
		alert("Error Retreiving Data."
			+ "\n\nReadyState: " + this.oLoader.readyState
			+ "\nStatus: " + this.oLoader.status
			+ "\nHeaders: " + this.oLoader.getAllResponseHeaders());
	};
};