﻿function MascaraTelefone(objeto) {
    if (objeto.value.length == 0)
        objeto.value = '(' + objeto.value;

    if (objeto.value.length == 3)
        objeto.value = objeto.value + ')';

    if (objeto.value.length == 8)
        objeto.value = objeto.value + '-';
}

/*
Tipos e padrões:
CPF: XXX.XXX.XXX-XX
CNPJ: XX.XXX.XXX/XXXX-XX
TEL: (XX) XXXX-XXXX
DATA: DD/MM/YYYY

Sintaxe:
Máscara(tipo, campo, teclaPressionada);

<input name="cpf" type="text" maxlength="14" onKeyPress="Mascara('CPF',this,event);">
*/

function Mascara(tipo, campo, teclaPress) {
    if (window.event) {
        var tecla = teclaPress.keyCode;
    } else {
        tecla = teclaPress.which;
    }

    var s = new String(campo.value);
    // Remove todos os caracteres à seguir: ( ) / - . e espaço, para tratar a string denovo.
    s = s.replace(/(\.|\(|\)|\/|\-| )+/g, '');

    tam = s.length + 1;

    if (tecla != 9 && tecla != 8) {
        switch (tipo) {
            case 'CPF':
                if (tam > 3 && tam < 7)
                    campo.value = s.substr(0, 3) + '.' + s.substr(3, tam);
                if (tam >= 7 && tam < 10)
                    campo.value = s.substr(0, 3) + '.' + s.substr(3, 3) + '.' + s.substr(6, tam - 6);
                if (tam >= 10 && tam < 12)
                    campo.value = s.substr(0, 3) + '.' + s.substr(3, 3) + '.' + s.substr(6, 3) + '-' + s.substr(9, tam - 9);
                break;

            case 'CNPJ':

                if (tam > 2 && tam < 6)
                    campo.value = s.substr(0, 2) + '.' + s.substr(2, tam);
                if (tam >= 6 && tam < 9)
                    campo.value = s.substr(0, 2) + '.' + s.substr(2, 3) + '.' + s.substr(5, tam - 5);
                if (tam >= 9 && tam < 13)
                    campo.value = s.substr(0, 2) + '.' + s.substr(2, 3) + '.' + s.substr(5, 3) + '/' + s.substr(8, tam - 8);
                if (tam >= 13 && tam < 15)
                    campo.value = s.substr(0, 2) + '.' + s.substr(2, 3) + '.' + s.substr(5, 3) + '/' + s.substr(8, 4) + '-' + s.substr(12, tam - 12);
                break;

            case 'TEL':
                if (tam > 2 && tam < 4)
                    campo.value = '(' + s.substr(0, 2) + ') ' + s.substr(2, tam);
                if (tam >= 7 && tam < 11)
                    campo.value = '(' + s.substr(0, 2) + ') ' + s.substr(2, 4) + '-' + s.substr(6, tam - 6);
                break;

            case 'DATA':
                if (tam > 2 && tam < 4)
                    campo.value = s.substr(0, 2) + '/' + s.substr(2, tam);
                if (tam > 4 && tam < 11)
                    campo.value = s.substr(0, 2) + '/' + s.substr(2, 2) + '/' + s.substr(4, tam - 4);
                break;
        }
    }
}
//////////////////////////////////////////////////
// Cursos para Empresas
//////////////////////////////////////////////////
function enviarProposta(theForm) {
    /*
    var f = document.form_empresas;	
    var i;
    var total;
    var nomes;
    var err = true;
    for( i=0; i < f.length; i++){
    if(f.elements[i].value != "" && f.elements[i].type == "select"){
    err = false;
    // total = total + f.elements[i].value+";";
    // nomes = nomes + f.elements[i].name+";";
    }
    }
    if(!err){
    // f.elements[0].value = nomes;
    // f.elements[1].value = total;
    f.submit();
    }
    else{
    alert("Por favor, escolha um dos cursos em que esteja interessado,\n"+ 
    "coloque uma quantidade de alunos estimada e confirme os\n"+
    "dados novamente.");
    return false;
    }*/
    // Nome
    if (theForm.nome.value == "") {
        alert("Preencha o campo \"Nome\".");
        theForm.nome.focus();
        return false;
    }
    // E-mail
    if (theForm.email.value == "") {
        alert("Preencha o campo \"E-mail\".");
        theForm.email.focus();
        return false;
    }
    if (Valida_Email(theForm) == false)
        return false;
    // Telefone DDD - Se existir
    if (theForm.ddd) {
        if (theForm.ddd.value == "") {
            alert("Preencha o campo \"DDD\".");
            theForm.ddd.focus();
            return false;
        }
    }
    // Telefone
    if (theForm.telefone.value == "") {
        alert("Preencha o campo \"Telefone\".");
        theForm.telefone.focus();
        return false;
    }
}

//////////////////////////////////////////////////
// Função para abrir pop-up
//////////////////////////////////////////////////
function abrir(pagina, largura, altura, noscroll, alvo, resizable) {
    var resize = 'yes';
    var scrollbars = 'yes';
    if (noscroll == null || !noscroll) {
        scrollbars = 'no';
    }
    if (resizable == null || !resizable) {
        resize = 'no';
    }
    config = "toolbar=no,location=no,width=" + largura + ",height=" + altura + ",status=0,menubar=no,scrollbars=" + scrollbars + ",resizable=" + resize;
    config = config + ",top=" + ((screen.height - altura) / 2) + ",left=" + ((screen.width - largura) / 2);
    popup_window = window.open(pagina, alvo, config);
    popup_window.focus();
}

//////////////////////////////////////////////////
// Função para adicionar aos favoritos
//////////////////////////////////////////////////
function favoritos() {
    var browser = navigator.appName;
    var bookmarkurl = "http://www.portaleducacao.com.br";
    var bookmarktitle = "Portal Educa" + String.fromCharCode(231) + "ão";
    if (browser == "Netscape") {
        alert("Aperte CTRL+D para adicionar o Portal Educa" + String.fromCharCode(231) + "ão aos seus favoritos")
    }
    else if (browser == "Microsoft Internet Explorer") {
        window.external.AddFavorite(bookmarkurl, bookmarktitle)
    }
}

//////////////////////////////////////////////////
// Função para checar ou unchecar todos checkbox
//////////////////////////////////////////////////
function checkaTodos(algumAlterado) {
    f = validar;
    if (algumAlterado) {
        if (algumAlterado.checked == false)
            f.br.checked = false;
    }
    else
        for (i = 0; i < f.length; i++)
        if (f.elements[i].type == "checkbox")
        if (f.br.checked) f.elements[i].checked = true
    else f.elements[i].checked = false
}

//////////////////////////////////////////////////
// Função para validar Cadastro
//////////////////////////////////////////////////
function Valida_Cadastro(theForm) {
    // Se e-mail existir
    if (theForm.email) {
        // E-mail
        if (theForm.email.value == "") {
            alert("Preencha o campo \"E-mail\".");
            theForm.email.focus();
            return false;
        }
        if (Valida_Email(theForm) == false)
            return false;
    }

    // Senha
    //Adicionado if existir pois em usuarios_detalhes nao ira possuir campo senha
    //caso usuario logado nao seja administrador
    if (theForm.senha) {
        if (theForm.senha.value == "") {
            alert("Preencha o campo \"Senha\".");
            theForm.senha.focus();
            return false;
        }
    }

    // Senha2 - Se existir senha2
    if (theForm.senha2) {
        // Senha 2
        if (theForm.senha2.value == "") {
            alert("Preencha o campo de confirma" + String.fromCharCode(231) + "ão de \"Senha\".");
            theForm.senha2.focus();
            return false;
        }

        if (theForm.senha.value != theForm.senha2.value) {
            alert("As senhas não conferem.");
            theForm.senha.focus();
            return false;
        }
    }

    //Pessoa Jurídica
    if (document.getElementById('cnpj')) {
        // Se estiver cadastrando pessoa juridica então valida seus dados 
        if (document.getElementById('pjuridica') && document.getElementById('pjuridica').checked == true) {
            if (theForm.cnpj.value == "") {
                alert("Preencha o campo \"CNPJ\" da pessoa jurídica.");
                theForm.cnpj.focus();
                return false;
            }
            if (theForm.nome_empresa.value == "") {
                alert("Preencha o campo \"Nome Empresa\" da pessoa jurídica.");
                theForm.nome_empresa.focus();
                return false;
            }
            if (theForm.jcep1.value == "") {
                alert("Preencha o campo \"CEP\" da pessoa jurídica.");
                theForm.jcep1.focus();
                return false;
            }
            if (theForm.jendereco.value == "") {
                alert("Preencha o campo \"Endere" + String.fromCharCode(231) + "o\" da pessoa jurídica.");
                theForm.jendereco.focus();
                return false;
            }
            if (theForm.jendereco_num.value == "") {
                alert("Preencha o campo \"Número\" da pessoa jurídica.");
                theForm.jendereco_num.focus();
                return false;
            }
            if (theForm.jbairro.value == "") {
                alert("Preencha o campo \"Bairro\" da pessoa jurídica.");
                theForm.jbairro.focus();
                return false;
            }
            if (theForm.jcidade.value == "") {
                alert("Preencha o campo \"Cidade\" da pessoa jurídica.");
                theForm.jcidade.focus();
                return false;
            }
            if (theForm.jestado.value == "") {
                alert("Preencha o campo \"Estado\" da pessoa jurídica.");
                theForm.jestado.focus();
                return false;
            }
            if (theForm.atividade.selectedIndex <= 0) {
                alert("Por favor selecione uma \"Atividade\" da pessoa jurídica.");
                theForm.atividade.focus();
                return false;
            }
        }
    }


    // Nome
    if (trim(theForm.nome.value) == "") {
        alert("Preencha o campo \"Nome\".");
        theForm.nome.focus();
        return false;
    }
    // Nome
    if (trim(theForm.nome.value).length < 10) {
        alert("Preencha o campo \"Nome\" com seu nome completo.");
        theForm.nome.focus();
        return false;
    }

    // Sexo - Requer que pelo menos um radiobutton esteja selecionado
    var radioSelected = false;
    for (i = 0; i < theForm.sexo.length; i++) {
        if (theForm.sexo[i].checked)
            radioSelected = true;
    }
    if (!radioSelected) {
        alert("Por favor selecione o \"Sexo\".");
        return false;
    }

    // Nascimento - Se existir
    if (theForm.dia) {
        if (theForm.dia.value == "") {
            alert("Informe o dia do \"Nascimento\".");
            theForm.dia.focus();
            return false;
        }

        if (theForm.mes.value == "") {
            alert("Informe o mês do \"Nascimento\".");
            theForm.mes.focus();
            return false;
        }

        if (theForm.ano.value == "") {
            alert("Informe o ano do \"Nascimento\".");
            theForm.ano.focus();
            return false;
        }
        /*		
        if (theForm.dia.value < 0 || theForm.dia.value > 31)
        {
        alert("O dia do \"Nascimento\" está incorreto.");
        theForm.dia.focus();
        return false;
        }
        if (theForm.mes.value < 0 || theForm.mes.value > 12)
        {
        alert("O Formato do mês do \"Nascimento\" está incorreto.");
        theForm.mes.focus();
        return false;
        }
        if (theForm.dia.value > 29 && (theForm.mes.value == 02 || theForm.mes.value == 2))
        {
        alert("O dia para o mês de fevereiro do \"Nascimento\" não confere.");
        theForm.dia.focus();
        return false;
        }
        */
    }

    // CPF - Se existir
    if (theForm.cpf) {
        if (theForm.cpf.value == "") {
            alert("Preencha o campo \"CPF\".");
            theForm.cpf.focus();
            return false;
        }
        if (Valida_CPF(theForm) == false)
            return false;
    }

    // CPF lite - Se existir
    if (theForm.cpf_lite) {
        if (trim(theForm.cpf_lite.value) != "") {
            if (Valida_CPFLite(theForm) == false)
                return false;
        }
    }

    // Telefone DDD - Se existir
    if (theForm.ddd1) {
        if (trim(theForm.ddd1.value) == "") {
            alert("Preencha o campo \"DDD\".");
            theForm.ddd1.focus();
            return false;
        }

        if (isNumeric(theForm.ddd1.value) == false) {
            alert("Informe um \"DDD\" válido.");
            theForm.ddd1.focus();
            theForm.ddd1.select();
            return false;
        }
    }

    // Telefone
    if (trim(theForm.fone1.value) == "") {
        alert("Preencha o campo \"Telefone\".");
        theForm.fone1.focus();
        return false;
    }

    if (isValidFone(theForm.fone1.value) == false) {
        alert("Informe um Telefone válido.");
        theForm.fone1.select();
        theForm.fone1.focus();
        return false;
    }

    // Telefone Comercial DDD  - Se existir
    if (theForm.ddd2) {
        if (trim(theForm.ddd2.value) != "" && isNumeric(theForm.ddd2.value) == false) {
            alert("Informe um \"DDD\" válido.");
            theForm.ddd2.focus();
            theForm.ddd2.select();
            return false;
        }
    }

    // Telefone Comercial - Se exister
    if (theForm.fone2 && trim(theForm.fone2.value) != "" && isValidFone(theForm.fone2.value) == false) {
        alert("Informe um Telefone Comercial válido.");
        theForm.fone2.select();
        theForm.fone2.focus();
        return false;
    }

    // Telefone Celular DDD  - Se existir
    if (theForm.ddd3) {
        if (trim(theForm.ddd3.value) != "" && isNumeric(theForm.ddd3.value) == false) {
            alert("Informe um \"DDD\" válido.");
            theForm.ddd3.focus();
            theForm.ddd3.select();
            return false;
        }
    }

    // Telefone Celular - Se exister
    if (theForm.fone3 && trim(theForm.fone3.value) != "" && isValidFone(theForm.fone3.value) == false) {
        alert("Informe um Telefone Celular válido.");
        theForm.fone3.select();
        theForm.fone3.focus();
        return false;
    }

    // Instituição - Se existir
    if (theForm.instituicao) {
        if (theForm.instituicao.value == "") {
            alert("Preencha o campo \"Institui" + String.fromCharCode(231) + "ão\".");
            theForm.instituicao.focus();
            return false;
        }
    }

    // Profissão
    if (theForm.profissao) {
        if (theForm.profissao.selectedIndex <= 0) {
            alert("Por favor selecione \"Profissão\".");
            theForm.profissao.focus();
            return (false);
        }
    }

    // CEP - Se existir cep1
    if (theForm.cep1) {
        if (theForm.cep1.value == "") {
            alert("Preencha o campo \"CEP\".");
            theForm.cep1.focus();
            return false;
        }
        if (theForm.cep1.value.length < 5) {
            alert("O campo \"CEP\" não está preenchido corretamente!");
            theForm.cep1.focus();
            return false;
        }
        if (theForm.cep2.value == "") {
            alert("Preencha o campo \"CEP\".");
            theForm.cep2.focus();
            return false;
        }
        if (theForm.cep2.value.length < 3) {
            alert("O campo \"CEP\" não está preenchido corretamente!");
            theForm.cep2.focus();
            return false;
        }
    }

    // CEP - Se existir cep
    if (theForm.cep) {
        if (theForm.cep.value == "") {
            alert("Preencha o campo \"CEP\".");
            theForm.cep.focus();
            return false;
        }
        if (theForm.cep.value.length < 8) {
            alert("O campo \"CEP\" não está preenchido corretamente!");
            theForm.cep.focus();
            return false;
        }
    }

    // Endereço
    if (trim(theForm.endereco.value) == "") {
        message = "Preencha o campo \"Endere" + String.fromCharCode(231) + "o\"."
        alert(message);
        theForm.endereco.focus();
        return false;
    }
    if (trim(theForm.endereco.value).length < 3) {
        message = "O campo \"Endere" + String.fromCharCode(231) + "o\" não está preenchido corretamente!"
        alert(message);
        theForm.endereco.focus();
        return false;
    }

    // Endereço - Número
    if (trim(theForm.endereco_num.value) == "") {
        message = "Preencha o campo \"Número do Endere" + String.fromCharCode(231) + "o\".";
        alert(message);
        theForm.endereco_num.focus();
        return false;
    }
    //isValidDigitNumber(theForm.endereco_num, "Número do Endereço");

    // Bairro
    if (trim(theForm.bairro.value) == "") {
        alert("Preencha o campo \"Bairro\".");
        theForm.bairro.focus();
        return false;
    }

    // Cidade
    if (trim(theForm.cidade.value) == "") {
        alert("Preencha o campo \"Cidade\".");
        theForm.cidade.focus();
        return false;
    }
    if (trim(theForm.cidade.value).length < 3) {
        alert("O campo \"Cidade\" não está preenchido corretamente!");
        theForm.cidade.focus();
        return false;
    }

    // País

    // Estado - Se existir
    if (theForm.estado) {
        if (theForm.estado.selectedIndex < 0) {
            alert("Por favor selecione um \"Estado\".");
            theForm.estado.focus();
            return false;
        }
    }

    // Provincia - Se existir
    if (theForm.provincia) {
        if (theForm.provincia.value == "") {
            alert("Preencha o campo \"Provincia\".");
            theForm.provincia.focus();
            return false;
        }
    }

    // Como ficou sabendo - Se existir
    if (theForm.como) {
        if (theForm.como.selectedIndex <= 0) {
            alert("Por favor selecione \"Como ficou sabendo dos cursos\".");
            theForm.como.focus();
            return (false);
        }
    }


    // Valida o campo senha do form em meus_dados.asp em que não é brigatório o preenchimento de senha, mas caso preencha deve preencher tb a confirmação de senha

    if (theForm.senha3) {
        if (theForm.senha3.value != "") {

            if (theForm.senha4) {
                // Senha 4 confirmação de senha
                if (theForm.senha4.value == "") {
                    alert("Preencha o campo de confirma" + String.fromCharCode(231) + "ão de \"Senha\".");
                    theForm.senha4.focus();
                    return false;
                }

                if (theForm.senha3.value != theForm.senha4.value) {
                    alert("As senhas não conferem.");
                    theForm.senha3.focus();
                    return false;
                }
            }
        }
    }

    // Verifica se é página de cadastro //
    if (theForm.residente) {
        try {
            pageTracker._trackPageview('/ga-ext/formulario/cadastro/botao_enviar');
        } catch (Exception) { }
    }
}

//////////////////////////////////////////////////
// Valida Identificação de Residente
//////////////////////////////////////////////////
function VerificaIdentificacao(form) {
    var ident = trim(form.email.value);

    if (ident == "") {
        alert("Por favor, informe o seu e-mail ou CPF!");
        form.email.focus();
        return false;
    }

    if (isEmail(ident) == false && isCPF(ident) == false) {
        ident = ident.replace(/-/g, "");
        ident = ident.replace(/\./g, "");

        if (!isNaN(ident))
            alert("O CPF informado é inválido!");
        else if (ident.indexOf("@") > -1)
            alert("O E-mail informado é inválido!");
        else
            alert("Informe um e-mail ou CPF válido!");


        form.email.select();
        form.email.focus();
        return false;
    }

    if (trim(form.senha.value) == "") {
        alert("Por favor, informe a sua senha!!")
        form.senha.focus();
        return false;
    }

    return true;
}

//////////////////////////////////////////////////
// Função que faz uma máscara para cep
//////////////////////////////////////////////////
function Formata_CEP(objeto) {
    if (objeto.value.indexOf("-") == -1 && objeto.value.length > 5) { objeto.value = ""; }
    if (objeto.value.length == 5) {
        objeto.value += "-";
    }
}
//OnKeyPress="Formata_CEP(this)"


//////////////////////////////////////////////////
// Verifica CPF
//////////////////////////////////////////////////
function Valida_CPF(theForm) {
    var CPF = theForm.cpf.value;

    var POSICAO, I, SOMA, DV, DV_INFORMADO;
    var DIGITO = new Array(10);
    DV_INFORMADO = CPF.substr(9, 2);

    for (I = 0; I <= 8; I++) {
        DIGITO[I] = CPF.substr(I, 1);
    }

    POSICAO = 10;
    SOMA = 0;
    for (I = 0; I <= 8; I++) {
        SOMA = SOMA + DIGITO[I] * POSICAO;
        POSICAO = POSICAO - 1;
    }
    DIGITO[9] = SOMA % 11;
    if (DIGITO[9] < 2) {
        DIGITO[9] = 0;
    }
    else {
        DIGITO[9] = 11 - DIGITO[9];
    }

    POSICAO = 11;
    SOMA = 0;
    for (I = 0; I <= 9; I++) {
        SOMA = SOMA + DIGITO[I] * POSICAO;
        POSICAO = POSICAO - 1;
    }
    DIGITO[10] = SOMA % 11;
    if (DIGITO[10] < 2) {
        DIGITO[10] = 0;
    }
    else {
        DIGITO[10] = 11 - DIGITO[10];
    }

    DV = DIGITO[9] * 10 + DIGITO[10];
    if (DV != DV_INFORMADO) {
        alert('CPF inválido');
        theForm.cpf.value = '';
        theForm.cpf.focus();
        return false;
    }

    for (I = 0; I <= 9; I++) {

        if (DIGITO[I] == DIGITO[9] && DIGITO[I] == DIGITO[8] && DIGITO[I] == DIGITO[7] && DIGITO[I] == DIGITO[6] && DIGITO[I] == DIGITO[5] && DIGITO[I] == DIGITO[4] && DIGITO[I] == DIGITO[3] && DIGITO[I] == DIGITO[2] && DIGITO[I] == DIGITO[1] && DIGITO[I] == DIGITO[0]) {
            alert('CPF inválido');
            theForm.cpf.value = '';
            theForm.cpf.focus();
            return false;
        }
    }

}


//////////////////////////////////////////////////
// Verifica CPFLite
//////////////////////////////////////////////////
function Valida_CPFLite(theForm) {
    var CPF = theForm.cpf_lite.value;

    var POSICAO, I, SOMA, DV, DV_INFORMADO;
    var DIGITO = new Array(10);
    DV_INFORMADO = CPF.substr(9, 2);

    for (I = 0; I <= 8; I++) {
        DIGITO[I] = CPF.substr(I, 1);
    }

    POSICAO = 10;
    SOMA = 0;
    for (I = 0; I <= 8; I++) {
        SOMA = SOMA + DIGITO[I] * POSICAO;
        POSICAO = POSICAO - 1;
    }
    DIGITO[9] = SOMA % 11;
    if (DIGITO[9] < 2) {
        DIGITO[9] = 0;
    }
    else {
        DIGITO[9] = 11 - DIGITO[9];
    }

    POSICAO = 11;
    SOMA = 0;
    for (I = 0; I <= 9; I++) {
        SOMA = SOMA + DIGITO[I] * POSICAO;
        POSICAO = POSICAO - 1;
    }
    DIGITO[10] = SOMA % 11;
    if (DIGITO[10] < 2) {
        DIGITO[10] = 0;
    }
    else {
        DIGITO[10] = 11 - DIGITO[10];
    }

    DV = DIGITO[9] * 10 + DIGITO[10];
    if (DV != DV_INFORMADO) {
        alert('CPF inválido');
        theForm.cpf_lite.value = '';
        theForm.cpf_lite.focus();
        return false;
    }

    for (I = 0; I <= 9; I++) {

        if (DIGITO[I] == DIGITO[9] && DIGITO[I] == DIGITO[8] && DIGITO[I] == DIGITO[7] && DIGITO[I] == DIGITO[6] && DIGITO[I] == DIGITO[5] && DIGITO[I] == DIGITO[4] && DIGITO[I] == DIGITO[3] && DIGITO[I] == DIGITO[2] && DIGITO[I] == DIGITO[1] && DIGITO[I] == DIGITO[0]) {
            alert('CPF inválido');
            theForm.cpf_lite.value = '';
            theForm.cpf_lite.focus();
            return false;
        }
    }

}


/**
Verifica se o CPF é válido. Retorna TRUE se o CPF for válido e FALSE se for inválido.
*/
function isCPF(cpfValue) {

    var CPF = cpfValue;

    CPF = CPF.replace(/-/g, "");
    CPF = CPF.replace(/\./g, "");

    var POSICAO, I, SOMA, DV, DV_INFORMADO;
    var DIGITO = new Array(10);
    DV_INFORMADO = CPF.substr(9, 2);

    for (I = 0; I <= 8; I++) {
        DIGITO[I] = CPF.substr(I, 1);
    }

    POSICAO = 10;
    SOMA = 0;
    for (I = 0; I <= 8; I++) {
        SOMA = SOMA + DIGITO[I] * POSICAO;
        POSICAO = POSICAO - 1;
    }
    DIGITO[9] = SOMA % 11;
    if (DIGITO[9] < 2) {
        DIGITO[9] = 0;
    }
    else {
        DIGITO[9] = 11 - DIGITO[9];
    }

    POSICAO = 11;
    SOMA = 0;
    for (I = 0; I <= 9; I++) {
        SOMA = SOMA + DIGITO[I] * POSICAO;
        POSICAO = POSICAO - 1;
    }
    DIGITO[10] = SOMA % 11;
    if (DIGITO[10] < 2) {
        DIGITO[10] = 0;
    }
    else {
        DIGITO[10] = 11 - DIGITO[10];
    }

    DV = DIGITO[9] * 10 + DIGITO[10];
    if (DV != DV_INFORMADO) {
        return false;
    }

    for (I = 0; I <= 9; I++) {

        if (DIGITO[I] == DIGITO[9] && DIGITO[I] == DIGITO[8] && DIGITO[I] == DIGITO[7] && DIGITO[I] == DIGITO[6] && DIGITO[I] == DIGITO[5] && DIGITO[I] == DIGITO[4] && DIGITO[I] == DIGITO[3] && DIGITO[I] == DIGITO[2] && DIGITO[I] == DIGITO[1] && DIGITO[I] == DIGITO[0]) {
            return false;
        }
    }

    return true;

}


//////////////////////////////////////////////////
// Função para validar entrada do Informativo
//////////////////////////////////////////////////
function Valida_Informativo(theForm) {
    // Nome
    if (theForm.nome.value == "") {
        alert("Preencha o campo \"Nome\".");
        theForm.nome.focus();
        return false;
    }

    // E-mail
    if (theForm.email.value == "") {
        alert("Preencha o campo \"E-mail\".");
        theForm.email.focus();
        return false;
    }
    if (Valida_Email(theForm) == false)
        return false;
}

//////////////////////////////////////////////////
// Função para validar entrada do Indique
//////////////////////////////////////////////////
function Valida_Indique(theForm) {
    // Nome
    if (theForm.nome.value == "") {
        alert("Preencha o campo \"Nome\".");
        theForm.nome.focus();
        return false;
    }

    // E-mail
    if (theForm.email.value == "") {
        alert("Preencha o campo \"E-mail\".");
        theForm.email.focus();
        return false;
    }
    if (Valida_Email(theForm) == false)
        return false;

    // Destinatário
    if (theForm.destinatario.value == "") {
        alert("Preencha o campo \"Destinatário\".");
        theForm.destinatario.focus();
        return false;
    }

    // E-mail do destinatário
    if (theForm.emaildestinatario.value == "") {
        alert("Preencha o campo \"E-mail do destinatário\".");
        theForm.emaildestinatario.focus();
        return false;
    }
    if (Valida_Email(theForm) == false)
        return false;
}

//////////////////////////////////////////////////
// Função para validar e-mail
//////////////////////////////////////////////////
/*
function Valida_Email(theForm)
{
var str = theForm.email.value;
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (!filter.test(str))
{
alert("Por favor digite um e-mail válido.");
return false;
}

}
*/

function Valida_Email(theForm) {
    var email = theForm.email.value;
    var BadChars = "*|,\":<>[]{}`\'';()&$#% ";
    var GoodChars = "@.";
    var posarroba = email.indexOf('@', 0);
    if (email.length < 6) {
        alert("E-mail inválido!");
        theForm.email.value = "";
        theForm.email.focus();
        return false;
    }
    for (var i = 0; i < email.length; i++) {
        if (BadChars.indexOf(email.charAt(i)) != -1) {
            alert("E-mail inválido!");
            theForm.email.value = "";
            theForm.email.focus();
            return false;
        }
    }
    for (var i = 0; i < GoodChars.length; i++) {
        if (email.indexOf(GoodChars.charAt(i)) == -1) {
            alert("E-mail inválido!");
            theForm.email.value = "";
            theForm.email.focus();
            return false;
        }
        if (email.indexOf(GoodChars.charAt(i), 0) == 0) {
            alert("E-mail inválido!");
            theForm.email.value = "";
            theForm.email.focus();
            return false;
        }
        if (email.lastIndexOf(GoodChars.charAt(i)) > email.length - 3) {
            alert("E-mail inválido!");
            theForm.email.value = "";
            theForm.email.focus();
            return false;
        }
    }
    if (email.lastIndexOf('@') > email.lastIndexOf('.')) {
        alert("E-mail inválido!");
        theForm.email.value = "";
        theForm.email.focus();
        return false;
    }

    if (email.indexOf('@.', 0) != -1 || email.indexOf('.@', 0) != -1) {
        alert("E-mail inválido!");
        theForm.email.value = "";
        theForm.email.focus();
        return false;
    }
    if (email.indexOf('@', posarroba + 1) != -1) {
        alert("E-mail inválido!");
        theForm.email.value = "";
        theForm.email.focus();
        return false;
    }
}

/**
Verifica se o e-mail é válido. Retorna TRUE para e-mail válido, e FALSE para e-mail inválido
*/
function isEmail(emailValue) {
    var email = emailValue;
    var BadChars = "*|,\":<>[]{}`\'';()&$#% ";
    var GoodChars = "@.";
    var posarroba = email.indexOf('@', 0);
    if (email.length < 6) {
        return false;
    }
    for (var i = 0; i < email.length; i++) {
        if (BadChars.indexOf(email.charAt(i)) != -1) {
            return false;
        }
    }
    for (var i = 0; i < GoodChars.length; i++) {
        if (email.indexOf(GoodChars.charAt(i)) == -1) {
            return false;
        }
        if (email.indexOf(GoodChars.charAt(i), 0) == 0) {
            return false;
        }
        if (email.lastIndexOf(GoodChars.charAt(i)) > email.length - 3) {
            return false;
        }
    }
    if (email.lastIndexOf('@') > email.lastIndexOf('.')) {
        return false;
    }

    if (email.indexOf('@.', 0) != -1 || email.indexOf('.@', 0) != -1) {
        return false;
    }
    if (email.indexOf('@', posarroba + 1) != -1) {
        return false;
    }

    return true;
}


//////////////////////////////////////////////////
// Valida Forma de Pagamento
//////////////////////////////////////////////////
function Valida_Forma_Pagto(theForm) {
    if (theForm.forma_pagto.length) {
        var radioSelected = false;
        for (i = 0; i < theForm.forma_pagto.length; i++) {
            if (theForm.forma_pagto[i].checked)
                radioSelected = true;
        }
        if (!radioSelected) {
            alert("Por favor selecione uma Forma de Pagamento.");
            return false;
        }
    }
    else {
        if (!theForm.forma_pagto || theForm.forma_pagto.value == "") {
            alert("Erro ao carregar as formas de pagamento! Tente novamente...");
            return false;
        }
    }

    if (theForm.aceito_termos && !theForm.aceito_termos.checked) {
        alert("Você deve aceitar os termos do contrato para continuar!!");
        theForm.aceito_termos.focus();
        return false;
    }
    /*
    try
    {
    var btnMatricular = document.getElementById("matricular");
    btnMatricular.src = '../../sistema/imagens/processando.gif';
    btnMatricular.title = "Processando matrícula";
    btnMatricular.disabled = true;
    }
    catch(e){}
    */
    return true;
}

//////////////////////////////////////////////////
// Passa cursos do CEP
//////////////////////////////////////////////////
function passa_cep() {
    var cep = document.form_cadastro.cep1.value;
    if (cep.length == 5) {
        document.form_cadastro.cep2.focus();
        return false
    }
}

//////////////////////////////////////////////////
// Valida Prova
//////////////////////////////////////////////////
function Valida_Prova(theForm, campo) {
    for (i = 0; i < 10; i++) {
        var nomecampo = parseInt(campo) + parseInt(i);
        alert(nomecampo);

        //var nomecampo1 = nomecampo.toString()
        //alert(nomecampo1);

        var radioSelected = false;
        for (i = 0; i < theForm.nomecampo.length; i++) {
            if (theForm.nomecampo[i].checked)
                radioSelected = true;
        }
        if (!radioSelected) {
            alert("Há perguntas não respondidas nesta Prova. Por favor verifique se todas as respostas estão marcadas.");
            return false;
        }
    }
}

//////////////////////////////////////////////////
// FAQ
//////////////////////////////////////////////////
function changeVisibility(id) {
    if (document.getElementById(id).style.display != "inline")
        document.getElementById(id).style.display = "inline";
    else
        document.getElementById(id).style.display = "none";
}

var answers = new Array(0);

function setVisibility(id, visibility) {
    if (visibility)
        document.getElementById(id).style.display = "inline";
    else
        document.getElementById(id).style.display = "none";
}

function expand(visibility) {
    for (i = 0; i < answers.length; i++) {
        setVisibility(answers[i], visibility);
    }
}

function openChecked() {
    var formulary = document.form;
    for (i = 0; i < formulary.elements.length; i++) {
        var element = formulary.elements[i];
        // alert("element = " + element.name);
        if (element.type == "checkbox" && element.checked) {
            // var parent = element.parentNode.parentNode.parentNode.nodeName;

            var parent = element.parentNode;

            while (parent != null && parent.nodeName != "DIV") {
                parent = parent.parentNode;
            }

            // alert("parent = " + parent.nodeName);

            // if (parent.nodeName == "DIV") {

            if (parent != null && parent.nodeName == "DIV") {
                // var par_element = element.parentNode.parentNode.parentNode;
                // alert("Check box! Parent node = " + par_element.nodeName);
                // alert("Name of the div = " + parent.id);

                if (parent.id != "") {
                    var avo = parent.parentNode;

                    // alert("Grand parent node = " + avo.id);

                    document.getElementById(parent.id).style.display = "inline";
                    // changeVisibility(par_element.id);

                    if (avo.id != "") {
                        document.getElementById(avo.id).style.display = "inline";
                        // changeVisibility(avo.id);
                    }
                }
            }
        }
    }
}

//////////////////////////////////////////////////
// USUARIOS
//////////////////////////////////////////////////
function changecheckVisibility(id) {

    if (document.getElementById(id).style.display != "inline")
        document.getElementById(id).style.display = "inline";
    else
        document.getElementById(id).style.display = "none";
}




/////////////////////////////////////////////////////////////////////////
// Formata cnpj  
// Forma de uso  ==> onKeyPress="javascript:FormataCNPJ(this,event);"
/////////////////////////////////////////////////////////////////////////
function FormataCNPJ(Campo, teclapres) {

    var tecla = teclapres.keyCode;

    var vr = new String(Campo.value);
    vr = vr.replace(".", "");
    vr = vr.replace(".", "");
    vr = vr.replace("/", "");
    vr = vr.replace("-", "");

    tam = vr.length + 1;


    if (tecla != 9 && tecla != 8) {
        if (tam > 2 && tam < 6)
            Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, tam);
        if (tam >= 6 && tam < 9)
            Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(5, tam - 5);
        if (tam >= 9 && tam < 13)
            Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(5, 3) + '/' + vr.substr(8, tam - 8);
        if (tam >= 13 && tam < 15)
            Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(5, 3) + '/' + vr.substr(8, 4) + '-' + vr.substr(12, tam - 12);
    }
}

//////////////////////////////////////////////////////////////
// Verifica se o CNPJ é válido
// Forma de usar onBlur="javascript:validaCnpj(this.value)"
///////////////////////////////////////////////////////////////
function validaCnpj(s) {

    var i;

    s = s.replace('-', '');
    s = s.replace('/', '');
    s = s.replace('.', '');
    s = s.replace('.', '');


    var c = s.substr(0, 12);
    var dv = s.substr(12, 2);
    var d1 = 0;

    for (i = 0; i < 12; i++) {
        d1 += c.charAt(11 - i) * (2 + (i % 8));
    }

    if (d1 == 0) {
        return false;
        s.focus();
    }

    d1 = 11 - (d1 % 11);

    if (d1 > 9) d1 = 0;

    if (dv.charAt(0) != d1) {
        return false;
        s.focus();
    }

    d1 *= 2;

    for (i = 0; i < 12; i++) {
        d1 += c.charAt(11 - i) * (2 + ((i + 1) % 8));
    }

    d1 = 11 - (d1 % 11);

    if (d1 > 9) d1 = 0;


    if (dv.charAt(1) != d1) {
        return false;
        s.focus();
    }

    return true;

}


// Verifica se a empresa já foi cadastrada
// Passa o cnpj e os id´s dos itens de retorno.
function verificaPessoaJuridica(id, cnpj, cep, endereco, bairro, cidade, complemento, numero, atividade, estado, nome_empresa) {

    try {
        xmlhttp = new XMLHttpRequest();
    } catch (ee) {
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp = false;
            }
        }
    }


    xmlhttp.open("GET", "../../sistema/codigo/verifica_cadastro_pjuridica.asp?cnpj=" + cnpj, true);
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            var texto = xmlhttp.responseText;
            var dados = texto.split("#");

            if (dados[0] != '') {

                // Atualiza valores			
                document.getElementById(id).value = dados[0];
                document.getElementById(cep).value = dados[6];
                document.getElementById(endereco).value = dados[2];
                document.getElementById(bairro).value = dados[4];
                document.getElementById(cidade).value = dados[7];
                document.getElementById(numero).value = dados[3];
                document.getElementById(complemento).value = dados[5];
                document.getElementById(nome_empresa).value = dados[10];



                for (var i = 0; i < document.getElementById("atividade").options.length; i++) {

                    if (document.getElementById("atividade").options[i].value == dados[8])
                        document.getElementById("atividade").selectedIndex = i;
                }
                for (var i = 0; i < document.getElementById(estado).options.length; i++) {

                    if (document.getElementById(estado).options[i].value == dados[9])
                        document.getElementById(estado).selectedIndex = i;
                }

            }
        }
    }
    xmlhttp.send(null)
}

//redimensiona iframes
function calcHeight(objIFrame) {
    //find the height of the internal page
    var the_height = objIFrame.contentWindow.document.body.scrollHeight;

    //change the height of the iframe
    objIFrame.height = the_height;
}

//copia o conteudo do iframe para o div
function insertIt() {
    var _y = document.getElementById('framediv');
    var _x = window.frames[0].document.body.innerHTML;
    _y.innerHTML = _x;
}

//copia o conteudo do iframe para o div
function insertIt2(iframename) {
    var _y = document.getElementById('framediv');
    var _x = window.frames[iframename].document.getElementById('content').innerHTML;
    _y.innerHTML = _x;
}

function expandCollapse(element) {
    element.style.display = (element.style.display == "none") ? "block" : "none";
}


/******************* 
Animated Expand Collapse Var And Functions START
*******************/
var timerlen = 5;
var slideAniLen = 1000;

var timerID = new Array();
var startTime = new Array();
var obj = new Array();
var endHeight = new Array();
var moving = new Array();
var dir = new Array();

function animatedExpandCollapse(rowId) {
    var divId = 'div_' + rowId;

    if (document.getElementById(divId).style.display == "none")
        slidedown(divId);
    else
        slideup(divId);
}

function slidedown(objname) {
    if (moving[objname])
        return;

    if (document.getElementById(objname).style.display != "none")
        return; // cannot slide down something that is already visible

    moving[objname] = true;
    dir[objname] = "down";
    startslide(objname);
}

function slideup(objname) {
    if (moving[objname])
        return;

    if (document.getElementById(objname).style.display == "none")
        return; // cannot slide up something that is already hidden

    moving[objname] = true;
    dir[objname] = "up";
    startslide(objname);
}

function startslide(objname) {
    obj[objname] = document.getElementById(objname);

    if (dir[objname] == "down") {
        obj[objname].style.height = "1px";
    }

    obj[objname].style.display = "block";
    startTime[objname] = (new Date()).getTime();
    endHeight[objname] = obj[objname].scrollHeight;

    timerID[objname] = setInterval('slidetick(\'' + objname + '\');', timerlen);
}

function slidetick(objname) {
    var elapsed = (new Date()).getTime() - startTime[objname];

    if (elapsed > slideAniLen)
        endSlide(objname)
    else {
        var d = Math.round(elapsed / slideAniLen * endHeight[objname]);
        if (dir[objname] == "up")
            d = endHeight[objname] - d;

        obj[objname].style.height = d + "px";
    }

    return;
}

function endSlide(objname) {
    clearInterval(timerID[objname]);

    if (dir[objname] == "up")
        obj[objname].style.display = "none";

    obj[objname].style.height = endHeight[objname] + "px";

    delete (moving[objname]);
    delete (timerID[objname]);
    delete (startTime[objname]);
    delete (endHeight[objname]);
    delete (obj[objname]);
    delete (dir[objname]);

    return;
}

/******************* 
Animated Expand Collapse Var And Functions END
*******************/


// Altera a visibilidade do cadastro de pessoa jurídica
function alteraVisibilidade(id, element) {

    if (element.id == "pfisica")
        document.getElementById(id).style.display = "none";
    else
        document.getElementById(id).style.display = "block";


}

//Valida campos obrigatórios do cadastro de cupom =================================
//limit_desc: usuario tem limite de desconto na hora de cadastrar cupom? true->sim; false->não
function validaCadCupom(frm, limit_desc) {
    if (frm.desconto.value > 20 && limit_desc == 'False') {
        alert('Valor de desconto não permitido!');
        return false;
    }
    if (frm.data_expira.value == "") {
        alert("Selecione a data de expira" + String.fromCharCode(231) + "ão.");
        return false;

    }
    else {

        for (i = 0; i < frm.elements.length; i++) {

            if (frm.elements[i].name == 'idutilizacao' && frm.elements[i].type == 'radio') {

                if (frm.elements[i].checked == true) {

                    if (frm.elements[i].value == 1 && frm.tipocurso.value != 1 && frm.tipocurso.value != 5 && frm.tipocurso.value != 6 && frm.tipocurso.value != 7) {
                        alert("Emissão de cupons para cartão de aniversário permitida apenas para cursos do tipo Padrão, 130h, Veterinário e Psicólogo!");
                        frm.tipocurso.focus();
                        return false;
                    }
                    else if (frm.elements[i].value == 6 && trim(frm.utilizacao_outro.value) == "") {
                        alert("Informe a utilização do cupom preenchendo o campo \"Outro\"");
                        frm.utilizacao_outro.focus();
                        return false;
                    }
                    return true;
                }
            }
        }

        alert("Selecione a utiliza" + String.fromCharCode(231) + "ão do cupom.");
        return false;
    }

}

// Função que carrega os níveis do usuário usando Ajax.
function getNivel(id) {

    try {
        xmlhttp = new XMLHttpRequest();
    } catch (ee) {
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                xmlhttp = false;
            }
        }
    }

    if (xmlhttp) {

        xmlhttp.open("GET", "UsuariosNiveis.aspx?id=" + id, true);
        xmlhttp.onreadystatechange = function() {

            if (xmlhttp.readyState == 1) {
                //<input name="" type="image" src="../../sistema/imagens/ajax-loader.gif" >Carregando...	
                document.getElementById("framediv").innerHTML = '<img id="carregando" src="../../sistema/imagens/ajax-loader.gif">Carregando...';
            }

            if (xmlhttp.readyState == 4) {
                document.getElementById("framediv").innerHTML = "";

                if (xmlhttp.status == 200) {

                    // Desfaz o urlencode
                    var texto = (xmlhttp.responseText);

                    texto = texto.replace("<title>", "");
                    texto = texto.replace("<html>", "");
                    texto = texto.replace("</html>", "");
                    texto = texto.replace("<body>", "");
                    texto = texto.replace("</body>", "");
                    texto = texto.replace("</title>", "");
                    texto = texto.replace("<head>", "");
                    texto = texto.replace("</head>", "");
                    texto = texto.replace(" ", "");

                    //texto = unescape(texto);
                    // Transforma a lista JSON em Javascript						
                    var d = document.getElementById("framediv");

                    d.innerHTML = texto;

                } else {
                    alert("Erro: " + xmlhttp.statusText);
                }
            }
        }
        xmlhttp.send(null);


    } else {
        alert("Erro");
    }

}

// ##### FUNÇÃO PARA RETIRAR OS ESPAÇOS DO INICIO E DO FIM DA STRING #####
function trim(STRING) {
    STRING = lTrim(STRING);
    return rTrim(STRING);
}

// ##### FUNÇÃO PARA RETIRAR OS ESPAÇOS DO FIM DA STRING #####
function rTrim(STRING) {
    while (STRING.charAt((STRING.length - 1)) == " ") {
        STRING = STRING.substring(0, STRING.length - 1);
    }
    return STRING;
}

// ##### FUNÇÃO PARA RETIRAR OS ESPAÇOS DO INICIO DA STRING #####
function lTrim(STRING) {
    while (STRING.charAt(0) == " ") {
        STRING = STRING.replace(STRING.charAt(0), "");
    }
    return STRING;
}

// ##### FUNÇÃO PARA VERIFICAR SE A STRING INFORMADA É NUMÉRICA #####
function isNumeric(sText) {

    var ValidChars = "0123456789";
    var Char;
    sText = trim(sText);

    for (var i = 0; i < sText.length; i++) {
        Char = sText.charAt(i);
        if (ValidChars.indexOf(Char) == -1)
            return false;
    }

    return true;
}

// ##### FUNÇÃO PARA VERIFICAR SE A STRING INFORMADA É UM NÚMERO TELEFÔNIO VÁLIDO (XXXX-XXXX OU XXXXXXXX) SEM DDD #####
function isValidFone(fone) {

    var novo_fone = trim(fone);
    novo_fone = novo_fone.replace(/ /g, "");
    novo_fone = novo_fone.replace(/-/g, "");
    novo_fone = novo_fone.replace(/\(/g, "");
    novo_fone = novo_fone.replace(/\)/g, "");

    if (isNumeric(novo_fone) == true && novo_fone.length >= 4)
        return true;
    else
        return false;
}

// ##### FUNÇÃO PERMITIR APENAS NÚMEROS #####
function onlyNumber(e) {
    var charCode = (e.which) ? e.which : event.keyCode;

    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;

    return true;
}

// ##### FUNÇÃO PARA GERENCIAR TAMANHO DA FONTE DE UM ELEMENTO #####
function getFontSizeElement(element) {
    var fontSize;

    try {
        fontSize = document.getElementById(element).style.fontSize;
        fontSize = fontSize == "" ? 12 : fontSize;
        fontSize = fontSize.split("px");
        fontSize = fontSize[0];
    }
    catch (e) {
        fontSize = 14;
    }

    return parseInt(fontSize);
}
function setFontSizeElement(element, fontSize) {
    try {
        document.getElementById(element).style.fontSize = fontSize + "px";
    }
    catch (e) { }
}
function diminuiFonte(element) {
    var fontSize = getFontSizeElement(element);

    if (fontSize > 10)
        setFontSizeElement(element, fontSize - 1)
}
function aumentaFonte(element) {
    var fontSize = getFontSizeElement(element);

    if (fontSize < 24)
        setFontSizeElement(element, fontSize + 1)
}
function findTagCloud(tag) {
    document.formBuscaTag.chave.value = tag;
    document.formBuscaTag.submit();
}
function validaSelecaoTurma() {
    var arrayTurmas = document.getElementsByName("turma");

    for (var i = 0; i < arrayTurmas.length; i++) {
        if (arrayTurmas[i].checked)
            return true;
    }

    if (arrayTurmas.length > 0) {
        alert("Por favor, selecione uma turma!");
        arrayTurmas[0].focus();
    }
    else
        alert("Não há turmas para este curso!");

    return false;

}

function form_submit(form) {
    if (typeof form.onsubmit == "function") {
        if (form.onsubmit()) {
            form.submit();
        }
    }
}

// ##### FUNÇÃO PARA VERIFICAR SE A DATA INFORMADA É VÁLIDA #####
/*function isValidData(data)
{

if (data.length == 0){
return;
}

aux = data.split('/');
var dia = parseInt(aux[0], 10);
var mes = parseInt(aux[1], 10);
var ano = parseInt(aux[2], 10);

if (dia <= 31 && mes <=12 && ano >= 1000)
{
if (data.substring(0,1)=='0' && data.substring(1,2) != '0' || data.substring(0,1)!='0')
{
if (data.substring(2,3)=="/")
{
if (data.substring(3,4)=='0' && data.substring(4,5)!='0' || data.substring(3,4)!='0')
{
if (data.substring(5,6)=="/")
{
if (data.substring(6,7)== '0' || data.substring(6,7)=='' && data.substring(7,8)!='0')
{
window.alert('++ Erro\n\nAno inválido!');
return false;
} 
else
{
if (mes == 2)
{
if ((dia > 0 ) && (dia <= 29))
{
if (dia == 29)
{
if ((ano % 4) == 0)
{
return true;
}
else
{
window.alert('++ Erro:\n\nDia inválido!');
return false;
}
}
} 
else
{
window.alert('++ Erro:\n\nDia Inválido!');
return false;
}
}
if ((mes == 4)||(mes == 6)||(mes == 9)||(mes == 11))
{
if ((dia > 0 ) && (dia <= 30))
{
return true;
}
else
{
window.alert('++ Erro:\n\nDia Inválido!');
return false;
}
}
if ((mes == 1)||(mes == 3)||(mes == 5)||(mes ==7)||(mes == 8)||(mes == 10)||(mes == 12))
{
if ((dia > 0) && (dia <= 31))
{
return true;
}
else
{
window.alert('++ Erro:\n\nDia Inválido!');
return false;
}
}
}
}
else
{
window.alert('++ Erro:\n\nA data foi digitada fora do padrão(dd/mm/aaaa).');
return false;
}
}
else
{
window.alert('++ Erro:\n\nMês Inválido!');
return false;
}
}
else
{
window.alert('++ Erro:\n\nA data foi digitada fora do padrão(dd/mm/aaaa).');
return false;
}
}
else
{
window.alert('++ Erro:\n\nDia Inválido!');
return false;	
}
}
else
{
window.alert('++ Erro:\n\nData inválida.');
return false;
}
return true; 
}

// ##### FUNÇÃO PARA VERIFICAR SE O PERÍODO DE DATAS INFORMADO É VÁLIDO #####
function isIntervalData(dataIni, dataFim)
{//função para verificar se a data final é superior à inicial
 
di = parseInt(dataIni.substring(0,2),10);
mi = parseInt(dataIni.substring(3,5),10);
ai = parseInt(dataIni.substring(6,10),10);
		
df = parseInt(dataFim.substring(0,2),10);
mf = parseInt(dataFim.substring(3,5),10);
af = parseInt(dataFim.substring(6,10),10);
			
datai = new Date(ai, mi - 1, di);
dataf = new Date(af, mf - 1, df);

// Se data final for maior ou igual a inicial, retorna true		
if(dataf.getTime() < datai.getTime())
return false;
else
return true;
	
}*/