// Con esta función se obtiene un objeto de htnl, si este falta se obtine null, la bisección se realiza para poder obtener tanto en navegadores con controles gecko como en los navegadores de la empresa multimillonaria
function sacaElemento(elemento){
    if(document.getElementById && !(document.all)) {
        var element = document.getElementById(elemento);
    } else if(document.all) {
        var element = document.all[elemento];
    }
    return element;
}

// Con esta función se obtiene un valor de un objeto de htnl, si este falta dara error pues no esta validado para ello.
function sacaValor(elemento){
    if(document.getElementById && !(document.all)) {
        var element = document.getElementById(elemento);
    } else if(document.all) {
        var element = document.all[elemento];
    }
    if ( element.value != null ) {
        return element.value;
    } else {
        return 0;
    }
}

// esta funcion es la que es llamada por el botonCancelar, para limpiar y enviar el formulario
function cancelarFormulario(formulario) {
    formulario.reset();
    formulario.contenido.value='';
    formulario.submit();
}

// esta funcion es la que es llamada por el botonEnviar, para ubicar el valor de la accion y enviar el formulario
function enviarFormulario (formulario, textoaccion) {
    formulario.accion.value = textoaccion;
    formulario.submit();
}

// esta funcion es la que es llamada por el botonImprimir, para imprimir el contenido identificado con valor
function llamarImprimir ( contenido , valor ) {
    window.open('sapdeb.php?imprimir=' + contenido + '&variable=' + valor );
}


// Esta funcion sirve para eliminar lso espacios en blanco al inicio y al final de alguna cadena
function trim(cadena) {
    for(i=0; i<cadena.length; ) {
        if(cadena.charAt(i)==" ") {
                cadena=cadena.substring(i+1, cadena.length);
        } else {
            break;
        }
    }
    for(i=cadena.length-1; i>=0; i=cadena.length-1) {
        if(cadena.charAt(i)==" ") {
            cadena=cadena.substring(0,i);
        } else {
            break;
        }
    }
    return cadena;
}

// con esta función se hace un resset y submit
function botonCancelar(identificador) {
    window.onload = function() {
        var element = sacaElemento(identificador);
        element.onclick = llamadaExterna;
    }
    function llamadaExterna() {
        cancelarFormulario(this.form);
    }
}

// con esta función hace una llamada de impresion
function botonImprimir(identificador , contenido , valor) {
    window.onload = function() {
        var element = sacaElemento(identificador);
        element.onclick = llamadaExterna;
    }
    function llamadaExterna() {
        llamarImprimir( contenido, valor );
    }
}

// Con esta función se simula un submit
function botonEnviar(identificador, textoaccion) {
    window.onload = function() {
        var element = sacaElemento(identificador);
        element.onchange = llamadaExterna;
    }
    function llamadaExterna() {
        enviarFormulario(this.form, textoaccion);
    }
}

// Esta funcion sirve para anular posteador
function anularBoton( botonid , objetobuscado ) {
    var boton  = sacaElemento(botonid);
    var objeto = sacaElemento(objetobuscado);
    if(objeto != null) {
        boton.disabled = false;
    } else {
        boton.disabled = true;
    }
}

// Funcion creada para comprobar suma
function validarSuma( valor, vector ){
    var suma = 0;
    var respuesta = true;
    for (i=0; i<vector.length; i++) {
        suma = suma + parseInt(sacaValor(vector[i]));
    }
    if ( suma != valor ) {
        respuesta = false;
    }
    return respuesta;
}

function sumar( vector ){
    var suma = 0;
    for (i=0; i<vector.length; i++) {
        suma = suma + parseInt(sacaValor(vector[i]));
    }
    return suma;
}

// validador de objetos de tipo requerido y sin restricciones mas que esa
function validaRequerido( identificador ){
    var f1 = new LiveValidation (
        identificador ,
        {
            validMessage: " Bien",
            wait: 500
        }
    );
    f1.add(
        Validate.Presence ,
        {
            failureMessage: " <- Requerido"
        }
    );
}


function validaNombreUsuario( identificador ){
     var f1 = new LiveValidation (
         identificador ,
            {
            validMessage: " Bien",
            wait: 500
            }
                                );
        f1.add (
            Validate.Presence,
            { failureMessage: " <- Requerido" }
               );
         f1.add  (
        Validate.Length,{
        minimum: 4 ,
        tooShortMessage : " <- 4 Caracteres mínimo"
                        }
                );
}

function validaClave1( identificador ){
     var clave1 = new LiveValidation (
    identificador ,
    { validMessage: " Bien" }
    );
    clave1.add (
        Validate.Presence ,
        { failureMessage: " <- Requerido" }
    );
    clave1.add (
        Validate.Length,    {
            minimum: 4  ,
            tooShortMessage : " <- 4 Caracteres mínimo"
        }
    );
}


function validaClave2( identificador,clave1 ){
    var clave2 = new LiveValidation (
        identificador,
        { validMessage: " Bien" }
    );
     clave2.add (
        Validate.Presence ,
         { failureMessage: " <- Requerido" }
    );
    clave2.add (
    Validate.Confirmation,
    {
        match: clave1 ,
        failureMessage: " <- No coinciden"
    }
    );
}


// validador de numeros de cuatro digitos
function valida4digitos( identificador ){
    var f2 = new LiveValidation (
            identificador ,
            {
                validMessage: " Bien",
                wait: 500
            }
        );
        f2.add (
        Validate.Presence ,
            {
                failureMessage: " <- Requerido"
            }
        );
        f2.add (
            Validate.Numericality , {
                notANumberMessage: " <- Debe ser un número" ,
                minimum: 1000,
                tooLowMessage: " <- número no menor de 4 cifras" ,
                maximum: 9999,
                tooHighMessage: " <- número no mayor de 4 cifras" ,
                onlyInteger: 'true' ,
                notAnIntegerMessage: " <- debe ser entero"
            }
        );
}

// validar numeros positivos.mayores que uno
function validaPositivos0( identificador ){
    var f3 = new LiveValidation (
            identificador ,
            {
                validMessage: " ",
                wait: 500
            }
        );
        f3.add (
        Validate.Presence ,
            {
                failureMessage: " "
            }
        );
        f3.add (
            Validate.Numericality , {
                notANumberMessage: " " ,
                minimum: 0,
                tooLowMessage: " " ,
                maximum: 999,
                tooHighMessage: " " ,
                onlyInteger: 'true' ,
                notAnIntegerMessage: " "
            }
        );
}

// validar numeros positivos.mayores que uno
function validaPositivos1( identificador ){
    var f3 = new LiveValidation (
            identificador ,
            {
                validMessage: " ",
                wait: 500
            }
        );
        f3.add (
        Validate.Presence ,
            {
                failureMessage: " "
            }
        );
        f3.add (
            Validate.Numericality , {
                notANumberMessage: " " ,
                minimum: 1,
                tooLowMessage: " " ,
                maximum: 999,
                tooHighMessage: " " ,
                onlyInteger: 'true' ,
                notAnIntegerMessage: " "
            }
        );
}

// validar que lo que se ingrese sean slo letras
function validaLetras( identificador ){
    var f2 = new LiveValidation (
     identificador ,    {
     validMessage: " Bien", wait: 500
                        }
                        );
        f2.add (
                Validate.Presence , {
                  failureMessage: " <- Requerido"
                                    }
                );
        f2.add(
                Validate.Exclusion, {
                within: [
                         '/',
                        '&',
                         '=',
                        '?',
                        '¿',
                        '¡',
                        '!',
                        '*',
                        '+',
                        '-',
                        '@',
                        '#',
                        '[',
                        ']',
                        '{',
                        '}',
                        '(',
                        ')',
                        '>',
                        '<',
                        ',',
                        '.',
                        '0',
                        '1',
                        '2',
                        '3',
                        '4',
                        '5',
                        '6',
                        '7',
                        '8',
                        '9',
                        ],
        partialMatch: true,
            failureMessage: " <- Caracteres no válidos"
            }
    );
}

// validar que lo que se ingrese sean solo letras y numeros
function validaLetrasNumerosSimbolos( identificador ){
    var f2 = new LiveValidation (
     identificador ,    {
     validMessage: " Bien", wait: 500
                        }
                        );
        f2.add (
                Validate.Presence , {
                  failureMessage: " <- Requerido"
                                    }
                );
        f2.add(
                Validate.Exclusion, {
                within: [
                        '/',
                        '&',
                        '=',
                        '?',
                        '¿',
                        '¡',
                        '!',
                        '*',
                        '+',
                        '-',
                        '@',
                        '#',
                        '[',
                        ']',
                        '{',
                        '}',
                        '>',
                        '<',
                        ',',
                        '.',
                        ],
        partialMatch: true,
            failureMessage: " <- Caracteres no válidos"
            }
    );
}

// funcion para validar que se ingresen 5 digitos
function valida5digitos( identificador ){
        var f2 = new LiveValidation (
            identificador ,  {
            validMessage: " Bien", wait: 500
                    }
                    );
        f2.add (
            Validate.Presence , {
                failureMessage: " <- Requerido"
                }
            );
        f2.add (
            Validate.Numericality , {
                notANumberMessage: " <- Debe ser un número" ,
                minimum: 10000,
                tooLowMessage: " <- número no menor de 5 cifras",
                maximum: 99999,
                tooHighMessage: " <- número no mayor de 5 cifras" ,
                onlyInteger: 'true' ,
                notAnIntegerMessage: " <- debe ser entero"
                }
            );
}

// funcion para validar anios
function validaAnios( identificador ){
        var f1 = new LiveValidation (
                identificador , {
                validMessage: " Bien", wait: 500
                }
            );
            f1.add (
                Validate.Presence , {
                failureMessage: " <- Requerido"
                }
            );
            f1.add (
            Validate.Numericality , {
                notANumberMessage: " <- Debe ser un número" ,
                minimum: 2008,
                tooLowMessage: " <- Año muy bajo",
                maximum: 2021,
                tooHighMessage: " <- Año muy alto" ,
                onlyInteger: 'true' ,
                notAnIntegerMessage: " <- El año es un número entero"
                }
            );
}

// Para poder hacer que una area de texto se transforme en editor y sea validada al mismo tiempo
function colocarEditor ( identificador ){
    bkLib.onDomLoaded(
        function() {
            new nicEditor(
            {
                buttonList : ['bold','italic','underline','strikethrough','subscript','superscript']
            }
            ).panelInstance( identificador );
        }
    );
    //fullPanel : true
    validaRequerido( identificador );
}

// Para poder hacer que una area de texto con mas opciones se transforme en editor y sea validada al mismo tiempo
function colocarEditorMedio ( identificador ){
    bkLib.onDomLoaded(
        function() {
            new nicEditor(
            {
                //['bold','italic','underline','left','center','right','ol','ul','fontSize','fontFamily','fontFormat','indent','outdent','link','image']
                buttonList : ['bold','italic','underline','strikethrough','subscript','superscript','hr','left','center','right','ol','ul','link','fontSize']
            }
            ).panelInstance( identificador );
        }
    );
    validaRequerido( identificador );
}