/**
 *  Ajax class to create, manage and process XMLHttpRequests
 */

/**
 *  Ajax class constructor
 *
 *  param	string	element			the element to use for processing
 *  param	string	rpc				the url to call to get new content
 */
function Ajax( sElement, sRPC )
{
	// hook the class to the window scope
	// now we can access the class by window.$_Ajax
	window[ "$_Ajax" ] = this;
	// initialize stuff
	this._rpc = sRPC;
	this.init( sElement );
}

/**
 *  Ajax initialiser. Creates XMLHttpRequest object and adds an onreadychangestate method
 *
 *  param	string	element			the element to use for processing
 */
Ajax.prototype.init = function( sElement )
{
	// try to create an XMLHttpRequest object
	try
	{
		// Opera >=8.0, Mozilla, Webkit
		this._request = new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			this._request = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			try
			{
				this._request = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				// still doesn’t work
				this._request = null;
			}
		}
	}
	// if we have an XMLHttpRequest object
	// add a method for if the state changes
	if( this._request )
		this._request.onreadystatechange = function()
		{
			// get the ready state.
			// IE6 doesn't know which scope we are in, so get it from the window scope
			var nReadyState = this.readyState ? this.readyState : window.$_Ajax._request.readyState;
			// get the required target element
			var oElement = document.getElementById( sElement );
			// if the target element does not exist, fail
			if( !oElement )
				return false;
			// if the request is completed
			if( nReadyState == 4 )
			{
				// just add the response to the element
				// same scoping problem as before
				oElement.innerHTML = this.responseText ? this.responseText : window.$_Ajax._request.responseText;
				//window.$_Ajax.appendContent( 'sElement' );
				window.$_Ajax.init( sElement );
			}
		}
}

/**
 *  Ajax call
 *
 *  param	string	query	optional	the query sting (if any) to append to the url
 */
Ajax.prototype.call = function( sQuery )
{
	// if there's no query that's fine
	// but we need one, so create it
	if( !sQuery )
		var sQuery = null;
	// make the call
	this._request.open("GET", this._rpc + ( sQuery ? "?" + sQuery : "" ), true);
	// send data
	this._request.send(null);

}

/*

Don't forget to load the class in the document's onload eh

document.onload = function()
{
	new Ajax( "string element", "string rpc url" );
}

*/
