﻿// FUNCIONES UTILITARIAS EN JAVASCRIPT

function VValidate(NameValidate, validationGroup) {
    var i;
    for (i = 0; i < Page_Validators.length; i++) {
        var validator = Page_Validators[i];
        if (validator.id == NameValidate) {
            ValidatorValidate(validator, validationGroup, null);
        }
    }
}

function CtrValidate(NameControl) {
    var targetedControl;
    var i;
    var vals;
    targetedControl = document.getElementById(NameControl);
    if (typeof (targetedControl.Validators) != "undefined") {
        vals = targetedControl.Validators;

        for (i = 0; i < vals.length; i++) {
            ValidatorValidate(vals[i], '', null);
        }
    }
}
//Agrega punto y coma al nStr "Formato de moneda de 1234567.00 a 1,234,567.00"
function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '.00';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}


//OnKeyPress
function maskNumericoDecimal(evento, Namecontrol, Fix) {
    setBrowserType();
    
    var rgx = /\d/; // Expresión regular que permite que pase solo numeros

    var control = document.getElementById(Namecontrol);

    AddEvent(control, 'onchange', 'maskNumericoDecimalValidate(this, ' + Fix + ');');
    
    // valor original del text
    var originalText = control.value;
    // obtengo la posision del cursor
    var posicion = obtenerPosicionCursor(control);

    // obtengo el keyCode de la tecla
    var tecla = (document.all) ? evento.keyCode : evento.which;
    if (tecla == 8 || tecla == 9 || tecla == 0 || tecla == 37 || tecla == 39 || tecla == 16) return true;

    // obtengo el valor de la tecla o caracter
    var caracter = String.fromCharCode(tecla);
    var seleccion = false;
    //  Verifico si se esta remplazando un caracter por otro y lo dejo pasar 
    if (sBrowser == "ie") {
        if (document.selection.type == 'Text') {
            // si no cumple no hace nada
            if (!rgx.test(caracter)) return false;
            var range = document.selection.createRange();
            control.value = control.value.substring(0, posicion) + control.value.substring(range.text.length + posicion, control.value.length)
            seleccion = true;
        }
    }
    else {
        if (control.selectionStart != control.selectionEnd) {
            // si no cumple no hace nada
            if (!rgx.test(caracter)) return false;
            control.value = control.value.substring(0, control.selectionStart) + control.value.substring(control.selectionEnd, control.value.length)
            seleccion = true;
        }
    }

    if (rgx.test(caracter)) {
        // LongintudText longitud del texto del control
        var LongintudText = control.value.length;
        // valorTxt texto del control sin comas y puntos.
        var valorTxt = control.value

        // Agrego el Caracter de entrada al Txt segun la posicion
        valorTxt = addCaracter(valorTxt, caracter, posicion)

        // Elimino los puntos y comas de la cadena
        valorTxt = valorTxt.split(".").join(",").replace(/,/gi, '');

        // x1 Numeros enteros
        var x1 = valorTxt;

        if (x1.length > Fix && Fix > 0) {
            // x2 Numeros Decimales
            var x2 = '.' + x1.substring(x1.length - Fix);
            x1 = x1.substring(0, x1.length - Fix);
        } else {
            var x2 = '';
        }

        // se agregan las comas a los numeros enteros
        rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        // cadena resultante, se forma el numero ya con el formato especifico
        var nStr = x1 + x2;

        // verifico si la longitud de la cadena resultante es mayor a lo que permite el control
        if (control.maxLength < nStr.length && control.maxLength != -1) {
            if (seleccion) {
                control.value = originalText;
                ponerCursorEnPosicion(posicion, control);
            }
            return false;
        } else {
            control.value = nStr;
        }

        // vandera que nos permite especificar el incremento de la nueva posicion del cursor
        var coma_punto = 1;
        coma_punto = (nStr.length - LongintudText);

        if (posicion == valorTxt.length && nStr.length == valorTxt.length + 1 || posicion == 0) {
            coma_punto = 1;
        }

        // se elimina el caracter agregado, segun las modificacion del texto.
        var valor1 = nStr.substring(0, posicion + ((coma_punto > 1) ? 1 : 0));
        var valor2 = nStr.substring(posicion + ((coma_punto > 1) ? 2 : 1), nStr.length);
        if (Fix > 0) {
            posicion -= (valor2.length == Fix) ? 1 : 0;
            valor1 = (valor2.length == Fix) ? valor1.substring(0, valor1.length - 1) : valor1;
            valor2 = (valor2.length == Fix) ? '.' + valor2 : valor2;
        }
        rgx = /([,\.])/
        var xop = rgx.test(valor2.substring(0, 3));
        if (!xop && valor2.substring(0, 3).length == 3) {
            valor2 = ',' + valor2;
            valor1 = valor1.substring(0, valor1.length - 1);
            posicion -= 1;
        }

        if (seleccion && coma_punto > 2) { posicion -= 1; }

        control.value = valor1 + valor2;
        ponerCursorEnPosicion(posicion + coma_punto - 1, control);
        return true;
    } else { return false; }
}

//  Funcion que permite agregar un caracter entre una cadena segun la posicion
//  valorTxt - Cadena de caracteres
//  caracter - caracter a agregar
//  posicion - posicion donde se va a agregar el caracter
//  retorna la cadena de caracteres con el caracter ya agregado
function addCaracter(valorTxt, caracter, posicion) {
    if (posicion >= valorTxt.length) {
        return valorTxt + caracter;
    } else {
        var valor1 = valorTxt.substring(0, posicion);
        return valor1 + caracter + valorTxt.substring(posicion, valorTxt.length);
    }
}

//Agrega punto y coma al nStr "Formato de moneda de 1234567.00 a 1,234,567.00"
function maskNumericoDecimalValidate(control, Fix) {
    nStr = control.value.replace(/,/gi, '');
    nStr += '';
    var x = nStr.split('.');
    var x1 = x[0];
    var x2 = '';
    if (x.length == Fix) {
        x2 = '.' + x[1]
        if (x2.length - 1 < Fix) {
            y = (x2.length-1);
            for (i = 1; i <= (Fix - y); i++) {
                x2 += '0';
            }
        }
    } else {
        if (Fix > 0) {
            for (i = 1; i <= Fix; i++) {
                x2 += '0';
            }
            x2 = '.' + x2;
        }
        if (x1.length == 0) {
            x1 = ''; // '0'
            x2 = ''; // 
         };
    }

    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    control.value = x1 + x2;
}

function AddEvent(control, eventType, functionPrefix) {
    var ev;
    var strFunction;
    eval("ev = control." + eventType + ";");
    if (typeof (ev) == "function") {
        try {
            strFunction = ev.toString();
            strFunction = strFunction.substring(strFunction.indexOf("{") + 1, strFunction.lastIndexOf("}"));
        }
        catch (err) { }
    }
    else {
        strFunction = "";
    }
    var func;
    if (strFunction.indexOf(functionPrefix) < 0) {
        if (navigator.appName.toLowerCase().indexOf('explorer') > -1) {

            func = new Function(functionPrefix + " " + strFunction);
        }
        else {

            func = new Function("event", functionPrefix + " " + strFunction);
        }
        eval("control." + eventType + " = func;");
    }
}

// Función para eliminar un registro de los catalogos
function Eliminar(formName, id, mensaje) {
    if (confirm(mensaje)) {
        var frm = document.forms[formName];
        for (var i = 0; i < frm.length; i++) {
            var ele = frm.elements[i];
            if (ele.type == "hidden" && ele.id.indexOf("hdfKey") != -1) {
                ele.value = id;
                frm.submit();
                return;
            }
        }
    }
}
// Función para ver un item de los datagrid
function VerItem(frmNombre, CodItem) {
    document.forms[frmNombre].hdfVer.value = CodItem;
    document.forms[frmNombre].submit();
}
// Función para editar un item de los datagrid
function EditarItem(frmNombre, CodItem) {
    document.forms[frmNombre].hdfEditar.value = CodItem;
    document.forms[frmNombre].submit();
}
// Función para borrar un item de los datagrid
function BorrarItem(frmNombre, CodItem, Mensaje) {
    if (confirm(Mensaje)) {
        document.forms[frmNombre].hdfBorrar.value = CodItem;
        document.forms[frmNombre].submit();
    }
}
// Función para validar que los caracteres ingresados en un input
// sean sólo números.
function SoloNumeros(e) {
    tecla = (document.all) ? e.keyCode : e.which;
    if (tecla == 8 || tecla == 0) return true;
    patron = /[1234567890]/;
    te = String.fromCharCode(tecla);
    return patron.test(te);
}
// Función para validar que los caracteres ingresados en un input 
// sean números y puntos.
function NumerosDecimales(e) {
    tecla = (document.all) ? e.keyCode : e.which;
    if (tecla == 8 || tecla == 0) return true;
    patron = /[1234567890.]/;
    te = String.fromCharCode(tecla);
    return patron.test(te);
}
// Función para validar que los caracteres ingresados en un input 
// sean sólo números positivos.
function SoloPositivos(CampoForm) {
    if (CampoForm.value <= 0) {
        alert('El valor del campo debe ser mayor que cero !!!');
        CampoForm.value = "";
        CampoForm.focus();
        return false;
    }
}
// Función para validar que los caracteres ingresados en un input
// sean sólo números y comas
function SoloNumerosyComa(e) {
    tecla = (document.all) ? e.keyCode : e.which;
    if (tecla == 8 || tecla == 44 || tecla == 0) return true;
    patron = /[1234567890,]/;
    te = String.fromCharCode(tecla);
    return patron.test(te);
}

// Función para validar que los caracteres ingresados en un input
// sean sólo números y guiones
function SoloNumLetyGuion(e) {
    tecla = (document.all) ? e.keyCode : e.which;
    if (tecla == 8 || tecla == 45 || tecla == 0) return true;
    patron = /[0-9a-zA-ZñÑáéíóúÁÉÍÓÚ]/;
    //    patron = /[1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]/;
    te = String.fromCharCode(tecla);
    return patron.test(te);
}

// Función para validar que los caracteres ingresados en un input
// sean sólo letras y espacio en blanco
function SoloLetrasyEspacio(e) {
    tecla = (document.all) ? e.keyCode : e.which;
    if (tecla == 8 || tecla == 32) return true;
    patron = /[a-zA-Z ñÑáéíóúÁÉÍÓÚ]/;
    //    patron = /[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]/;
    te = String.fromCharCode(tecla);
    return patron.test(te);
}

// Funciones para validar el formato de las fechas
// Formato Europeo: (dd/mm/yyyy)
function EW_checkeurodate(source, args) {
    var object_value = args.Value;
    if (args.Value.length == 0) {
        args.IsValid = true;
        return true;
    }

    var isplit = object_value.indexOf('/');

    if (isplit == -1) {
        isplit = object_value.indexOf('.');
    }

    if (isplit == -1 || isplit == args.Value.length) {
        args.IsValid = false;
        return false;
    }
    var sDay = object_value.substring(0, isplit);

    var monthSplit = isplit + 1;

    isplit = object_value.indexOf('/', monthSplit);

    if (isplit == -1) {
        isplit = object_value.indexOf('.', monthSplit);
    }

    if (isplit == -1 || (isplit + 1) == args.Value.length) {
        args.IsValid = false;
        return false;
    }
    var sMonth = object_value.substring((sDay.length + 1), isplit);

    var sYear = object_value.substring(isplit + 1);

    if (!EW_checkint(sMonth)) {
        args.IsValid = false;
        return false;
    }
    else
        if (!EW_numberrange(sMonth, 1, 12)) {
        args.IsValid = false;
        return false;
    }
    else
        if (!EW_checkint(sYear)) {
        args.IsValid = false;
        return false;
    }
    else
        if (!EW_numberrange(sYear, 0, null)) {
        args.IsValid = false;
        return false;
    }
    else
        if (!EW_checkint(sDay)) {
        args.IsValid = false;
        return false;
    }
    else
        if (!EW_checkday(sYear, sMonth, sDay)) {
        args.IsValid = false;
        return false;
    }
    else {
        args.IsValid = true;
        return true;
    }
}

function EW_checkday(checkYear, checkMonth, checkDay) {

    var maxDay = 31;

    if (checkMonth == 4 || checkMonth == 6 ||
			checkMonth == 9 || checkMonth == 11)
        maxDay = 30;
    else
        if (checkMonth == 2) {
        if (checkYear % 4 > 0)
            maxDay = 28;
        else
            if (checkYear % 100 == 0 && checkYear % 400 > 0)
            maxDay = 28;
        else
            maxDay = 29;
    }

    return EW_numberrange(checkDay, 1, maxDay);
}

function EW_checkinteger(src, args) {
    args.IsValid = EW_checkint(args.Value);
}


function EW_checkint(object_value) {
    if (object_value.length == 0)
        return true;

    var decimal_format = ".";
    var check_char;

    check_char = object_value.indexOf(decimal_format)
    if (check_char < 1)
        return EW_checknum(object_value);
    else
        return false;
}

function EW_numberrange(object_value, min_value, max_value) {
    if (min_value != null) {
        if (object_value < min_value)
            return false;
    }

    if (max_value != null) {
        if (object_value > max_value)
            return false;
    }

    return true;
}

function EW_checknumber(src, args) {
    if (args.Value.length == 0) {
        args.IsValid = true;
        return true;
    }

    var start_format = " .+-0123456789";
    var number_format = " .0123456789";
    var check_char;
    var decimal = false;
    var trailing_blank = false;
    var digits = false;
    var object_value = args.Value;
    check_char = start_format.indexOf(object_value.charAt(0))
    if (check_char == 1)
        decimal = true;
    else if (check_char < 1) {
        args.IsValid = false;
        return false;
    }

    for (var i = 1; i < args.Value.length; i++) {
        check_char = number_format.indexOf(object_value.charAt(i))
        if (check_char < 0) {
            args.IsValid = false;
            return false;
        }
        else if (check_char == 1) {
            if (decimal) {
                args.IsValid = false;
                return false;
            }
            else
                decimal = true;
        }
        else if (check_char == 0) {
            if (decimal || digits)
                trailing_blank = true;
        }
        else if (trailing_blank) {
            args.IsValid = false;
            return false;
        }
        else
            digits = true;
    }

    args.IsValid = true;
    return true;
}

function EW_checknum(object_value) {
    if (object_value.length == 0) {
        return true;
    }

    var start_format = " .+-0123456789";
    var number_format = " .0123456789";
    var check_char;
    var decimal = false;
    var trailing_blank = false;
    var digits = false;

    check_char = start_format.indexOf(object_value.charAt(0))
    if (check_char == 1)
        decimal = true;
    else if (check_char < 1) {
        return false;
    }

    for (var i = 1; i < object_value.length; i++) {
        check_char = number_format.indexOf(object_value.charAt(i))
        if (check_char < 0) {
            return false;
        }
        else if (check_char == 1) {
            if (decimal) {
                return false;
            }
            else
                decimal = true;
        }
        else if (check_char == 0) {
            if (decimal || digits)
                trailing_blank = true;
        }
        else if (trailing_blank) {
            return false;
        }
        else
            digits = true;
    }

    return true;
}

// Función para ver un registro pasando dos parámetros
function VerItemDosParametros(formName, id, codigo) {
    document.forms[formName].hdfEditar.value = id;
    document.forms[formName].hdfCodigoSolicitud.value = codigo;
    document.forms[formName].submit();
}


// Función para ver un registro pasando dos parámetros
function VerItemDosParametrosConvenio(formName, id, codigo) {
    document.forms[formName].hdfEditar.value = id;
    document.forms[formName].hdfNumeroConvenio.value = codigo;
    document.forms[formName].submit();
}

// Función para eliminar un registro pasando dos parámetros
function EliminarDosParametros(formName, id, codigo, mensaje) {
    if (confirm(mensaje)) {
        document.forms[formName].hdfKey.value = id;
        document.forms[formName].hdfCodigoSolicitud.value = codigo;
        document.forms[formName].submit();
    }
}

function NumerosDecimalesExactos(e, ctlId, numDecimales) {
    var cadena = ctlId.value;
    var cantPuntos = 1;
    var teclaPermitida = true;
    var d;
    var pos;
    var tecla;

    setBrowserType();

    //tecla = (document.all) ? e.keyCode : e.which;

    if (sBrowser == "ie") { //Internet Explorer
        tecla = window.event.keyCode

    } else if (sBrowser == "mo") { //Mozilla Firefox
        tecla = e.which;
        keyCode = e.keyCode;
        //Fin, Inicio, Izquierda, Derecha, Delete, BackSpace, Tab
        if (keyCode == 35 | keyCode == 36 | keyCode == 37 | keyCode == 39 | keyCode == 46 | keyCode == 8 | keyCode == 9)
            tecla = keyCode;
    }


    //if (tecla == 8) return true;
    if ((tecla < 48 || tecla > 57) & tecla != 35 & tecla != 36 & tecla != 37 & tecla != 39 & tecla != 46 & tecla != 8 & tecla != 9) {
        if (sBrowser == "ie") {
            window.event.keyCode = 0;
            //teclaPermitida = false;
        }
        else {
            return false;
            //teclaPermitida = false;
        }
    }

    //patron = /[1234567890.]/;

    //te = String.fromCharCode(tecla);

    if (tecla == 46) {
        //////valida que solo se permita un punto decimal   
        for (var i = 0; i <= cadena.length; i++) {
            if ((cadena.charAt(i) == ".")) {
                cantPuntos = cantPuntos + 1;
                if (cantPuntos > 1) {
                    return false;
                }
            }
        }
    }

    //valida que la cantidad de decimales
    var decimales = cadena.split(".");

    var totalEnteros = ctlId.maxLength - (numDecimales + 1);

    //valida los números antes del punto
    if (totalEnteros > 1) {
        if (decimales.length > 1) {
            d = cadena.length - (decimales[1].length + 1);
        }
        else {
            d = totalEnteros - 1;
        }

        if (document.selection)
            pos = getPosCaret(ctlId);
        else
            pos = ctlId.selectionStart;

        if ((decimales[0].length >= totalEnteros)) {
            if (tecla != 46 & tecla != 8 & tecla != 37 & tecla != 39) {
                if ((pos = d) && (decimales.length == 1)) {
                    return false;
                }
                else if (pos < d) {
                    return false;
                }
            }
        }
    }

    //valida los números despues del punto
    if (decimales.length > 1) {
        d = cadena.length - (decimales[1].length + 1);

        if (document.selection)
            pos = getPosCaret(ctlId);
        else
            pos = ctlId.selectionStart;

        //alert(decimales[1].length + ">" + s + "y" + pos + ">" + d);

        if ((decimales[1].length > numDecimales - 1) && (pos > d)) {
            if (tecla != 46 & tecla != 8 & tecla != 37 & tecla != 39) {
                return false;
            }
        }
    }
    //return patron.test(te);
}

/////////////////////////Obtiene la posición del cursor en el textbox///////////////////////////////
function getPosCaret(input) {
    var range = document.selection.createRange(); //document
    var range2 = input.createTextRange();

    range2.collapse(true);

    range2.moveEnd('character', 0);
    range2.setEndPoint('EndToStart', range);

    distancia = range2.text.length;
    //alert(distancia);
    //pos_final = parseFloat(input.value.length) - parseFloat(distancia);
    //range2.move('character', pos_final);
    //alert(distancia);
    return distancia;
}


