/* Libreria AjaxLib version 1.2 */
var PeticionesPage = "PeticionesServer.aspx";
var AjaxLib = {};

/*NAMESPACE */
AjaxLib.comm = {

//Constantes

	XML : "XML",
	TEXTO : "TEXTO",
	JSON : "JSON",


/*Content Type por defecto*/
DEFAULT_CONTENT_TYPE: "application/x-www-form-urlencoded; charset=UTF-8",
/*Opciones para el metodo */
	GET : "GET",
	POST: "POST",

/* Metodos para crear el XHR XMLHTTPREQUEST */
_createXHR : function(){
	  xmlHttp = false;

    /*Mozilla, Safari, ...*/
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
    	try {
			xmlHttp = new XMLHttpRequest();
        } catch(e) {
			xmlHttp = false;
        }
    /*IE*/
    } else if(window.ActiveXObject) {
       	try {
        	xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		xmlHttp = false;
        	}
		}
    }

    return xmlHttp;
},

sendRequest : function(url, opciones){
    //alert("AjaxLib " + url);
	var request = new Object();
	var payload = "";
	var paginaPeticiones = "";
	
	request.method = AjaxLib.comm.GET;
	request.async = true;
	request.preventCache = false;
	request.requestContentType = AjaxLib.comm.DEFAULT_CONTENT_TYPE;
	request.requestContentTransferEncoding = "";
	request.payload = "";
	
	request.method = AjaxLib.comm.GET;
	request.onSucess = function(){};
	request.onfinish = function(){};
	request.onFail = function(){};
	
	
	request.abort = false;
	request.inProgress = false;
	request.received = false;
	
	/*Aplicamos las opciones definidas por el usuario*/
	for(option in opciones) {
		request[option] = opciones[option];
	}
	
	if(request.avisoCargando != undefined){
	    AjaxLib.comm._AjaxCargando(request.avisoCargando ,true);
	}
//	if(request.method.toUpperCase() == "GET"){
//		request.url = url + "?" + request.payload;
//	} else {
//		request.url = url;
//	}
	request.url = PeticionesPage;
	if(request.method.toUpperCase() == "POST"){
		request.postBody = request.payload;
	} else {
		request.postBody = null;
	}
	/* invocamos al metodo request */
	AjaxLib.comm._makeRequest(request);
},

_makeRequest : function(request){
	request.xhr = AjaxLib.comm._createXHR();
	if(!request.xhr){
		return;
	}
	
	request.xhr.open(request.method, request.url, request.async);
	if(request.method.toUpperCase() == "POST"){
		request.xhr.setRequestHeader("Content-Type", request.requestContentType);
		if(request.requestContentTransferEncoding != ""){
			request.xhr.setRequestHeader("Content-Transfer-Enconding",request.requestContentTranferEncoding);
		}
	}

	if(request.preventCache){
		request.xhr.setRequestHeader("if-Modifield-Since","Web, 15 Nov 1995");
	}
	
	if(request.async){
		request.xhr.onreadystatechange = function(){ AjaxLib.comm._handleResponse(request);};
	}
		request.xhr.send(AjaxLib.comm.encodeValue(request.postBody));
		
		if(!request.async){
			AjaxLib.comm._handleResponse(request);
		}
},
	
_handleResponse : function(response){
	response.endtime = (new Date()).getTime();
	response.received = true;
	AjaxLib.comm._handleCallbacks(response);
},

/*Estado de la peticion y devolución del Mensaje */
_handleCallbacks : function(response){
	var status;
	if(response.avisoCargando != undefined){
	    AjaxLib.comm._AjaxCargando(response.avisoCargando ,false);
	}
	/* solo para el firefox */
	try { status = response.xhr.status;} catch(e) {status = 3507;}
	response.inProgress = false;
	if(response.xhr.readyState == 4) {
	    if(status == 200) {
		    if(response.tipoRespuesta != undefined){
		        var respuesta = response.tipoRespuesta;
		        switch(respuesta){
		            case AjaxLib.comm.TEXTO:
		                response.onSucess(response);
		                break;
		            case AjaxLib.comm.XML:
		                response.onSucess(response);
		                break;
		            case AjaxLib.comm.JSON:
		                //Intentamos evaluar el JSON por si no es valido
		                var objeto;
		                try {
		                    //objeto = eval("(" + response.xhr.responseText + ")");
		                    objeto = response.xhr.responseText.evalJSON();
		                }
		                catch(e){
		                    AjaxLib.comm._AjaxError(response,
		                        {
		                            code: -1,
		                            message: "JSON no valido"
		                        }
		                        );
		                 return;
		                 }
		                  response.onSucess(objeto);
		                break;
		       }
		    }
	      } else {response.onSucess(response); }
	}else {
		response.onFail(response, status + " " + response.httpStatusText);
	}
//		response = null;
		
},
/* Si tenemos letrero de cargando lo mostramos o ocultamos */
_AjaxCargando : function(div, visualizar){
        if(visualizar){
            $(div).show();
        }else {
            $(div).hide();
        }
},

HTTPencodeFormData : function(data) {
var pairs = [];
var regexp = /%20/g; // A regular expression to match an encoded space
for(var name in data) {
    var value = data[name].toString();
    // Create a name/value pair, but encode name and value first
    // The global function encodeURIComponent does almost what we want,
    // but it encodes spaces as %20 instead of as "+". We have to
    // fix that with String.replace()
    var pair = encodeURIComponent(name).replace(regexp,"+") + '=' +
    encodeURIComponent(value).replace(regexp,"+");
    pairs.push(pair);
}
// Concatenate all the name/value pairs, separating them with &
return pairs.join('&');
},
encodeValue : function (val)
{
var encodedVal;
if (!encodeURIComponent)
{
encodedVal = escape(val);
/* fix the omissions */
encodedVal = encodedVal.replace(/@/g,"%40");
encodedVal = encodedVal.replace(/\+s/g,"%2F");
encodedVal = encodedVal.replace(/\+/g,"%2B");
}
else
{
encodedVal = encodeURIComponent(val);
/* fix the omissions */
encodedVal = encodedVal.replace(/~/g,"%7E");
encodedVal = encodedVal.replace(/!/g,"%21");
encodedVal = encodedVal.replace(/\(/g,"%28");
encodedVal = encodedVal.replace(/\)/g,"%29");
encodedVal = encodedVal.replace(/'/g,"%27");
}
/* clean up the spaces and return */
return encodedVal.replace(/\%20/g, "+");
}
};/*CERRAMOS EL NAMESPACE*/