//=======================================================================
//Función para formatear los números en javascript
//=======================================================================
//Objeto oNumero
function oNumero(numero) {
    //Propiedades 
    this.valor = numero || 0
    this.dec = -1;
    this.separadorMiles = '.';
    this.separadorDecimales = ',';
    //Métodos 
    this.formato = numFormat;
    this.ponValor = ponValor;
    //Definición de los métodos 

    function ponValor(cad) {
        if (cad == '-' || cad == '+') return
        if (cad.length == 0) return
        if (cad.indexOf('.') >= 0)
            this.valor = parseFloat(cad);
        else
            this.valor = parseInt(cad);
    }

    function numFormat(dec, miles) {
        var num = this.valor, signo = 3, expr;
        var cad = "" + this.valor;
        var ceros = "", pos, pdec, i;
        for (i = 0; i < dec; i++)
            ceros += '0';
        pos = cad.indexOf('.')
        if (pos < 0)
            cad = cad + "." + ceros;
        else {
            pdec = cad.length - pos - 1;
            if (pdec <= dec) {
                for (i = 0; i < (dec - pdec); i++)
                    cad += '0';
            } else {
                num = num * Math.pow(10, dec);
                num = Math.round(num);
                num = num / Math.pow(10, dec);
                cad = new String(num);
            }
        }
        pos = cad.indexOf('.')
        if (pos < 0) pos = cad.lentgh
        if (cad.substr(0, 1) == '-' || cad.substr(0, 1) == '+')
            signo = 4;
        if (miles && (pos > signo))
            do {
                expr = /([+-]?\d)(\d{3}[\.\,]\d*)/
                cad.match(expr)
                cad = cad.replace(expr, RegExp.$1 + ',' + RegExp.$2)
            } while (cad.indexOf(',') > signo)

            if (dec < 0) cad = cad.replace(/\./, '')
            cad = reemplazaTodo(cad, ",", "m");
            cad = reemplazaTodo(cad, ".", ",");
            cad = reemplazaTodo(cad, "m", ".");
            return cad;
        }
    }
    //Fin del objeto oNumero:
    //=======================================================================

    //==========================================================================================
    // Reemplaza un texto dentro de otra cadena. Mejora le funcion replace de JavaScript
    //==========================================================================================
    function reemplazaTodo(cadena, original, cambio) {
        var strFinal, i, caracter;
        strFinal = cadena;
        while (strFinal.indexOf(original) > -1) {
            strFinal = strFinal.replace(original, cambio);
        }
        return strFinal;
    }

    //==========================================================================================
    // Reemplaza un texto con acentos (&acoute) a acentos (á)
    //==========================================================================================
    function quitarAcentos(texto) {
        texto = texto.replace('&Aacute;', 'A');
        texto = texto.replace('&Eacute;', 'E');
        texto = texto.replace('&Iacute;', 'I');
        texto = texto.replace('&Oacute;', 'O');
        texto = texto.replace('&Uacute;', 'U');
        texto = texto.replace('&aacute;', 'a');
        texto = texto.replace('&eacute;', 'e');
        texto = texto.replace('&iacute;', 'i');
        texto = texto.replace('&oacute;', 'o');
        texto = texto.replace('&uacute;', 'u');
        texto = texto.replace('&Ntilde;', 'N');
        texto = texto.replace('&ntilde;', 'n');
        return texto;
    }


    // """"""""""""""""""""""""""""""""""""""""""""""""""""""
    // "	Funciones Comunes para el Filtrado de campos	" 
    // """"""""""""""""""""""""""""""""""""""""""""""""""""""

    // Variable Comunes/Públicas...
    var Merr = ''; // Para componer los mensajes resultantes de los errores detectados.	 

    // """"""""""""""""""""""""""""""""""""""""""""""""""
    // "	Funciones para el Tratamiento de Fechas...	" 
    // """"""""""""""""""""""""""""""""""""""""""""""""""
    var Df = '';
    var Hf = '';
    var wDF = '';
    var wHF = '';

    function DiasEnElMes(mes, anio) {
        var DiasMes = CrearTablaVacia(12);
        DiasMes[1] = 31;
        DiasMes[2] = DiasEnFebrero(anio); //(anno  % 4==0 && (!(anno  % 100==0) || (anno  % 400==0)) ? 29 : 28);
        DiasMes[3] = 31; DiasMes[4] = 30;
        DiasMes[5] = 31; DiasMes[6] = 30; DiasMes[7] = 31; DiasMes[8] = 31;
        DiasMes[9] = 30; DiasMes[10] = 31; DiasMes[11] = 30; DiasMes[12] = 31;

        return DiasMes[parseInt(mes, 10)];
    }

    function CrearTablaVacia(n) {
        for (var i = 1; i <= n; i++) {
            this[i] = 0;
        }
        return this;
    }

    function DiasEnFebrero(ElAno) {
        return (ElAno % 4 == 0 && (!(ElAno % 100 == 0) || (ElAno % 400 == 0)) ? 29 : 28);
    }

    function ComprobarFecha(laFecha, obligatoria) {
        Merr = '';
        if (laFecha == '' && obligatoria == false) { return true; }
        if (laFecha == '' && obligatoria == true) { Merr = 'es obligatioria.'; return false; }

        t = laFecha.split('/');

        if (t.length != 3) { Merr = 'no tiene el formato adecuado.'; return false; }
        if (t[0] == '' || t[1] == '' || t[2] == '') { Merr = 'no tiene valores adecuados.'; return false; }
        if (t[2] > 2078) { Merr = 'no tiene el formato adecuado.'; return false; }
        if (t[2] < 1950) { Merr = 'no tiene el formato adecuado.'; return false; }
        if (isNaN(t[0]) || isNaN(t[1]) || isNaN(t[2])) { Merr = 'no posee valores numericos.'; return false; }

        if (t[0].length == 1) { t[0] = '0' + t[0]; }
        if (t[1].length == 1) { t[1] = '0' + t[1]; }
        if (t[2].length == 1) { t[2] = '200' + t[2]; }
        if (t[2].length == 2) { t[2] = '20' + t[2]; }
        wDF = t[0] + '/' + t[1] + '/' + t[2];

        var xd = parseVal(t[0], 10);
        var xm = parseVal(t[1], 10);
        var xa = parseVal(t[2], 10);

        if (xm < 01 || xm > 12) { Merr = 'el dia es erroneo.'; return false; }
        if (xd > DiasEnElMes(xm, xa)) { Merr = 'el dia/mes es erroneo.'; return false; }
        //if (xm==2 && xd>DiasEnFebrero(xa))	{ Merr='el dia de Febrero es erroneo.';		return false; }

        return true;
    }

    function ComprobarRangoFecha(laFechaIni, laFechaFin) {
        if (laFechaIni == '' && laFechaFin == '') return true;
        if (laFechaIni == '' && laFechaFin != '') return false;
        if (laFechaIni != '' && laFechaFin == '') return false;
        if (ComprobarFecha(laFechaIni, true) == true && ComprobarFecha(laFechaFin, true) == true) {
            t1 = laFechaIni.split('/');
            t2 = laFechaFin.split('/');
            var zD = t1[2] + '/' + t1[1] + '/' + t1[0];
            var zH = t2[2] + '/' + t2[1] + '/' + t2[0];
            if (zD > zH) return false;
            else return true;
        } else return false;
    }

    function FechaMenorQueHoy(laFecha) {
        var Hoy = new Date();
        var zHoy = Hoy.getDate() + '/' + (Hoy.getMonth() + 1) + '/' + Hoy.getFullYear();

        t1 = laFecha.split('/');
        t2 = zHoy.split('/');

        if (t1[0].length == 1) { t1[0] = '0' + t1[0]; }
        if (t1[1].length == 1) { t1[1] = '0' + t1[1]; }

        if (t2[0].length == 1) { t2[0] = '0' + t2[0]; }
        if (t2[1].length == 1) { t2[1] = '0' + t2[1]; }

        var zF = t1[2] + '/' + t1[1] + '/' + t1[0];
        var zH = t2[2] + '/' + t2[1] + '/' + t2[0];
        if (zF < zH) { return true; }
        else { return false; }
    }

    function diferenciaFechas(fechaIni, fechaFin) {
        var fechaI = String(document.getElementById(fechaIni).value).split("/");
        var fechaF = String(document.getElementById(fechaFin).value).split("/");
        var fechaInicio = new Date(parseInt(fechaI[2], 10), (parseInt(fechaI[1], 10) - 1), parseInt(fechaI[0], 10));
        var fechaFinal = new Date(parseInt(fechaF[2], 10), (parseInt(fechaF[1], 10) - 1), parseInt(fechaF[0], 10));
//        var stringInic = document.getElementById(fechaIni).value;
//        var inicDia = 01;
//        var inicMes = parseInt((stringInic.substring(3, 5)), 10);
//        var inicAno = parseInt((stringInic.substring(6, 10)), 10);
//        var fechaInicio = new Date(inicAno, (inicMes), inicDia);

//        var stringFin = document.getElementById(fechaFin).value;
//        var finDia = 01;
//        var finMes = parseInt((stringFin.substring(3, 5)), 10);
//        var finAno = parseInt((stringFin.substring(6, 10)), 10);
//        var fechaFinal = new Date(finAno, finMes, finDia);

        var diferencia = (fechaFinal.getTime() - fechaInicio.getTime()) / 1000 / 60 / 60 / 24;
        return diferencia;
    }

    // """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

    function es_mail(mail) {
        /*if (mail.indexOf('@') == -1) return false;
        else {
            mail_tmp = mail.substring(mail.indexOf('@'), mail.length);
            if (mail_tmp.indexOf('.') == -1) return false;
            else return true;
        }*/
        var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
        return emailPattern.test(mail);
    }

    function es_numerico(texto) {
        caracteres_validos = "1234567890";
        for (k = 0; k < texto.length; k++) {
            tmp = texto.substr(k, 1);
            if (caracteres_validos.search(tmp) == "-1") {
                return false;
            }
        }
        return true;
    }

    function isInteger(s) {
        var i;
        for (i = 0; i < s.length; i++) {
            var c = s.charAt(i);
            if (((c < "0") || (c > "9"))) return false;
        }
        return true;
    }

    function stripCharsInBag(s, bag) {
        var i;
        var returnString = "";
        for (i = 0; i < s.length; i++) {
            var c = s.charAt(i);
            if (bag.indexOf(c) == -1) returnString += c;
        }
        return returnString;
    }

    var dtCh = "/";
    var minYear = 1900;
    var maxYear = 2100;

    function validarFecha(fecha, obligatoria) {
        var datos;
        var RExp = /(?:\d{2})\/(?:\d{2})\/(?:\d{4})/
        if (fecha == "" && obligatoria == false) return true;
        if (!RExp.test(fecha)) return false;
        datos = String(fecha).split("/");
        if (parseInt(datos[0], 10) > DiasEnElMes(datos[1], 10, datos[2], 10)) return false;
        if (parseInt(datos[1], 10) < 1 || parseInt(datos[1], 10) > 12) return false;
        if (parseInt(datos[2], 10) < minYear || parseInt(datos[2], 10) > maxYear) return false;
        return true;
    }

    function isDate(dtStr) {
        var pos1 = dtStr.indexOf(dtCh)
        var pos2 = dtStr.indexOf(dtCh, pos1 + 1)
        var strDay = dtStr.substring(0, pos1)
        var strMonth = dtStr.substring(pos1 + 1, pos2)
        var strYear = dtStr.substring(pos2 + 1)
        strYr = strYear
        if (strDay.charAt(0) == "0" && strDay.length > 1) strDay = strDay.substring(1)
        if (strMonth.charAt(0) == "0" && strMonth.length > 1) strMonth = strMonth.substring(1)
        for (var i = 1; i <= 3; i++) {
            if (strYr.charAt(0) == "0" && strYr.length > 1) strYr = strYr.substring(1)
        }
        month = parseVal(strMonth)
        day = parseVal(strDay)
        year = parseVal(strYr)
        if (pos1 == -1 || pos2 == -1) {
            alert("El formato de fecha debe de ser: dd/mm/aaaa")
            return false
        }
        if (strMonth.length < 1 || month < 1 || month > 12) {
            alert("Please enter a valid month")
            return false
        }
        if (strDay.length < 1 || day < 1 || day > 31 || (month == 2 && day > DiasEnFebrero(year)) || day > DiasEnElMes(month, year)) {
            alert("Por favor, introduce un día válido")
            return false
        }
        if (strYear.length != 4 || year == 0 || year < minYear || year > maxYear) {
            alert("Por favor introduce un año válido de cuatro cifras")
            return false
        }
        if (dtStr.indexOf(dtCh, pos2 + 1) != -1 || isInteger(stripCharsInBag(dtStr, dtCh)) == false) {
            alert("Por favor, introduce una fecha válida")
            return false
        }
        return true
    }

    function ultimoDiaMes(fecha) {
        var datos = fecha.split("/");
        var dia = parseVal(datos[0]);
        var mes = parseVal(datos[1]);
        var ano = parseVal(datos[2]);
        dias = DiasEnElMes(mes, ano);
        return formatearFecha(dia + "/" + mes + "/" + ano);
    }

    function parseVal(val) {
        if (val == null) return "0";
        while (val.charAt(0) == '0')
            val = val.substring(1, val.length);
        return parseInt(val);
    }

    function addDiasAFecha(fecha, dias) {
        var nDias = parseVal(String(dias));
        var datos = fecha.split("/");

        var dia = parseVal(datos[0]);
        var mes = parseVal(datos[1]);
        var ano = parseVal(datos[2]);
        nDias += dia;


        while (nDias < 1 || nDias > DiasEnElMes(mes, ano)) {
            if (nDias < 1) {
                mes--;
                if (mes < 1) { mes = 12; ano--; }
                nDias += DiasEnElMes(mes, ano);
            }
            if (nDias > DiasEnElMes(mes, ano)) {
                nDias -= DiasEnElMes(mes, ano);
                mes++;
                if (mes > 12) { mes = 1; ano++; }
            }
        }
        return formatearFecha(cerosIzquierda(nDias, 2) + "/" +
						cerosIzquierda(mes, 2) + "/" +
						cerosIzquierda(ano, 4));
    }

    function addMesAFecha(fecha, meses) {
        var datos = fecha.split("/");
        var dia = parseVal(datos[0]);
        var mes = parseVal(datos[1]);
        var ano = parseVal(datos[2]);
        mes += meses;
        while (mes < 1) { mes += 12; ano--; }
        while (mes > 12) { mes -= 12; ano++; }
        if (dia > DiasEnElMes(mes, ano)) dia = DiasEnElMes(mes, ano);
        return formatearFecha(dia + "/" + mes + "/" + ano);
    }

    function ValidateForm() {
        var dt = document.frmSample.txtDate;
        if (isDate(dt.value) == false) {
            dt.focus()
            return false;
        }
        return true;
    }

    function lanzarURL(id, url) {
        lanzarURLConPregunta(id, url, "");
    }

    function lanzarURLConPregunta(id, url, pregunta) {
        var bIr = true;
        if (pregunta != "") {
            bIr = confirm(pregunta);
        }
        if (bIr) {
            var obj = document.getElementById(id);
            obj.action = url;
            obj.submit();
        }
    }

    function controlarTamano(id, maximo) {
        var obj = document.getElementById(id);
        if (obj != null) {
            if (obj.value.length > maximo) {
                alert("La longitud maxima de este campo es " + maximo);
                obj.value = obj.value.substring(0, maximo);
            }
        } else {
            alert("El id " + id + " no ha sido encontrado");
        }
    }

    function formatearFecha(fecha) {
        aFecha = fecha.split("/");
        if (aFecha[0].length == 1) { aFecha[0] = "0" + aFecha[0]; }
        if (aFecha[1].length == 1) { aFecha[1] = "0" + aFecha[1]; }
        fecha = aFecha[0] + "/" + aFecha[1] + "/" + aFecha[2];
        return fecha;
    }

    function test() {
        alert("Funciones.js se ha incluido correctamente");
    }

    function cerosIzquierda(sTexto, tamTotal) {
        while (sTexto.length < tamTotal) {
            sTexto = "0" + sTexto;
        }
        return sTexto;
    }

    function formatearFechaDMA(dia, mes, ano) {
        while (dia < 1) dia++;
        while (mes < 1) { mes += 12; ano--; }
        while (mes > 12) { mes -= 12; ano++; }
        if (dia > DiasEnElMes(mes, ano)) dia = DiasEnElMes(mes, ano);
        return formatearFecha(cerosIzquierda(dia, 2) + "/" +
							cerosIzquierda(mes, 2) + "/" +
							cerosIzquierda(ano, 4));
    }

    function setVisible(id, visible) {
        var obj = document.getElementById(id);
        if (visible)
            obj.style.display = "";
        else
            obj.style.display = "none";
    }

    function CopiarAlPortapapeles(texto) {
        window.clipboardData.setData('Text', texto);
    }

    function PegarDelPortapapeles(obj) {
        obj.value = window.clipboardData.getData('Text');
        window.clipboardData.clearData();
    }

    //===============================================================================================
    // Controla los caracteres introducidos en una caja de texto
    //===============================================================================================

    function tipoDatos(tipo, control) {
        var tecla, evento;
        evento = (arguments[2]) ? arguments[2] : event;
        if (evento.which) {
            tecla = evento.charCode;
        } else {
            tecla = evento.keyCode;
        }
        /*if (arguments[2]) {
            tecla = arguments[2].charCode;
        } else {
            tecla = event.keyCode;
        }*/
        if (tipo == "numero") { //SOLO NÚMEROS. SUSTITUYE LA COMA POR UN PUNTO
            //Punto por coma
            if (tecla == 46) {
                tecla = 44;
            }
            if ((tecla < 48 || tecla > 57) && (tecla != 44) && (tecla != 45)) {
                tecla = 0;
            }
            //sólo permitimos una coma en todo el número
            if (tecla == 44 && control.value.indexOf(",") >= 0) {
                tecla = 0;
            }
            //sólo permitimos signo - en todo el número
            if (tecla == 45 && control.value.indexOf("-") >= 0) {
                tecla = 0;
            }
        } else if (tipo == "numeroE") { //SOLO NÚMEROS ENTEROS.
            if ((tecla < 48 || tecla > 57)) {
                tecla = 0;
            }
        } else if (tipo == "lower") { //SOLO LETRAS MINÚSCULAS
            if (tecla < 97 || tecla > 122) {
                tecla = 0;
            }
        } else if (tipo == "upper") { //SOLO LETRAS MINÚSCULAS
            if (tecla < 65 || tecla > 90) {
                tecla = 0;
            }
        }
        else if (tipo == "letra") { //SOLO LETRAS
            if (!((tecla >= 65 && tecla <= 90) || (tecla >= 97 && tecla <= 122))) {
                tecla = 0;
            }
        }
        if (tecla == 0) {
            if (evento.which) {
                evento.preventDefault();
            } else {
                evento.keyCode = tecla;
            }
        }
    }

    //===============================================================================================
    // Fuerza en envío de un CheckBox para el formulario
    //		obj - control CheckBox
    //		valorTrue - Valor que se asignará cuando el CheckBox esté seleccionado
    //		valorTrue - Valor que se asignará cuando el CheckBox no esté seleccionado
    //		cadenaControles - cadena donde se encuentran los id de los CheckBox a forzar
    //===============================================================================================
    function forzarEnvioCheckBox(obj, valorTrue, valorFalse) {
        if (obj) {
            if (obj.checked) {
                obj.value = valorTrue;
            } else {
                obj.value = valorFalse;
            }
            if (controlesCB.indexOf("," + obj.id + ",") < 0) {
                controlesCB += obj.id + ",";
            }
        }
    }

    function abrirCerrarCapa(IDCapa) {
        if (jQuery("#" + IDCapa)) {
            if (jQuery("#" + IDCapa).hasClass('visible') == true) {
                jQuery("#" + IDCapa).removeClass('visible').addClass('noVisible');
            } else {
                jQuery("#" + IDCapa).removeClass('noVisible').addClass('visible');
            }

        }
    }

    function padLeft(Cadena, Relleno, Longitud) {
        var regEx = new RegExp(".{" + Longitud + "}$");
        var pad = "";
        if (!Relleno) Relleno = " ";
        do {
            pad += Relleno;
        } while (pad.length < Longitud);
        return regEx.exec(pad + Cadena)[0];
    }

    function padRight(Cadena, Relleno, Longitud) {
        var regEx = new RegExp("^.{" + Longitud + "}");
        var pad = "";
        if (!Relleno) Relleno = " ";
        do {
            pad += Relleno;
        } while (pad.length < Longitud);
        return regEx.exec(Cadena + pad)[0];
    }

    function trim(dato) {
        if (dato == undefined) return "";
        return dato.replace(/^\s+|\s+$/g, '');
    }

    function DEC_HEX(dec) {
        var Char_hexadecimales = "0123456789ABCDEF";
        var low = dec % 16;
        var high = (dec - low) / 16;
        hex = "" + Char_hexadecimales.charAt(high) + Char_hexadecimales.charAt(low);
        return hex;
    }
    
    function HEX_DEC(hex) {
        return parseInt(hex, 16);
    }

    function getColorComplementario(color) {
        if (String(color).length != 6) return color;
        var colorR = HEX_DEC(String(color).substr(0, 2));
        var colorG = HEX_DEC(String(color).substr(2, 2));
        var colorB = HEX_DEC(String(color).substr(4, 2));

        colorR = DEC_HEX(255 - colorR);
        colorG = DEC_HEX(255 - colorG);
        colorB = DEC_HEX(255 - colorB);

        return colorR + colorG + colorB;
    }


    function restarFechas(fechaIni, fechaFin) {
        var stringInic = document.getElementById(fechaIni).value;
        var inicDia = parseInt((stringInic.substring(0, 2)), 10);
        var inicMes = parseInt((stringInic.substring(3, 5)), 10);
        var inicAno = parseInt((stringInic.substring(6, 10)), 10);
        var fechaInicio = new Date(inicAno, (inicMes), inicDia);

        var stringFin = document.getElementById(fechaFin).value;
        var finDia = parseInt((stringFin.substring(0, 2)), 10);
        var finMes = parseInt((stringFin.substring(3, 5)), 10);
        var finAno = parseInt((stringFin.substring(6, 10)), 10);
        var fechaFinal = new Date(finAno, finMes, finDia);

        var diferencia = (fechaFinal.getTime() - fechaInicio.getTime()) / 1000 / 60 / 60 / 24;
        diferencia += '_' + (finMes - inicMes) + '_' + (finDia - inicDia) + '_' + (finAno - inicAno);
        return diferencia;
    }

    function dateDiff(fechaInicio, fechaFin) {
        return (fechaFin - fechaInicio) / (1000 * 60 * 60 * 24);        
    }
