/*
* Description: Request class which encapsulates XMLHttpRequest calls
* Author:      Kirill Volkov
* Date:        2006-07-06
*/

//constructor
function Request(url)
{
	this._url = url; //url of the server script
	this._xhr = this._createXMLHttpRequest(); //XMLHttpRequest object
	this._response = null; //response of the server script
	
	var _this = this; //allows to call _processChange with correct scope
	this._xhr.onreadystatechange = function() { _this._processChange(); };
}

//callback for when the the server script responds
Request.prototype._processChange = function()
{
	//if complete
	if (this._xhr.readyState == 4)
	{
		//if "OK"
		if (this._xhr.status == "200")
		{
			this._response = this._xhr.responseXML.documentElement;
			
			//handler defined by the client
			if (this.onReady)
				this.onReady();
		}
		else
		{	
			//handler defined by the client
			if (this.onError)
				this.onError();
		}
		
		//clean up
		delete this._xhr;
	}
}

//returns browser specific XMLHttpRequest object
Request.prototype._createXMLHttpRequest = function()
{
	var xhr;

	//native XMLHttpRequest object
	if (window.XMLHttpRequest)
	{
		xhr = new XMLHttpRequest();
	}
	//IE ActiveX version
 	else if (window.ActiveXObject)
	{
		try
		{
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
			}
		}
	}
	return xhr;
}

//opens the url
Request.prototype.load = function()
{
	var str; //append to url to prevent caching
	if (this._url.indexOf("?") >= 0)
		str = "&";
	else
		str = "?";
	var d = new Date;
	str += "time=" + d.getTime();

	this._xhr.open("GET", this._url + str, true);
	this._xhr.send(null);
}

//returns response received from the server script
Request.prototype.getResponse = function()
{
	return this._response;
}

//returns value contained in <return> tag of the response
Request.prototype.getResult = function()
{
	if (this._response)
		return this._response.getElementsByTagName("return")[0].firstChild.nodeValue;
	else
		return -1;
}

