
/**
    Encapsulates Ajax requests.
    @param string method the submission method
    @param string action the url to submit the data to
    @optional param function(request, dataTransferObj) successDelegate the success delegate
    @optional param function(request, dataTransferObj) failDelegate the fail delegate
    @optional param DataTransferObj dataTransferObj a derived object of DataTransferObj.
    @return AjaxObj
*/

function AjaxObj(method, action){
    this.getRequest = AjaxObj_getAjaxRequest;
    
    var rnd = Math.floor(Math.random() * 98563258963);
    if(action.indexOf('?') >= 0) action += '&' + rnd + '=' + rnd;
    else action += '?' + rnd + '=' + rnd;

    var onSuccess = (AjaxObj.arguments.length > 2 ? AjaxObj.arguments[2] : null);
    var onFail = (AjaxObj.arguments.length > 3 ? AjaxObj.arguments[3] : null);
    var data = (AjaxObj.arguments.length > 4 ? AjaxObj.arguments[4] : null);
    
    var request = this.getRequest();
   	if(!request || request == null){
   	    alert('Unable to create XMLHTTP Instance.');
   	    return;
    }
    
    request.onreadystatechange = function() {
        if(request.readyState == 4){
            if(request.status == 200){
                if(onSuccess) onSuccess(request, data)
            }
            else if(request.status >= 400){
                if(onFail) onFail(request, data);
                else alert('Your submission failed. Status: ' + request.status);
            }
        }
        
    }
    request.open(method, action, true);
    request.send(null);
    
    return this;
}

function AjaxObj_getAjaxRequest()
{
    var httpRequest = null;
	
	if(window.ActiveXObject){ // IE
		try{
			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}catch(ex1){
			try{
				httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}catch(ex2) { }
		}
	}
	else if(window.XMLHttpRequest){ // Mozilla, Safari,...
		httpRequest = new XMLHttpRequest();
		if(httpRequest.overrideMimeType) httpRequest.overrideMimeType('text/xml');
	} 
	
    return httpRequest;
}

/**
    Interface
    Implement this object as necessary to transfer data from request to response.

*/
function DataTransferObj(){

}
