var gCSNW_Ajax = new CSNW_Ajax();

function CSNW_Ajax(){
	// This is a singleton object. Catch any attempts to create more and fail
	if( gCSNW_Ajax != null ){
		alert("Attempt to create additional CSNW_Ajax object");
		return null;
	}
	
	this.request = null;
	this.requestObjectType = null;
	this.url = null;
	this.callback = null;
	this.status = 'idle';
};

CSNW_Ajax.prototype.Call = function( url, callback, method, data ){
	
	if( url == null ){
		alert("Attempt to call CSNW_Ajax without URL");
		return false;
	}
	this.url = url;
	
	if( callback == null ){
		alert("Attept to call CSNW_Ajax without callback");
		return false;
	}
	this.callback = callback;
	
	if( ! method ){ method = "GET"; }
	if( (method.toUpperCase() != "POST") && (method.toUpperCase() != "GET") ){
		alert("Invalid method in CSNW_Ajax.Call: "+method);
		return false;
	}
	
	
	try{
		this.GetNewRequestObject();
		this.request.open( method, url, true );
		this.request.onreadystatechange = CSNW_AjaxHandleResponse;
		
		this.request.send(data);
		return true;
		
	}catch(exception){
		callback(false, "Unable to initiate request");
	}
	
	return false;
}

CSNW_Ajax.prototype.GetNewRequestObject = function(){
	if( window.XMLHttpRequest ){
		this.request = new XMLHttpRequest();
	}else if( window.ActiveXObject ){
		if( this.requestObjectType ){
			this.request = new ActiveXObject( this.requestObjectType );
		}else{
			var versions = ["Msxml2.XMLHTTP.7.0", "Msxml2.XMLHTTP.6.0", "Msxml2.XMLHTTP.5.0", "Msxml2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
			for( var i=0; i<versions.length; i++){
				try{
					this.request = new ActiveXObject(version[i]);
					if( this.request ){
						this.requestObjectType = version[i];
						break;
					}
				}catch(exception){alert("Got an IE instantiation error");}
			}
		}
	}
}

CSNW_Ajax.prototype.Complete = function(status, responseData){
	this.callback( status, responseData );
	this.request = null;
}

function CSNW_AjaxHandleResponse(){
	if( gCSNW_Ajax && gCSNW_Ajax.request ){
		if( gCSNW_Ajax.request.readyState == 4 ){
			// We only care about completion
			
			var status = -1000;
			var responseData = 'Unable to communicate with server';
			var responseStatus = false;
			
			try{
				status = gCSNW_Ajax.request.status;
				responseData = gCSNW_Ajax.request.statusText;
			}catch(e){}
			
			if( status == 200 ){
				responseStatus = true;
				responseData = gCSNW_Ajax.request.responseText;
			}else{
				responseData = 'Unable to communicate with server';
				responseStatus = false;
			}
			gCSNW_Ajax.Complete( responseStatus, responseData );
		}
	}
	return true;
}