var $tipo = {
    XML: 0,
    TEXTO: 1,
    JSON: 2
}
var $metodo =  {
    GET: "GET",
    POST: "POST"
}
function $Ajax(url, opciones) {	
    if (__$P(opciones, "cache", true)==false){
        var caracter = "?";
        if (url.indexOf("?")>0) caracter = "&";
        url += caracter + Math.random();
    }
    var metodo = __$P(opciones, "metodo", $metodo.GET);
    var parametros = __$P(opciones, "parametros");
    var protoOpc = {
        method: metodo,
        onSuccess: __$AjaxRecibir.bind(this, opciones),
        onException: __$AjaxError.bind(this, opciones),
        onFailure: __$AjaxError.bind(this, opciones)
    }
    if (parametros!=undefined) {
        protoOpc.parameters = parametros;
    }
    var peticion = new Ajax.Request(url, protoOpc);
    if (__$P(opciones, "avisoCargando")!=undefined) {
        __$AjaxCargando(opciones.avisoCargando, true);
    }    
    
}
function __$AjaxRecibir(opciones, xhr) {
    if (__$P(opciones, "avisoCargando")!=undefined) {
        __$AjaxCargando(opciones.avisoCargando, false);
    }      
    var funcionRetorno = __$P(opciones, "onfinish");
    var id = __$P(opciones, "id"); 
    if (funcionRetorno!= undefined) {
        var tipoRespuesta = __$P(opciones, "tipoRespuesta", $tipo.TEXTO);
        switch(tipoRespuesta) {
            case $tipo.TEXTO:
                funcionRetorno(xhr.responseText, id);
                break;
            case $tipo.XML:
                funcionRetorno(xhr.responseXML, id);
                break;
            case $tipo.JSON:
                var objeto;
                try {
                    objeto = xhr.responseText.evalJSON();
                } catch (e) {
                    __$AjaxError(opciones, xhr, {
                        code: -1,
                        message: "JSON No válido"
                    });
                    return;
                }
                funcionRetorno(objeto, id);
        }
    }
}
function __$AjaxCargando(cartel, prender) {
    if (prender) {
        $(cartel).className = "msg msgloading";
    } else {        
        $(cartel).className = "msg msghidden";
        //$("success").className = "msg msgsuccess";
    }
}
function __$AjaxError(opciones, xhr, excepcion) {
    if (__$P(opciones, "avisoCargando")!=undefined) {
        __$AjaxCargando(opciones.avisoCargando, false);
    }
    if (excepcion==undefined) {
        excepcion = {
            code: xhr.status,
            message: "Error del servidor"
        }
    }
    var funcionError = __$P(opciones, "onerror");
    if (funcionError!=undefined) {
        funcionError(excepcion, __$P(opciones, "id"));
    }
}
function __$P(coleccion, parametro, defecto) {
    if (coleccion==undefined) {
        return defecto;
    } else {
        if (coleccion[parametro]==undefined) {
            return defecto;
        } else {
            return coleccion[parametro];
        }
    }
}
