var tempoSessao = -1;
var calendarioJS = document.createElement('script');
calendarioJS.setAttribute('type', 'text/javascript');
calendarioJS.setAttribute('src', 'javascript/dhtmlgoodies_calendar.js');
document.getElementsByTagName('head')[0].appendChild(calendarioJS);

var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
        || this.searchVersion(navigator.appVersion)
        || "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++)	{
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
    {
        string: navigator.userAgent,
        subString: "Chrome",
        identity: "Chrome"
    },
    {
        string: navigator.userAgent,
        subString: "OmniWeb",
        versionSearch: "OmniWeb/",
        identity: "OmniWeb"
    },
    {
        string: navigator.vendor,
        subString: "Apple",
        identity: "Safari",
        versionSearch: "Version"
    },
    {
        prop: window.opera,
        identity: "Opera"
    },
    {
        string: navigator.vendor,
        subString: "iCab",
        identity: "iCab"
    },
    {
        string: navigator.vendor,
        subString: "KDE",
        identity: "Konqueror"
    },
    {
        string: navigator.userAgent,
        subString: "Firefox",
        identity: "Firefox"
    },
    {
        string: navigator.vendor,
        subString: "Camino",
        identity: "Camino"
    },
    {		// for newer Netscapes (6+)
        string: navigator.userAgent,
        subString: "Netscape",
        identity: "Netscape"
    },
    {
        string: navigator.userAgent,
        subString: "MSIE",
        identity: "Explorer",
        versionSearch: "MSIE"
    },
    {
        string: navigator.userAgent,
        subString: "Gecko",
        identity: "Mozilla",
        versionSearch: "rv"
    },
    { 		// for older Netscapes (4-)
        string: navigator.userAgent,
        subString: "Mozilla",
        identity: "Netscape",
        versionSearch: "Mozilla"
    }
    ],
    dataOS : [
    {
        string: navigator.platform,
        subString: "Win",
        identity: "Windows"
    },
    {
        string: navigator.platform,
        subString: "Mac",
        identity: "Mac"
    },
    {
        string: navigator.userAgent,
        subString: "iPhone",
        identity: "iPhone/iPod"
    },
    {
        string: navigator.platform,
        subString: "Linux",
        identity: "Linux"
    }
    ]

};
BrowserDetect.init();

function removerDoisEspacos(texto){
    while (texto.indexOf("  ") != -1){
        texto = texto.replace("  ", " ");
    }
    return texto;
}
unidade = new Array(20);
unidade[1] = "hum";
unidade[2] = "dois";
unidade[3] = "três";
unidade[4] = "quatro";
unidade[5] = "cinco";
unidade[6] = "seis";
unidade[7] = "sete";
unidade[8] = "oito";
unidade[9] = "nove";
unidade[10] = "dez";
unidade[11] = "onze";
unidade[12] = "doze";
unidade[13] = "treze";
unidade[14] = "quatorze";
unidade[15] = "quinze";
unidade[16] = "dezeseis";
unidade[17] = "dezesete";
unidade[18] = "dezoito";
unidade[19] = "dezenove";

dezena = new Array(10);
dezena[1] = "";
dezena[2] = "vinte";
dezena[3] = "trinta";
dezena[4] = "quarenta";
dezena[5] = "cinquenta";
dezena[6] = "sessenta";
dezena[7] = "setenta";
dezena[8] = "oitenta";
dezena[9] = "noventa";

centena = new Array(10);
centena[1] = "cento";
centena[2] = "duzentos";
centena[3] = "trezentos";
centena[4] = "quatrocentos";
centena[5] = "quinhentos";
centena[6] = "seiscentos";
centena[7] = "setecentos";
centena[8] = "oitocentos";
centena[9] = "novecentos";
deReais = false;
function right(texto, tam){
    return texto.substring(texto.length-tam,texto.length);
}

function calculaBilhao(valor) {
    var sb = "";
    var valorTexto = valor.toString();
    var bilhaoTexto = valorTexto.substring(0, valorTexto.length - 9);
    var valorBilhao = parseInt(bilhaoTexto);
    var milhaoTexto = valorTexto.substring(valorTexto.length - 9, valorTexto.length - 6);
    var valorMilhao = parseInt(milhaoTexto);
    var milharTexto = valorTexto.substring(valorTexto.length - 6, valorTexto.length - 3);
    var valorMilhar = parseInt(milharTexto);
    var centenaTexto = right(valorTexto, 3);
    var valorCentena = parseInt(centenaTexto);
    sb += calculaCentena(valorBilhao);
    deReais = true;
    var  virgula = false;
    if (valorBilhao == 1) {
        sb += " bilhão";
    } else {
        sb += " bilhões";
    }
    if (valorMilhao > 0) {
        sb += ", ";
        sb += calculaCentena(valorMilhao);
        if (valorMilhao == 1) {
            sb += " milhão";
        } else {
            sb += " milhões";
        }
    }
    if (valorMilhar > 0) {
        if (!virgula) {
            sb += ", ";
        }
        if (!right(sb, 1) == " ") {
            sb += " ";
        }
        sb += calculaCentena(valorMilhar) + " mil";
        if (valorCentena >= 100) {
            sb += ", ";
        }else{
            sb += " ";
        }
        deReais = false;
    }

    if (valorCentena > 0 && valorCentena < 100) {
        if (!right(sb, 1) == " ") {
            sb += " ";
        }
        sb += "e ";
    }
    sb += calculaCentena(valorCentena);
    return sb;
}

function calculaMilhao(valor) {
    var sb = "";
    var valorTexto = valor.toString();
    var milhaoTexto = valorTexto.substring(0, valorTexto.length - 6);
    var valorMilhao = parseInt(milhaoTexto);
    var milharTexto = valorTexto.substring(valorTexto.length - 6, valorTexto.length - 3);
    var valorMilhar = parseInt(milharTexto);
    var centenaTexto = right(valorTexto, 3);
    var valorCentena = parseInt(centenaTexto);
    sb += calculaCentena(valorMilhao);
    var virgula = false;
    if (valorMilhao == 1) {
        sb += " milhão";
    } else {
        sb += " milhões";
    }
    if (valorMilhar > 0) {
        deReais = false;
        sb += ", ";
        virgula = true;
        sb += calculaCentena(valorMilhar) + " mil";
        if (valorCentena >= 100) {
            sb += ", ";
        }else{
            sb += " ";
        }

    }
    if (valorCentena > 0) {
        deReais = false;
    }
    if (valorCentena >= 100) {
        if (!virgula) {
            sb += ", ";
        }
    }
    if (!right(sb, 1) == " ") {
        sb += " ";
    }
    if (valorCentena > 0 && valorCentena < 100) {
        sb += "e ";
    }
    sb += calculaCentena(valorCentena);
    return sb;
}

function calculaCentena(valor) {
    if (valor == 0) {
        return "";
    }
    var sb = "";
    var valorTexto = valor.toString();
    var tam = valorTexto.length;
    if (tam < 3) {
        if (valor < 20) {
            sb += unidade[valor];
        }else {
            sb += dezena[parseInt(valor.toString().substring(0, 1))];
            if (parseInt(valor.toString().substring(1, 2)) > 0) {
                sb += " e " + unidade[parseInt(valor.toString().substring(1, 2))];
            }
        }
    } else {
        if (valor == 100) {
            sb += "cem";
        } else {

            sb += centena[parseInt(valor.toString().substring(0, 1))];
            var valorDezena = parseInt(valor.toString().substring(1, 3));
            if (valorDezena > 0) {
                sb += " e ";
                if (valorDezena < 20) {
                    sb += unidade[valorDezena];
                } else {
                    sb += dezena[parseInt(valorDezena.toString().substring(0, 1))];
                    if (parseInt(valorDezena.toString().substring(1, 2)) > 0) {
                        sb += " e " + unidade[parseInt(valorDezena.toString().substring(1, 2))];
                    }
                }
            }
        }
    }
    return sb;
}
function calculaMilhar(valor) {
    deReais = false;
    var sb = "";
    var valorTexto = valor.toString();
    var milharTexto = valorTexto.substring(0, valorTexto.length - 3);
    var valorMilhar = parseInt(milharTexto);
    var centenaTexto = right(valorTexto, 3);
    var valorCentena = parseInt(centenaTexto);
    sb += calculaCentena(valorMilhar) + " mil";
    if (valorCentena >= 100) {
        sb += ", ";
    }else{
        sb += " ";
    }
    if (valorCentena > 0 && right(centenaTexto, 2) == "00") {
        sb += "e ";
    }
    if (valorCentena > 0 && valorCentena < 200) {
        sb += "e ";
    }
    sb += calculaCentena(valorCentena);
    return sb;
}

function escreverValorPorExtenso(valor) {

    valor = replaceAll(valor, '.', '');
    valor = replaceAll(valor, ',', '.');
    var moeda = " reais";
    if (valor < 0) {
        valor = valor * -1;
    }
    var valorLong = parseInt(valor);
    var valorCentavo = Math.round((valor - valorLong) * 100);

    var centavoTexto = "";
    if (valorCentavo > 0) {
        var e = "";
        if (valorLong >= 1) {
            e = " e ";
        }
        centavoTexto = e + calculaCentena(valorCentavo) + (valorCentavo > 1 ? " centavos" : " centavo");
    }
    if (valorLong < 2 && valorLong >= 1) {
        moeda = " real";
    }
    if (valorLong < 1) {
        moeda = "";
    }
    if (valorLong < 1) {
        return removerDoisEspacos(centavoTexto);
    }else if (valorLong >= 1 && valorLong < 1000) {
        deReais = false;
        return removerDoisEspacos(calculaCentena(parseInt(valorLong)) + (deReais ? " de" : "") + moeda + centavoTexto);
    } else if (valorLong < 1000000) {
        return removerDoisEspacos(calculaMilhar(parseInt(valorLong)) + (deReais ? " de" : "") + moeda + centavoTexto);
    } else if (valorLong < 1000000000) {
        return removerDoisEspacos(calculaMilhao(parseInt(valorLong)) + (deReais ? " de" : "") + moeda + centavoTexto);
    }
    else if (valorLong <= 1000000000000) {
        return removerDoisEspacos(calculaBilhao(valorLong) + (deReais ? " de" : "") + moeda + centavoTexto);
    }
    return "";
}

function abrirPagina(pagina){
    if (document.getElementById("idChave") != null){
        document.getElementById("idChave").value = "0";
    }
    if (pagina == "hdfw/geracaoCodigo.jsp?action=exibir"){
        window.open("hdfw/geracaoCodigo.jsp", "GeracaoCodigo", "");
    }else{
        requisitarPaginaAjax(pagina);
    }
}

function verificaSenha(){
    if (document.getElementById("senha").value == document.getElementById("confirmaSenha").value){
        return true;
    }
    alert("A senha não confere. Favor digitar novamente.");
    document.getElementById("senha").focus();
    return false;
}

function alterarSenhaUsuarioClick(){
    if (campoPreenchimentoObrigatorio("Senha atual", "senhaAtual")){
        if (campoPreenchimentoObrigatorio("Nova senha", "novaSenha")){
            if (campoPreenchimentoObrigatorio("Confirma Senha", "confirmaSenha")){
                if (verificaSenha()){
                    document.getElementById("pwcod").value = hex_md5(document.getElementById("senhaAtual").value);
                    document.getElementById("novaPwcod").value = hex_md5(document.getElementById("novaSenha").value);
                    document.getElementById("senhaAtual").value = "";
                    document.getElementById("novaSenha").value = "";
                    document.getElementById("confirmaSenha").value = "";
                    if (confirm("Alterar senha. Você tem certeza?")){
                        acaoSalvar("alteraSenhaForm");
                    }
                }
            }
        }
    }
}
function salvarUsuarioClick(idChave){
    document.getElementById("idChave").value = idChave;
    if (campoPreenchimentoObrigatorio("Login", "login")){
        if (campoPreenchimentoObrigatorio("Nome", "nome")){
            if (campoNumericoPreenchimentoObrigatorio("Perfil usuário", "idPerfilUsuario")){
                if (campoPreenchimentoObrigatorio("Senha", "senha")){
                    if (campoPreenchimentoObrigatorio("Confirma Senha", "confirmaSenha")){
                        if (verificaSenha()){
                            document.getElementById("pwcod").value = hex_md5(document.getElementById("senha").value);
                            document.getElementById("senha").value = "";
                            document.getElementById("confirmaSenha").value = "";
                            //acaoSalvar("cadastroUsuarioForm");
                            requisitarPaginaAjax("autenticacaoSeguranca/cadastroUsuario.jsp?action=salvar");
                        }
                    }
                }
            }
        }
    }
}
function salvarAtualizarUsuarioClick(idChave){
    document.getElementById("idChave").value = idChave;
    if (campoPreenchimentoObrigatorio("Login", "login")){
        if (campoPreenchimentoObrigatorio("Nome", "nome")){
            if (campoNumericoPreenchimentoObrigatorio("Perfil usuário", "idPerfilUsuario")){
                if (document.getElementById("senha").value.length > 0){
                    if (campoPreenchimentoObrigatorio("Confirma Senha", "confirmaSenha")){
                        if (!verificaSenha()){
                            return;
                        }else{
                            document.getElementById("pwcod").value = hex_md5(document.getElementById("senha").value);
                            document.getElementById("senha").value = "";
                            document.getElementById("confirmaSenha").value = "";
                            //acaoSalvar("cadastroUsuarioForm");
                            requisitarPaginaAjax("autenticacaoSeguranca/cadastroUsuario.jsp?action=salvar");
                        }
                    }
                }else{
                    document.getElementById("pwcod").value = "";
                    requisitarPaginaAjax("autenticacaoSeguranca/cadastroUsuario.jsp?action=salvar");
                }
            }
        }
    }
}
function alterarSenhaUsuario(){
    if (campoPreenchimentoObrigatorio("Nova senha", "senha")){
        if (campoPreenchimentoObrigatorio("Confirma Senha", "confirmaSenha")){
            if (!verificaSenha()){
                return;
            }else{
                document.getElementById("pwcodAtual").value = hex_md5(document.getElementById("senhaAtual").value);
                document.getElementById("pwcod").value = hex_md5(document.getElementById("senha").value);
                document.getElementById("senhaAtual").value = "";
                document.getElementById("senha").value = "";
                document.getElementById("confirmaSenha").value = "";
                requisitarPaginaAjax("autenticacaoSeguranca/alteracaoSenha.jsp?action=salvar");
            }
        }
    }else{
        document.getElementById("pwcod").value = "";
        acaoSalvar("cadastroUsuarioForm");
    }
}

function campoPreenchimentoObrigatorio(nomeCampo, campo){
    if (document.getElementById(campo).value == ''){
        alert("O preenchimento do campo '" + nomeCampo + "' é obrigatório.");
        document.getElementById(campo).focus();
        return false;
    }
    return true;
}
function campoNumericoPreenchimentoObrigatorio(nomeCampo, campo){
    if (document.getElementById(campo).value == '' || parseInt(document.getElementById(campo).value) == 0){
        alert("O preenchimento do campo '" + nomeCampo + "' é obrigatório.");
        document.getElementById(campo).focus();
        return false;
    }
    return true;
}

function comboBoxPreenchimentoObrigatorio(nomeCampo, campo){
    if (document.getElementById(campo).value == '' || parseInt(document.getElementById(campo).value) == 0){
        alert("O preenchimento do campo '" + nomeCampo + "' é obrigatório.");
        document.getElementById(campo).focus();
        return false;
    }
    return true;
}

function excluirClick(entidade, pagina){
    acaoExcluirAjax(entidade, pagina);
}

function listarClick(pagina){
    document.getElementById('idChave').value = '0'
    acaoPesquisarAjax(pagina);
}

function selecionarRegistro(idChave, pagina){
    acaoSelecionarRegistroAjax(idChave, pagina);
}
tempoSessao = 0;
var mostraSegundos = 0;
function showSessionTimeOut(contextpath){
    if (tempoSessao >= 0){
        if(tempoSessao == 0 && mostraSegundos == 0 ){
            document.getElementsByTagName("body")[0].style.opacity = 0.3;
            document.getElementsByTagName("body")[0].style.filter = 'alpha(opacity=' + 30 + ')';
            document.getElementById("tempoSessao").innerHTML =  "Tempo restante da sessão: 00:00 min";
            alert("Caro usuário. O tempo de sessão expirou por inatividade. Favor logar novamente.");
            //requisitarPaginaAjax("index.jsp?action=sair");
            location = "../gpg/"

        }else{
            document.getElementById("tempoSessao").innerHTML =  "Tempo restante da sessão: " +
            ((tempoSessao-1) < 10 ? "0" + (tempoSessao) : (tempoSessao)) + ":" +
            (mostraSegundos < 10 ? "0" + mostraSegundos : mostraSegundos) + " min";
            if(mostraSegundos == 0){
                tempoSessao--;
                mostraSegundos = 60;
            }
            mostraSegundos--;
            setTimeout("showSessionTimeOut('" + contextpath + "')",1000);
        }
    }
}


function showtime(){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var seconds = now.getSeconds();
    var timeValue = "" + hours;
    timeValue  += ((minutes < 10) ? ":0" : ":") + minutes;
    timeValue  += ((seconds < 10) ? ":0" : ":") + seconds;
    document.getElementById("relogioTxt").innerHTML = timeValue;
    setTimeout("showtime()",1000);
}
function goToPage(pageNumber, page){
    minutosParaExpirarSessao = tempoSessao;
    mostraSegundos = 0;
    if (page.substring(page.length-3,page.length) == "jsp"){
        requisitarPaginaAjax(page + "?action=goToPage&pagina=" + pageNumber);
    }else{
        requisitarPaginaAjax(page + "&action=goToPage&pagina=" + pageNumber);
    }
}

function acaoNovoComQueryString(){
    requisitarPaginaAjax(location.href + "&action=novo&idChave=0");
}

function acaoSalvarAjax(pagina){
    minutosParaExpirarSessao = tempoSessao;
    mostraSegundos = 0;
    if (pagina.substring(pagina.length-3,pagina.length) == "jsp"){
        requisitarPaginaAjax(pagina + "?action=salvar");
    }else{
        requisitarPaginaAjax(pagina + "&action=salvar");
    }
}

function acaoSalvarAjaxComQueryString(){
    minutosParaExpirarSessao = tempoSessao;
    mostraSegundos = 0;
    requisitarPaginaAjax(location.href + "&action=salvar");
}

function acaoSalvar(formulario){
    document.getElementById("action").value = "salvar";
    document.getElementById(formulario).submit();
}

function acaoExcluir(formulario, entidade){
    if (confirm("Excluir " + entidade + ". Você tem certeza?")){
        document.getElementById("action").value = "excluir";
        document.getElementById(formulario).submit();
    }
}

//function acaoExcluirAjax(entidade){
//    if (confirm("Excluir " + entidade + ". Você tem certeza?")){
//        minutosParaExpirarSessao = tempoSessao;
//        mostraSegundos = 0;
//        if (location.href.substring(location.href.length-3,location.href.length) == "jsp"){
//            requisitarPaginaAjax(location.href + "?action=excluir&idChave=" + document.getElementById("idChave").value);
//        }else{
//            requisitarPaginaAjax(location.href + "&action=excluir&idChave=" + document.getElementById("idChave").value);
//        }
//    }
//}

function acaoExcluirAjax(entidade, pagina){
    if (confirm("Excluir " + entidade + ". Você tem certeza?")){
        minutosParaExpirarSessao = tempoSessao;
        mostraSegundos = 0;
        if (pagina.substring(pagina.length-3,pagina.length) == "jsp"){
            requisitarPaginaAjax(pagina + "?action=excluir&idChave=" + document.getElementById("idChave").value);
        }else{
            requisitarPaginaAjax(pagina + "&action=excluir&idChave=" + document.getElementById("idChave").value);
        }
    }
}

function acaoExcluirAjaxComQueyString(entidade){
    if (confirm("Excluir " + entidade + ". Você tem certeza?")){
        minutosParaExpirarSessao = tempoSessao;
        mostraSegundos = 0;
        requisitarPaginaAjax(location.href + "&action=excluir&idChave=" + document.getElementById("idChave").value);
    }
}

function acaoPesquisar(formulario){
    document.getElementById("action").value = "pesquisar";
    document.getElementById(formulario).submit();
}

function acaoPesquisarAjax(pagina){
    minutosParaExpirarSessao = tempoSessao;
    mostraSegundos = 0;
    if (pagina.substring(pagina.length-3,pagina.length) == "jsp"){
        requisitarPaginaAjax(pagina + "?action=pesquisar");
    }else{
        requisitarPaginaAjax(pagina + "&action=pesquisar");
    }
}

//function acaoPesquisarAjax(){
//    minutosParaExpirarSessao = tempoSessao;
//    mostraSegundos = 0;
//    if (location.href.substring(location.href.length-3,location.href.length) == "jsp"){
//        requisitarPaginaAjax(location.href + "?action=pesquisar");
//    }else{
//        requisitarPaginaAjax(location.href + "&action=pesquisar");
//    }
//}

function acaoPesquisarAjaxComQueryString(){
    minutosParaExpirarSessao = tempoSessao;
    mostraSegundos = 0;
    requisitarPaginaAjax(location.href + "&action=pesquisar");
}

function acaoSelecionarRegistroAjax(idChave, pagina){
    minutosParaExpirarSessao = tempoSessao;
    mostraSegundos = 0;
    if (pagina.substring(pagina.length-3,pagina.length) == "jsp"){
        requisitarPaginaAjax(pagina + "?idChave=" + idChave);
    }else{
        requisitarPaginaAjax(pagina + "&idChave=" + idChave);
    }
}

function novoClick(pagina){
    document.getElementById("idChave").value = "0";
    if (pagina.substring(pagina.length-3,pagina.length) == "jsp"){
        requisitarPaginaAjax(pagina + "?action=novo");
    }else{
        requisitarPaginaAjax(pagina + "&action=novo");
    }
}

function acaoSelecionarRegistroAjaxComQueryString(idChave){
    minutosParaExpirarSessao = tempoSessao;
    mostraSegundos = 0;
    requisitarPaginaAjax(location.href + "&idChave=" + idChave);
}

function quantidadeCaracteresPermitida(src, qtdCaracteresPermitidos){
    if(src != null && src.value.length > qtdCaracteresPermitidos){
        alert("O campo em foco possui mais caracteres que o permitido. Por favor verifique!");
        src.value = src.value.substring(0,qtdCaracteresPermitidos);
        src.focus();
        return 0;
    }
    return 1;
}

function campoPreenchimentoObrigatorio(nomeCampo, campo){
    if (document.getElementById(campo).value == ''){
        alert("O preenchimento do campo '" + nomeCampo + "' é obrigatório.");
        document.getElementById(campo).focus();
        return false;
    }
    return true;
}
function campoNumericoPreenchimentoObrigatorio(nomeCampo, campo){
    if (document.getElementById(campo).value == '' || parseInt(document.getElementById(campo).value) == 0){
        alert("O preenchimento do campo '" + nomeCampo + "' é obrigatório.");
        document.getElementById(campo).focus();
        return false;
    }
    return true;
}
var descricaoNoticiaCrime = '';
function setDescricaoNoticiaCrime(dica){
    descricaoNoticiaCrime = dica;
}
function getHoraAtual(){
    var now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var horaAtual = "" + (hours < 10 ? "0" + hours : hours);
    horaAtual  += ((minutes < 10) ? ":0" : ":") + minutes;
    return horaAtual;
}

function compararHora(src){
    now = new Date();
    var hours = now.getHours();
    var minutes = now.getMinutes();
    var horaAtual = '' + hours;
    horaAtual  += ((minutes < 10) ? ':0' : ':') + minutes;
    if (compararHorarios(src.value, horaAtual,'>')){
        alert('Hora inválida! Digite uma hora menor ou igual a atual');
    }
}

function redimensionar(){
    document.getElementById("bodyDiv").style.height = (document.documentElement.clientHeight - 35) + "px";
}
function confirmacao(botao,mensagemDialogo){
    var url = "../projeto/telaConfirmacao.jsp";
    if (navigator.appName == "Microsoft Internet Explorer"){
        if (botao.length > 0){
            url += "?botao=" + botao + "&textoMensagem='" + mensagemDialogo + "'";
        }else{
            url += "?botao=SIM_NAO&textoMensagem=" + mensagemDialogo;
        }
    }else{
        if (botao.length > 0){
            url += "?botao=" + botao;
        }
        else{
            url += "?botao=SIM_NAO";
        }
    }
    document.getElementById("textoMensagem").value = mensagemDialogo;
    return window.showModalDialog(url,"Confirmacao","dialogwidth:430px;dialogheight:150px;resizable:no;scroll:no");
}
function calcular_idade(data){
    //variaveis do formulario 01/01/1999
    dia1 = parseInt(data.value.substring(0,2));
    mes1 = parseInt(data.value.substring(3,5));
    ano1 = parseInt(data.value.substring(6,10));

    //variaveis do dia/mes/ano de hj
    data = new Date();
    dia2 = data.getDate();
    mes2 = data.getMonth()+1;
    ano2 = data.getFullYear();


    anos = ano2 - ano1;
    if (mes2 < mes1) {
        anos--;
    }
    if (mes1 == mes2 && dia2 < dia1) {
        anos--;
    }
    return anos;
}

/*
 <table width="100%" border="0">
    <tr>
        <td colspan="2" align="center"><strong>Exemplos de Funções de mascaras em javascript</strong></td>
    </tr>
    <tr bgcolor="#e1e1e1">
        <td width="13%">[Só numeros]</td>
        <td width="87%"><input name="int" type="text" id="int" onKeyDown="Mascara(this,Integer);" onKeyPress="Mascara(this,Integer);" onKeyUp="Mascara(this,Integer);"></td>
    </tr>
    <tr>
        <td width="13%">[Telefone]</td>
        <td width="87%"><input name="tel" type="text" id="tel" maxlength="14" onKeyDown="Mascara(this,Telefone);" onKeyPress="Mascara(this,Telefone);" onKeyUp="Mascara(this,Telefone);"></td>
    </tr>
    <tr bgcolor="#e1e1e1">
        <td width="13%">[CPF]</td>
        <td width="87%"><input name="cpf" type="text" id="cpf" maxlength="14" onKeyDown="Mascara(this,Cpf);" onKeyPress="Mascara(this,Cpf);" onKeyUp="Mascara(this,Cpf);"></td>
    </tr>
    <tr>
        <td width="13%">[Cep]</td>
        <td width="87%"><input name="cep" type="text" id="cep" maxlength="9" onKeyDown="Mascara(this,Cep);" onKeyPress="Mascara(this,Cep);" onKeyUp="Mascara(this,Cep);"></td>
    </tr>
    <tr bgcolor="#e1e1e1">
        <td width="13%">[CNPJ]</td>
        <td width="87%"><input name="cnpj" type="text" id="cnpj" maxlength="18" onKeyDown="Mascara(this,Cnpj);" onKeyPress="Mascara(this,Cnpj);" onKeyUp="Mascara(this,Cnpj);"></td>
    </tr>
    <tr>
        <td width="13%">[Romanos]</td>
        <td width="87%"><input name="rom" type="text" id="rom"  onKeyDown="Mascara(this,Romanos);" onKeyPress="Mascara(this,Romanos);" onKeyUp="Mascara(this,Romanos);"></td>
    </tr>
    <tr bgcolor="#e1e1e1">
        <td width="13%">[Site]</td>
        <td width="87%"><input name="sit" type="text" id="sit"  onKeyDown="Mascara(this,Site);" onKeyPress="Mascara(this,Site);" onKeyUp="Mascara(this,Site);"></td>
    </tr>
    <tr>
        <td width="13%">[Data]</td>
        <td width="87%"><input name="date" type="text" id="date" maxlength="10" onKeyDown="Mascara(this,Data);" onKeyPress="Mascara(this,Data);" onKeyUp="Mascara(this,Data);"></td>
    </tr>
    <tr bgcolor="#e1e1e1">
        <td width="13%">[Area Valor]</td>
        <td width="87%"><input name="arevalo" type="text" id="arevalo"  onKeyDown="Mascara(this,Area);" onKeyPress="Mascara(this,Area);" onKeyUp="Mascara(this,Area);"></td>
    </tr>
</table>

 */
/*Função Pai de Mascaras*/
function Mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}

/*Função que Executa os objetos*/
function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}

/*Função que Determina as expressões regulares dos objetos*/
function leech(v){
    v=v.replace(/o/gi,"0")
    v=v.replace(/i/gi,"1")
    v=v.replace(/z/gi,"2")
    v=v.replace(/e/gi,"3")
    v=v.replace(/a/gi,"4")
    v=v.replace(/s/gi,"5")
    v=v.replace(/t/gi,"7")
    return v
}

/*Função que permite apenas numeros*/
function Integer(v){
    return v.replace(/\D/g,"")
}


function MatriculaMascara(v){
    v=v.replace(/\D/g,"")  //permite digitar apenas números
    //v=v.replace(/[0-9]{13}/,"inválido")   //limita pra máximo 999.999.999-9
    v=v.replace(/(\d{1})(\d{7})$/,"$1.$2")  //coloca ponto antes dos últimos 8 digitos
    v=v.replace(/(\d{1})(\d{4})$/,"$1.$2")  //coloca ponto antes dos últimos 8 digitos
    v=v.replace(/(\d{1})(\d{1})$/,"$1-$2")  //coloca ponto antes dos últimos 5 digitos
    return v
}

/*Função que padroniza telefone (11) 4184-1241*/
function TelefoneMascara(v){
    v=v.replace(/\D/g,"")  //permite digitar apenas números
    if (v.length > 8)
        v=v.replace(/^(\d\d)(\d)/g,"($1) $2")
    v=v.replace(/(\d{4})(\d)/,"$1-$2")
    return v
/*
    v=v.replace(/\D/g,"")
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2")
    v=v.replace(/(\d{4})(\d)/,"$1-$2")
    return v
     */
}

/*Função que padroniza telefone (11) 41841241*/
function TelefoneCall(v){
    v=v.replace(/\D/g,"")
    v=v.replace(/^(\d\d)(\d)/g,"($1) $2")
    return v
}

/*Função que padroniza CPF*/
function Cpf(v){
    v=v.replace(/\D/g,"")
    v=v.replace(/(\d{3})(\d)/,"$1.$2")
    v=v.replace(/(\d{3})(\d)/,"$1.$2")

    v=v.replace(/(\d{3})(\d{1,2})$/,"$1-$2")
    return v
}

/*Função que padroniza CEP*/
function Cep(v){
    v=v.replace(/D/g,"")
    v=v.replace(/^(\d{5})(\d)/,"$1-$2")
    return v
}

/*Função que padroniza CNPJ*/
function Cnpj(v){
    v=v.replace(/\D/g,"")
    v=v.replace(/^(\d{2})(\d)/,"$1.$2")
    v=v.replace(/^(\d{2})\.(\d{3})(\d)/,"$1.$2.$3")
    v=v.replace(/\.(\d{3})(\d)/,".$1/$2")
    v=v.replace(/(\d{4})(\d)/,"$1-$2")
    return v
}

/*Função que permite apenas numeros Romanos*/
function Romanos(v){
    v=v.toUpperCase()
    v=v.replace(/[^IVXLCDM]/g,"")

    while(v.replace(/^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/,"")!="")
        v=v.replace(/.$/,"")
    return v
}

/*Função que padroniza o Site*/
function Site(v){
    v=v.replace(/^http:\/\/?/,"")
    dominio=v
    caminho=""
    if(v.indexOf("/")>-1)
        dominio=v.split("/")[0]
    caminho=v.replace(/[^\/]*/,"")
    dominio=dominio.replace(/[^\w\.\+-:@]/g,"")
    caminho=caminho.replace(/[^\w\d\+-@:\?&=%\(\)\.]/g,"")
    caminho=caminho.replace(/([\?&])=/,"$1")
    if(caminho!="")dominio=dominio.replace(/\.+$/,"")
    v="http://"+dominio+caminho
    return v
}

/*Função que padroniza DATA*/
function Data(v){
    v=v.replace(/\D/g,"")
    v=v.replace(/(\d{2})(\d)/,"$1/$2")
    v=v.replace(/(\d{2})(\d)/,"$1/$2")
    return v
}

/*Função que padroniza DATA*/
function Hora(v){
    v=v.replace(/\D/g,"")
    v=v.replace(/(\d{2})(\d)/,"$1:$2")
    return v
}

/*Função que padroniza valor monétario*/
function Valor(v){
    v=v.replace(/\D/g,"") //Remove tudo o que não é dígito
    v=v.replace(/^([0-9]{3}\.?){3}-[0-9]{2}$/,"$1.$2");
    //v=v.replace(/(\d{3})(\d)/g,"$1,$2")
    v=v.replace(/(\d)(\d{2})$/,"$1.$2") //Coloca ponto antes dos 2 últimos digitos
    return v
}

/*Função que padroniza Area*/
function Area(v){
    v=v.replace(/\D/g,"")
    v=v.replace(/(\d)(\d{2})$/,"$1.$2")
    return v

}

function Mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}
function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}
function numeroFormatado(z){
    v = z.value;
    v=v.replace(/\D/g,"")  //permite digitar apenas números
    v=v.replace(/[0-9]{12}/,"inválido")   //limita pra máximo 999.999.999
    v=v.replace(/(\d{1})(\d{9})$/,"$1.$2")  //coloca ponto antes dos últimos 8 digitos
    v=v.replace(/(\d{1})(\d{6})$/,"$1.$2")  //coloca ponto antes dos últimos 8 digitos
    v=v.replace(/(\d{1})(\d{3})$/,"$1.$2")  //coloca ponto antes dos últimos 5 digitos
    z.value = v;
}
function adicionarTodosOnChange(comboDisponiveis, comboSelecionados){
    disponiveis = document.getElementById(comboDisponiveis);
    selecionados = document.getElementById(comboSelecionados);
    for (i = 0;i < disponiveis.length;i++){
        inserirValorCombo(comboSelecionados,disponiveis.options[i].value,disponiveis.options[i].text);
    }
    for (n = disponiveis.length;n >= 0;n--){
        disponiveis.remove(n);
    }
    ordenarCombo(selecionados);
}
function removerTodosOnChange(comboDisponiveis, comboSelecionados){
    disponiveis = document.getElementById(comboDisponiveis);
    selecionados = document.getElementById(comboSelecionados);
    for (i = 0;i < selecionados.length;i++){
        inserirValorCombo(comboDisponiveis,selecionados.options[i].value,selecionados.options[i].text);
    }
    for (n = selecionados.length;n >= 0;n--){
        selecionados.remove(n);
    }
    ordenarCombo(disponiveis);
}
function disponiveisOnChange(comboDisponiveis, comboSelecionados){
    disponiveis = document.getElementById(comboDisponiveis);
    selecionados = document.getElementById(comboSelecionados);
    var posicao = disponiveis.selectedIndex;
    if (posicao < 0){
        alert("Selecione um item do lado 'Disponíveis'");
        return;
    }
    inserirValorCombo(comboSelecionados,disponiveis.options[disponiveis.selectedIndex].value,disponiveis.options[disponiveis.selectedIndex].text);
    disponiveis.remove(disponiveis.selectedIndex);
    ordenarCombo(selecionados);
}
function disponiveisOnChangeSemRemover(comboDisponiveis, comboSelecionados){
    disponiveis = document.getElementById(comboDisponiveis);
    selecionados = document.getElementById(comboSelecionados);
    var posicao = disponiveis.selectedIndex;
    if (posicao < 0){
        alert("Selecione um item do lado 'Disponíveis'");
        return;
    }
    valor = disponiveis.options[disponiveis.selectedIndex].value
    texto = disponiveis.options[disponiveis.selectedIndex].text.trim();
    //Só para tipificação do PJNET
    inserirValorCombo(comboSelecionados,valor,texto);
    atualizarTextoTipificacao();
//ordenarCombo(selecionados);
}

function atualizarTextoTipificacao(){
    document.getElementById("textoTipificacao").value = "";
    combo = document.getElementById("_selecionados");
    for (i = 0;i < combo.length;i++){
        if (combo.options[i].text.substring(0,1) != ","){
            document.getElementById("textoTipificacao").value += " " + combo.options[i].text;
        }else{
            document.getElementById("textoTipificacao").value += combo.options[i].text;
        }

    }
}
function selecionadosOnChange(comboDisponiveis, comboSelecionados){
    disponiveis = document.getElementById(comboDisponiveis);
    selecionados = document.getElementById(comboSelecionados);
    var posicao = selecionados.selectedIndex;
    if (posicao < 0){
        alert("Selecione um item do lado 'Selecionados'");
        return;
    }
    valor = selecionados.options[selecionados.selectedIndex].text;
    inserirValorCombo(comboDisponiveis,valor,valor);
    selecionados.remove(selecionados.selectedIndex);
    ordenarCombo(disponiveis);
}
function selecionadosOnChangeSemRemover(comboDisponiveis, comboSelecionados){
    //disponiveis = document.getElementById(comboDisponiveis);
    selecionados = document.getElementById(comboSelecionados);
    var posicao = selecionados.selectedIndex;
    if (posicao < 0){
        alert("Selecione um ítem do lado 'Selecionados'");
        return;
    }
    //valor = selecionados.options[selecionados.selectedIndex].text;
    selecionados.remove(selecionados.selectedIndex);
    //PJNET
    atualizarTextoTipificacao();
    ordenarCombo(disponiveis);
}
function ordenarCombo(combo){
    var listaItens = new Array(combo.length);
    for (i = 0;i < combo.length;i++){
        listaItens[i] = combo.options[i].text + "__" + combo.options[i].value;
    }
    listaItens.sort();
    for (i = 0;i < combo.length;i++){
        var s = listaItens[i].split('__');
        combo.options[i].text = s[0];
        combo.options[i].value = s[1];
    }
}
function inserirValorCombo(objeto,valor,texto){
    var combo = document.getElementById(objeto);
    var opcao = document.createElement('option');
    opcao.text = texto;
    opcao.value = valor;
    combo.selectedIndex = combo.length - 1;
    try {
        combo.add(opcao,null); // Não funciona no IE
    } catch(ex) {
        combo.add(opcao); // IE
    }
}

function criarArray (x) {
    array = new Array(x);
    for (i = 0; i < array.length; ++ i){
        array [i] = '';
    }
    return array;
}
function criarArrayBiDimensional(x,y){
    arrayBi = new Array(x);
    for (i = 0; i < arrayBi.length; ++ i){
        arrayBi [i] = new Array(y);
    }
    return arrayBi;
}
function criarArrayTriDimensional(x,y,z){
    arrayTri = new Array(x);
    for (i = 0; i < arrayTri.length; ++ i){
        arrayTri [i] = new Array(y);
        for (n = 0; n < arrayTri [i].length; ++ n){
            arrayTri [i][n] = new Array(z);
        }
    }
    return arrayTri;
}

function setValorCampoDocumentoModelo(src){
    i = 1;
    var nome;
    nome = src.name.substring(0,src.name.length - 3);
    for (i = 0;i < 50;i++){
        if (document.getElementById(nome + "_" + (i<10?"0":"") + i + "_span") != null){
            document.getElementById(nome + "_" + (i<10?"0":"") + i + "_span").innerHTML = src.value;
        }
    }
}

function popularSpans(nomeCampo, valor){
    if (nomeCampo.substring(nomeCampo.length - 6,nomeCampo.length) == "HIDDEN"){
        nomeCampo = nomeCampo.substring(0,nomeCampo.length - 7);
    }else{
        nomeCampo = nomeCampo.substring(0,nomeCampo.length - 2);
    }
    for (i = 1;i < 80;i++){
        if (document.getElementById(nomeCampo + "_" + i + "_span") != null){
            document.getElementById(nomeCampo + "_" + i + "_span").innerHTML = valor;
        }
        i++;
    }
}
function popularSpanMultiSelecao(campo, valor){
    for (i = 1;i < 50;i++){
        if (document.getElementById(campo.substring(0,campo.length - 15) + "_" + i + "_span") != null){
            document.getElementById(campo.substring(0,campo.length - 15) + "_" + i + "_span").innerHTML = valor;
        }
        i++;
    }
}
function popularCampoSelecao(textoAnterior,textoPosterior,nomeCampo,nomeCombo){
    i = 1;
    nome = nomeCombo.substring(0,nomeCombo.length-3);
    index = document.getElementById(nomeCombo).selectedIndex;
    textoIndex = (index<10?"0":"") + index;
    valorOutroCampo = "";
    textoAnteriorOpcao = "";
    textoPosteriorOpcao = "";
    if (document.getElementById("OUTRO_CAMPO_OPCAO_" + textoIndex + "_" + nomeCombo) != null){
        valorOutroCampo = document.getElementById("OUTRO_CAMPO_OPCAO_" + textoIndex + "_" + nomeCombo).value;
    }else{
        valorOutroCampo = document.getElementById(nomeCombo).value;
    }
    if (document.getElementById(nomeCombo + "_TEXTO_ANTERIOR_OPCAO_" + textoIndex) != null){
        textoAnteriorOpcao = document.getElementById(nomeCombo + "_TEXTO_ANTERIOR_OPCAO_" + textoIndex).innerHTML;
    }
    if (document.getElementById(nomeCombo + "_TEXTO_POSTERIOR_OPCAO_" + textoIndex) != null){
        textoPosteriorOpcao = document.getElementById(nomeCombo + "_TEXTO_POSTERIOR_OPCAO_" + textoIndex).innerHTML;
    }
    valorFinal = textoAnterior + (textoAnterior.length > 0?" ":"") +
    textoAnteriorOpcao + (textoAnteriorOpcao.length > 0?" ":"") +
    valorOutroCampo +
    (textoPosteriorOpcao.length > 0?" ":"") + textoPosteriorOpcao +
    (textoPosterior.length > 0?" ":"") + textoPosterior;
    for (i = 1;i < 50;i++){
        if (document.getElementById(nome + "_" + (i<10?"0":"") + i + "_span") != null){
            document.getElementById(nome + "_" + (i<10?"0":"") + i + "_span").innerHTML = valorFinal;
        }
        i++;
    }
}
function popularCampoMultiSelecao(campo){
    document.getElementById(campo).value = "";
    for (i = 0;i < 50;i++){
        if (document.getElementById(campo + "@" + i) != null){
            if (document.getElementById(campo + "@" + i).checked){
                if (document.getElementById(campo).value.length > 0){
                    document.getElementById(campo).value = document.getElementById(campo).value.replace(" e ",", ");
                    document.getElementById(campo).value += " e ";
                }
                document.getElementById(campo).value += document.getElementById(campo + "@" + i).value;
            }
        }
        i++;
    }
    popularSpanMultiSelecao(campo, document.getElementById(campo).value);
}

function opcaoExibirCampo(opcao, campoImpactado){
    if (opcao.checked){
        document.getElementById(campoImpactado).style.visibility = 'visible';
        document.getElementById(campoImpactado).style.height = '20px';
    }else{
        document.getElementById(campoImpactado).style.visibility = 'hidden';
        document.getElementById(campoImpactado).style.height = '0px';
    }
}

function escreverValorPorExtensoTemp(c){
    var ex = [
    ["zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis", "dezessete", "dezoito", "dezenove"],
    ["dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"],
    ["cem", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"],
    ["mil", "milhão", "bilhão", "trilhão", "quadrilhão", "quintilhão", "sextilhão", "setilhão", "octilhão", "nonilhão", "decilhão", "undecilhão", "dodecilhão", "tredecilhão", "quatrodecilhão", "quindecilhão", "sedecilhão", "septendecilhão", "octencilhão", "nonencilhão"]
    ];
    var a, n, v, i, n = c.replace(c ? /[^,\d]/g : /\D/g, "").split(","), e = " e ", $ = "real", d = "centavo", sl;
    for(var f = n.length - 1, l, j = -1, r = [], s = [], t = ""; ++j <= f; s = []){
        j && (n[j] = (+("." + n[j])).toFixed(Math.max(2, n[j].length)).slice(2, 4));
        if(!(a = (v = n[j]).slice((l = v.length) % 3).match(/\d{3}/g), v = l % 3 ? [v.slice(0, l % 3)] : [], v = a ? v.concat(a) : v).length) continue;
        for(a = -1, l = v.length; ++a < l; t = ""){
            if(!(i = v[a] * 1)) continue;
            i % 100 < 20 && (t += ex[0][i % 100]) ||
            i % 100 + 1 && (t += ex[1][(i % 100 / 10 >> 0) - 1] + (i % 10 ? e + ex[0][i % 10] : ""));
            s.push((i < 100 ? t : !(i % 100) ? ex[2][i == 100 ? 0 : i / 100 >> 0] : (ex[2][i / 100 >> 0] + e + t)) +
                ((t = l - a - 2) > -1 ? " " + (i > 1 && t > 0 ? ex[3][t].replace("ão", "ões") : ex[3][t]) : ""));
        }

        a = ((sl = s.length) > 1 ? (a = s.pop(), s.join(" ") + e + a) : s.join("") || ((!j && (n[j + 1] * 1 > 0) || r.length) ? "" : ex[0][0]));
        a && r.push(a + (c ? (" " + (v.join("") * 1 > 1 ? j ? d + "s" : (sl == 1 ? "" : "") + $.replace("l", "is") : j ? d : $)) : ""));
    }
    return r.join(e);
}

function escreverDiaPorExtenso(c){
    var x = '';
    if (c <= 1){
        x = escreverNumeroPorExtenso(c);
        x = x.replace("um","primeiro");
    }
    else{
        x = escreverNumeroPorExtenso(c);
    }
    return x;
}

function escreverNumeroPorExtenso(c){
    var ex = [
    ["zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis", "dezessete", "dezoito", "dezenove"],
    ["dez", "vinte", "trinta", "quarenta", "cinquenta", "sessenta", "setenta", "oitenta", "noventa"],
    ["cem", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"],
    ["mil", "milhão", "bilhão", "trilhão", "quadrilhão", "quintilhão", "sextilhão", "setilhão", "octilhão", "nonilhão", "decilhão", "undecilhão", "dodecilhão", "tredecilhão", "quatrodecilhão", "quindecilhão", "sedecilhão", "septendecilhão", "octencilhão", "nonencilhão"]
    ];
    var a, n, v, i, n = c.replace(c ? /[^,\d]/g : /\D/g, "").split(","), e = " e ", $ = "", d = "", sl;
    for(var f = n.length - 1, l, j = -1, r = [], s = [], t = ""; ++j <= f; s = []){
        j && (n[j] = (+("." + n[j])).toFixed(Math.max(2, n[j].length)).slice(2, 4));
        if(!(a = (v = n[j]).slice((l = v.length) % 3).match(/\d{3}/g), v = l % 3 ? [v.slice(0, l % 3)] : [], v = a ? v.concat(a) : v).length) continue;
        for(a = -1, l = v.length; ++a < l; t = ""){
            if(!(i = v[a] * 1)) continue;
            i % 100 < 20 && (t += ex[0][i % 100]) ||
            i % 100 + 1 && (t += ex[1][(i % 100 / 10 >> 0) - 1] + (i % 10 ? e + ex[0][i % 10] : ""));
            s.push((i < 100 ? t : !(i % 100) ? ex[2][i == 100 ? 0 : i / 100 >> 0] : (ex[2][i / 100 >> 0] + e + t)) +
                ((t = l - a - 2) > -1 ? " " + (i > 1 && t > 0 ? ex[3][t].replace("ão", "ões") : ex[3][t]) : ""));
        }

        a = ((sl = s.length) > 1 ? (a = s.pop(), s.join(" ") + e + a) : s.join("") || ((!j && (n[j + 1] * 1 > 0) || r.length) ? "" : ex[0][0]));
        a && r.push(a + (c ? (" " + (v.join("") * 1 > 1 ? j ? d + "" : (sl == 1 ? "" : "") + $.replace("", "") : j ? d : $)) : ""));
    }
    var texto = r.join(e);
    return texto.substring(0,texto.length-1);
}

function getValorDouble(valorComDecimal)
{
    var valor = valorComDecimal + "";
    valor = valor.replace('.','');
    valor = valor.replace(',','.');
    return (valor*1);
}

function getValorMoeda(valor)
{
    var retorno = "";
    valorProvisorio = valor;
    if (valorProvisorio < 0) valorProvisorio = valorProvisorio * -1;
    if (valorProvisorio < 0.1)
    {
        if (valor < 0) return "-0,0" + Math.round(valorProvisorio * 100);
        return "0,0" + Math.round(valorProvisorio * 100);
    }
    if (valorProvisorio < 1)
    {
        if (valor < 0) return "-0," + Math.round(valorProvisorio * 100);
        return "0," + Math.round(valorProvisorio * 100);
    }

    valorString = Math.round(valorProvisorio * 100) + "";
    valorInteiro = valorString.substring(0,valorString.length-2);
    valorInteiroPontuado = "";
    tam = valorInteiro.length;
    if (tam > 3)
    {
        if ((tam%3) > 0)
        {
            valorInteiroPontuado += valorInteiro.substring(0,(tam%3)) + ".";
            valorInteiro = valorInteiro.substring( (tam%3),tam);
            tam = tam - (tam%3);
        }
        posInicial = 0;
        for (i = 1;i <= tam;i++)
        {
            if ((i%3) == 0)
            {
                if (posInicial != 0 && posInicial != tam) valorInteiroPontuado += ".";
                valorInteiroPontuado += valorInteiro.substring(posInicial,i);
                posInicial = i;
            }
        }
    }
    else
    {
        valorInteiroPontuado += valorInteiro;
    }
    retorno = valorInteiroPontuado + "," + valorString.substring(valorString.length-2,valorString.length);
    if (valor < 0) return "-" + retorno;
    return retorno;
}

function getMesesEntreDatas(aaaammdd_1, aaaammdd_2)
{
    var meses = 0;
    var data1 = aaaammdd_1;
    var data2 = aaaammdd_2;
    if (aaaammdd_1.substring(6,7) == "0")
        dia = aaaammdd_1.substring(7,8) - 1;
    else
        dia = aaaammdd_1.substring(6,8) - 1;
    if (aaaammdd_1.substring(4,5) == "0")
        mes = aaaammdd_1.substring(5,6);
    else
        mes = aaaammdd_1.substring(4,6);
    var ano = aaaammdd_1.substring(0,4);
    while (data1 < data2)
    {
        if (mes < 12)
        {
            mes++;
        }
        else
        {
            mes = 1;
            ano ++;
        }
        meses++;
        data1 = "" + ano + (mes<10?"0":"") + "" + mes + "" + dia;
    }
    if (meses > 0) meses--;
    return meses;
}

function getDiasEntreDatas(aaaammdd_1, aaaammdd_2)
{
    var nDias = 0;
    var dia = aaaammdd_1;
    while(dia < aaaammdd_2)
    {
        nDias++;
        dia = proximoDia(dia);
    }
    return nDias;
}
function converterPara_AAAAmmdd(ddmmaaaa)
{
    var data = ddmmaaaa.substring(6,10) + ddmmaaaa.substring(3,5) + ddmmaaaa.substring(0,2);
    return data;
}
//Retorna o proximo dia no formato aaaammdd
function proximoDia(aaaammdd)
{
    var dia = 0;
    var mes = 0;
    if (aaaammdd.substring(6,7) == "0")
        dia = aaaammdd.substring(7,8);
    else
        dia = aaaammdd.substring(6,8);
    if (aaaammdd.substring(4,5) == "0")
        mes = aaaammdd.substring(5,6);
    else
        mes = aaaammdd.substring(4,6);
    mes--;
    var ano = aaaammdd.substring(0,4);
    var diaTeste = dia;
    dia++;
    novoDia = new Date(ano,mes,dia);
    if (novoDia.getDate() < dia)
    {
        mes++;
        dia = 1;
    }
    novoDia = new Date(ano,mes,dia);
    if (novoDia.getYear()<2000)
        ano = 1900 + novoDia.getYear();
    else
        ano = novoDia.getYear();
    if (novoDia.getMonth()<9)
        mes = "0" + (novoDia.getMonth() + 1);
    else
        mes = novoDia.getMonth() + 1;
    if (novoDia.getDate()<10)
        dia = "0" + (novoDia.getDate());
    else
        dia = novoDia.getDate();
    return ano + "" + mes + "" + dia;
}

function seNumeroVazioPreencherCom(src,valor)
{
    if (src.value.length == 0)
    {
        src.value = valor;
    }
    if (src.value.length > 1 && (src.value.substring(1,2) != ",") && src.value.substring(0,1) == "0"){
        src.value = src.value.substring(1,src.value.length);
        seNumeroVazioPreencherCom(src,valor)
    }
}

function seVazioPreencherCom(src,valor)
{
    if (src.value.length == 0)
    {
        src.value = valor;
    }
    else
    {
        if (src.value.substring(0,1) == ",") src.value = "0" + src.value;
        if (src.value.substring(src.value.length-3,src.value.length-2 != ","))
        {

            if (src.value.substring(src.value.length-3,src.value.length-2) != ",")
            {
                if (src.value.substring(src.value.length-2,src.value.length-1) == ",")
                {
                    src.value = src.value + "0";
                }
                else
                {
                    if (src.value.substring(src.value.length-1,src.value.length) == ",")
                    {
                        src.value = src.value + "00";
                    }
                    else
                    {
                        src.value = src.value + ",00";
                    }
                }
            }
        }
    }

}

function toProperCase(s)
{
    return s.toLowerCase().replace(/^(.)|\s(.)/g, function($1) {
        return $1.toUpperCase();
    });
}

function trim(objeto)
{
    while(''+objeto.value.charAt(0)==' ')objeto.value=objeto.value.substring(1,objeto.value.length);
    objeto.value += " ";
    sString = "";
    charValor = objeto.value.charAt(0);
    for (i = 1; i < objeto.value.length;i++)
    {
        if (!(objeto.value.charAt(i)== ' ' && charValor == ' '))
        {
            sString = sString + charValor;
        }
        charValor = objeto.value.charAt(i);
    }
    objeto.value = sString;
}

function replaceAll(texto, token, newtoken) {
    while (texto.indexOf(token) != -1) {
        texto = texto.replace(token, newtoken);
    }
    return texto;
}

function propername(objeto)
{
    trim(objeto);
    objeto.value = toProperCase(objeto.value);
    objeto.value = replaceAll(objeto.value," De "," de ");
    objeto.value = replaceAll(objeto.value," Ao "," ao ");
    objeto.value = replaceAll(objeto.value," Aos "," aos ");
    objeto.value = replaceAll(objeto.value," Da "," da ");
    objeto.value = replaceAll(objeto.value," Do "," do ");
    objeto.value = replaceAll(objeto.value," Das "," das ");
    objeto.value = replaceAll(objeto.value," Dos "," dos ");
    objeto.value = replaceAll(objeto.value," E "," e ");
    if (objeto.value.substring(0,2) == "E ")
    {
        objeto.value = "e " + objeto.value.substring(1,objeto.value.length);
    }

    objeto.value = replaceAll(objeto.value," Ii "," II ");
    objeto.value = replaceAll(objeto.value," Iii "," III ");
    objeto.value = replaceAll(objeto.value," Iv "," IV ");
    objeto.value = replaceAll(objeto.value," Vi "," VI ");
    objeto.value = replaceAll(objeto.value," Vii "," VII ");
    objeto.value = replaceAll(objeto.value," Viii "," VIII ");
    objeto.value = replaceAll(objeto.value," Ix "," IX ");
    objeto.value = replaceAll(objeto.value," Xi "," XI ");
    objeto.value = replaceAll(objeto.value," Xii "," XII ");
    objeto.value = replaceAll(objeto.value," Xiii "," XIII ");

    /*if (objeto.value.substring(0,3) == "De ")
    {
        objeto.value = "de" + objeto.value.substring(2,objeto.value.length);
    }
    if (objeto.value.substring(0,3) == "Da ")
    {
        objeto.value = "da" + objeto.value.substring(2,objeto.value.length);
    }
    if (objeto.value.substring(0,3) == "Do ")
    {
        objeto.value = "do" + objeto.value.substring(2,objeto.value.length);
    }
    if (objeto.value.substring(0,4) == "Das ")
    {
        objeto.value = "das" + objeto.value.substring(3,objeto.value.length);
    }
    if (objeto.value.substring(0,4) == "Dos ")
    {
        objeto.value = "dos" + objeto.value.substring(3,objeto.value.length);
    }
    if (objeto.value.substring(0,3) == "Ao ")
    {
        objeto.value = "ao" + objeto.value.substring(2,objeto.value.length);
    }

    if (objeto.value.substring(0,4) == "Aos ")
    {
        objeto.value = "aos" + objeto.value.substring(3,objeto.value.length);
    }

     */
    if (objeto.value.substring(objeto.value.length-3,objeto.value.length) == " Ii")
    {
        objeto.value = objeto.value.substring(0,objeto.value.length-3) + " II";
    }
    if (objeto.value.substring(objeto.value.length-4,objeto.value.length) == " Iii")
    {
        objeto.value = objeto.value.substring(0,objeto.value.length-4) + " III";
    }
    if (objeto.value.substring(objeto.value.length-3,objeto.value.length) == " Iv")
    {
        objeto.value = objeto.value.substring(0,objeto.value.length-3) + " IV";
    }
    if (objeto.value.substring(objeto.value.length-3,objeto.value.length) == " Vi")
    {
        objeto.value = objeto.value.substring(0,objeto.value.length-3) + " VI";
    }
    if (objeto.value.substring(objeto.value.length-4,objeto.value.length) == " Vii")
    {
        objeto.value = objeto.value.substring(0,objeto.value.length-4) + " VII";
    }
    if (objeto.value.substring(objeto.value.length-5,objeto.value.length) == " Viii")
    {
        objeto.value = objeto.value.substring(0,objeto.value.length-5) + " VIII";
    }
    if (objeto.value.substring(objeto.value.length-3,objeto.value.length) == " Ix")
    {
        objeto.value = objeto.value.substring(0,objeto.value.length-3) + " IX";
    }
    if (objeto.value.substring(objeto.value.length-3,objeto.value.length) == " Xi")
    {
        objeto.value = objeto.value.substring(0,objeto.value.length-3) + " XI";
    }
    if (objeto.value.substring(objeto.value.length-4,objeto.value.length) == " Xii")
    {
        objeto.value = objeto.value.substring(0,objeto.value.length-4) + " XII";
    }
    if (objeto.value.substring(objeto.value.length-5,objeto.value.length) == " Xiii")
    {
        objeto.value = objeto.value.substring(0,objeto.value.length-5) + " XIII";
    }
}


function validaCNPJ(objeto) {
    CNPJ = objeto.value;
    if (CNPJ.length == 0){
        return true;
    }
    erro = new String;
    if (CNPJ.length < 18) erro += "É necessario preencher corretamente o número do CNPJ! \n\n";
    if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-")){
        if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
    }
    //substituir os caracteres que não são números
    if(document.layers && parseInt(navigator.appVersion) == 4){
        x = CNPJ.substring(0,2);
        x += CNPJ. substring (3,6);
        x += CNPJ. substring (7,10);
        x += CNPJ. substring (11,15);
        x += CNPJ. substring (16,18);
        CNPJ = x;
    } else {
        CNPJ = CNPJ. replace (".","");
        CNPJ = CNPJ. replace (".","");
        CNPJ = CNPJ. replace ("-","");
        CNPJ = CNPJ. replace ("/","");
    }
    var nonNumbers = /\D/;
    if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n";
    var a = [];
    var b = new Number;
    var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
    for (i=0; i<12; i++){
        a[i] = CNPJ.charAt(i);
        b += a[i] * c[i+1];
    }
    if ((x = b % 11) < 2) {
        a[12] = 0
    } else {
        a[12] = 11-x
    }
    b = 0;
    for (y=0; y<13; y++) {
        b += (a[y] * c[y]);
    }
    if ((x = b % 11) < 2) {
        a[13] = 0;
    } else {
        a[13] = 11-x;
    }
    if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
        erro +="CNPJ inválido!";
    }
    if (erro.length > 0){
        alert(erro);
        objeto.value = '';
        objeto.focus();
    }
}


function validaCPF(objeto)
{
    cpf = objeto.value;
    if (cpf.length == 0){
        return true;
    }
    cpf = cpf.replace(".","");
    cpf = cpf.replace(".","");
    cpf = cpf.replace("-","");
    erro = new String;
    if (cpf.length < 11) erro += "São necessários 11 dígitos para verificação do CPF! \n\n";
    var nonNumbers = /\D/;
    if (nonNumbers.test(cpf)) erro += "A verificação de CPF suporta apenas números! \n\n";
    if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
        erro += "Número de CPF inválido!"
    }
    var a = [];
    var b = new Number;
    var c = 11;
    for (i=0; i<11; i++){
        a[i] = cpf.charAt(i);
        if (i < 9) b += (a[i] * --c);
    }
    if ((x = b % 11) < 2) {
        a[9] = 0
    } else {
        a[9] = 11-x
    }
    b = 0;
    c = 11;
    for (y=0; y<10; y++) b += (a[y] * c--);
    if ((x = b % 11) < 2) {
        a[10] = 0;
    } else {
        a[10] = 11-x;
    }
    if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])){
        erro +="CPF inválido!";
    }
    if (erro.length > 0){
        alert(erro);
        objeto.value = '';
        objeto.focus();
        return false;
    }
    return true;
}

function validaAAAAmm(src){
    if (src.value.length < 7 && src.value.length >= 1){
        alert("Formato inválido. Use AAAA/mm");
        if (navigator.appName == "Microsoft Internet Explorer"){
            src.focus();
        }else{
            src.value = "";
        }
    }
    if (parseInt(src.value.substring(5,7))> 12){
        alert("Mês inválido");
        if (navigator.appName == "Microsoft Internet Explorer"){
            src.focus();
        }else{
            src.value = "";
        }
    }
}

//CEP  - OnKeyPress="formataTudo(this, '#####-###')"
//CPF  - OnKeyPress="formataTudo(this, '###.###.###-##')"
//DATA - OnKeyPress="formataTudo(this, '##/##/####')"
//Periodo - OnKeyPress="formatar(this, '####/#')"
function formataTudo(src, mask)
{
    if (src.value.length == mask.length)
    {
        src.value = src.value.substring(0,mask.length-1);
    }
    else
    {
        var i = src.value.length;
        var saida = mask.substring(0,1);
        var texto = mask.substring(i)
        if (texto.substring(0,1) != saida)
        {
            src.value += texto.substring(0,1);
        }
    }
}

function formataValor(valor)
{
    v = valor * 1000;
    valorTexto = "" + Math.round(v);
    if(valor < 0.1) return "0.0" + valorTexto.substring(0,1);
    if(valor < 1) return "0." + valorTexto.substring(0,2);
    return valorTexto.substring(0,valorTexto.length - 3) + "." + valorTexto.substring(valorTexto.length - 3,valorTexto.length - 1);
}
function temUmPonto(src)
{
    quantos = 0;
    for (i = 0;i < src.length;i++)
    {
        if (src.substring(i,i+1) == "," || src.substring(i,i+1) == ".")
        {
            quantos++;
            if (quantos == 1)
            {
                return true;
            }
        }
    }
    return false;
}
function validaHora(src)
{
    if (src.value != "" ){
        src.value = src.value.substring(0,5);
        if (!isNumber(src.value.substring(0,1)) ||
            !isNumber(src.value.substring(1,2)) ||
            !isNumber(src.value.substring(3,4)) ||
            !isNumber(src.value.substring(4,5)) ||
            src.value.substring(2,3) != ":"){
            alert("Hora inválida. Formato = HH:MM");
            src.value = "";
            src.focus();
            return false;
        }
        valor1 = 0;
        valor1 = src.value.substring(0,2);
        valor2 = 0;
        valor2 = src.value.substring(3,5);
        if (valor1 > 23 || valor2 > 59)
        {
            alert("Hora inválida. Formato = HH:MM");
            src.value = "";
            src.focus();
            return false;
        }
        else
        {
            if (src.value.length < 5 && src.value.length > 0)
            {
                alert("Hora inválida. Formato = HH:MM");
                src.value = "";
                src.focus();
                return false;
            }
        }
    }
    return true;
}


function validaHoraSemLimite(src)
{
    src.value = src.value.substring(0,5);
    valor1 = 0;
    valor1 = src.value.substring(0,2);
    valor2 = 0;
    valor2 = src.value.substring(3,5);
    if (valor2 > 59)
    {
        alert("Hora inválida. Formato = HH:MM");
        src.focus();
        return false;
    }
    else
    {
        if (src.value.length < 5 && src.value.length > 0)
        {
            alert("Hora inválida. Formato = HH:MM");
            src.focus();
            return false;
        }
    }
    return true;
}


function formataPlaca(src,event){
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(event.keyCode == 46 || keyCode == 37 || keyCode == 39 || keyCode == 8 || keyCode == 36 || keyCode == 35))
    {
        if (!(keyCode == 13 || keyCode == 37 || keyCode == 39 || keyCode == 9)){
            if (src.value.length < 3){
                if (!((keyCode >= 97 && keyCode <= 122) || (keyCode >= 65 && keyCode <= 90))){
                    event.preventDefault? event.preventDefault() : event.returnValue = false;
                }
            }
            if (src.value.length == 3){
                event.preventDefault? event.preventDefault() : event.returnValue = false;
                src.value = src.value + "-";
            }
            if (src.value.length > 3){
                if (!(keyCode >= 48 && keyCode <= 57)){
                    event.preventDefault? event.preventDefault() : event.returnValue = false;
                }
            }
        }
    }
}
function formataPlacaOnBlur(src){
    if (src.value.length > 0){
        var erro = false;
        if (src.value.length > 8){
            src.value = src.value.substring(0,8);
        }
        if (src.value.length < 8){
            erro = true;
        }else{
            if (!(src.value.charCodeAt(0) >= 65 && src.value.charCodeAt(0) <= 90)){
                erro = true
            }
            if (!(src.value.charCodeAt(1) >= 65 && src.value.charCodeAt(1) <= 90)){
                erro = true
            }
            if (!(src.value.charCodeAt(2) >= 65 && src.value.charCodeAt(2) <= 90)){
                erro = true
            }
            if (src.value.charCodeAt(3) != 45){
                erro = true
            }
            if (!(src.value.charCodeAt(4) >= 48 && src.value.charCodeAt(4) <= 57)){
                erro = true
            }
            if (!(src.value.charCodeAt(5) >= 48 && src.value.charCodeAt(5) <= 57)){
                erro = true
            }
            if (!(src.value.charCodeAt(6) >= 48 && src.value.charCodeAt(6) <= 57)){
                erro = true
            }
            if (!(src.value.charCodeAt(7) >= 48 && src.value.charCodeAt(7) <= 57)){
                erro = true
            }
        }
        if (erro){
            alert("Formato de placa incorreto.\nDigite a placa no formato AAA 9999\n(três letras em maiúsculo seguidas de um espaço e mais quatro números).");
            src.value = "";
            src.focus();
        }
    }
}
function formataPlacaOnKeyUp(src){
    src.value = src.value.toUpperCase();
}

function formataData(src,event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35))
    {
        if ((keyCode >= 48 && keyCode <= 57) || keyCode == 46 || keyCode == 13 || keyCode == 37 || keyCode == 39 || keyCode == 9)
        {
            if (src.value.length == 2)
            {
                src.value = src.value.substring(0,2) + "/";
            }
            if (src.value.length == 5)
            {
                src.value = src.value.substring(0,5) + "/";
            }
            if (src.value.length > 10)
            {
                src.value = src.value.substring(0,10);
            }
        }
        else
        {
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}

function formataDataMMAAAA(src,event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35))
    {
        if ((keyCode >= 48 && keyCode <= 57) || keyCode == 46 || keyCode == 13 || keyCode == 37 || keyCode == 39 || keyCode == 9)
        {
            if (src.value.length == 2)
            {
                src.value = src.value.substring(0,2) + "/";
            }
            if (src.value.length > 7)
            {
                src.value = src.value.substring(0,7);
            }
        }
        else
        {
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}

function formataDataAAAAMM(src,event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35))
    {
        if ((keyCode >= 48 && keyCode <= 57) || keyCode == 46 || keyCode == 13 || keyCode == 37 || keyCode == 39 || keyCode == 9)
        {
            if (src.value.length == 4)
            {
                src.value = src.value.substring(0,4) + "/";
            }
            if (src.value.length > 7)
            {
                src.value = src.value.substring(0,7);
            }
        }
        else
        {
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}

function formataHora(src, mask,event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    //alert(keyCode);
    if (src.value.length == 5)
    {
    //keyCode = 0;
    }
    if ((keyCode >= 48 && keyCode <= 57) || keyCode == 8 || keyCode == 9 || keyCode == 127 || keyCode == 46 || keyCode == 37 || keyCode == 39)
    {
        //formataTudo(src,mask);
        if (src.value.length == 2 && keyCode != 8)
        {
            src.value = src.value.substring(0,2) + ":";
        }
        if (src.value.length > 5 && keyCode != 8)
        {
            src.value = src.value.substring(0,5);
        }
    }
    else
    {
        event.preventDefault? event.preventDefault() : event.returnValue = false;
    }

}

function temUmaVirgula(src)
{
    quantos = 0;
    for (i = 0;i < src.length;i++)
    {
        if (src.substring(i,i+1) == "," || src.substring(i,i+1) == ".")
        {
            quantos++;
            if (quantos == 1)
            {
                return true;
            }
        }
    }
    return false;
}

function formataNumeroComDecimal(src, mask, event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (keyCode == 45 && src.value.length > 0)
    {
        event.preventDefault? event.preventDefault() : event.returnValue = false;
    }
    valorTemp = src.value * 10 + "";
    if (valorTemp.replace(",","").length != valorTemp.length)
    {
        event.preventDefault? event.preventDefault() : event.returnValue = false;
    }
    else
    {
        if (keyCode == 46)
        {
            keyCode = 44;
        }
        if (keyCode == 46 || keyCode == 44)
        {
            if (temUmPonto(src.value))
            {
                event.preventDefault? event.preventDefault() : event.returnValue = false;
            }
            else
            {
                keyCode = 44;
            }
        }
        if ((keyCode >= 48 && keyCode <= 57) || (keyCode == 44 && keyCode == 46))
        {
            formataTudo(src,mask);
        }
        else
        {
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}

function formataNumero(event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35 || keyCode == 46)){
        if (!( (keyCode >= 48 && keyCode <= 57) || keyCode == 13 || keyCode == 9)){
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}
function formataNumeroInteiro(event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35 || keyCode == 46)){
        if (!( (keyCode >= 48 && keyCode <= 57) || keyCode == 13 || keyCode == 9)){
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}
function maiusculas(src, event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35 || keyCode == 46)){
        if (!( (keyCode >= 65 && keyCode <= 122) || keyCode == 13 || keyCode == 9)){
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }else{
            src.value = src.value.toUpperCase();
        }
    }
}

function formataTelefone(src, event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35 || keyCode == 46 || (keyCode == 9 && (src.value.length == 12|| src.value.length == 0))))
    {
        if (keyCode >= 48 && keyCode <= 57)
        {
            formataTudo(src,'## ####-####');
        }
        else
        {
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}


function FormataRG(campo,teclapres)
{
    var tecla = teclapres.keyCode;
    var keyCode = tecla;

    if (!(keyCode == 46 || keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 36 || keyCode == 35)){
        vr = Limpar(campo.value,"0123456789");
        tam = vr.length;

        if ((tam == 3 || tam == 6) && (keyCode >= 48 && keyCode <= 57))
        {
            campo.value += ".";
        }
    }
}


function formataCPF(src, event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    //alert(keyCode);
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35 || (keyCode == 9 && src.value.length == 14)))
    {
        if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 127 || keyCode == 127 || keyCode == 36 || keyCode == 46)){
            if (keyCode >= 48 && keyCode <= 57)
            {
                formataTudo(src,'###.###.###-##');
            }
            else
            {
                event.preventDefault? event.preventDefault() : event.returnValue = false;
            }
        }
    }
}
function formataData1(src)
{
    if (window.event.keyCode >= 48 && window.event.keyCode <= 57)
    {
        formataTudo(src,'##/##/####');
    }
    else
    {
        window.event.keyCode = 0;
    }
}
function formataCEP(src, event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 127 || keyCode == 36 || keyCode == 46 || keyCode == 35 || (keyCode == 9 && (src.value.length == 9 || src.value.length == 0))))
    {
        if (keyCode >= 48 && keyCode <= 57)
        {
            formataTudo(src,'#####-###');
        }
        else
        {
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}
function formataCNPJ(src, event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35 || (keyCode == 9 && src.value.length == 18)))
    {
        if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 127 || keyCode == 127 || keyCode == 36 || keyCode == 46)){
            if (keyCode >= 48 && keyCode <= 57)
            {
                formataTudo(src,'##.###.###/####-##');
            }
            else
            {
                event.preventDefault? event.preventDefault() : event.returnValue = false;
            }
        }
    }
}

function pop(html){
    window.open(html, "", "width=710, heigth=610");
}

function getNumeroDeData(numero)
{
    if (numero < 10)
        return  "0" + numero;
    else
        return numero;
}
function getData_ddmmAAAA_hhmm_Atual()
{
    dt = new Date();
    if (navigator.appName == "Microsoft Internet Explorer")
        return getNumeroDeData(dt.getDate())+"/"+getNumeroDeData(dt.getMonth()+1)+"/"+getNumeroDeData(dt.getYear()) + " " + getNumeroDeData(dt.getHours())+":"+getNumeroDeData(dt.getMinutes());
    else
        return getNumeroDeData(dt.getDate())+"/"+getNumeroDeData(dt.getMonth()+1)+"/"+(dt.getYear()+ 1900) + " " + getNumeroDeData(dt.getHours())+":"+getNumeroDeData(dt.getMinutes());
}
function getData_ddmmAAAA_hhmmss_Atual()
{
    dt = new Date();
    if (navigator.appName == "Microsoft Internet Explorer")
        return getNumeroDeData(dt.getDate())+"/"+getNumeroDeData(dt.getMonth()+1)+"/"+getNumeroDeData(dt.getYear()) + " " + dt.getHours()+":"+dt.getMinutes()+":"+dt.getSeconds();
    else
        return getNumeroDeData(dt.getDate())+"/"+getNumeroDeData(dt.getMonth()+1)+"/"+(dt.getYear()+1900) + " " + dt.getHours()+":"+dt.getMinutes()+":"+dt.getSeconds();
}
function getData_ddmmAAAA_Atual()
{
    dt = new Date();
    if (navigator.appName == "Microsoft Internet Explorer")
        return getNumeroDeData(dt.getDate())+"/"+getNumeroDeData(dt.getMonth()+1)+"/"+getNumeroDeData(dt.getYear());
    else
        return getNumeroDeData(dt.getDate())+"/"+getNumeroDeData(dt.getMonth()+1)+"/"+(dt.getYear()+1900);
}
var dtCh= "/";
var minYear=1900;
var maxYear=2030;



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 = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
    for (var i = 1; i <= n; i++) {
        this[i] = 31
        if (i==4 || i==6 || i==9 || i==11) {
            this[i] = 30
        }
        if (i==2) {
            this[i] = 29
        }
    }
    return this
}

function validarData(objeto)
{
    data = objeto.value;
    if (data != "")
    {
        data=data.substring(3,5) + "/" + data.substring(0,2) + "/" + data.substring(6,10);
        isDate(data,objeto);
    }
}

function isDate(dtStr,objeto){
    var daysInMonth = DaysArray(12)
    var pos1=dtStr.indexOf(dtCh)
    var pos2=dtStr.indexOf(dtCh,pos1+1)
    var strMonth=dtStr.substring(0,pos1)
    var strDay=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=parseInt(strMonth)
    day=parseInt(strDay)
    year=parseInt(strYr)
    if (pos1==-1 || pos2==-1){
        alert("A data deve ser no formato : dd/mm/AAAA")
        objeto.value = "";
        objeto.focus();
        return false;
    }
    if (strMonth.length<1 || month<1 || month>12){
        alert("O mês não é válido")
        objeto.value = "";
        objeto.focus();
        return false;
    }
    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
        alert("O dia não é válido");
        objeto.value = "";
        objeto.focus();
        return false;
    }
    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
        alert("Entre com um ano de quatro dígitos entre "+minYear+" e "+maxYear)
        objeto.value = "";
        objeto.focus();
        return false;
    }
    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
        alert("Esta data não é valida");
        objeto.value = "";
        objeto.focus();
        return false;
    }
    return true
}

function ValidateForm(){
    var dt=document.frmSample.txtDate
    if (isDate(dt.value)==false){
        dt.focus()
        return false
    }
    return true
}

function completaFormatacaoData(objeto)
{
    if (objeto.value.length < 10){
        objeto.value = "";
    }
    if (objeto.value.length > 10 && objeto.value.length < 14)
    {
        objeto.value = objeto.value.substring(0,10);
    }
    if (objeto.value.length > 16)
    {
        objeto.value = objeto.value.substring(0,16);
    }
    validarData(objeto);

}
function eNumero(texto)
{
    var numeros = "0123456789";
    retorno = false;
    for (n=0;n < texto.length;n++)
    {
        retorno = false;
        for (i=0;i<numeros.length;i++)
        {
            if (texto.substring(n,i+1) == numeros.charAt(i))
            {
                retorno = true;
                break;
            }
        }
    }
    return retorno;
}
function isNumber(texto)
{
    var numeros = "0123456789";
    for (i=0;i<numeros.length;i++)
    {
        if (texto == numeros.charAt(i))
        {
            return texto;
            break;
        }
    }
    return "";
}
function isSlashOrNumber(texto)
{
    if (isNumber(texto) != ""){
        return texto;
    }
    if (texto == "/")
    {
        return "/";
    }
    else
    {
        return "";
    }
}
function isCollonOrNumber(texto)
{
    if (isNumber(texto) != ""){
        return texto;
    }
    if (texto == ":")
    {
        return ":";
    }
    else
    {
        return "";
    }
}
function isBlankSpaceOrNumber(texto)
{
    if (isNumber(texto) != ""){
        return texto;
    }
    if (texto == " ")
    {
        return " ";
    }
    else
    {
        return "";
    }
}


function formataDataHora(objeto)
{
    if (objeto.value.length == 1)objeto.value = isNumber(objeto.value.substring(0,1));
    if (objeto.value.length == 2)objeto.value = objeto.value.substring(0,1) + isNumber(objeto.value.substring(1,2));
    if (objeto.value.length == 3)objeto.value = objeto.value.substring(0,2) + isSlashOrNumber(objeto.value.substring(2,3));
    if (objeto.value.length == 4)objeto.value = objeto.value.substring(0,3) + isNumber(objeto.value.substring(3,4));
    if (objeto.value.length == 5)objeto.value = objeto.value.substring(0,4) + isNumber(objeto.value.substring(4,5));
    if (objeto.value.length == 6)objeto.value = objeto.value.substring(0,5) + isSlashOrNumber(objeto.value.substring(5,6));
    //if (objeto.value.length == 7)objeto.value = objeto.value.substring(0,6) + isNumber(objeto.value.substring(6,7));
    //if (objeto.value.length == 8)objeto.value = objeto.value.substring(0,7) + isNumber(objeto.value.substring(7,8));
    //if (objeto.value.length == 9)objeto.value = objeto.value.substring(0,8) + isNumber(objeto.value.substring(8,9));
    //if (objeto.value.length == 10)objeto.value = objeto.value.substring(0,9) + isNumber(objeto.value.substring(9,10));
    //if (objeto.value.length == 11)objeto.value = objeto.value.substring(0,10) + " " + isBlankSpaceOrNumber(objeto.value.substring(10,11));;
    //if (objeto.value.length == 12)objeto.value = objeto.value.substring(0,11) + isNumber(objeto.value.substring(11,12));
    //if (objeto.value.length == 13)objeto.value = objeto.value.substring(0,12) + isNumber(objeto.value.substring(12,13));
    //if (objeto.value.length == 14)objeto.value = objeto.value.substring(0,13) + isCollonOrNumber(objeto.value.substring(13,14));
    //if (objeto.value.length == 15)objeto.value = objeto.value.substring(0,14) + isNumber(objeto.value.substring(14,15));
    //if (objeto.value.length == 16)objeto.value = objeto.value.substring(0,15) + isNumber(objeto.value.substring(15,16));
    if (objeto.value.length == 3)
    {
        if(objeto.value.substring(2,3) != "/")
        {
            objeto.value = objeto.value.substring(0,2) + "/" + objeto.value.substring(2,3);
        }
    }
    if (objeto.value.length == 6)
    {
        if(objeto.value.substring(5,6) != "/")
        {
            objeto.value = objeto.value.substring(0,5) + "/" + objeto.value.substring(5,6);
        }
    }
    if (objeto.value.length == 11)
    {
        if(objeto.value.substring(10,11) != " ")
        {
            objeto.value = objeto.value.substring(0,10) + " " + objeto.value.substring(10,11);
        }
    }
    if (objeto.value.length == 14)
    {
        if(objeto.value.substring(13,14) != ":")
        {
            objeto.value = objeto.value.substring(0,13) + ":" + objeto.value.substring(13,14);
        }
    }
    if (objeto.value.length > 15)
    {
        objeto.value = objeto.value.substring(0,15);
    }
}
//Compara data no formato dd/mm/aaaa
function compararDatas(data1,data2,criterio)
{
    d1 = 0;
    d2 = 0;
    d1 = data1.substring(6,10) + data1.substring(3,5) + data1.substring(0,2);
    d2 = data2.substring(6,10) + data2.substring(3,5) + data2.substring(0,2);
    if (criterio == "<") return d1 < d2;
    if (criterio == ">") return d1 > d2;
    if (criterio == "<=") return d1 <= d2;
    if (criterio == ">=") return d1 >= d2;
    return true;
}

//Compara data no formato mm/aaaa
function compararDatasMMAAAA(data1,data2,criterio)
{
    d1 = 0;
    d2 = 0;
    d1 = data1.substring(3,7) + data1.substring(0,2);
    d2 = data2.substring(3,7) + data2.substring(0,2);
    if (criterio == "<") return d1 < d2;
    if (criterio == ">") return d1 > d2;
    if (criterio == "<=") return d1 <= d2;
    if (criterio == ">=") return d1 >= d2;
    return true;
}

function compararHorarios(horario1,horario2,criterio)
{
    h1 = 0;
    h2 = 0;
    h1 = horario1.substring(0,2) + horario1.substring(3,5);
    h2 = horario2.substring(0,2) + horario2.substring(3,5);
    if (criterio == "<") return h1 < h2;
    if (criterio == ">") return h1 > h2;
    if (criterio == "<=") return h1 <= h2;
    if (criterio == ">=") return h1 >= h2;
    return true;
}

function soNumero(event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35)){
        if ((keyCode < 48 || keyCode > 57) && !(keyCode == 46 || keyCode == 45 || keyCode == 9 || keyCode == 8 || keyCode == 37))
        {
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}

function soNota(event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (!(keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 8 || keyCode == 36 || keyCode == 35 || keyCode == 46)){
        if ((keyCode < 48 || keyCode > 57) && !(keyCode == 45 || keyCode == 9 || keyCode == 16 || keyCode == 36 || keyCode == 46 || keyCode == 44 || keyCode == 8 || keyCode == 37))
        {
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}

function Limpar(valor, validos)
{
    // retira caracteres invalidos da string
    var result = "";
    var aux;
    for (var i=0; i < valor.length; i++)
    {
        aux = validos.indexOf(valor.substring(i, i+1));
        if (aux>=0)
        {
            result += aux;
        }
    }
    return result;
}

//Formata número tipo moeda usando o evento onKeyDown

function FormataMoeda(campo,tammax,teclapres,decimal)
{
    var tecla = teclapres.keyCode;
    var keyCode = tecla;
    //alert(keyCode);
    if (!(keyCode == 46 || keyCode == 37 || keyCode == 39 || keyCode == 99 || keyCode == 36 || keyCode == 35)){
        if (campo.value == "0,00") campo.value = "";
        sinal = "";
        if (campo.value.substring(0,1) == "-") {
            sinal = "-";
        }

        vr = Limpar(campo.value,"0123456789");
        tam = vr.length;
        dec=decimal
        if (tam < tammax && tecla != 8){
            tam = vr.length + 1 ;
        }

        if (tecla == 8 ){
            tam = tam - 1 ;
        }

        if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
        {

            if ( tam <= dec ){
                campo.value = vr ;
            }

            if ( (tam > dec) && (tam <= 5) )
            {
                campo.value = vr.substr( 0, tam - 2 ) + "," + vr.substr( tam - dec, tam ) ;
            }
            if ( (tam >= 6) && (tam <= 8) )
            {
                campo.value = vr.substr( 0, tam - 5 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
            }
            if ( (tam >= 9) && (tam <= 11) )
            {
                campo.value = vr.substr( 0, tam - 8 ) + "." + vr.substr( tam - 8, 3 ) + "." + vr.substr( tam - 5, 3 ) + "," + vr.substr( tam - dec, tam ) ;
            }
            if ( (tam >= 12) && (tam <= 14) )
            {
                campo.value = vr.substr( 0, tam - 11 ) + "." +
                vr.substr( tam - 11, 3 ) + "." +
                vr.substr( tam - 8, 3 ) + "." +
                vr.substr( tam - 5, 3 ) + "," +
                vr.substr( tam - dec, tam ) ;
            }
            if ( (tam >= 15) && (tam <= 17) )
            {
                campo.value = vr.substr( 0, tam - 14 ) + "." +
                vr.substr( tam - 14, 3 ) + "." +
                vr.substr( tam - 11, 3 ) + "." +
                vr.substr( tam - 8, 3 ) + "." +
                vr.substr( tam - 5, 3 ) + "," +
                vr.substr( tam - 2, tam ) ;
            }
            campo.value = sinal + campo.value;
        }
        if (campo.value.substring(0,1) == "0" && campo.value.length > 3)
            campo.value = campo.value.substring(1,4);
    }
}

function temValor(valor, procuraValor)
{
    var aux = valor;
    for (var i=0; i < aux.length; i++){
        if (procuraValor == aux.substring(i, i+1)) {
            return true;
        }
    }
    return false;
}
//Nota
function completaFormatacaoNota(campo){
    if (campo.value.substring(campo.value.length-1,campo.value.length) == ","){
        campo.value = campo.value + "0";
    }
}

function FormataNota(campo,tammax,event,decimal)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    //alert(keyCode);
    if (keyCode != 16 && keyCode != 39 && keyCode != 46 && keyCode != 37){

        if ((temValor(campo.value,".") || temValor(campo.value,",")) && (keyCode == 188 || keyCode == 190)){
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
        campo.value = campo.value.replace(".",",");

        if (keyCode >= 48 && keyCode <= 57 && campo.value.substring(campo.value.length-2,campo.value.length-1) == ","){
            event.preventDefault? event.preventDefault() : event.returnValue = false;
        }
    }
}

function nomeIndexOnKeyPress(event)
{
    var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
    if (keyCode == 13)
    {
        if (document.getElementById("NomeIndexTb") != null &&
            document.getElementById("NomeIndexTb").value.length < 3 &&
            !eNumero(document.getElementById("NomeIndexTb").value))
            {
            alert("Digite pelo menos 3 caracteres no campo 'Nome ou código'.");
            return false;
        }
        document.getElementById("pagina").value = 1;
        if (document.getElementById("pesquisaCompletaCk") != null) {
            if (document.getElementById("pesquisaCompletaCk").checked) {
                document.getElementById("pesquisaCompleta").value = "S";
            } else {
                document.getElementById("pesquisaCompleta").value = "N";
            }
        }
        document.getElementById("acao").value = "Listar";
    }
}

//Autor Luiz Paulo M. Pires
//Calendário Javascript
//Horizonte Digital
//16/04/2005

function Calendario(nome, nomeCampo, nomeCampoDiv) {
    this.nome = nome;
    this.nomeCampo = nomeCampo;
    this.nomeMes = nome + "_Mes";
    this.nomeDiv = nome + "_DIV";
    this.nomeFrame = nome + "_FRAME";
    if (nomeCampoDiv != null) {
        this.nomeCampoDiv = nomeCampoDiv;
    }
    else {
        this.nomeCampoDiv = this.nomeCampo+"_Div";
    }
    //	this.nomeCampoDiv = (nomeCampoDiv != "")?nomeCampoDiv:this.nomeCampo+"Div";
    //	this.campo = document.getElementById(this.nomeCampo);
    //	this.mes = document.getElementById(this.nomeMes);
    //	this.div = document.getElementById(this.nomeDiv);
    //	this.frame = document.getElementById(this.nomeFrame);

    this.data = new Date();
    this.hoje = new Date();

    this.Mon3 = ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'];
    this.Day3 = ['Dom','Seg','Ter','Qua','Qui','Sex','Sab']

    this.Lz = function(x) {
        return (x<0||x>=10?"":"0") + x /* local */
    }

    this.ClickDia = function(x) {
        campo = document.getElementById(this.nomeCampo);
        var DV = +x.value;
        if (DV==0) {
            div.style.display = 'none';
            frame.style.display = 'none';
            document.getElementById(this.nome.substring(6,this.nome.length)).focus();
            return;
        }
        with (this.data) {
            setDate(DV);
            campo.value = this.Lz(getDate()) + '/' + this.Lz(getMonth()+1) + '/' + getFullYear();
            }
        x.className = 'btn';
        document.getElementById(this.nome.substring(6,this.nome.length)).focus();
        this.mostraDiv();
    }

    this.PreencheDias = function() {
        campo = document.getElementById(this.nomeCampo);
        mes = document.getElementById(this.nomeMes);
        var J, Q, W, EoM, Sp = ' ',
        W = ( this.data.getDay() - this.data.getDate() + 77 )%7
        with (new Date(+this.data)) {
            setDate(32) ;
            EoM = 32-getDate()
            }
        for (J=0 ; J<42 ; J++) {
            Q = J-W;
            document.getElementById('BB_' + this.nome + "_" + this.Lz(J)).value = Q<1 || Q>EoM ? '    ' : Sp+Q+Sp
            //deixa azul o dia de hj
            if ((Q == this.hoje.getDate()) && (this.data.getMonth() == this.hoje.getMonth()) && (this.data.getFullYear() == this.hoje.getFullYear())) {
                document.getElementById('BB_' + this.nome + "_" + this.Lz(J)).style.color = '#0000FF';
            }
            else {
                //deixa sábado e domingo vermelho
                if ((J+1)%7 == 0 || J%7 == 0) {
                    document.getElementById('BB_' + this.nome + "_" + this.Lz(J)).style.color = '#FF0000';
                }
                else {
                    document.getElementById('BB_' + this.nome + "_" + this.Lz(J)).style.color = '';
                }
            }
        }
        with (mes) { // focus() // ?
            value = Sp + this.Mon3[this.data.getMonth()] + Sp + this.data.getFullYear()
            }
    }

    this.Mes = function(x) {
        with (this.data) {
            setMonth(getMonth()+x);
            }
        this.PreencheDias();
    }

    this.Now = function(X) {
        var T = new Date('1 '+X.value);
        if (isNaN(T)) {
            alert('Erro');
        }
        else {
            this.data = T;
            this.PreencheDias();
        }
    }

    this.InitCalendario = function() {
        //form = (nomeForm != null)?document.getElementById(nomeForm):document.forms[0];
        campoDiv = document.getElementById(this.nomeCampoDiv);

        div = document.createElement("DIV");
        div.name = this.nomeDiv;
        div.id = this.nomeDiv;
        div.style.display = "none";
        div.style.position = "absolute";
        div.style.zIndex = "10";
        div.style.width = "210px";
        //		div.style.filter = "wave";
        campoDiv.appendChild(div);

        frame = document.createElement("IFRAME");
        frame.style.display = "none";
        frame.style.position = "absolute";
        frame.style.top = 0;
        frame.style.left = 0;
        frame.name = this.nomeFrame;
        frame.id = this.nomeFrame;
        frame.src = "";
        frame.frameborder = "0";
        frame.scrolling = "no";
        campoDiv.appendChild(frame);

        //		div = document.getElementById(this.nomeDiv);
        //		frame = document.getElementById(this.nomeFrame);

        html = '';
        html += '<input type="button" class="btn" value="<" onClick="'+this.nome+'.Mes(-12)" onMouseOver="this.className=\'btnOver\'" onMouseOut="this.className=\'btn\'">';
        html += '<input type="button" class="btn" value="-" onClick="'+this.nome+'.Mes(-1)" onMouseOver="this.className=\'btnOver\'" onMouseOut="this.className=\'btn\'">';
        html += '<input type="text" name="'+this.nomeMes+'" id="'+this.nomeMes+'" onChange="Now(this)" class="btnMesAno" style="width:86;text-align:center;" readonly>';
        html += '<input type="button" class="btn" value="+" onClick="'+this.nome+'.Mes(+1)" onMouseOver="this.className=\'btnOver\'" onMouseOut="this.className=\'btn\'">';
        html += '<input type="button" class="btn" value=">" onClick="'+this.nome+'.Mes(+12)" onMouseOver="this.className=\'btnOver\'" onMouseOut="this.className=\'btn\'">';
        html += '<br>';
        for (x=0; x<this.Day3.length; x++) {
            html += '<input type="button" class="btn" value="' + this.Day3[x] + '">';
        }

        html += '<br>';
        for (var J=0 ; J<42 ; J++) {
            html += '<input type="button" class="btn" name="BB_' + this.nome + "_" + this.Lz(J) + '" id="BB_' + this.nome + "_" + this.Lz(J) +'" value=" ?? " onClick="'+this.nome+'.ClickDia(this)" onMouseOver="this.className=\'btnOver\'" onMouseOut="this.className=\'btn\'">';
            if (J%7==6) {
                html += '<br>';
            }
        }

        div.innerHTML = html;
        //		this.data = new Date();
        //		this.data.setDate(1); // Create Global
        this.atualizaData();
    //	PreencheDias();
    }

    this.atualizaData = function() {
        campo = document.getElementById(this.nomeCampo);
        if (campo.value != "") {
            var dataAtual = campo.value.split('/');
            this.data.setDate(dataAtual[0]);
            this.data.setMonth(dataAtual[1]-1);
            this.data.setYear(dataAtual[2]);
        }
        this.PreencheDias();
    }

    this.mostraDiv = function() {
        div = document.getElementById(this.nomeDiv);
        frame = document.getElementById(this.nomeFrame);
        campoDiv = document.getElementById(this.nomeCampoDiv);
        if (div.style.display == 'block') {
            div.style.display = 'none';
            frame.style.display = 'none';
        }
        else {
            this.atualizaData();
            div.style.top = campoDiv.style.top+25;
            if (campoDiv.style.left == "") {
                campoDiv.style.left = 0;
            }
            div.style.left = campoDiv.style.left;
            div.style.display = 'block';
            frame.width = div.offsetWidth;
            frame.height = div.offsetHeight;
            frame.style.top = div.style.top;
            frame.style.left = div.style.left;
            frame.style.zIndex = div.style.zIndex - 1;
            frame.style.display = '';
        }
    }
}

String.prototype.trim = function()
{
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim



function adicionarItemAoCombo(valor, texto, id)
{
    document.getElementById(id).options[document.getElementById(id).length] = new Option(texto.trim(), valor.trim());
}
function remover(id)
{
    while (document.getElementById(id).length > 0)
    {
        document.getElementById(id).options[document.getElementById(id).length - 1] = null;
    }
}
var httpRequest;
var fimProcessamentoAjax;
function comboAjaxOnChange(arquivo,id)
{
    fimProcessamentoAjax = 'nao';
    if (window.ActiveXObject)
    {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        httpRequest = new XMLHttpRequest();
    }
    httpRequest.open("GET", arquivo, true);
    httpRequest.onreadystatechange = function() {
        processarRequisicao(id);
    } ;
    httpRequest.send(null);
}

function textBoxAjaxOnFocus(src){
    document.getElementById(src.id + "DivAjax").style.height = "0";
    document.getElementById(src.id + "DivAjax").style.width = "0";
    document.getElementById(src.id + "DivAjax").style.visibility = "hidden";
}
function textBoxAjaxOnBlur(src){
    if (document.getElementById(src.id + "Hidden") == null || document.getElementById(src.id + "Hidden").value == ""){
        document.getElementById(src.id).value = "";
    }
}
function textBoxAjaxOnKeyUp(arquivo,src,numeroMininoDeCaracteresParaPesquisa){
    if (src.value.length >= numeroMininoDeCaracteresParaPesquisa){
        fimProcessamentoAjax = 'nao';
        document.getElementById(src.id + "Hidden").value = "";
        if (window.ActiveXObject)
        {
            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else if (window.XMLHttpRequest)
        {
            httpRequest = new XMLHttpRequest();
        }
        httpRequest.open("GET", arquivo, true);
        tabela = document.getElementById(src.id + "TabelaAjax");
        var registros = tabela.rows.length;
        for(var i=1; i<registros; i++) {
            tabela.deleteRow(i);
            i--;
            registros--;
        }
        document.getElementById(src.id + "DivAjax").style.height = "150px";
        document.getElementById(src.id + "DivAjax").style.zIndex = 0;
        document.getElementById(src.id + "TabelaAjax").style.zIndex = 101;
        if (src.style.width.substring(src.style.width.length-2,src.style.width.length) == "px"){
            var valorWidth = parseInt(src.style.width.substring(0,src.style.width.length-2)) + 7;
            document.getElementById(src.id + "DivAjax").style.width = valorWidth + "px";
            document.getElementById(src.id + "TabelaAjax").style.width = "99%";
        }else{
            document.getElementById(src.id + "DivAjax").style.width = src.style.width;
            document.getElementById(src.id + "DivAjax").style.width = "99%";
            document.getElementById(src.id + "TabelaAjax").style.width = "100%";
        }
        document.getElementById(src.id + "DivAjax").style.top = src.style.top;
        document.getElementById(src.id + "DivAjax").style.left = src.style.left;
        document.getElementById(src.id + "DivAjax").style.visibility = "visible";
        httpRequest.onreadystatechange = function() {
            processarRequisicaoTextBox(src);
        } ;
        httpRequest.send(null);
    }else{
        document.getElementById(src.id + "DivAjax").style.height = "0";
        document.getElementById(src.id + "DivAjax").style.width = "0";
        document.getElementById(src.id + "DivAjax").style.visibility = "hidden";
        document.getElementById(src.id + "Hidden").value = "";
    }
}

function inserirLinhaTabela(src, valor, texto){
    tabela = document.getElementById(src.id + "TabelaAjax");
    var newRow = tabela.insertRow(-1);
    var resto = tabela.rows.length % 2;
    if (resto == 0)
        newRow.style.backgroundColor = "#EEEEEE";
    else
        newRow.style.backgroundColor = "#fafafa";
    var newCell = newRow.insertCell(0);
    newCell.innerHTML = "<a href=\"javascript:selecionarItemTabelaAjax('" + src.id + "','" + valor + "','" + texto + "');\">" + texto + "</a>";
}

function selecionarItemTabelaAjax(nome, valor, texto){
    document.getElementById(nome + "Hidden").value = valor;
    document.getElementById(nome).value = texto;
    document.getElementById(nome + "DivAjax").style.height = "0";
    document.getElementById(nome + "DivAjax").style.width = "0";
    document.getElementById(nome + "DivAjax").style.visibility = "hidden";
}

function processarRequisicaoTextBox(src)
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
        {
            i = 0;
            while (httpRequest.responseXML.getElementsByTagName("valor")[i] != null)
            {
                valor = httpRequest.responseXML.getElementsByTagName("valor")[i].childNodes[0].nodeValue;
                texto = httpRequest.responseXML.getElementsByTagName("texto")[i].childNodes[0].nodeValue;
                inserirLinhaTabela(src, valor, texto);
                i++;
            }
            fimProcessamentoAjax = 'fim';
        }
        else
        {
            alert("Error ao carregar a página\n"+ httpRequest.status +":"+ httpRequest.statusText);
            fimProcessamentoAjax = 'fim';
        }
    }else{
        fimProcessamentoAjax = 'fim';
    }

}


function requisitarInformacaoAjaxRetornarDadosSeparadosPorVirgula(pagina,id)
{
    fimProcessamentoAjax = 'nao';
    if (window.ActiveXObject)
    {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        httpRequest = new XMLHttpRequest();
    }
    httpRequest.open("GET", pagina, true);
    httpRequest.onreadystatechange = function() {
        processarRequisicaoRetornarValorSeparadosPorVirgula(id);
    } ;
    httpRequest.send(null);
}

function processarRequisicao(id)
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
        {
            remover(id);
            i = 0;
            adicionarItemAoCombo("0","Selecione",id);
            while (httpRequest.responseXML.getElementsByTagName("valor")[i] != null)
            {
                adicionarItemAoCombo(httpRequest.responseXML.getElementsByTagName("valor")[i].childNodes[0].nodeValue,
                    httpRequest.responseXML.getElementsByTagName("texto")[i].childNodes[0].nodeValue, id);
                i++;
            }
            fimProcessamentoAjax = 'fim';
        }
        else
        {
            alert("Error ao carregar a página\n"+ httpRequest.status +":"+ httpRequest.statusText);
            fimProcessamentoAjax = 'fim';
        }
    }else{
        fimProcessamentoAjax = 'fim';
    }

}
function processarRequisicaoRetornarValorSeparadosPorVirgula(nomeId)
{
    id = document.getElementById(nomeId);
    var textoRetorno = "";
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
        {
            n = 0;
            while (httpRequest.responseXML.getElementsByTagName("valor")[n] != null){
                n++;
            }
            i = 0;
            while (httpRequest.responseXML.getElementsByTagName("valor")[i] != null){
                if (textoRetorno.length > 0){
                    if (i == (n-1)){
                        textoRetorno += " e ";
                    }else{
                        textoRetorno += ", ";
                    }
                }
                textoRetorno += httpRequest.responseXML.getElementsByTagName("texto")[i].childNodes[0].nodeValue;
                i++;
            }
            id.value = textoRetorno;
            fimProcessamentoAjax = 'fim';
        }
        else
        {
            alert("Error ao carregar a página\n"+ httpRequest.status +":"+ httpRequest.statusText);
            fimProcessamentoAjax = 'fim';
        }
    }else{
        fimProcessamentoAjax = 'fim';
    }
}

function requisitarValoresAjax(arquivo)
{
    fimProcessamentoAjax = 'nao';
    if (window.ActiveXObject) {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    } else if (window.XMLHttpRequest) {
        httpRequest = new XMLHttpRequest();
    }
    httpRequest.open("GET", arquivo, true);
    httpRequest.onreadystatechange = function() {
        getValoresAjax();
    } ;
    httpRequest.send(null);
}

function getValoresAjax()
{
    i = 0;
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
        {
            while (httpRequest.responseXML.getElementsByTagName("valor")[i] != null)
            {
                alert("Valor: " + httpRequest.responseXML.getElementsByTagName("valor")[i].childNodes[0].nodeValue);
                alert("Texto: " + httpRequest.responseXML.getElementsByTagName("texto")[i].childNodes[0].nodeValue);
                i++;
            }
        }
        else
        {
            alert("Error ao carregar a página\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
    fimProcessamentoAjax = 'fim';
}

function getPaginaAjax(pagina){
    if (window.ActiveXObject)
    {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        httpRequest = new XMLHttpRequest();
    }
    httpRequest.open("post", pagina, true);
    httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    httpRequest.setRequestHeader("charset","UTF-8");
    httpRequest.setRequestHeader("Encoding","UTF-8");


    httpRequest.onreadystatechange = function() {
        gePaginaAjaxProcessada();
    } ;
    httpRequest.send(null);
}

function gePaginaAjaxProcessada(){
    if (httpRequest.readyState == 4){
        if(httpRequest.status == 200){
            document.write(httpRequest.responseText);
        }else{
            alert("Error ao carregar a página\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
}

function requisitarPaginaAjaxSimples(pagina){
    if (window.ActiveXObject)
    {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        httpRequest = new XMLHttpRequest();
    }
    httpRequest.open("post", pagina, true);
    httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    httpRequest.setRequestHeader("charset","UTF-8");
    httpRequest.setRequestHeader("Encoding","UTF-8");


    httpRequest.onreadystatechange = function() {
        processarRequisicaoPaginaSimples();
    } ;
    httpRequest.send(null);
}

function processarRequisicaoPaginaSimples(){
    if (httpRequest.readyState == 4){
        if(httpRequest.status == 200){
            document.write(httpRequest.responseText);
        }else{
            alert("Error ao carregar a página\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
}

function requisitarPaginaAjaxSemValores(pagina){
    if (window.ActiveXObject)
    {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        httpRequest = new XMLHttpRequest();
    }
    httpRequest.open("post", pagina, true);
    httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    httpRequest.setRequestHeader("charset","UTF-8");
    httpRequest.setRequestHeader("Encoding","UTF-8");


    httpRequest.onreadystatechange = function() {
        processarRequisicaoPagina();
    } ;
    httpRequest.send(null);
}

function requisitarPaginaAjax(pagina){
    tempoSessao = 30;
    mostraSegundos = 0;
    var elementos = document.getElementsByTagName("*");
    var teste = "";
    try{
        for (var i = 0; i < elementos.length; i++) {
            if (elementos[i].value != null && (elementos[i].value.length > 0 || elementos[i].checked) && elementos[i].id.length > 0){
                pagina += "&" + elementos[i].id + "=" + encodeURI(elementos[i].value);
                teste += elementos[i].id + "\\\n";
            }
        }
    }
    catch(ex){

    }
    if (window.ActiveXObject)
    {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        httpRequest = new XMLHttpRequest();
    }
    httpRequest.open("post", pagina, true);
    httpRequest.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
    httpRequest.setRequestHeader("charset","UTF-8");
    httpRequest.setRequestHeader("Encoding","UTF-8");


    httpRequest.onreadystatechange = function() {
        processarRequisicaoPagina();
    } ;
    httpRequest.send(null);
}

function processarRequisicaoPagina(){
    if (httpRequest.readyState == 4){
        if(httpRequest.status == 200){
            var div1 = httpRequest.responseText.split("<divisaoHD><div id='divisaoHD'>");
            div1 = div1[1].split("</div></divisaoHD>");
            var div2 = div1[0].split("<divisaoHD2><div id='divisaoHD2'>");
            if (div2 != null && div2.length > 1){
                div2 = div2[1].split("</div2></divisaoHD2>");
                document.getElementById("divisaoHD").innerHTML = "<divisaoHD><div id='divisaoHD'>" + div2[0] + "</div></divisaoHD>";
            }else{
                document.getElementById("divisaoHD").innerHTML = div1[0];
            }
            if (document.getElementById("mensagemHD") != null && document.getElementById("mensagemHD").value.length > 0){
                alert(document.getElementById("mensagemHD").value);
            }
        }else{
            document.write(httpRequest.responseText);
        //alert("Error ao carregar a página\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
}

function SomarData(txtData,DiasAdd)
{
    DiasAdd = parseInt(DiasAdd);
    // Tratamento das Variaveis.
    // var txtData = "01/01/2007"; //poder ser qualquer outra
    // var DiasAdd = 10 // Aqui vem quantos dias você quer adicionar a data
    var d = new Date();
    // Aqui eu "mudo" a configuração de datas.
    // Crio um obj Date e pego o campo txtData e
    // "recorto" ela com o split("/") e depois dou um
    // reverse() para deixar ela em padrão americanos YYYY/MM/DD
    // e logo em seguida eu coloco as barras "/" com o join("/")
    // depois, em milisegundos, eu multiplico um dia (86400000 milisegundos)
    // pelo número de dias que quero somar a txtData.
    d.setTime(Date.parse(txtData.split("/").reverse().join("/"))+(86400000*(DiasAdd)))

    // Crio a var da DataFinal
    var DataFinal;

    // Aqui comparo o dia no objeto d.getDate() e vejo se é menor que dia 10.
    if(d.getDate() < 10)
    {
        // Se o dia for menor que 10 eu coloca o zero no inicio
        // e depois transformo em string com o toString()
        // para o zero ser reconhecido como uma string e não
        // como um número.
        DataFinal = "0"+d.getDate().toString();
    }
    else
    {
        // Aqui a mesma coisa, porém se a data for maior do que 10
        // não tenho necessidade de colocar um zero na frente.
        DataFinal = d.getDate().toString();
    }

    // Aqui, já com a soma do mês, vejo se é menor do que 10
    // se for coloco o zero ou não.
    if((d.getMonth()+1) < 10){
        DataFinal += "/0"+(d.getMonth()+1).toString()+"/"+d.getFullYear().toString();
    }
    else
    {
        DataFinal += "/"+((d.getMonth()+1).toString())+"/"+d.getFullYear().toString();
    }
    return DataFinal;
}
