READY_STATE_UNINITIALIZED = 0;
READY_STATE_LOADING = 1;
READY_STATE_LOADED = 2;
READY_STATE_INTERACTIVED = 3;
READY_STATE_COMPLETE = 4;

function Ajax( url, params, onload, onerror ) {

	this.url = url;
	this.params = params;
	this.onload = onload;
	this.onerror = onerror;
	this.req = this.getXMLHttpRequest();
	var ajax = this;
	this.req.onreadystatechange = function() {

		ajax.onReadyStateChange.call( ajax );
	}

	this.sendRequest();
}

Ajax.prototype.getXMLHttpRequest = function() {

	if ( window.XMLHttpRequest ) {

		return new XMLHttpRequest();
	} else if ( window.ActiveXObject ) {

		return new ActiveXObject('Microsoft.XMLHTTP');
	} else {
	
		return false;
	}
}

Ajax.prototype.sendRequest = function() {

	// create params string
	var paramsString = '';
	var i = 0;
	for ( var key in this.params ) {
	
		paramsString += (
				i ? '&' : ''
			) + key + '=' + this.params[ key ]
		;
		
		i++;
	}

	try {
		this.req.open( 'POST', this.url, true );
		this.req.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
		this.req.send( paramsString );
	} catch( e ) {

		if ( this.onerror ) {

			this.onerror();
		}
	}
}

Ajax.prototype.onReadyStateChange = function() {

	if (
		( this.req.readyState == READY_STATE_COMPLETE ) &&
		(
			( this.req.status == 200 ) ||
			( this.req.status == 0 )
		)
	) {

		if ( this.onload ) {
			this.onload();
		}
	} else {
	
		if ( this.onerror ) {
			
			this.onerror();
		}
	}
}
