function GM_ValidaCNPJ(NroCNPJ) {
    if ((NroCNPJ.length != 18)) {
        return false;
    }

    var semFormat = NroCNPJ.replace("/", "");
    semFormat = semFormat.replace(".", "");
    semFormat = semFormat.replace(".", "");
    semFormat = semFormat.replace("-", "");

    NroCNPJ = semFormat;

    if (NroCNPJ < 1) {
        return false;
    }

    var dig1 = 0;
    var dig2 = 0;
    var x;
    var Mult1 = '543298765432';
    var Mult2 = '6543298765432';

    for (x = 0; x <= 11; x++) {
        dig1 = dig1 + (parseInt(NroCNPJ.slice(x, x + 1)) * parseInt(Mult1.slice(x, x + 1)));
    }
    for (x = 0; x <= 12; x++) {
        dig2 = dig2 + (parseInt(NroCNPJ.slice(x, x + 1)) * parseInt(Mult2.slice(x, x + 1)));
    }


    dig1 = (dig1 * 10) % 11;
    dig2 = (dig2 * 10) % 11;

    if (dig1 == 10) { dig1 = 0; }
    if (dig2 == 10) { dig2 = 0; }

    if (dig1 != parseInt(NroCNPJ.slice(12, 13))) {
        return false;
    }
    else {
        if (dig2 != parseInt(NroCNPJ.slice(13, 14))) {
            return false;
        }
        else {
            return true;
        }
    }
}


function GM_ValidaLoginCNPJ(CNPJ, ID_Campo) {
    var vCNPJ = GM_ValidaCNPJ(CNPJ);
    if (vCNPJ == false) {
        document.getElementById(ID_Campo).value = "";
        alert('CNPJ inválido')
    }
}

function ValidaCPF(CPF) {
    dig_1 = 0;
    dig_2 = 0;
    controle_1 = 10;
    controle_2 = 11;
    lsucesso = 1;
    numero = CPF;
    if (
         numero == "000000000-00" ||
         numero == "111111111-11" ||
         numero == "222222222-22" ||
         numero == "333333333-33" ||
         numero == "444444444-44" ||
         numero == "555555555-55" ||
         numero == "666666666-66" ||
         numero == "777777777-77" ||
         numero == "888888888-88" ||
         numero == "999999999-99"
        ) {
        return false;
    }
    if ((numero.length != 12) || (numero.substring(9, 10) != "-")) {
        return false;
    }
    else {
        for (i = 0; i < 9; i++) {
            dig_1 = dig_1 + parseInt(numero.substring(i, i + 1) * controle_1);
            controle_1 = controle_1 - 1;
        }
        resto = dig_1 % 11;
        dig_1 = 11 - resto;
        if ((resto == 0) || (resto == 1))
            dig_1 = 0;
        for (i = 0; i < 9; i++) {
            dig_2 = dig_2 + parseInt(numero.substring(i, i + 1) * controle_2);
            controle_2 = controle_2 - 1;
        }
        dig_2 = dig_2 + 2 * dig_1;
        resto = dig_2 % 11;
        dig_2 = 11 - resto;

        if ((resto == 0) || (resto == 1))
            dig_2 = 0;

        dig_ver = (dig_1 * 10) + dig_2;

        if (dig_ver != parseFloat(numero.substring(numero.length - 2, numero.length))) {
            return false;
        }
    }
    return true;
}

function GM_ValidaLoginCPF(cpf, campo) {
    var semFormat = cpf.replace(".", "");
    semFormat = semFormat.replace(".", "");
    
    var vRetorno = ValidaCPF(semFormat);
    if (vRetorno == false) {
        document.getElementById(campo).value = '';
        alert('CPF Inválido')
    }
}







function MM_reloadPage(init) {  //reloads the window if Nav4 resized
    if (init == true) with (navigator) {
        if ((appName == "Netscape") && (parseInt(appVersion) == 4)) {
            document.MM_pgW = innerWidth; document.MM_pgH = innerHeight; onresize = MM_reloadPage;
        } 
    }
    else if (innerWidth != document.MM_pgW || innerHeight != document.MM_pgH) location.reload();
}




function GM_AplicaMascara_Moeda(vElement) {
    var vAplicaMascara = vElement.value;
    vAplicaMascara = vAplicaMascara.replace(/\D/g, "")  //permite digitar apenas números
    vAplicaMascara = vAplicaMascara.replace(/[0-9]{13}/, "inválido")   //limita pra máximo 999.999.999,99
    vAplicaMascara = vAplicaMascara.replace(/(\d{1})(\d{8})$/, "$1.$2")  //coloca ponto antes dos últimos 8 digitos
    vAplicaMascara = vAplicaMascara.replace(/(\d{1})(\d{5})$/, "$1.$2")  //coloca ponto antes dos últimos 5 digitos
    //    vAplicaMascara = vAplicaMascara.replace(/(\d{1})(\d{2,2})$/,"$1,$2")    //coloca virgula antes dos últimos 2 digitos
    vAplicaMascara = vAplicaMascara.replace(/(\d{1})(\d{1,2})$/, "$1,$2")    //coloca virgula antes dos últimos 2 digitos
    vElement.value = vAplicaMascara;
}



function GM_Verifica_Data(vAno, vMes, vDia) {
    vOk = false;
    //Cria uma data
    vData = new Date(vAno, vMes - 1, vDia);
    //Verifica se a data criada é a mesma que foi digitada
    vDia1 = vData.getDate();
    if (vDia1 < 10) {
        vDia1 = '0' + vDia1
    }

    vMes1 = vData.getMonth();
    vAno1 = vData.getFullYear();
    //alert(vDia + ' - ' + vDia1) 
    //alert(vMes-1 + ' - ' + vMes1)
    //alert(vAno + ' - ' + vAno1)
    vOk = isDateJS(vAno, vMes, vDia) && (vDia == vDia1) && ((vMes - 1) == vMes1) && (vAno == vAno1);
    return vOk;
}

function isDateJS(year, month, day) {   // catch invalid years (not 2- or 4-digit) and invalid months and days.
    //alert(year)
    //alert(month)
    //alert(day)
    if (parseInt(month.substring(0, 1)) == 0) {
        month = parseInt(month.substring(1, 2))
    }
    if (parseInt(day.substring(0, 1)) == 0) {
        day = parseInt(day.substring(1, 2))
    }
    if (!(isYear(year, false) && isMonth(month, false) && isDay(day, false))) return false;
    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false;

    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;

    return true;
}

function fVoltar() {
    history.go(-1);
}

function onBlurData(campo_obj_data) {
    var erro = 0;
    var Data = campo_obj_data.value;
    var ArrayData = Data.split("/");
    if (Data != '') {
        vAnoOriginal = ArrayData[2]
        if (vAnoOriginal < 1900) {
            erro = erro + 1;
        }
        if (Data.length != 10) // Valida o len do campo
        {
            erro = erro + 1;
        }
        if (ArrayData.length != 3) // valida o tamanho do array de barras (/) DD/MM/YYYY
        {
            erro = erro + 1;
        }
        else {
            biSexto(Data, campo_obj_data);
        }        
        if (erro > 0) {
            campo_obj_data.value = '';
            alert('Data inválida');
            return false;
        }
    }
}

function biSexto(data_valor, nome_campo) {
    var sData = data_valor.split("/");
    var entrou;
    sDia = sData[0];
    sMes = sData[1];
    sAno = (sData[2] % 4);
    sAnoOriginal = sData[2];
    entrou = 0;

    if ((sData[1] == 2) && (sData[0] > 27)) {
        if (sAno == 0) {//ano bisexto (Fev tem 29 dias)
            if (sDia > 29) {
                alert('O mês de Fevereiro ocorre variação em ano bisexto.\nVocê escolheu uma data de ano bisexto. \nEstamos corrigindo a data.');
                nome_campo.value = '29' + '/' + sData[1] + '/' + sData[2];
                entrou = 1;
            }
        }
        else {//nao eh ano bisexto, fev tem 28 dias
            if (sDia > 28) {
                alert('O mês de Fevereiro ocorre variação em ano bisexto.\n A Data escolhida não é valida. \nEstamos corrigindo a data.');
                nome_campo.value = '28' + '/' + sData[1] + '/' + sData[2];
                entrou = 1;
            }
        }
    }
    if (entrou == 0) {
        if (GM_Verifica_Data(sAnoOriginal, sMes, sDia) == false) {
            nome_campo.value = '';
            alert('Data inválida!');
            nome_campo.focus();
        }
    }
}


function mascara_data(data_valor, nome_campo, evento) {
    CharCode = evento.keyCode;
    var sData = data_valor.split("/");
    var ano;
    ano = sData[2];
    if ((sData[0] > 31) || (sData[1] > 12)) {
        nome_campo.value = '';
        alert('Data Inválida');
    }
    else {
        if (CharCode != 8)//verificacao do BACKSPACE, so entra qnd nao for backspace
        {
            var mydata = '';
            mydata = mydata + data_valor;
            if (mydata.length == 2) {
                mydata = mydata + '/';
                nome_campo.value = mydata;
            }
            if (mydata.length == 5) {
                mydata = mydata + '/';
                nome_campo.value = mydata;
            }
        }
    }
}



function fValidarEmail(valor) {
    email = valor.value;
    if (email != '') {
        if (email.indexOf("@") > 0 && email.indexOf(".") > 0) {
            return true;
        }
        else {
            valor.focus();
            valor.select();
            alert('O campo e-mail deve contar um endereco eletrônico válido.');
            return false;
        }
    }
}


function mascara_hora(hora_valor, nome_campo) {
    var sHora = hora_valor.split(":");
    if ((sHora[0] > 23) || (sHora[1] > 59)) {
        alert('Hora Inválida')
        nome_campo.value = ''
        nome_campo.focus()
    }
    else {
        var myHora = '';
        myHora = myHora + hora_valor;
        if (myHora.length == 2) {
            myHora = myHora + ':';
            nome_campo.value = myHora;
        }
    }
}

function fValidaNumerico(oEvento) {
    oEvento = (oEvento) ? oEvento : event;
    var charCode = (oEvento.charCode) ? oEvento.charCode : ((oEvento.keyCode) ? oEvento.keyCode : ((oEvento.which) ? oEvento.which : 0));
    if (charCode == 44) return true;
    if (charCode > 31 && (charCode < 48 || charCode > 57)) {
        return false;
    }
    return true;
}


function excluiReg(id, nome) {
    var excluir = confirm("Tem certeza que deseja excluir " + nome + "?")
    if (excluir == true) {
        document.form_excluir.codigo.value = id;
        document.form_excluir.submit();
    }
}

function gotoPage(pag) {
    document.form_gotopage.pagina.value = pag;
    document.form_gotopage.submit();
}





/*********** NEW FUNCTIONS ****************/




function criaMascara(_RefObjeto, _Modelo) {

    var valorAtual = _RefObjeto.value;
    var valorNumerico = '';
    var nIndexModelo = 0;
    var nIndexString = 0;
    var valorFinal = '';
    var adicionarValor = true;


    // limpa a string valor atual para verificar
    // se todos os caracteres são números
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) != '#') {
            valorAtual = valorAtual.replace(_Modelo.substr(i, 1), '');
        }
    }

    // verifica se todos os caracteres são números
    for (i = 0; i < valorAtual.length; i++) {
        if (!isNaN(parseFloat(valorAtual.substr(i, 1)))) {
            valorNumerico = valorNumerico + valorAtual.substr(i, 1);
        } 
    }

    // aplica a máscara ao campo informado usando
    // o modelo de máscara informado no script
    for (i = 0; i < _Modelo.length; i++) {

        if (_Modelo.substr(i, 1) == '#') {
            if (valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + valorNumerico.substr(nIndexModelo, 1);
                nIndexModelo++; nIndexString++;
            }
            else {
                adicionarValor = false;
            } 
        }

        else {
            if (adicionarValor && valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + _Modelo.substr(nIndexString, 1)
                nIndexString++;
            } 
        }
    }

    _RefObjeto.value = valorFinal

}
// modelo input: onfocus="criaMascara(this,'##.###.###/####-##');" onkeypress="criaMascara(this,'##.###.###/####-##');" onkeyup="criaMascara(this,'##.###.###/####-##');" onblur="criaMascara(this,'##.###.###/####-##');"




/********** POSICIONAR DIV OCULTA **************/


function MM_findObj(n, d) { //v4.01
    var p, i, x; if (!d) d = document; if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document; n = n.substring(0, p);
    }
    if (!(x = d[n]) && d.all) x = d.all[n]; for (i = 0; !x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; !x && d.layers && i < d.layers.length; i++) x = MM_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
    var i, p, v, obj, args = MM_showHideLayers.arguments;
    for (i = 0; i < (args.length - 2); i += 3) if ((obj = MM_findObj(args[i])) != null) {
        v = args[i + 2];
        if (obj.style) { obj = obj.style; v = (v == 'show') ? 'visible' : (v == 'hide') ? 'hidden' : v; }
        obj.visibility = v;
    }
}

function hide(lyr) {
    var x = document.getElementById(lyr);
    x.style.visibility = (hide) ? 'hidden' : 'visible';
}



function setLyrDetalheAutor(obj, lyr, vTop, vLeft, vID_Autor) {
    var coors = findPos(obj);
    var x = document.getElementById(lyr);
    x.style.top = eval(coors[1] + vTop) + 'px';
    x.style.left = eval(coors[0] + vLeft) + 'px';
    P7_autoLayers(0, lyr);
    P7_autoHide(lyr); // apaga div
    GM_MostraDetalheAutorAJAX(vID_Autor);

    //document.getElementById('total_pag').style.display="none"; (exemplo)

    return false;
}



function setLyrErros(obj, lyr, vTop, vLeft, vErro) {
    var coors = findPos(obj);
    var x = document.getElementById(lyr);
    x.style.top = eval(coors[1] + vTop) + 'px';
    x.style.left = eval(coors[0] + vLeft) + 'px';
    P7_autoLayers(0, lyr);
    P7_autoHide(lyr); // apaga div
    GM_MostraErrosAJAX(vErro);
    return false;
}


// MODELO DIV:
// <div ID="NOME_DIV"  style="position: absolute; z-index:9; visibility: hidden;">
//
// </div>

// MODELO CHAMADA: onclick="return setLyr_Denuncia(this,'NOME_DIV',-180,-295)"






function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft, curtop];
}

function P7_autoHide() { //v1.3 by PVII
    var i, g, args = P7_autoHide.arguments;
    for (i = 0; i < args.length; i++) {
        if ((g = MM_findObj(args[i])) != null) {
            g.p7aHide = true; if (document.layers) {
                g.captureEvents(Event.MOUSEOUT);
            } g.onmouseout = P7_hideDiv; g.p7ahD = true;
        } 
    }
}

function P7_hideDiv(evt) { //v1.3 by PVII
    var b, relT, mT = false;
    if (document.layers) {
        b = evt.target; if (b.p7aHide) {
            b.visibility = "hidden";
        } else { routeEvent(evt); }
    } else if (document.all && !window.opera) {
        b = event.srcElement;
        while (b != null) { if (b.tagName == "DIV" && b.p7ahD) { mT = true; break; } b = b.parentElement; }
        if (!b.contains(event.toElement)) { b.style.visibility = "hidden"; }
    } else if (document.getElementById) {
        b = evt.currentTarget; relT = evt.relatedTarget;
        while (relT != null) {
            if (b == relT) { mT = true; break; }
            relT = relT.parentNode;
        } if (!mT) { b.style.visibility = "hidden"; } 
    }
}

function P7_autoLayers() { //v1.4 by PVII
    var g, b, k, f, args = P7_autoLayers.arguments; a = parseInt(args[0]); if (isNaN(a)) a = 0;
    if (!document.p7setc) {
        p7c = new Array(); document.p7setc = true; for (var u = 0; u < 10; u++) {
            p7c[u] = new Array();
        } 
    } for (k = 0; k < p7c[a].length; k++) {
        if ((g = MM_findObj(p7c[a][k])) != null) {
            b = (document.layers) ? g : g.style; b.visibility = "hidden";
        } 
    } for (k = 1; k < args.length; k++) {
        if ((g = MM_findObj(args[k])) != null) {
            b = (document.layers) ? g : g.style; b.visibility = "visible"; f = false;
            for (var j = 0; j < p7c[a].length; j++) { if (args[k] == p7c[a][j]) { f = true; } }
            if (!f) { p7c[a][p7c[a].length++] = args[k]; } 
        } 
    }
}


function OcultaForm(form) {
    document.getElementById(form).style.visibility = "hidden";
    return false;
}





function setLyr(obj, lyr, vTop, vLeft) {

    var coors = findPos(obj);
    var x = document.getElementById(lyr);
    x.style.top = eval(coors[1] + vTop) + 'px';
    x.style.left = eval(coors[0] + vLeft) + 'px';
    P7_autoLayers(0, lyr);
    P7_autoHide(lyr);
    return false;
}


function setLyr_ResultadoEnquete(obj, lyr, vTop, vLeft, vID_Enquete, vIDIOMA) {


    var coors = findPos(obj);
    var x = document.getElementById(lyr);




    x.style.top = eval(coors[1] + vTop) + 'px';
    x.style.left = eval(coors[0] + vLeft) + 'px';


    P7_autoLayers(0, lyr);
    //P7_autoHide(lyr);

    GM_AjaxBuscaResultado_Enquete(vID_Enquete, vIDIOMA);

    return false;

}




function setLyr_DetalheAgenda(obj, lyr, vTop, vLeft, vID_ItemAgenda, vIDIOMA) {


    var coors = findPos(obj);
    var x = document.getElementById(lyr);



    x.style.top = eval(coors[1] + vTop) + 'px';
    x.style.left = eval(coors[0] + vLeft) + 'px';


    P7_autoLayers(0, lyr);
    //P7_autoHide(lyr);

    GM_AjaxBuscaItemAgenda(vID_ItemAgenda, vIDIOMA);

    return false;

}







function GM_ComparaHora(horaInicio, horaFim) {
    //DECLARAÇÃO DE VARIÁVEIS
    var iHoraInicio, iHoraFim;
    var iMinutoInicio, iMinutoFim;
    var iSegundoInicio, iSegundoFim;
    var sResultado;
    var bEncerrado;

    //SEPARA A HORA
    iHoraInicio = horaInicio.substring(0, 2);
    iHoraFim = horaFim.substring(0, 2);

    //SEPARA O MINUTO
    iMinutoInicio = horaInicio.substring(3, 5);
    iMinutoFim = horaFim.substring(3, 5);

    //SEPARA OS SEGUNDOS
    iSegundoInicio = horaInicio.substring(6, 8);
    iSegundoFim = horaFim.substring(6, 8);
    bEncerrado = false;

    //COMPARA OS VALORES
    //HORA
    if (iHoraInicio != iHoraFim) {
        if (iHoraInicio > iHoraFim) {
            sResultado = false; //"Hora inicial é maior 1";
            bEncerrado = true;
            //alert('h1\n'+iHoraInicio+'\n'+iHoraFim);
        }
        else {
            sResultado = true; //"Hora final é maior 2";
            bEncerrado = true;
            //alert('h2\n'+iHoraInicio+'\n'+iHoraFim);
        }
    }

    //SE NÃO RESOLVEU NA HORA, VERIFICA OS MINUTOS
    if (bEncerrado == false) {
        if ((iHoraInicio == iHoraFim) && (iMinutoInicio == iMinutoFim)) {
            sResultado = false;
            bEncerrado = true;
            //alert('1\n'+iMinutoInicio+'\n'+iMinutoFim);
        }
        else if ((iHoraInicio == iHoraFim) && (iMinutoInicio > iMinutoFim)) {
            sResultado = false;
            bEncerrado = true;
            // alert('2\n'+iMinutoInicio+'\n'+iMinutoFim);
        }
        else if ((iHoraInicio == iHoraFim) && (iMinutoInicio < iMinutoFim)) {
            sResultado = true;
            bEncerrado = true;
            //alert('3')
        }
    }

    ////SE NÃO RESOLVEU NA HORA E NEM NOS MINUTOS, VERIFICA OS SEGUNDOS
    //if (!bEncerrado && (iSegundoInicio != iSegundoFim)){
    //if (iSegundoInicio > iSegundoFim){
    //sResultado = "Hora inicial é maior 5";
    //bEncerrado = true;
    //}
    //else{
    //sResultado = "Hora final é maior 6";
    //bEncerrado = true;
    //}
    //}

    //SE bEncerrado FOR FALSE, É PORQUE AS HORAS SÃO IGUAIS
    if (!bEncerrado)
        sResultado = false; //"Horas iguais";

    //IMPRIME O RESULTADO
    //alert(sResultado);
    return sResultado
}

function GM_ValidaCampoValor(ID_Campo) {
  if (document.getElementById(ID_Campo).value = "") {
    document.getElementById(ID_Campo).value = "0,00";
  }
}

  

