// JavaScript Document

READY_STATE_UNINITIALIZED=0;

READY_STATE_LOADING=1;

READY_STATE_LOADED=2;

READY_STATE_INTERACTIVE=3;

READY_STATE_COMPLETE=4;

//constructor

function Connection(url, onload, onerror, method, params, contentType)

{

	

	this.url = url;

	this.req = null;

	this.onload = onload;

	this.onerror = (onerror)? onerror:this.defaultError;

	this.SendReceive(url, method, params, contentType);

}



Connection.prototype={

	//SendReceive

	SendReceive:function(url, method, params, contentType)

	{

		if (!method)

		{

			method="GET";

		}

		if (!contentType && method=="POST")

		{

			contentType="application/x-www-form-urlencoded";

		}

		

		

		var msxmlhttp = new Array(

				'Msxml2.XMLHTTP.5.0',

				'Msxml2.XMLHTTP.4.0',

				'Msxml2.XMLHTTP.3.0',

				'Msxml2.XMLHTTP',

				'Microsoft.XMLHTTP');

		for (var i = 0; i < msxmlhttp.length; i++) 

		{

			try

			{

				this.req = new ActiveXObject(msxmlhttp[i]);

				break;

			}

		    catch (e) 

		    {

				this.req = null;

			}

		}

 			

		if(!this.req && typeof XMLHttpRequest != "undefined")

				this.req = new XMLHttpRequest();

		

		if( this.req )

		{

			try

			{

				var loader = this;

								

				this.req.onreadystatechange=function()

					{

						loader.onReadyState.call(loader);

					}

					

				this.req.open(method,url,true);

				

				if (contentType)

				{

					this.req.setRequestHeader("Content-Type", contentType);

				}

				this.req.send(params);

			}

			catch(err)

			{				

				this.onerror.call(this);

			}

		}

	},

	//Refactored call back

	onReadyState:function()

	{

		if( this.req.readyState == 4)//READY_STATE_COMPLETE )

		{

			if( this.req.status == 200 || this.req.status == 0 )

			{

				this.onload.call(this);

			}

			else

			{

				this.onerror.call(this);

			}

		}

	},

	response:function()

	{

		return this.req.responseText;		

	},

	//default error

	defaultError:function()

	{

		alert("error fetching data!"

			+"\n\nreadyState:"+this.req.readyState

			+"\nstatus: "+this.req.status

			+"\nheaders: "+this.req.getAllResponseHeaders());

	}

	

}




