var AJAX_Objects = [];

function AJAXConnection( onreadystate )
{
	this.error = AJAX_Error;
	this.index = AJAX_Objects.length;
	this.conn = null;
	
	if ( window.XMLHttpRequest ) this.conn = new XMLHttpRequest();
	else if ( window.ActiveXObject )
	{
		try {
			this.conn = new ActiveXObject("MSXML2.XMLHTTP.3.0");
		} catch(e) {
			try {
				this.conn = new ActiveXObject("MSXML2.XMLHTTP");
			} catch(e) {
				try {
					this.conn = new ActiveXObject("Microsoft.XMLHTTP");
				} catch(e) {
					this.error("Could not initialize Microsoft's XMLHTTP connection object.", e);
					return( null );
				}
			}
		}
	}
	
	// data member variables
	this.data = null
	this.xml = null;
	this.readystate_intv = null;
	this.is_open = false;				// true if there is an active connection
	
	// data member methods
	this.send = AJAX_Send;
	this.checkReadyState = AJAX_CheckReadyState;
	
	// custom, scriptable events
	this.onSuccess = undefined;
	this.onBadStatus = undefined;
	this.onError = undefined;
	
	if ( typeof onreadystate == "function" && this.conn )
		this.conn.onreadystatechange = onreadystate;
	
	AJAX_Objects[ this.index ] = this;
}

function AJAX_Send(method, url, async, data)
{
	method = method.toUpperCase();
	
	this.conn.open( method , url , async );
	this.is_open = true;
	
	if ( method == "POST" )
	{
		this.conn.setRequestHeader(
			"Content-Type" ,
			"application/x-www-form-urlencoded; charset=UTF-8"
		);
		
		if ( data && data.toString().length > 0 )
			this.conn.send( data );
	} else
		this.conn.send( null );

	if ( typeof this.conn.onreadystatechange != "function" )
		this.readystate_intv = setInterval("AJAX_Objects["+ this.index +"].checkReadyState()", 5);
}

function AJAX_CheckReadyState()
{
	if ( this.conn.readyState == 4 )
	{
		this.is_open = false;
		
		if ( this.readystate_intv != null )
		{
			clearInterval( this.readystate_intv );
			this.readystate_intv = null;
		}
		if ( this.conn.status == 200 )
		{
			this.data = this.conn.responseText;
			this.xml = this.conn.responseXML;
			
			if ( typeof this.onSuccess == "function" )
				this.onSuccess();
			
			return( true );
		} else {
			if ( typeof this.onBadStatus == "function" )
				this.onBadStatus( this.conn.status );
			else
				this.error("Connection failed, HTTP Status is: "+ this.conn.status);
		}
	}
	return( false );
}

function AJAX_Error( strError , errObj )
{
	if ( typeof this.onError == "function" )
		this.onError( strError , errObj )
	else
		throw( strError );
}