/**
 * Ajax Request Class
 * Make ajax requests and include callback functions
 * @param url(String) - php script to call
 * @param params(String) - list of parameters for the php file (automatically adds none caching param)
 * @param method(String) - method request type (GET or POST)
 * @param datatype(String) - type of data to receive in server response (TEXT, XML, or, JSON)
 * @param callbacks(Object) - callbacks functions to trigger at different states in the request (onLoading, onSuccess, onFailure)
 */

Inventure.AjaxRequest = function(url, params, method, datatype, callbacks)
{
	//Ajax properties
	this.url = url;
	this.params = params;
	this.method = method;
	this.datatype = datatype;
	this.callbacks = callbacks;
	
	//Open and send request
	this.transport = this.getTransport();
	
	if(!this.method || this.method.toUpperCase() == "GET"){
		this.transport.open(this.method, this.url+"?"+this.params+"&sid="+new Date().getTime(), true);
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		this.transport.send(null);			
	}else{
		this.transport.open(this.method, this.url, true);
		this.transport.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		this.transport.setRequestHeader("Content-length", this.params.length);
		this.transport.setRequestHeader("Connection", "close");
		this.transport.onreadystatechange = this.onStateChange.bind(this);
		this.transport.send(this.params);
	}
}

Inventure.AjaxRequest.prototype = {
	
	//Get the request object
	getTransport : function()
	{
		try
		{
			return new XMLHttpRequest();
		}
		catch (trymicrosoft)
		{
			try
			{
				return new ActiveXObject("Msxm12.XMLHTTP");
			}
			catch (othermicrosoft)
			{
				try
				{
					return new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (failed)
				{
					return null;
				}
			}
		}
	},
	
	//Trigger callbacks on request state change
	onStateChange : function()
	{
		if(this.transport.readyState != 4)
		{
			if(this.callbacks.onLoading)
				this.callbacks.onLoading();	
		}
		else
		{				
			if(this.transport.status == 200)
			{		
				switch(this.datatype)
				{
					case("text"):
						this.response = this.transport.responseText;
					break;
					case("xml"):
						this.response = this.transport.responseXML;
					break;
					case("json"):
						this.response = (this.transport.responseText).parseJSON();
					break;
				}
				
				this.callbacks.onSuccess(this.response);	
			}
			else
			{
				if(this.callbacks.onFailure)
					this.callbacks.onFailure(this.transport.responseText);	
			}
		}
	}
}		



