/**
 * @author jordi.touza
 *
 * AJAX Prototype
 * v1
 */

if (typeof(_funky.AJAX) == "undefined") _funky.AJAX = {};
else alert("var name 'AJAX' is already set!");

/**
 * Constructor
 * @param {String} sURL
 * @param {String} sMethod [GET | POST] default POST
 */
_funky.AJAX = function (){

	this.http_request 	= {};
};

/**
 * getXmlHttpObject:
 */
_funky.AJAX.prototype.getXmlHttpObject = function(){

	if (window.ActiveXObject) {   	// IE

		try {

			this.http_request = new ActiveXObject("Msxml2.XMLHTTP");

		} catch(e) {

			try {

				this.http_request = new ActiveXObject("Microsoft.XMLHTTP");

			} catch(e){

				throw new Error ("No es posible crear una instancia XMLHTTP");
			}
		}

	} else if (window.XMLHttpRequest) { // DOM

		this.http_request = new XMLHttpRequest();

		if (this.http_request.overrideMimeType) this.http_request.overrideMimeType('text/xml');
	}

	if (!this.http_request){

		throw new Error ("No es posible crear una instancia XMLHTTP");

		return false;
	}

	return this.http_request;
};

_funky.AJAX.prototype.addPostParam = function(sParams, sParamName, sParamValue){

	if (sParams.length > 0) sParams +="&";

	return sParams + encodeURIComponent(sParamName) + "=" + encodeURIComponent(sParamValue);
};

/**
 *
 * @param {String} sURL
 * @param {String} sMethod
 * @param {Function} onSuccess
 * @param {Function} onError
 * @param {array} params
 *
 */
_funky.AJAX.prototype.request = function (sURL, sMethod, onSuccess, onError, sParams){

	sMethod	= sMethod.toUpperCase() == "POST" ? "POST" : "GET";

	var p 									= this;
	this.onSuccess 							= onSuccess;
	this.onError 							= onError;
	this.http_request 						= this.getXmlHttpObject();
	this.http_request.onreadystatechange 	= function () {p.response();};
	this.http_request.open(sMethod, sURL, true);

	if (sMethod == "POST")

		this.http_request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');

	this.http_request.send(sParams);


};

/**
 * response:
 */
_funky.AJAX.prototype.response = function (){

	if (this.http_request.readyState == 4){

		if (this.http_request.status == 200){ 		// onSuccess

			this.onSuccess(this.http_request);

		} else {									// onError

			this.onError(this.http_request.status);
		}
	}
};