﻿/**
* @version = 0.1.20080823
* @date = 23/08/2008
*/

function $(parametros) {
    return document.getElementById(parametros);
};


function HttpRequest(url, funcionRetorno, parametrosFuncionRetorno, tipoResultado, metodo, asincrono, objeto, parametrosPost, deserializar) {
    if (parametrosPost == "undefined" || !parametrosPost) {
        parametrosPost = null;
    }

    var PeticionHttp = null;
    var Salida = null;

    if (window.XMLHttpRequest) {
        PeticionHttp = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        PeticionHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
        return;
    }

    if (PeticionHttp) {
        PeticionHttp.onreadystatechange = function() {
            if (PeticionHttp.readyState == 4) {
                if (PeticionHttp.status == 200) {
                    if (funcionRetorno != "") {
                        var Respuesta = null;
                        switch (tipoResultado) {
                            case "XML":
                                Respuesta = PeticionHttp.responseXML;
                                break;
                            default:
                                Respuesta = PeticionHttp.responseText;
                                break;
                        }
                        eval(funcionRetorno + "(Respuesta,parametrosFuncionRetorno,objeto);");
                        return;
                    }
                    else {
                        switch (tipoResultado) {
                            case "XML":
                                Salida = PeticionHttp.responseXML;
                                break;
                            default:
                                Salida = PeticionHttp.responseText;
                                break;
                        }
                    }
                }
            }
        };

        if (metodo == "POST") {
            PeticionHttp.open("POST", url, asincrono);
            PeticionHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
            PeticionHttp.send(parametrosPost);
        }
        else {
            PeticionHttp.open("GET", url, asincrono);
            PeticionHttp.send(null);
        }

        if (!asincrono) {
            switch (tipoResultado) {
                case "XML":
                    Salida = PeticionHttp.responseXML;
                    break;
                default:
                    Salida = PeticionHttp.responseText;
                    break;
            }
            if (PeticionHttp.status != 200) {
                return Salida;
            }
        }
        try {
            return Salida;
        }
        finally {
            Salida = null;
        }
    }
};

var grAjax = new Object();
grAjax.asincrono = false;
grAjax.funcionRetorno = "";
grAjax.cache = false;

grAjax.getUrl = function(url) {
    var Sep = (url.indexOf("?") > -1 ? "&" : "?");
    var Salida = HttpRequest(url + (this.cache ? "" : Sep + "rndAjax=" + Math.random()), this.funcionRetorno, null, "TXT", "GET", this.asincrono, this, null, true);
    try {
        return Salida;
    }
    finally {
        Salida = null;
    }

};





var grEncodingTools = {

    //booleano para el navegador actual
    browser: {
        IE: !!(window.attachEvent && !window.opera),
        Opera: !!window.opera,
        WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
        Gecko: navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1,
        MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)
    },

    //Manera eficiente de insertar HTML en una capa para IE
    addHTML: function(id, html) {
        if (id && html) {
            if (this.browser.IE) {
                document.getElementById(id).insertAdjacentHTML("afterBegin", html);
            }
            else {
                document.getElementById(id).innerHTML += html;
            }
        }
    },

    // private method for UTF-8 encoding
    utf8Encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    utf8Decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

};

var DivCarga = DivCarga ? DivCarga : {

    //Id del div de carga
    idDivCarga: "idCapaCargando",

    //Muestra la imagen de carga solo si existe. Sumamos uno al contador, para indicarlo cuanso se oculte la imagen    
    Mostrar: function() {
        var divCargando = document.getElementById(this.idDivCarga);
        if (divCargando != null) {
            /*divCargando.style.top = this.GetScrollTop() + (this.GetClientHeight() / 3);
            if (parseInt(divCargando.style.top) < 200)
                divCargando.style.top = "200px";
            divCargando.style.left = this.GetScrollLeft() + (this.GetClientWidth() / 2);*/
            divCargando.style.display = "block";
        }
    },

    //Oculta el div de carga si existe. Pero solo cuando el contador de módulos está a 0
    Ocultar: function() {
        var divCargando = document.getElementById(this.idDivCarga);
        if (divCargando != null) {
            divCargando.style.display = "none";
        }
    },

    //Obtiene la anchura del cliente
    GetClientWidth: function() {
        return this.f_filterResults(
		    window.innerWidth ? window.innerWidth : 0,
		    document.documentElement ? document.documentElement.clientWidth : 0,
		    document.body ? document.body.clientWidth : 0
	    );
    },

    //Obtiene la altura del cliente
    GetClientHeight: function() {
        return this.f_filterResults(
		    window.innerHeight ? window.innerHeight : 0,
		    document.documentElement ? document.documentElement.clientHeight : 0,
		    document.body ? document.body.clientHeight : 0
	    );
    },

    //Obtiene la medida desde el lado izquierdo hasta la posición del scroll horizontal
    GetScrollLeft: function() {
        return this.f_filterResults(
		    window.pageXOffset ? window.pageXOffset : 0,
		    document.documentElement ? document.documentElement.scrollLeft : 0,
		    document.body ? document.body.scrollLeft : 0
	    );
    },

    //Obtiene la medida desde arriba hasta la posición del scroll vertical
    GetScrollTop: function() {
        return this.f_filterResults(
		    window.pageYOffset ? window.pageYOffset : 0,
		    document.documentElement ? document.documentElement.scrollTop : 0,
		    document.body ? document.body.scrollTop : 0
	    );
    },

    //Obtiene la medida especificada para todos los navegadores
    f_filterResults: function(n_win, n_docel, n_body) {
        var n_result = n_win ? n_win : 0;
        if (n_docel && (!n_result || (n_result > n_docel))) {
            n_result = n_docel;
        }
        return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
    }
};

String.prototype.toSentenceCase = function() {
    var str = "";
    var SentenceBrake = true;
    for (var i = 0; i < this.length; i++) {
        str += SentenceBrake ? this.charAt(i).toUpperCase() : this.charAt(i).toLowerCase();
        SentenceBrake = (SentenceBrake && this.charCodeAt(i) <= 32) || "\r\n.,?:;!".indexOf(this.charAt(i)) != -1;
    }
    return str;
};

function ArrayContains(array, elemento) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == elemento) {
            return true;
        }
    }
    return false;
};

String.IsNullOrEmpty = function(value) {
    if (value) {
        if (typeof (value) == 'string') {
            if (value.length > 0)
                return false;
        }
    }
    return true;
};

//Comprueba si un objeto tiene la propiedad display a block (true) o none (false)
if (!checkDisplay) var checkDisplay = function(myObj) {
    /*if (!isNullOrUndefined(myObj)) {
        if (myObj.style.display == 'block')
            return true;
    }
    return false;*/
    return (isNullOrUndefined(myObj) || myObj.style.display != 'none');
};

//Comprueba si un objeto existe
if (!isNullOrUndefined) var isNullOrUndefined = function(myObj) {
    return (typeof (myObj) == 'undefined' || myObj == null);
};

//Deshabilita un objeto button
if (!disableButton) var disableButton = function(myObj) {
    if (!isNullOrUndefined(myObj)) {
        myObj.style.opacity = "0.4";
        //Por problemas con ClearType, en IE se obvia la opacidad
        /*myObj.style.filter = "alpha(opacity=40)";*/
        myObj.disabled = true;
        myObj.style.cursor = "default";
    }
};

//Habilita un objeto button
if (!enableButton) var enableButton = function(myObj) {
    if (!isNullOrUndefined(myObj)) {
        myObj.style.opacity = "1";
        //Por problemas con ClearType, en IE se obvia la opacidad
        /*myObj.style.filter = "alpha(opacity=100)";*/
        myObj.disabled = false;
        myObj.style.cursor = "pointer";
    }
}; 

//Clona un objeto
function clone(obj) {
    if (obj == null || typeof (obj) != 'object')
        return obj;

    var temp = new obj.constructor(); // changed (twice)
    for (var key in obj)
        temp[key] = clone(obj[key]);

    return temp;
};

//Convierte una cadena en un valor Boolean.
//El valor por defecto es false
function stringToBool(str) {
    if (!String.IsNullOrEmpty(str)) {
        if (str.toLowerCase() == "true")
            return true;
        else
            return false;
    }
    else
        return false;
};

function getDocHeight() {
    var D = document;
    return Math.max(
        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
    );
};

//Creo el objeto JSON si no existe
if (!JSON) var JSON = {};
//Convierte un objeto JSON en una cadena
JSON.stringify = function(obj) {

    var t = typeof (obj);
    if (t != "object" || obj === null) {

        // simple data type
        if (t == "string") obj = '"' + obj + '"';
        return String(obj);

    }
    else {

        // recurse array or object
        var n, v, json = [], arr = (obj && obj.constructor == Array);

        for (n in obj) {
            v = obj[n]; t = typeof (v);

            if (t == "string") {
                v = '"' + v + '"';
                json.push((arr ? "" : '"' + n + '":') + String(v));
            }
            else if (t == "object" && v !== null) {
                v = JSON.stringify(v);
                json.push((arr ? "" : '"' + n + '":') + String(v));
            }

        }
        return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
    }
};


//Se redefinen los alerts
/*if (document.getElementById) {
    window.alert = function(txt) {
        OpenCustomAlert(txt);
    }
};*/

function OpenCustomAlert(txt) {    
    
    //Establezco el ancho y alto de la máscara
    $("modalMask").style.width = document.body.scrollWidth;
    $("modalMask").style.height = document.body.scrollHeight;

    //Establezco el texto del alert
    $("txtModalAlert").innerHTML = txt;
    
    //Muestro la máscara y el alert
    showElement("modalMask");
    showElement("modalAlert");
    
    //Centro el alert en la ventana
    $("modalContainer").style.top = "-" + ($("modalAlert").offsetHeight / 2) + "px";
    $("modalContainer").style.left = "-" + ($("modalAlert").offsetWidth / 2) + "px";

    //Enfoco el botón del alert
    $("btnModalAlert").focus();
};

function CloseCustomAlert() {
    hideElement("modalMask");
    hideElement("modalAlert");
};

//Si se pulsa la tecla escape se cierra la ventana modal
function CustomAlertEscape(e) {
    try {
        var key = 0;

        if (window.event && window.event.keyCode) {
            key = window.event.keyCode;
        }
        else if (e && e.keyCode) {
            key = e.keyCode;
        }

        if (key == 27)
            CloseCustomAlert(); 
    }
    catch (ex) {
        manageException(ex);
    }
};

window.onresize = function() {
    //Establezco el ancho y alto de la máscara del alert
    if ($("modalMask") != null && typeof ($("modalMask")) != "undefined") {
        $("modalMask").style.width = document.body.scrollWidth;
        $("modalMask").style.height = document.body.scrollHeight;
    }
};

