/**
 * BARRA DE NAVEGACAO MOBILE
 */
document.getElementById('botao_navegacao').onclick = function () {
    const navegacao = document.getElementById('navegacao');
    if (navegacao.className.indexOf('aberto') < 0) {
        navegacao.className += " aberto";
    } else {
        navegacao.className = navegacao.className.replace(' aberto', '');
    }
}

/**
 * MODAL DE LOGIN E RECUPERAR SENHA
 */
if (document.getElementById('link_acesso')) {
    document.getElementById('link_acesso').onclick = function () {
        $('#modal_login').modal('show');
    }
}
if (document.getElementById('link_recuperarsenha')) {
    document.getElementById('link_recuperarsenha').onclick = function () {
        $('#modal_login').modal('hide');
        setTimeout(
            function () {
                return $('#modal_recuperarsenha').modal('show');
            },
            350
        );
    }
}

/**
 * RECUPERAR SENHA
 */
$('#remember-enviar').click(function (e) {
    let barra_progresso = document.getElementById('modal_recuperarsenha_progress');
    let cpf = $('#remember_cpf').val();
    let mail = $('#remember_email').val();
    let recaptcha = $('#g-recaptcha-response').val();

    $(document).ajaxStart(function () {
        barra_progresso.style.display = 'block';
        barra_progresso.children[0].style.animationPlayState = 'running';
        if (document.getElementById('mensagem_recuperarsenha_alert')) {
            document.getElementById('mensagem_recuperarsenha_alert').remove();
        }
    }).ajaxSuccess(function () {
        barra_progresso.removeAttribute('style');
        barra_progresso.children[0].removeAttribute('style');
    });

    if (cpf != '' && mail != '') {
        $.ajax({
            cache: false,
            type: "POST",
            url: "/site/remember",
            data: { 'cpf': cpf, 'mail': mail, 'g-recaptcha-response': recaptcha },
            success: function (response) {
                data = JSON.parse(response);
                if (data.st == 'sucesso') {
                    AlertaInterno('mensagem_recuperarsenha_alert', 'modal_recuperarsenha_alert', 'success', data.msg);
                } else if (data.st == 'erro') {
                    AlertaInterno('mensagem_recuperarsenha_alert', 'modal_recuperarsenha_alert', 'danger', data.msg);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                AlertaInterno('mensagem_recuperarsenha_alert', 'modal_recuperarsenha_alert', 'danger', 'Ocorreu um erro: ' + errorThrown);
            }
        });
    } else {
        AlertaInterno('mensagem_recuperarsenha_alert', 'modal_recuperarsenha_alert', 'danger', 'Favor preencher todos os dados!');
    }
});

/**
 * MÁSCARAS
 */
$(document).ready(function ($) {
    if($(".mask_cpf")) {
        let mask_cpf = $(".mask_cpf");
        let mask_cep = $(".mask_cep");
        let mask_telefone = $(".mask_telefone");
        let mask_celular = $(".mask_celular");
        let mask_tel_e_cel = $('.mask_tel_e_cel');
        let mask_date = $('.mask_date');

        mask_cpf.mask('000.000.000-00', {reverse: true});
        mask_cep.mask('00000-000');
        mask_date.mask('00/00/0000');
        mask_telefone.mask('(00) 0000-0000');
        mask_celular.mask('(00) 00000-0000');

        let VerificaTelCel = function (v) {
            return v.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
        },
            OpcoesTelCel = {
                onKeyPress: function (v, e, input, opcoes) {
                    input.mask(VerificaTelCel.apply({}, arguments), opcoes);
                }
            };
        mask_tel_e_cel.mask(VerificaTelCel, OpcoesTelCel);
    }
    /**
     * INTERVALO CARROSSSEL
     */
    $('#carrossel').carousel({
        interval: 10000
    });
});

/**
 * BUSCA CEP
 * @param valor
 * @constructor
 */
function PesquisaCep(valor) {
    if (valor != '') {
        let cep = valor.replace(/\D/g, '');
        let pesquisa_cep = document.getElementById('pesquisa_cep');
        let input_cep = document.getElementById('emitentes-cep');

        $(document).ajaxStart(function () {
            pesquisa_cep.style.animationName = "rotacao";
            pesquisa_cep.className = "bi bi-arrow-repeat";
            pesquisa_cep.style.color = "#7BBC54";
            pesquisa_cep.style.display = "block";
        }).ajaxSuccess(function () {
            pesquisa_cep.style.animationName = "null";
            pesquisa_cep.className = "bi bi-check-circle-fill";
            pesquisa_cep.style.color = "#00A100";
        });

        $.ajax({
            cache: false,
            url: '/cadastro/pesquisacep?cep=' + cep,
            dataType: 'json',
            success: function (response) {
                if (document.getElementById('empresas-logradouro') != null) {
                    document.getElementById('empresas-logradouro').value = response.logradouro;
                    document.getElementById('empresas-bairro').value = response.bairro;
                }
                else if (document.getElementById('emitentes-logradouro') != null) {
                    document.getElementById('emitentes-logradouro').value = response.logradouro;
                    document.getElementById('emitentes-bairro').value = response.bairro;
                }
                else if (document.getElementById('emitenteentregas-logradouro') != null) {
                    document.getElementById('emitenteentregas-logradouro').value = response.logradouro;
                    document.getElementById('emitenteentregas-bairro').value = response.bairro;
                }
                else if (document.getElementById('empresaentregas-logradouro') != null) {
                    document.getElementById('empresaentregas-logradouro').value = response.logradouro;
                    document.getElementById('empresaentregas-bairro').value = response.bairro;
                }
                else if (document.getElementById('pessoas-logradouro') != null) {
                    document.getElementById('pessoas-logradouro').value = response.logradouro;
                    document.getElementById('pessoas-bairro').value = response.bairro;
                }
                else if (document.getElementById('candidatos-logradouro') != null) {
                    document.getElementById('candidatos-logradouro').value = response.logradouro;
                    document.getElementById('candidatos-bairro').value = response.bairro;
                }
                else if (document.getElementById('recrutamentovagas-logradouro') != null) {
                    document.getElementById('recrutamentovagas-logradouro').value = response.logradouro;
                    document.getElementById('recrutamentovagas-bairro').value = response.bairro;
                }
                else {
                    document.getElementById('logradouro').value = response.logradouro;
                    document.getElementById('bairro').value = response.bairro;
                }

                if (document.getElementById('empresas-cidade_id') != null) {
                    if ($("#empresas-cidade_id").find("option[value=" + response.localidade + "]").length == 0) {
                        $("#empresas-cidade_id").append("<option value='" + response.localidade + "'>" + response.municipio + "</option>")
                    }

                    document.getElementById('empresas-cidade_id').value = response.ibge;
                    document.getElementById('empresas-estado_id').value = response.uf;
                    document.getElementById('empresas-pais_id').value = 1;
                }

                if (document.getElementById('emitentes-cidade_id') != null) {

                   if ($("#emitentes-cidade_id").find("option[value='" + response.localidade + "']").length == 0) {
                        $("#emitentes-cidade_id").append("<option value='" + response.localidade + "'>" + response.municipio + "</option>")
                    }
                    $("#emitentes-cidade_id").val(response.localidade).trigger("change");
                    $("#emitentes-estado_id").val(response.uf).trigger("change");
                    $("#emitentes-pais_id").val(1).trigger("change");
                }

                if (document.getElementById('emitenteentregas-cidade_id') != null) {

                    if ($("#emitenteentregas-cidade_id").find("option[value=" + response.localidade + "]").length == 0) {
                        $("#emitenteentregas-cidade_id").append("<option value='" + response.localidade + "'>" + response.municipio + "</option>")
                    }
                    document.getElementById('emitenteentregas-cidade_id').value = response.ibge;
                    document.getElementById('emitenteentregas-estado_id').value = response.uf;
                    document.getElementById('emitenteentregas-pais_id').value = 1;
                }

                if (document.getElementById('empresaentregas-cidade_id') != null) {

                    if ($("#empresaentregas-cidade_id").find("option[value=" + response.localidade + "]").length == 0) {
                        $("#empresaentregas-cidade_id").append("<option value='" + response.localidade + "'>" + response.municipio + "</option>")
                    }
                    document.getElementById('empresaentregas-cidade_id').value = response.ibge;
                    document.getElementById('empresaentregas-estado_id').value = response.uf;
                    document.getElementById('empresaentregas-pais_id').value = 1;
                }

                if (document.getElementById('pessoas-cidade_id') != null) {

                    if ($("#pessoas-cidade_id").find("option[value=" + response.localidade + "]").length == 0) {
                        $("#pessoas-cidade_id").append("<option value='" + response.localidade + "'>" + response.municipio + "</option>")
                    }
                    document.getElementById('pessoas-cidade_id').value = response.ibge;
                    document.getElementById('pessoas-estado_id').value = response.uf;
                    document.getElementById('pessoas-pais_id').value = 1;
                }

                if (document.getElementById('candidatos-cidade_id') != null) {
                    if ($("#candidatos-cidade_id").find("option[value=" + response.localidade + "]").length == 0) {
                        $("#candidatos-cidade_id").append("<option value='" + response.localidade + "'>" + response.municipio + "</option>")
                    }

                    $("#candidatos-cidade_id").val(response.localidade).trigger("change");
                    $("#candidatos-estado_id").val(response.uf).trigger("change");
                    $("#candidatos-pais_id").val(1).trigger("change");
                }

                if (document.getElementById('recrutamentovagas-cidade_id') != null) {
                    if ($("#recrutamentovagas-cidade_id").find("option[value=" + response.localidade + "]").length == 0) {
                        $("#recrutamentovagas-cidade_id").append("<option value='" + response.localidade + "'>" + response.municipio + "</option>")
                    }

                    $("#recrutamentovagas-cidade_id").val(response.localidade).trigger("change");
                    $("#recrutamentovagas-estado_id").val(response.uf).trigger("change");
                    $("#recrutamentovagas-pais_id").val(1).trigger("change");
                }

                $('.busca-cep').hide();
            },
            error: function (xhr) {
                console.log(xhr.responseText);
                pesquisa_cep.style.animationName = "null";
                pesquisa_cep.className = "bi bi-x-circle-fill";
                pesquisa_cep.style.color = "#A10000";
                pesquisa_cep.style.display = "block";
                input_cep.value = null;
            }
        });
    }
};

/**
 * ESTILIZAR SELECT2 FORMULÁRIO [BACKUP]
 *
if (document.getElementsByClassName('form_select2')[0]) {
    document.getElementsByClassName('form_select2')[0].onclick = () => {
        if (document.querySelector('span.select2-dropdown')) {
            let dropdown = document.querySelector('span.select2-dropdown');
            let input = document.querySelector('input.select2-search__field');
            dropdown.style.border = "solid 1px #7bbc54";
            dropdown.style.borderRadius = "0";
            input.style.border = "solid 2px #7bbc54";
            input.style.borderRadius = "0";
        }
    }
}
*/

/**
 * VALIDAR FORMULÁRIO CREATE
 */
$('#form_create').on('beforeSubmit', function (e) {
    let retorno = true;

    let email = $('#users-email').val();
    if (ValidaEmail(email) != true && email != '') {
        AlertaExterno('mensagem_alert_email', 'danger', 'E-mail informado inválido!');
        retorno = false;
    }

    let cpf = $('#emitentes-cpf').val();
    if (ValidaCpf(cpf) != true && cpf != '') {
        AlertaExterno('mensagem_alert_cpf', 'danger', 'CPF informado inválido!');
        retorno = false;
    }

    let senha = $('#users-password').val();
    let confirma = $('#confirma-senha').val();
    if (senha != confirma && senha != '' && confirma != '') {
        AlertaExterno('mensagem_alert_senha', 'danger', 'As senhas não conferem!');
        retorno = false;
    }

    return retorno;
});


/**
 * VALIDAR FORMULÁRIO UPDATE
 */
const email = $('#users-email').val();
$('#form_update').on('beforeSubmit', function (e) {
    let retorno = true;

    if (email != $('#users-email').val()) {
        AlertaExterno('mensagem_alert_email', 'danger', 'E-mail não pode ser alterado!');
        retorno = false;
    }

    let cpf = $('#emitentes-cpf').val().replace('.', '').replace('-', '');
    if (ValidaCpf(cpf) != true && cpf != '') {
        AlertaExterno('mensagem_alert_cpf', 'danger', 'CPF informado inválido!');
        retorno = false;
    }

    let senha = $('#users-password').val();
    let confirma = $('#confirma-senha').val();
    let alterar_senha = document.getElementById('alterar_senha');
    if (alterar_senha.checked) {
        if ((senha != confirma) && (senha != '') && (confirma != '')) {
            AlertaExterno('mensagem_alert_senha', 'danger', 'As senhas não conferem!');
            retorno = false;
        }
    }

    return retorno;
});

/**
 * ALTERA ÍCONES NO CAMPO CPF
 */
if (document.getElementById('emitentes-cpf')) {
    var input_cpf = document.getElementById('emitentes-cpf');
    var valida_cpf = document.getElementById('valida_cpf');
    input_cpf.onchange = function () {
        let cpf = input_cpf.value.replace('-', '').replace('.', '');
        if (ValidaCpf(cpf) == true) {
            valida_cpf.className = "bi bi-check-circle-fill";
            valida_cpf.style.color = "#00A100";
        } else {
            valida_cpf.className = "bi bi-x-circle-fill";
            valida_cpf.style.color = "#A10000";
        }
    }
}

/**
 * TERMOS DE USO
 */
if (document.getElementById('termos_uso')) {
    var termos_uso = document.getElementById('termos_uso');
    termos_uso.onchange = function () {
        if (this.checked) {
            enviar_cadastro.disabled = false;
        } else {
            enviar_cadastro.disabled = true;
        }
    }
}
if (document.getElementById('aceitar_termos')) {
    let aceitar_termos = document.getElementById('aceitar_termos');
    let enviar_cadastro = document.getElementById('enviar_cadastro');
    aceitar_termos.onclick = () => {
        termos_uso.checked = true;
        enviar_cadastro.disabled = false;
    }
}
if (document.getElementById('negar_termos')) {
    let negar_termos = document.getElementById('negar_termos');
    let enviar_cadastro = document.getElementById('enviar_cadastro');
    negar_termos.onclick = () => {
        termos_uso.checked = false;
        enviar_cadastro.disabled = true;
    }
}

/**
 * VISUALIZAR ALTERAR SENHA
 */
if (document.getElementById('alterar_senha')) {
    let alterar_senha = document.getElementById('alterar_senha');
    let input_senha = document.querySelectorAll('input.form_input-transition');
    alterar_senha.onchange = function () {
        if (this.checked) {
            for (var va of input_senha) {
                let classes = va.className;
                va.className = classes.replace('fechado', 'aberto');
                va.required = true;
            }
        } else {
            for (var va of input_senha) {
                let classes = va.className;
                va.className = classes.replace('aberto', 'fechado');
                va.required = false;
            }
        }
    }
}

/**
 * BUSCA DADOS DO CADASTRO
 */
$('#emitentes-cpf').blur(function (e) {
    var cpf = $('#emitentes-cpf').val();
    if (cpf) {
        $('.verfica-email').hide();
        $('.positivo-email').hide();
        $('.negativo-email').hide();
        $('.load-email').show();

        $.ajax({
            type: "POST",
            url: "/cadastro/mail",
            data: { 'cpf': cpf },
            success: function (response) {

                data = JSON.parse(response);

                if (data['st'] == 'ok') {
                    let fone_princ = '(' + data['ddd_fone_princ'] + ') ' + FormatoFone(data['fone_princ']);
                    let fone_sec = '(' + data['ddd_fone_sec'] + ') ' + FormatoFone(data['fone_sec']);
                    $('#users-email').val(data['email_principal']);
                    $('#emitentes-fone_princ').val(fone_princ);
                    $('#emitentes-fone_sec').val(fone_sec);
                    $('#emitentes-cep').val(data['cep']);
                    $('#emitentes-logradouro').val(data['logradouro']);
                    $('#emitentes-numero').val(data['numero']);
                    $('#emitentes-complemento').val(data['complemento']);
                    $('#emitentes-bairro').val(data['bairro']);
                    $('#emitentes-cidade_id').val(data['cidade']);
                    $('#emitentes-estado_id').val(data['estado']);
                    $('#emitentes-pais_id').val(data['pais']);

                    $('.load-email').hide();
                    $('.positivo-email').show();
                } else {
                    $('.load-email').hide();
                    $('.negativo-email').show();
                }

            }
        });
    }
});

/**
 * ALERTA DE RETORNO DO CADASTRO
 */
window.onload = (() => {
    if (document.getElementById('msg_alert_cadastro') && document.getElementById('msg_alert_cadastro').innerText != '') {
        let msg_alert = document.getElementById('msg_alert_cadastro');
        AlertaExterno(false, 'danger', msg_alert.innerText);
    }
})(true);

/**
 * ALERTA DE RETORNO DO LOGIN
 */
window.onload = (() => {
    if (document.getElementById('msg_alert_login') && document.getElementById('msg_alert_login').innerText != 'null') {
        $('#modal_login').modal('show');
        let msg_alert = document.getElementById('msg_alert_login');
        let json_alert = JSON.parse(msg_alert.innerText);
        AlertaInterno(false, 'modal_login_alert', json_alert.alerta, json_alert.mensagem);
    }
})(true);

/**
 * ALERTA DE RETORNO DO E-MAIL
 */
window.onload = (() => {
    if (document.getElementById('msg_alert_email') && document.getElementById('msg_alert_email').innerText != 'null') {
        let msg_alert = document.getElementById('msg_alert_email');
        let json_alert = JSON.parse(msg_alert.innerText);
        AlertaExterno(false, json_alert.tipo, json_alert.mensagem);
    }
})(true);

/**
 * ACOMPANHAR SLIDE DO CARROSSEL
 */
$('#carrossel').on('slide.bs.carousel', function () {
    document.getElementById('carrossel_texto').style.opacity = '0';
    setTimeout(() => {
        AlterarLegenda();
        AnimarLegenda();
    }, 650);
})

/**
 * ALTERAR LEGENDA DO CARROSSEL
 * @returns {string}
 * @constructor
 */
function AlterarLegenda() {
    const item_carrossel = document.querySelector('div.item.active');
    const texto_carrossel = document.getElementById('carrossel_texto');
    return texto_carrossel.innerText = item_carrossel.querySelector('img').alt;
}

/**
 * ANIMAÇÃO DE TRANSIÇÃO DA LEGENDA
 * @returns {string}
 * @constructor
 */
function AnimarLegenda() {
    return document.getElementById('carrossel_texto').removeAttribute('style');
}

/**
 * MODAL DE TROCA DE ESCOLA
 */
if (document.getElementById('troca_escola')) {
    const troca_escola = document.getElementById('troca_escola');
    troca_escola.onclick = () => {
        $('#modal-escolas').modal('show');
    }
}

/**
 * SELECIONAR ESCOLA
 */
$('button.seleciona_escola').click(function (e) {
    let mail = $('#sel_contrato').val();
    if (mail == "") {
        AlertaInterno('selecione', 'modal_troca_escola', 'danger', "Selecione uma escola.");
    } else {
        $.ajax({
            type: "POST",
            url: "/site/selescolas",
            data: { 'mail': mail },
            cache: false,
            success: function (response) {
                if (response == 'ok') {
                    window.location.reload();
                } else if (response == 'senha') {
                    AlertaInterno('senha', 'modal_troca_escola', 'danger', "Usuário e/ou senha inválido(s)!");
                } else if (response == 'usuario') {
                    AlertaInterno('usuario', 'modal_troca_escola', 'danger', "Contrato não localizado!");
                } else if (response == 'experiado') {
                    AlertaInterno('experiado', 'modal_troca_escola', 'danger', "Contrato expirado!");
                } else if (response == 'Contrato fora período') {
                    AlertaInterno('periodo', 'modal_troca_escola', 'danger', "Contrato fora do período!");
                } else {
                    AlertaInterno('invalido', 'modal_troca_escola', 'danger', "Contrato inválido!");
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                AlertaInterno('erro', 'modal_troca_escola', 'danger', "Ocorreu um erro: " + errorThrown);
            }
        });
    }
});

/**
 * TROCAR ESCOLA
 */
$('button.troca_escola').click(function (e) {
    let mail = $('.users-escolas').val();
    let pass = $('.mail-escolas').val();
    if (mail == "" || pass == "") {
        AlertaInterno('selecione', 'modal_troca_escola', 'danger', "Preencha e-mail e senha.");
    } else {
        $.ajax({
            type: "POST",
            url: "/site/escolas",
            data: { 'mail': mail, 'pass': pass },
            cache: false,
            success: function (response) {
                if (response == 'ok') {
                    window.location.reload();
                } else if (response == 'senha') {
                    AlertaInterno('senha', 'modal_troca_escola', 'danger', "Usuário e/ou senha inválido(s)!");
                } else if (response == 'usuario') {
                    AlertaInterno('usuario', 'modal_troca_escola', 'danger', "Contrato não localizado!");
                } else if (response == 'experiado') {
                    AlertaInterno('experiado', 'modal_troca_escola', 'danger', "Contrato expirado!");
                } else if (response == 'Contrato fora período') {
                    AlertaInterno('periodo', 'modal_troca_escola', 'danger', "Contrato fora do período!");
                } else {
                    AlertaInterno('invalido', 'modal_troca_escola', 'danger', "Contrato inválido!");
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                AlertaInterno('erro', 'modal_troca_escola', 'danger', "Ocorreu um erro: " + errorThrown);
            }
        });
    }
});

/**
 * ALERTA EXTERNO
 * @param id
 * @param tipo
 * @param texto
 * @constructor
 */
function AlertaExterno(id, tipo, texto) {
    let mensagem_alert = null;
    if (!document.getElementById('container_alert')) {
        let container_alert = document.createElement('div');
        container_alert.id = "container_alert";
        container_alert.style.left = "20px";
        container_alert.style.bottom = "10px";
        container_alert.style.zIndex = "2";
        container_alert.style.position = "fixed";
        document.body.insertAdjacentElement('beforeend', container_alert);
    }
    if (document.getElementById(id)) {
        document.getElementById(id).remove();
        mensagem_alert = document.createElement('div');
        mensagem_alert.id = id;
        document.getElementById('container_alert').insertAdjacentElement('afterbegin', mensagem_alert);
    } else {
        mensagem_alert = document.createElement('div');
        mensagem_alert.id = id;
        document.getElementById('container_alert').insertAdjacentElement('afterbegin', mensagem_alert);
    }
    mensagem_alert.innerText = texto;
    mensagem_alert.className = 'alert alert-' + tipo + ' alert-dismissible';
    mensagem_alert.innerHTML += '<button class="close" data-dismiss="alert">&times;</button>';
}

/**
 * ALERTA INTERNO
 * @param id
 * @param container
 * @param tipo
 * @param texto
 * @constructor
 */
function AlertaInterno(id, container, tipo, texto) {
    let mensagem_alert = null;
    if (document.getElementById(id)) {
        document.getElementById(id).remove();
        mensagem_alert = document.createElement('div');
        mensagem_alert.id = id;
        document.getElementById(container).insertAdjacentElement('afterbegin', mensagem_alert);
    } else {
        mensagem_alert = document.createElement('div');
        mensagem_alert.id = id;
        document.getElementById(container).insertAdjacentElement('afterbegin', mensagem_alert);
    }
    mensagem_alert.innerText = texto;
    mensagem_alert.className = 'alert alert-' + tipo + ' alert-dismissible';
    mensagem_alert.innerHTML += '<button class="close" data-dismiss="alert">&times;</button>';
}

/**
 * VALIDA E-MAIL
 * @param email
 * @returns {boolean}
 * @constructor
 */
function ValidaEmail(email) {
    if (email.indexOf('@') > 0 && email.indexOf('.') > 0) {
        return true;
    } else {
        return false;
    }
}

/**
 * VALIDA CPF
 * @param cpf
 * @returns {boolean|string|String|*}
 * @constructor
 */
function ValidaCpf(cpf) {
    cpf = String(cpf);
    cpf = cpf.replace(/\D/g, '');
    erro = new String;
    if (cpf.length < 11) erro += "São necessarios 11 digitos para verificão do CPF! \n\n";
    var nonNumbers = /\D/;
    if (nonNumbers.test(cpf)) erro += "A verificão de CPF suporta apenas numeros! \n\n";
    if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999") {
        erro += "Numero de CPF invalido!";
        return erro;
    }
    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; }
    status = a[9] + "" + a[10]
    if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10])) {
        erro += "Digito verificador com problema!";
        return erro;
    }
    if (erro.length > 0) {
        return false;
    }
    return true;
}

/**
 * CORRIGIR FORMATO DO FONE
 * @param fone
 * @returns {string}
 * @constructor
 */
function FormatoFone(fone) {
    fone = String(fone);
    let formatado = '';
    if (fone.length < 9) {
        for (let a = 0; a < fone.length; a++) {
            formatado += fone[a];
            if (a == 3)
                formatado += '-';
        }
    } else {
        for (let a = 0; a < fone.length; a++) {
            formatado += fone[a];
            if (a == 4)
                formatado += '-';
        }
    }
    return formatado;
}

// function modal_final_de_ano() {
//     $('#modal_final_de_ano').modal('show');
// }
//
// //Descomentar para funcionamento do pop-up
// $("#modal_final_de_ano_close").on("click", function () {
//     setCookie('mostrarModalAvisoCliente202401', 'valor', 1);
//     $('#modal_final_de_ano').modal('hide');
// });

function setCookie(cname = '', cvalue = '', exdays = 1000) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

// var msgFinalDeAno = getCookie('mostrarModalAvisoCliente202401');
// if (msgFinalDeAno === "")
//     modal_final_de_ano();