﻿var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
// Configuração pickadate (meses, dias da semana...)
var datepicker_pt_br = {
    today: 'Hoje',
    clear: 'Limpar',
    done: 'Ok',
    cancel: 'Fechar',
    nextMonth: 'Próximo mês',
    previousMonth: 'Mês anterior',
    weekdaysAbbrev: ['D', 'S', 'T', 'Q', 'Q', 'S', 'S'],
    weekdaysShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
    weekdays: ['Domingo', 'Segunda-Feira', 'Terça-Feira', 'Quarta-Feira', 'Quinta-Feira', 'Sexta-Feira', 'Sábado'],
    monthsShort: ['Jan', 'Fev', 'Mar', 'Abr', 'Mai', 'Jun', 'Jul', 'Ago', 'Set', 'Out', 'Nov', 'Dez'],
    months: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro']
};

var vFormat = 'dd/mm/yyyy';
var vContainer = 'body';
var vDiasAntesDepoisDoMesAtual = true;
var vCloseOnSelect = true;
var cbo;

// Expressões regulares para serem testadas:
var digitsOnly = /[1234567890]/g;
var floatOnly = /[0-9\.]/g;
var alphaOnly = /[A-Za-z]/g;
var alphaNumeric = /[A-Za-z0-9\s]/g;

/* MODAL CSS */
var modalStyleAlert = 'background-color: #fbc02d !important';

$("#dadosUsuario-trigger").click(function () {
    if ($("#dadosUsuario").hasClass("scale-out")) {
        $("#dadosUsuario").removeClass('scale-out').addClass('scale-in');
    } else {
        $("#dadosUsuario").removeClass('scale-in').addClass('scale-out');
    }
});

function retornaBoolean(stringvalue) {
    return stringvalue == "true";
}


function pageLoad(sender, args) {

    $('.chatVueJs').click(function () {
        var show = $('#iframeChat').toggle();
        //console.log(show[0].style.display);
        window.sessionStorage.setItem("atualiza_msg_chat", show[0].style.display == 'none' ? false : true);
    });

    /* BIOMETRIA FACIAL */
    $('.registrarBiometriaFacial').click(function () {
        registrarBiometriaFacial();
    });

    $('.validarBiometriaFacial').click(function () {
        validarBiometriaFacial();
    });
    /* FIM BIOMETRIA FACIAL */

    // Esta chamada corrige o problema do Chrome preencher input-texts com o valor do username preenchido no form de login
    $(function () {
        $('form').autoCompleteFix();
    });

    //chamada para os botões flutuantes
    $('.fixed-action-btn').floatingActionButton();

    $("#updLoading2").hide();

    $('select').formSelect();
    $('.tooltipped').tooltip({ enterDelay: 50, exitDelay: 50 });

    $('ul.tabs').tabs();

    $('.collapsible').collapsible();

    $('.lnkExpand').click(function () {
        var elemento = $(this).parent().children(".conteudo");
        elemento.slideToggle(200);
    });

    $('.expand_row').click(function () {
        var elemento = $(this).closest('tr').next('tr');
        elemento.slideToggle(200);
    });

    $('.timepicker').timepicker({
        defaultTime: 'now', // Set default time: 'now', '1:30AM', '16:30'
        twelvehour: false, // Use AM/PM or 24-hour format
        done: 'OK', // text for done-button
        clear: 'Limpar', // text for clear-button
        cancel: 'Cancelar', // Text for cancel-button
    });

    if ($("input[class*='hora']").length > 0) $("input[class*='hora']").mask("99:99");
    if ($('.date_mask')) $('.date_mask').mask("99/99/9999");
    


    if (document.getElementById('alertaConfirmacaoCancelamentoPedidoMedico')) {
        $('#alertaConfirmacaoCancelamentoPedidoMedico').modal({
            dismissible: false,
            complete: function () {
                $('.modal-overlay').hide();
            }
        });
    }
    var key = window.location.pathname + '#lineChecked';
    //var lineChecked = localStorage.setItem(key, "");

    $(".datepicker_smal").click(function (event) {
        event.stopPropagation();
        $(".datepicker_smal").first().datepicker("picker").open();
    });
   
    
    $('.datepicker_maxDate').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 10,
        autoClose: vCloseOnSelect,
        minDate: subDaysToDatePick(365),
        maxDate: new Date(),
        onOpen: function () {
            var newdate = $('.datepicker_maxDate').val();
            if (newdate)
                this.setDate(newdate.toDate('dd/mm/yyyy'));
        },
        onClose: function () {
            $(document.activeElement).blur();
        }
    }).on('mousedown', function (e) { e.preventDefault(); });

    /** PICKADATE **/
    $('.datepicker_smal').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 10,
        autoClose: vCloseOnSelect,
        onClose: function () {
            $(document.activeElement).blur()
        }
    });


    $('.datepicker').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 10,
        autoClose: vCloseOnSelect,
        onClose: function () {
            $(document.activeElement).blur()
        }
    }).on('mousedown', function (e) { e.preventDefault(); });
    
   $('.dataInicial').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 6,
        autoClose: vCloseOnSelect,
        onClose: function () {
            $(document.activeElement).blur();

            var newdate = this.date;
            newdate.setDate(newdate.getDate() + 1);
            var instance = M.Datepicker.getInstance($('.dataFinal'));
            instance.options.minDate = newdate;

            var dataFinal = new Date(instance.date);

            if (dataFinal < newdate) {
                instance.setDate(newdate);
            }
        },
        onSelect: function (thingSet) {
            //console.log('Set stuff:', thingSet);
        }
    });
    
    $('.dataFinal').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 6,
        autoClose: vCloseOnSelect,
        onClose: function () {
            $(document.activeElement).blur();

            var newdate = this.date;
            newdate.setDate(newdate.getDate() + 1);
            var instance = M.Datepicker.getInstance($('.dataInicial'));
            instance.options.maxDate = newdate;

            var dataInicial = new Date(instance.date);

            if (dataInicial > newdate) {
                instance.setDate(newdate);
            }
        },
        onSelect: function (thingSet) {
            //console.log('Set stuff:', thingSet); 
        }
    });
    
    $('.dataInicialPeriodo30Dias').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 5,
        autoClose: vCloseOnSelect,
        onClose: function () {
            $(document.activeElement).blur();

            var data = this.date;
            data.setDate(data.getDate() + 1);

            var dias = 30;

            var instance = M.Datepicker.getInstance($('.dataFinalPeriodo30Dias'));
            var dataFinal = instance.date;
            var maxDate = new Date(data.getTime() + (dias * 24 * 60 * 60 * 1000));

            if (dataFinal > maxDate) {
                instance.setDate(maxDate);

                buldModalAlert('Periodo30Dias', 'ALERTA', 'Período permitido é de 30 dias. A data final foi modificada.', modalStyleAlert);
            }
        },
        onSelect: function (thingSet) {
            //console.log('Set stuff:', thingSet);
        }
    });
    
    $('.dataFinalPeriodo30Dias').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 5,
        autoClose: vCloseOnSelect,
        onClose: function () {
            $(document.activeElement).blur();
            var data = this.date;
            data.setDate(data.getDate() + 1);

            var dias = 30;

            var instance = M.Datepicker.getInstance($('.dataInicialPeriodo30Dias'));
            var dataInicial = instance.date;
            var minDate = new Date(data.getTime() - (dias * 24 * 60 * 60 * 1000));

            if (dataInicial < minDate) {
                instance.setDate(minDate);

                buldModalAlert('Periodo30Dias', 'ALERTA', 'Período permitido é de 30 dias. A data inicial foi modificada.', modalStyleAlert);
            }

            //console.log(newdate);
        },
        onSelect: function (thingSet) {
            //console.log('Set stuff:', thingSet); 
        }
    });

    $('.dataInicialPeriodo90Dias').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 5,
        autoClose: vCloseOnSelect,
        onClose: function () {
            $(document.activeElement).blur();

            var data = this.date;
            data.setDate(data.getDate() + 1);

            var dias = 90

            var instance = M.Datepicker.getInstance($('.dataFinalPeriodo90Dias'));
            var dataFinal = instance.date;
            var maxDate = new Date(data.getTime() + (dias * 24 * 60 * 60 * 1000));

            if (dataFinal > maxDate) {
                instance.setDate(maxDate);

                buldModalAlert('Periodo90Dias', 'ALERTA', 'Período permitido é de 90 dias. A data final foi modificada.', modalStyleAlert);
            }
        },
        onSelect: function (thingSet) {
            //console.log('Set stuff:', thingSet);
        }
    });

    $('.dataFinalPeriodo90Dias').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 5,
        autoClose: vCloseOnSelect,
        onClose: function () {
            $(document.activeElement).blur();
            var data = this.date;
            data.setDate(data.getDate() + 1);

            var dias = 90;

            var instance = M.Datepicker.getInstance($('.dataInicialPeriodo90Dias'));
            var dataInicial = instance.date;
            var minDate = new Date(data.getTime() - (dias * 24 * 60 * 60 * 1000));

            if (dataInicial < minDate) {
                instance.setDate(minDate);

                buldModalAlert('Periodo90Dias', 'ALERTA', 'Período permitido é de 90 dias. A data inicial foi modificada.', modalStyleAlert);
            }

            //console.log(newdate);
        },
        onSelect: function (thingSet) {
            //console.log('Set stuff:', thingSet); 
        }
    });

    $('.dataInicialRecurso').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 3,
        autoClose: vCloseOnSelect,
        minDate: subDaysToDatePick(parseInt($(".prazoRecurso").val())),
        maxDate: new Date(),
        onClose: function () {
            $(document.activeElement).blur();

            var newdate = this.date;
            newdate.setDate(newdate.getDate() + 1);
            var instance = M.Datepicker.getInstance($('.dataFinalRecurso'));
            instance.options.minDate = newdate;
            //console.log(newdate);
        }
    });

    $('.dataFinalRecurso').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 3,
        autoClose: vCloseOnSelect,
        minDate: subDaysToDatePick(parseInt($(".prazoRecurso").val())),
        maxDate: new Date(),
        onClose: function () {
            $(document.activeElement).blur();
            var newdate = this.date;
            newdate.setDate(newdate.getDate() + 1);
            var instance = M.Datepicker.getInstance($('.dataInicialRecurso'));
            instance.options.maxDate = newdate;
            //console.log(newdate);
        }
    });

    $('.dataValidade').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 5,
        autoClose: vCloseOnSelect,
        minDate: new Date(),
        maxDate: addDaysToDatePick(1100),
        onClose: function () {
            $(document.activeElement).blur()
        }
    });

    $('.dpNascimento').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 100,
        autoClose: vCloseOnSelect,
        minDate: new Date('1917-01-01 00:00:00'),
        maxDate: new Date(),
        onClose: function () {
            $(document.activeElement).blur()
        }
    });

    $('.dataInicialFaturamento').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 3,
        autoClose: vCloseOnSelect,
        minDate: subDaysToDatePick(365),
        maxDate: new Date(),
        onClose: function () {
            $(document.activeElement).blur();

            var newdate = this.date;
            newdate.setDate(newdate.getDate() + 1);
            var instance = M.Datepicker.getInstance($('.dataFinalFaturamento'));
            instance.options.minDate = newdate;
            //console.log(newdate);
        }
    });

    $('.dataFinalFaturamento').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 3,
        autoClose: vCloseOnSelect,
        minDate: subDaysToDatePick(365),
        maxDate: new Date(),
        onClose: function () {
            $(document.activeElement).blur();
            var newdate = this.date;
            newdate.setDate(newdate.getDate() + 1);
            var instance = M.Datepicker.getInstance($('.dataInicialFaturamento'));
            instance.options.maxDate = newdate;
            //console.log(newdate);
        }
    });

    costumize_datepick();
    costumize_timepick();

    /** FIM - PICKADATE **/

    $(".readonly").attr("readonly", "readonly");

    /** VALIDAÇÃO DE CAMPOS **/
    // apenas números para os campos do tipo numérico    
    $("input[class*=numero]").keypress(function (e) {
        //if the letter is not digit then display error and don't type anything
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57))
            return false;
    });

    $("input[class~=decimal]").priceFormat({
        prefix: '',
        limit: 6,
        centsLimit: 2,
        centsSeparator: ',',
        thousandsSeparator: '.'
    });

    $("input[class*=decimal_10-2]").priceFormat({
        prefix: '',
        limit: 10,
        centsLimit: 2,
        centsSeparator: ',',
        thousandsSeparator: '.'
    });

    $("input[class*=decimal_6-2]").priceFormat({
        prefix: '',
        limit: 6,
        centsLimit: 2,
        centsSeparator: ',',
        thousandsSeparator: '.'
    });

    $("input[class*=decimal_8-2]").priceFormat({
        prefix: '',
        limit: 8,
        centsLimit: 2,
        centsSeparator: ',',
        thousandsSeparator: '.'
    });

    $("input[class*=decimal_7-4]").priceFormat({
        prefix: '',
        limit: 7,
        centsLimit: 4,
        centsSeparator: ',',
        thousandsSeparator: '.'
    });

    $("input[class*=decimal_7-2]").priceFormat({
        prefix: '',
        limit: 7,
        centsLimit: 2,
        centsSeparator: ',',
        thousandsSeparator: '.'
    });

    $("input[class*=decimal_5-2]").priceFormat({
        prefix: '',
        limit: 5,
        centsLimit: 2,
        centsSeparator: ',',
        thousandsSeparator: '.'
    });

    $("input[class*=decimal_4-2]").priceFormat({
        prefix: '',
        limit: 4,
        centsLimit: 2,
        centsSeparator: ',',
        thousandsSeparator: '.'
    });

    $("input[class*=decimal_3-2]").priceFormat({
        prefix: '',
        limit: 3,
        centsLimit: 2,
        centsSeparator: ',',
        thousandsSeparator: '.'
    });

    //Validação dos telefones
    $('.mascaraTel').each(function (i, el) {
        $('#' + el.id).mask("00 00000 0000");
    })

    //Mascara do CPF
    $('.mascaraCPF').each(function (i, el) {
        $('#' + el.id).mask("999.999.999-99");
    })

    //Mascara do CEP
    $('.mascaraCEP').each(function (i, el) {
        $('#' + el.id).mask("00000-000");
    })

    //Mascara do PIS
    $('.mascaraPIS').each(function (i, el) {
        $('#' + el.id).mask("000.00000.00.0");
    })

    function updateMask(event) {
        var $element = $('#' + this.id);
        $(this).off('blur');
        $element.unmask();
        if (this.value.replace(/\D/g, '').length > 10) {
            $element.mask("00 00000 0000");
        } else {
            $element.mask("00 0000 00009");
        }
        $(this).on('blur', updateMask);
    }
    $('.mascaraTel').on('blur', updateMask);
    //Fim da validação dos telefones


    // Calcular o campo superficie corporal do anexo de quimioterapia
    $(".CalculaSuperficieCorporal").blur(function () {
        var peso = $(".txbPeso").val().replace(",", ".");
        var altura = $(".txbAltura").val().replace(",", ".");
        var valor = 0;

        valor = (0.007184 * (Math.pow(altura, 0.725)) * (Math.pow(peso, 0.425)));

        $(".txbSuperficieCorporal").val(valor.toFixed(2).replace(".", ","));
    });
    /** FIM - VALIDAÇÃO DE CAMPOS **/

    $('.sidenav').sidenav({
        menuWidth: 280, // Default is 300
        edge: 'left', // Choose the horizontal origin        
        draggable: true, // Choose whether you can drag to open on touch screens,
        onOpenStart: function (el) { /* Do Stuff */ }, // A function to be called when sideNav is opened        
    });

    $('.dropdown-trigger-navbar').dropdown({
        inDuration: 250,
        outDuration: 250,
        constrainWidth: false, // Does not change width of dropdown to that of the activator
        hover: false, // Activate on hover        
        coverTrigger: false, // Displays dropdown below the button
        alignment: 'left', // Displays dropdown with edge aligned to the left of button        
    });

    $('.collapsible-navbar').collapsible({
        accordion: false, // A setting that changes the collapsible behavior to expandable instead of the default accordion style        
        onClose: function (el) { /*alert('Closed');*/ } // Callback for Collapsible close
    });

    //if (window.location.pathname.indexOf("Agendamento/Consulta.aspx") != -1) 
    //carregaAgenda();

    $('[class^=checkPai_]').click(function () {
        var CheckFilhos = $('.checkFilho_' + getPapel($(this))).find('input[type="checkbox"]');

        for (var i = 0; i < CheckFilhos.length; i++) {
            var CurrentCheck = CheckFilhos[i];
            if (CurrentCheck.type === "checkbox")
                CurrentCheck.checked = this.checked;
        }

        if (getPapel($(this)) == "Grid")
            totalValorRecursado();

        var itens_selecionados = $(this).closest('.ucDataTableContainer').parent().find(".Hidden_ItensSelecionados")[0];

        if (this.checked) {
            var itens_selecionados_JSON = JSON.parse(itens_selecionados.value ? itens_selecionados.value : '{"SelectedIDs":[]}');

            for (var i = 0; i < CheckFilhos.length; i++) {
                if (!itens_selecionados_JSON["SelectedIDs"].contains("" + i))
                    itens_selecionados_JSON["SelectedIDs"].push("" + i);
            }

            itens_selecionados.value = JSON.stringify(itens_selecionados_JSON);
        } else {
            itens_selecionados.value = '{"SelectedIDs":[]}';
        }

    });

    $('[class^=checkFilho_]').click(function () {
        if (getPapel($(this)) == "Grid")
            totalValorRecursado();

        var papel = getPapel($(this));

        var totalCheckboxes = $('[class^=checkFilho_' + papel + '][type=checkbox]').length;
        var totalCheckboxesMarcados = $('[class^=checkFilho_' + papel + '][type=checkbox]:checked').length;

        if (totalCheckboxes == totalCheckboxesMarcados && totalCheckboxesMarcados != 0) {
            //$(".checkPai_" + papel).find("[type='checkbox']").attr("checked", true);
            $(".checkPai_" + papel)[0].checked = true;
        } else {
            //$(".checkPai_" + papel).find("[type='checkbox']").attr("checked", false);
            $(".checkPai_" + papel)[0].checked = false;
        }
    });

    var CheckBoxPais = $('[class^=checkPai_]');
    if (CheckBoxPais.length > 0) {
        for (var i = 0; i < CheckBoxPais.length; i++) {
            var CurrentCheckBoxPai = CheckBoxPais[i];

            if (getPapel(CurrentCheckBoxPai) == "Grid")
                totalValorRecursado();

            var papel = getPapel(CurrentCheckBoxPai);

            var totalCheckboxes = $('[class^=checkFilho_' + papel + '][type=checkbox]').length;
            var totalCheckboxesMarcados = $('[class^=checkFilho_' + papel + '][type=checkbox]:checked').length;

            if (totalCheckboxes == totalCheckboxesMarcados && totalCheckboxesMarcados != 0) {
                CurrentCheckBoxPai.checked = true;
            } else {
                CurrentCheckBoxPai.checked = false;
            }
        }
    }

    var CheckBoxes = $('[type=checkbox]');

    for (var i = 0; i < CheckBoxes.length; i++) {
        var Checkbox = CheckBoxes[i];

        if ($(Checkbox).attr('checked')) {
            Checkbox.checked = true;
        } else {
            Checkbox.checked = false;
        }

        //Adiciona classe a todos as tabelas do checkbox. Contorno para o materialize
        if (!$("form input:checkbox").hasClass("checkFilho_ucDataTable") &&
            !$("form input:checkbox").hasClass("checkPai_ucDataTable")) {
            $("form input:checkbox").closest('table').addClass("checkBoxListTipo");
        }
    }



    /* Leitura do cartão magnético*/
    $("#imgCartaoUnimed").click(function () {
        $("#cphConteudo_txbCartaoMag").focus();
        $("#cphConteudo_txbCartaoMag").val("");
        $("#hdfNomeBenef").val("");
        $("#hdfViaCartao").val("");
    });

    $("#cphConteudo_txbCartaoMag").keyup(function () {
        var leituraCartao = $("#cphConteudo_txbCartaoMag").val();
        var numeroCarteira = $("#txbNumeroCarteira");
        var nomeBeneficiario = $("#hdfNomeBenef");
        var viaCartao = $("#hdfViaCartao");
        var nome = "";
        var via = "";
        var numeroCartao = leituraCartao.split("\n");
        if (numeroCartao.length > 2) {
            nome = numeroCartao[0].substring(1, 26);
            nomeBeneficiario.val(nome);
            via = numeroCartao[1].substring(19, 21);
            viaCartao.val(via);
            numeroCartao = numeroCartao[1].substring(1, 18);
            numeroCarteira.val(numeroCartao);
            __doPostBack('ctl00$cphConteudo$udbBeneficiario$UcBlocoConteudo1$ctl00$imbPesquisaBenef', 'OnClick');
            $("#caixaCartao").modal('close');
        }
    });
    
    $(".limpaCampoData").change(function () {
        limparInput('txbDataRecurso');
    });

    function limparInput(nomeClass) {
        $("." + nomeClass).val("");
    }



    $("ul.tabs").click(function () {
        var index = $('ul.tabs .active').attr('data-tab');

        $("#cphConteudo_hdfTabIndex").val(index);
    });

    //verificaRadioUsuarioPerfil();
    //$(".radioGrupoPerfil input[type=radio]").click(function () {
    //    verificaRadioUsuarioPerfil();
    //});

    //function verificaRadioUsuarioPerfil() {
    //    if ($(".radioGrupoPerfil input:checked").val() == "P") {
    //        $("#sectionUsuarioGrupo").hide();
    //        $('#sectionUsuarioGrupo').addClass('disabled');
    //        $("#sectionUsuarioPerfil").show();
    //    } else {
    //        $("#sectionUsuarioPerfil").hide();
    //        $('#sectionUsuarioGrupo').removeClass('disabled');

    //        $("#sectionUsuarioGrupo").show();
    //    }
    //}

    $('[class^=checkMaster_GridView]').click(function () {

        var checkelements = $("#" + $(this).closest('table')[0].attributes['Id'].value).find($('[class^=checkChildren_' + getPapel($(this)) + ']').find("[type='checkbox']"));

        if ($(this).find("[type='checkbox']")[0].checked) {
            for (var i = 0; i < checkelements.length; i++) {
                checkelements[i].checked = true;
            }
            totalValorRecursado();
        }
        else {
            for (var i = 0; i < checkelements.length; i++) {
                checkelements[i].checked = false;
            }
        }
    });
    
    $('[class^=checkChildren_GridView]').click(function () {
        if (getPapel($(this)) == "Grid")
            totalValorRecursado();
        var papel = getPapel($(this));

        var totalCheckboxes = $("#" + $(this).closest('table')[0].attributes['Id'].value).find($('[class^=checkChildren_' + getPapel($(this)) + ']').find("[type='checkbox']")).length;
        var totalCheckboxesMarcados = $("#" + $(this).closest('table')[0].attributes['Id'].value).find($('[class^=checkChildren_' + getPapel($(this)) + ']').find("[type='checkbox']:checked")).length;

        if (totalCheckboxes == totalCheckboxesMarcados) {
            $("#" + $(this).closest('table')[0].attributes['Id'].value).find($(".checkMaster_" + papel).find("[type='checkbox']"))[0].checked = true;
            //  $(".checkMaster_" + papel).find("[type='checkbox']")[0].checked = true;
        } else {
            $("#" + $(this).closest('table')[0].attributes['Id'].value).find($(".checkMaster_" + papel).find("[type='checkbox']"))[0].checked = false;
            // $(".checkMaster_" + papel).find("[type='checkbox']")[0].checked = false;
        }
    });
    

    //Ajuste no Menu
    var h = $(".navbar-fixed").width(),
       w = $(".left.hide-on-med-and-down").width(),
       y = $(".right.hide-on-med-and-down").width();

    //ajusteMenu(h, w, y);

    // realizar verificação
    $(window).resize(function () {
       width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
       height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        // recolher valores actuais/
        
       var nh = $(".navbar-fixed").width();
       var nw = 0 /*$(".left.hide-on-med-and-down").width()*/;
        var ny = 0 /*$(".right.hide-on-med-and-down").width()*/;

        /* comparar os valores antigos com os novos
         * e realizar acção pretendida aqui!
         */
        ajusteMenu(nh, nw, ny);

        // atualizar os valores nas variáveis que guardam o valor antigo
        h = nh; w = nw; y = ny;

    });

    /* modificação do estilo para campos obrigatórios */

    $('.obrigatorio').each(function () {
        var tag = '<span id="span_obg" style="color: red;"> * </span>';
        if ($(this).html($(this).html())[0].innerHTML.contains(tag) == false) {
            $(this).html($(this).html() + tag);
        }
    });

    /*Validação para o campo Auto-Complete do DevExpress apagar automaticamente caracteres especiais*/
    jQuery(".alfanumerico input[type=text]").keypress(function (ev) {
        var campo = $(this);
        var isValid = restringirCaracteres(campo, ev, alphaNumeric);
        if (!isValid) {
            return false;
        } else {
            if (!isNaN(campo.val())) {
                campo.val(campo.val().substring(0, 17));
            } else {
                campo.val(campo.val().substring(0, 70));
            }
        }
    });
    jQuery(".alfanumerico input[type=text]").on("paste", function (ev) {
        if (ev.originalEvent.clipboardData.getData('text').match(/[^\w\s]/gi)) {
            ev.preventDefault(); //previne o comportamento padrão
        }
    })
    /************************************************************************************************/
    
    $(".verificaTamanhoMinimo").keyup(function () {
        verificaTamanhoMin("TextoMin", "15");
    });

    $(".verificaTamanhoMinimo").blur(function () {
        verificaTamanhoMin("TextoMin", "15");
    });

    // Verificação do estado do checkbox list do perfil Beneficiário no módulo administrador
    $(".checkFilho_B :checkbox").each(function () {
        VerificaEstadoDoCbxListBI($(this));
    });
    

    $(".txbOnKeyUp").keyup(function () {
        var text = $(this).val();
        var indice = text.search("&#");

        while (indice != -1) {
            var strUm = text.substring(0, indice + 1);
            var strDois = text.substring((indice + 2), (text.length));
            text = strUm + ' ' + strDois;
            $(this).val(text);

            indice = text.search("&#");
        }
    });

    $(".clearLocalStorage").click(function () {
        var key = window.location.pathname + '#lineChecked';
        var lineChecked = localStorage.setItem(key, "");

    });
}
    

function VerificaEstadoDoCbxListBI(control) {
    var $t = control,
            val = $t.val(),
            key = val.charAt(val.length - 1);

    if ($t[0].checked) {
        $(".checkFilho_BI :checkbox").each(function () {
            var $f = $(this);
            if ($f.val() == val) {
                $f.removeAttr("disabled");
            }
        });
    } else {
        $(".checkFilho_BI :checkbox").each(function () {
            var $f = $(this);
            if ($f.val() == val) {
                $f.attr("disabled", "disabled");
                $f.prop('checked', false);
            }
        });
    }
    MudaEstadodoCbxPaiBI();
}

function MudaEstadodoCbxPaiBI() {
    var allChecked = true;
    $(".checkFilho_B :checkbox").each(function (index, element) {
        if (!element.checked) {
            allChecked = false;
            return false;
        }
    });

    if (allChecked) {
        $("#chkServicoBenefInativo").removeAttr("disabled");
    } else {
        $("#chkServicoBenefInativo").attr("disabled", "disabled");
        $("#chkServicoBenefInativo").prop("checked", false);
    }
}

/*Remove acentos de caracteres contido em um texto*/
function removeAcentos(txtAcentuado) {
    var strAccents = txtAcentuado.split('');
    var strAccentsOut = new Array();
    var strAccentsLen = strAccents.length;
    var acentos = "ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž";
    var semAcentos = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
    for (var y = 0; y < strAccentsLen; y++) {
        if (acentos.indexOf(strAccents[y]) != -1) {
            strAccentsOut[y] = semAcentos.substr(acentos.indexOf(strAccents[y]), 1);
        } else
            strAccentsOut[y] = strAccents[y];
    }
    strAccentsOut = strAccentsOut.join('');

    return strAccentsOut;
}

function obtemTamanho() {
    //Ajuste no Menu
    width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    h = $(".navbar-fixed").width();
    w = $(".left.hide-on-med-and-down").width();
    y = $(".right.hide-on-med-and-down").width();
}

function ajusteMenu(x, y, z) {

    //if (((x - (y + z)) < 200) || (y == 0 && z == 0)) {
    if (width <= 600) {
        //$(".hide-on-med-and-down").css("display", "none");
        //alert($("nav a.sidenav").css("display"));
        $("nav a.sidenav").css("display", "block");
        ajusteBotoesMobile();

    } else {
        //$(".hide-on-med-and-down").css("display", "block");
        //alert($(window).width());
        ajusteBotoesDesktop();
        if ($(window).width() > 980) {
            $("nav a.sidenav").css("display", "none");
        }
    }
    $("main").css("min-height", ($(window).height() - 160));

}

function ajusteBotoesMobile() {
    var botoes = document.getElementsByClassName("ButtonTable");

    for (var b = 0; b < botoes.length; b++) {
        if (botoes[b] != null) {
            if (botoes[b].children.length == 1) {

                var btnUnico = botoes[b].getElementsByTagName('a');
                if (btnUnico.length == 1) {
                    for (var index = 0; index < btnUnico.length; index++) {
                        var i = btnUnico[index];

                        if (i.classList.contains("btn-table")) {
                            $('#' + i.id).removeClass("btn btn-table").addClass("btn-floating btn-large waves-effect waves-light");
                            $('#' + i.id).removeAttr('data-position');
                            $('#' + i.id).attr('data-position', 'left');
                            //btnUnico[index].innerHTML += "<a class='btn-floating mobile-fab-tip'>" + i.title + "</a>";
                        }
                    }
                    $('#' + botoes[b].id).removeClass("ButtonTable col s12 m6 l6").addClass('fixed-action-btn');

                    //$('#ButtonTable').removeClass("ButtonTable col s12 m6 l6");
                    //$('.ButtonTable').removeClass("ButtonTable col s12 m6 l6").addClass('fixed-action-btn vertical');
                } else {
                    var listaBotoes = $('#' + botoes[b].id).find('li').find('a');
                    if (listaBotoes.length > 0) {
                        //if ($('#main-btn').length == 0)
                        botoes[b].innerHTML += "<a class='btn-floating btn-large waves-effect waves-light green darken-3 tooltipped btnOption' id='main-btn'  data-position='left' data-tooltip='Opções'><i class='material-icons'>menu</i></a>";

                        for (var index = 0; index < listaBotoes.length; index++) {
                            var link = listaBotoes[index];

                            //if (link.classList.contains("btn-table")) {
                            $('#' + link.id).removeClass("btn btn-table").addClass("btn-floating waves-effect waves-light");
                            $('#' + link.id).removeAttr('data-position');
                            $('#' + link.id).attr('data-position', 'left');
                            //listaBotoes[index].innerHTML += "<a class='btn-floating mobile-fab-tip'>" + link.title + "</a>";
                        }
                        //}


                        $('#' + botoes[b].id).removeClass("ButtonTable col s12 m6 l6").addClass("fixed-action-btn click-to-toggle");
                        //$('.ButtonTable').removeClass("col s12 m6 l6").addClass("fixed-action-btn vertical click-to-toggle");
                    }
                }
            }
        }
    }
    $('.fixed-action-btn').floatingActionButton();
}

function ajusteBotoesDesktop() {
    var botoes = document.getElementById("ButtonTable");

    if (botoes != null) {
        if (!botoes.classList.contains('useButtonFloat')) {

            var mainBtn = document.getElementById('main-btn');
            if (mainBtn != null) {
                mainBtn.parentNode.removeChild(mainBtn);
            }

            var btnUnico = botoes.getElementsByTagName('a');
            if (btnUnico.length > 0) {
                for (var index = 0; index < btnUnico.length; index++) {
                    var i = btnUnico[index];

                    if (i.classList.contains("btn-floating")) {
                        $('#' + i.id).removeClass("btn-floating btn-large waves-effect waves-light").addClass("btn btn-table");
                        $(".mobile-fab-tip").remove();
                    }
                }
                $('#ButtonTable').addClass("ButtonTable col s12 m6 l6");
                $('.fixed-action-btn').addClass("ButtonTable col s12 m6 l6").removeClass('fixed-action-btn');
            }

            if (botoes.children.length > 0) {
                var listaBotoes = botoes.getElementsByTagName('li');
                $('#' + botoes.id).removeClass("fixed-action-btn click-to-toggle").addClass("ButtonTable col s12 m6 l6");

                if (listaBotoes.length > 0) {
                    for (var index = 0; index < listaBotoes.length; index++) {
                        var link = listaBotoes[index].children[0];

                        if (link.classList.contains("btn-floating")) {
                            $('#' + link.id).removeAttr("style");
                            $('#' + link.id).removeClass("btn-floating waves-effect waves-light").addClass("btn btn-table");
                            $(".mobile-fab-tip").remove();
                        }
                    }
                }
            }
        }
    }
}

function tamanhoMaximo() {
    var arq = $('input:file')[0].files[0];

    if (arq.size > 2097152) {
        $('input:file').replaceWith($('input:file').val('').clone(true));
        buldModalAlert("AlertaInserArquivo151", "ALERTA", "Não foi possível carregar o arquivo.<br>* Tamanho máximo permitido é de 2MB.", "background-color: #fbc02d !important", "", "true", "");
        return false;
    }
    __doPostBack();
}

function verificaFiltroEstatisticas() {
    $("#cphConteudo_txbDataInicial").show().attr("readonly", "readonly");
    $("#cphConteudo_txbDataFinal").show().attr("readonly", "readonly");

}

function NotifyAllListeners(Enable, listeners_ids) {
    var listeners_ids_collection = listeners_ids.split(';');
    for (var i = 0; i < listeners_ids_collection.length; i++) {
        if (Enable) {
            if (listeners_ids_collection[i] != null && listeners_ids_collection[i] != "") {
                if ($("." + listeners_ids_collection[i]).length > 0) {
                    $("." + listeners_ids_collection[i]).removeClass("disabled");
                    $("." + listeners_ids_collection[i]).removeAttr("disabled");
                    $("." + listeners_ids_collection[i]).prop("disabled", false);
                    $("." + listeners_ids_collection[i]).removeClass('aspNetDisabled');
                }
                if ($("#" + listeners_ids_collection[i]).length > 0) {
                    $("#" + listeners_ids_collection[i]).removeClass("disabled");
                    $("#" + listeners_ids_collection[i]).prop("disabled", false);
                    $("#" + listeners_ids_collection[i]).removeClass('aspNetDisabled');
                }
            }

        } else {
            if (listeners_ids_collection[i] != null && listeners_ids_collection[i] != "") {
                if ($("." + listeners_ids_collection[i]).length > 0) {
                    $("." + listeners_ids_collection[i]).addClass("disabled");
                    $("." + listeners_ids_collection[i]).attr("disabled");
                    $("." + listeners_ids_collection[i]).prop("disabled", true);
                    $("." + listeners_ids_collection[i]).addClass('aspNetDisabled');
                }
                if ($("#" + listeners_ids_collection[i]).length > 0) {
                    $("#" + listeners_ids_collection[i]).addClass("disabled");
                    $("#" + listeners_ids_collection[i]).prop("disabled", true);
                    $("#" + listeners_ids_collection[i]).addClass('aspNetDisabled');
                }
            }
        }
    }
}

function VerifyContentsPage(StringJSON, IndexPage) {

    var PagesContainers = JSON.parse(StringJSON);

    for (var i = 0; i < PagesContainers.length; i++) {
        if (PagesContainers[i].Page == IndexPage) {
            return true;
        }
    }

    return false;
}

Array.prototype.contains = function (obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}

Array.prototype.remByVal = function (val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) {
            this.splice(i, 1);
            i--;
        }
    }
    return this;
}

String.prototype.contains = function (it) {
    return this.indexOf(it) != -1;
};

$(".verificaSenhas").keyup(function () {
    verificaSenhas("senha", "confirmaSenha");
});

var url = window.location;
if ((url.pathname.search("ManutUsuarioEdicao.aspx") != -1) && ($("#forcaSenha").html() != null))
    verificaForcaSenha($(".verificaForcaSenha"));

$(".verificaSenhas").blur(function () {
    verificaSenhas("senha", "confirmaSenha");
});

// verifica se as senhas são iguais
function verificaSenhas(campo1, campo2) {
    var senha1 = $("." + campo1);
    var senha2 = $("." + campo2);

    if (senha1.val() == senha2.val()) {
        //senha2.css("border-color", "").css("background-color", "");
        senha2.removeClass("invalid");
        senha2.addClass("valid");
    } else {
        //senha2.css("border-color", "#FF0000").css("background-color", "#FF5555");
        senha2.removeClass("valid");
        senha2.addClass("invalid");
    }
}

/** USUARIO EDIÇÃO **/
// Força da senha para o fomulário de usuário
$(".verificaForcaSenha").keyup(function () {
    verificaForcaSenha($(this));
});

function getParametrosIntegracaoOpme() {
    return {
        'isIntegracaoOpme': $('#cphConteudo_cmbIntegracaoOcorrencia'),
        'setorOrigemOcorrencia': $('#cphConteudo_cmbSetorOrigem'),
        'naturezaOcorrencia': $('#cphConteudo_cmbNaturezaOcorrencia'),
        'codInicioPrest': $('#cphConteudo_txtCodPrestIntervaloInicio'),
        'codFimPrest': $('#cphConteudo_txtCodPrestIntervaloFim'),
        'tabelaPagmntServicos': $('#cphConteudo_cmbTabelaPagmtServicos'),
        'tipoContratoPrestador': $('#cphConteudo_cmbTipoContratoPrestador'),
        'grupoFornecedor': $('#cphConteudo_cmbGrupoDoFornecedor')
    }
}

function validaCamposObrigatoriosIntegracaoOpme() {
    let paramsIntegracaoOpme = getParametrosIntegracaoOpme();
    let msg = 'Os campos a seguir precisam ser preenchidos: \n';
    let camposInvalidos = [];

    if (paramsIntegracaoOpme.isIntegracaoOpme.val() != 'S') return true;

    for (let chave in paramsIntegracaoOpme) {
        if (!paramsIntegracaoOpme[chave].val() || paramsIntegracaoOpme[chave].val() == undefined) {
            camposInvalidos.push(chave);
            msg += paramsIntegracaoOpme[chave].attr('title') + ', ';
        }
    }

    msg = msg.trim();

    if (camposInvalidos.length > 0) {
        buldModalAlert('todos', 'ALERTA', msg.slice(0, msg.length -1), modalStyleAlert);

        return false;
    }

    return true;
}

function validaIntervaloCodPrestadores() {
    let paramsIntegracaoOpme = getParametrosIntegracaoOpme();
    let msg = 'O primeiro valor do intervalo de códigos de prestadores deve ser menor que o segundo valor.';

    if (paramsIntegracaoOpme.isIntegracaoOpme.val() != 'S')
        return true;

    if (paramsIntegracaoOpme.codInicioPrest && paramsIntegracaoOpme.codFimPrest && paramsIntegracaoOpme.codInicioPrest.val() >= paramsIntegracaoOpme.codFimPrest.val()) {
        buldModalAlert('todos', 'ALERTA', msg, modalStyleAlert);
        return false;
    }

    return true;
}

/** VALIDAÇÃO DOS CAMPOS OBRIGATÓRIOS DO FORMULÁRIO **/
function validarFormulario(campoPai) {
    var erro = 0;
    $(campoPai + ' .validar').each(function (index) {
        //Verifica se o campo é referente ao autocomplete para capturar o valor do campo que está no table do autocomplete.
        if ($(this).attr("class").contains('autocompletecbx')) {
            if ($(this).is(":visible") && $(this).children()[1].value.trim() == '') {
                buldModalAlert('todos', 'ALERTA', " Preencha o campo: " + $(this).attr("title").bold(), modalStyleAlert);
                erro += 1;
                return false;
            }
        } else if ($(this).is(":visible") && $(this).val().trim() == '') {
            if (!this.classList.contains('select-wrapper')) {
                buldModalAlert('todos', 'ALERTA', " Preencha o campo: " + $(this).attr("title").bold(), modalStyleAlert);

                var fococo = document.getElementById($(this).attr("ID"));
                fococo.focus();             

                erro += 1;
                return false;                
            }
        } else if ($(this).attr("title").contains("E-mail")) {
            var expressao = /([\w-\.]+)@((?:[\w-]+\.)+)([a-zA-Z]{2,4})/;
            if (!expressao.test($(this).val())) {
                buldModalAlert('email', 'ALERTA', " E-mail inválido! ", modalStyleAlert);
                erro += 1;
                return false;
            }
        } else if ($(this).attr("title").contains("URL") && $(this).attr("readonly") != "readonly") {
            var expressao = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
            if (!expressao.test($(this).val())) {
                buldModalAlert('URL', 'ALERTA', " URL inválida! ", modalStyleAlert);
                erro += 1;
                return false;
            }
        } else if (this.nodeName == "SELECT") {
            if (this.options.selectedIndex == 0) {
                buldModalAlert('todos', 'ALERTA', " Preencha o campo: " + $(this).attr("title").bold(), modalStyleAlert);
                erro += 1;
                return false;
            }
        } else if ($(this).attr("title").contains("CEP")) {
            var expressao = /^[0-9]{2}.[0-9]{3}-[0-9]{3}$/;
            if (!expressao.test($(this).val())) {
                buldModalAlert('CEP', 'ALERTA', " Preencha o campo: " + $(this).attr("title").bold(), modalStyleAlert);
                erro += 1;
                return false;
            }
        } else if ($(this).attr("title").contains("Número do CPF")) {
            var expressao = /^\d.\d.\d-\d$/i;
            if (!expressao.test($(this).val())) {
                buldModalAlert('CPF', 'ALERTA', " Preencha o campo: " + $(this).attr("title").bold(), modalStyleAlert);
                erro += 1;
                return false;
            }
        } else if ($(this).attr("title").contains("nascimento")) {
            var expressao = /^\d.\d.\d-\d$/i;
            if (!expressao.test($(this).val())) {
                buldModalAlert('Data de Nascimento', 'ALERTA', " Preencha o campo: " + $(this).attr("title").bold(), modalStyleAlert);
                erro += 1;
                return false;
            }
        }
    });

    if (erro > 0) {
        return false;
    }


    var checked = 0;
    $(campoPai + ' .validarCheckBoxList input[type=checkbox]').each(function (index) {
        if ($(this).attr("checked") == "checked") {
            checked = 1;
            return true;
        }
    });

    if ($(campoPai + " .validarCheckBoxList").html() != null && checked == 0) {
        buldModalAlert('chklst', 'ALERTA', " Necessário marcar pelo menos um item em " + $(campoPai + " .validarCheckBoxList").attr("title") + " ou outro de sua escolha.", modalStyleAlert);

        return false;
    }

    /** CASO ESPECIFICO PARA EDIÇÃO DE USUÁRIOS **/
    //$(campoPai + " .radioGrupoPerfil input[type=radio]").each(function (index) {
    //    if ($(this).val() == "P" && $(this).attr("checked")) {
    //        checked = 0;
    //        $(campoPai + ' .validarCheckBoxListGrupoPerfil input[type=checkbox]').each(function (index) {
    //            if ($(this).attr("checked") == "checked") {
    //                //alert($(this).html());
    //                checked = 1;
    //                return true;
    //            }
    //        });
    //    } else if ($(this).val() == "G" && $(this).attr("checked")) {
    //        checked = 1;
    //    }
    //});

    //if ($(campoPai + " .validarCheckBoxListGrupoPerfil").html() != null && checked == 0) {
    //    buldModalAlert('chkGP', 'ALERTA', " O " + $(campoPai + " .validarCheckBoxListGrupoPerfil").attr("title") + " é obrigatório. Marque um item.", modalStyleAlert);
    //    return false;
    //}
    /** FIM CASO ESPECIFICO PARA EDIÇÃO DE USUÁRIOS **/
    return true;
}

//// Verifica a força da senha
function verificaForcaSenha(campo) {
    var forcaSenha = $('#forcaSenha');
    var forcaSenhaBox = $('#forcaSenha > #forcaSenhaBox');
    var forcaSenhaTexto = $('#forcaSenha > #forcaSenhaTexto');
    var valor = campo.val();
    var contemNumeros = /[0-9]/;
    var contemLetras = /[a-z]/i;
    var contemEspecial = /[@#$%&*]/;
    var contagem = 0;

    if (valor != '' && valor.length > 7) {
        if (contemNumeros.test(valor))
            contagem++;
        if (contemLetras.test(valor))
            contagem++;
        if (contemEspecial.test(valor))
            contagem++;

        //alert(contagem);
        switch (contagem) {
            case 1:
                //div.style.background = "#CCCCCC";
                //div.innerHTML = "Senha Fraca!";
                forcaSenhaBox.css("background-color", "#FF0000").width(40);
                forcaSenhaTexto.html("Senha Fraca!");
                break;
            case 2:
                //div.style.background = "#009900";
                //div.innerHTML = "Senha Relevante!";
                forcaSenhaBox.css("background-color", "#FF9900").width(80);
                forcaSenhaTexto.html("Senha Relevante!");
                break;
            case 3:
                //div.style.background = "#FF0000";
                //div.innerHTML = "Senha Forte!";
                forcaSenhaBox.css("background-color", "#009900").width(120);
                forcaSenhaTexto.html("Senha Forte!");
                break;
            default:
                //div.style.background = "#FFFFFF";
                //div.innerHTML = "Ops! O que Aconteceu?";
                forcaSenhaBox.css("background-color", "#FFFFFF").width(1);
                forcaSenhaTexto.html("Digite sua senha!");
                break;
        }
    } else {
        forcaSenhaBox.css("background-color", "#FFFFFF").width(1);
        forcaSenhaTexto.html("Digite sua senha!");
    }
}

function verificaTotalCheckboxesMarcados(papel) {
    var totalCheckboxes = $('[class^=checkFilho_' + papel + ']').find("[type='checkbox']").length;
    var totalCheckboxesMarcados = $('[class^=checkFilho_' + papel + ']').find("[type='checkbox']:checked").length;

    if (totalCheckboxes == totalCheckboxesMarcados) {
        $(".checkPai_" + papel).find("[type='checkbox']").attr("checked", true);
    } else {
        $(".checkPai_" + papel).find("[type='checkbox']").attr("checked", false);
    }
}

function CarregaFeeds() {
    $.get("Default.aspx?feed=1", function (dados) {
        try {
            if (dados != "") {
                json = eval(dados).Itens;
                $("#feed_preloader").hide();
                $('#divFeed li').remove();
                for (var i = 0; i < json.length; i++) {
                    $('#divFeed').append(
                        $('<li class="collection-item">').append(
                            $('<label>').html(json[i].PubDate)
                        ).append(
                            $('<a>').attr("target", "_blank").attr("href", json[i].Link).append(
                                $('<h6>').html(json[i].Title)
                            )
                        )
                   );
                }
            }
        } catch (e) {
            buldModalAlert('AlertaFeed', 'ALERTA', 'Não foi possível preencher o informativo.', modalStyleAlert);
        }
    });
}

//carrossel
$('.carousel').carousel({
    indicators: true,
    fullWidth: true,
    duration: 250
}
);

setInterval(function () {
    $('.carousel').carousel('next');
}, 18000); // 16seg para ir ao próx

function verificaFiltroLog() {
    if ($("#cphConteudo_cmbPesquisarPor").val() == 'D') {
        $(".logUsuario").hide();
        $("#cphConteudo_txbLogUsuario").hide();
        $(".logData").show();
        //$("#cphConteudo_txbLogDataInicial").show().attr("readonly", "readonly");
        //$("#cphConteudo_txbLogDataFinal").show().attr("readonly", "readonly");
        $(".ui-datepicker-trigger").show();
    } else {
        $("#cphConteudo_txbLogDataInicial").hide();
        $("#cphConteudo_txbLogDataFinal").hide();
        $(".logData").hide();
        $(".ui-datepicker-trigger").hide();
        $(".logUsuario").show();
        $("#cphConteudo_txbLogUsuario").show();
    }
}

function SendToHiddenValue(bindable_attribute, value, hidden_id, valueIsJSON, sender) {

    var bindable_object = document.getElementById(hidden_id);

    if (bindable_object == null) {
        bindable_object = $(sender).closest('.modal').find(".Hidden_ModalForm")[0];
    }

    var bindable_object_JSON = JSON.parse(bindable_object.value ? bindable_object.value : '{}');

    if (valueIsJSON) {
        bindable_object_JSON[bindable_attribute] = JSON.parse(value);
    } else {
        bindable_object_JSON[bindable_attribute] = JSON.stringify(value);
    }

    bindable_object.value = JSON.stringify(bindable_object_JSON);

    return false;
}

// WEBMETHODS - INICIO

function CallWebMethod(url_method, data) {



    var teste = JSON.parse("{}");

    teste["Mensagem"] = "aSDKASODKSD";
    teste["TipoMensagem"] = "AsdofkASKDASKDAOSDK";

    $.ajax({
        url: url_method,
        data: JSON.stringify(teste),
        type: "POST",
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (retorno) {
            alert(retorno.d);
        },
        error: function (req, status, error) {
            alert(error);
        }
    });
}

// WEBMETHODS - FIM

/** AGENDAMENTO **/
function carregaAgenda() {
    var date = new Date();
    var d = date.getDate();
    var m = date.getMonth();
    var y = date.getFullYear();
    var ID = 1;
    var diaClicado;

    $('#calendar').fullCalendar({
        header: {
            left: '',
            center: 'title',
            right: ''//'month,agendaWeek,agendaDay'
        },
        //eventLimit: true,
        dayClick: function (date, allDay, jsEvent, view) {
            diaClicado = date;
        },
        allDaySlot: false,
        timeFormat: 'H:mm',
        slotLabelFormat: 'HH:mm',
        views: {
            month: {
                titleFormat: 'MMMM YYYY'
            },
            week: {
                titleFormat: 'MMM D YYYY'
            },
            day: {
                titleFormat: 'D MMMM YYYY',
            }
        },
        //defaultView: $(window).width() < 765 ? 'basicDay' : 'month',
        columnFormat: 'dddd',
        dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
        dayNames: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'], //['Domingo', 'Segunda', 'Terça', 'Quarta', 'Quinta', 'Sexta', 'Sábado'],
        monthNames: ['Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'],
        aspectRatio: 1.8,
        eventClick: function (event, element) {
            var viewName = $('#calendar').fullCalendar('getView').name;

            if (viewName != 'agendaDay') {
                var dataClicada = moment(event.start).format("DD/MM/YYYY");
                var prestador = $("#cphConteudo_cmbPrestador").val();
                var especialidade = $("#cphConteudo_cmbEspecialidade").val();

                if (event.title.indexOf('Agendado') != -1) {
                    $('#calendar').fullCalendar('changeView', 'agendaDay');
                    $('#calendar').fullCalendar('gotoDate', event.start);
                    carregarEventosDia(dataClicada);
                } else {
                    $(location).attr('href', 'Edicao.aspx?data=' + dataClicada + '&esp=' + especialidade + '&prest=' + prestador);
                }
            }
        },
    });

    $('#calendar').fullCalendar('gotoDate', new Date($("#cphConteudo_cmbAgendaAno").val(), ($("#cphConteudo_cmbAgendaMes").val() - 1), 1));

}

// Pesquisa os dias disponiveis para consulta conforme filtro.
function carregarEventos() {

    var mes = $("#cphConteudo_cmbAgendaMes").val();
    var ano = $("#cphConteudo_cmbAgendaAno").val();
    var prestador = $("#cphConteudo_cmbPrestador").val();

    if (prestador != "" && prestador != null) {
        $.ajaxSetup({ cache: false });
        $("#updLoading2").show();


        $.get("Consulta.aspx?get=eventos&prestador=" + prestador + "&mes=" + mes + '&ano=' + ano, function (dados) {

            if (dados != null && dados.toString() != '') {
                var json = eval(dados);

                // Remove todos os eventos para que não seja duplicado.
                $('#calendar').fullCalendar('destroy');
                carregaAgenda();

                // Alterando o mês visualizado conforme filtro
                //$('#calendar').fullCalendar('gotoDate', Date(ano, (mes - 1), 1));

                if (json.length > 0) {
                    if (json[0].contexto == 'semHorarios') {
                        buildGenericModal("#InfModal");
                        //visualizarAlerta(2, '#', 'O prestador não possui horários disponíveis.');
                        return;
                    } else {
                        if (json[0].contexto != "B") {
                            for (var i = 0; i < json.length; i++) {
                                var item = json[i].dataAgend.split("/");
                                //alert(json[i].dataDisponivel);
                                if (json[i].disponivel - json[i].agendado > 0) {
                                    $('#calendar').fullCalendar('renderEvent', {
                                        id: item[2],
                                        title: 'Disponível - ' + (json[i].disponivel - json[i].agendado),
                                        start: new Date(item[0], item[1], item[2]),
                                        allDay: true,
                                        color: '#368225'
                                    });
                                }

                                if (json[i].agendado > 0) {
                                    $('#calendar').fullCalendar('renderEvent', {
                                        id: item[2],
                                        title: 'Agendado - ' + json[i].agendado,
                                        start: new Date(item[0], item[1], item[2]),
                                        allDay: true,
                                        color: '#F74A03'
                                    });
                                }
                            }

                        } else {
                            for (var i = 0; i < json.length; i++) {
                                var item = json[i].dataAgend.split("/");

                                if (json[i].agendado > 0) {
                                    $('#calendar').fullCalendar('renderEvent', {
                                        id: item[2],
                                        title: 'Agendado',
                                        start: new Date(item[0], item[1], item[2]),
                                        allDay: true,
                                        color: '#F74A03'
                                    });
                                } else if (json[i].disponivel > 0) {
                                    $('#calendar').fullCalendar('renderEvent', {
                                        id: item[2],
                                        title: 'Disponível',
                                        start: new Date(item[0], item[1], item[2]),
                                        allDay: true,
                                        color: '#368225'
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }).done(function () {
            $("#updLoading2").hide();
        }).fail(function () {
            $("#updLoading2").hide();
        });
    }
}

// Pesquisa as consultas agendadas para o dia selecionado
function carregarEventosDia(data) {
    var prestador = $("#cphConteudo_cmbPrestador").val();

    if (prestador != "" && prestador != null) {
        $("#updLoading2").show();
        $.get("Consulta.aspx?get=eventosDia&prestador=" + prestador + "&data=" + data, function (dados) {
            if ((dados != "false")) {

                var json = eval(dados);

                // Remove todos os eventos para que não seja duplicado.
                $('#calendar').fullCalendar('removeEvents');

                for (var i = 0; i < json.length; i++) {
                    if (json[i].status != 'Cancelado') {
                        $('#calendar').fullCalendar('renderEvent', {
                            id: json[i].codBeneficiario,
                            title: json[i].codBeneficiario + ' - ' + json[i].nomeBeneficiario,
                            start: json[i].dataAgend,
                            color: '#368225'
                        });
                    }
                }

            }
        }).done(function () {
            $("#updLoading2").hide();
            var offset = $(".fc-time-grid-event").offset();
            $('.fc-agendaDay-view div.fc-time-grid-container').animate({
                scrollTop: (offset.top - 100)
            }, 500);
        }).fail(function () {
            $("#updLoading2").hide();
        });
    }
}
/** FIM - AGENDAMENTO **/

function Enable(ID) {
    if ($("." + ID)) {
        $("." + ID).removeClass("disabled");
    }
    if ($("#" + ID)) {
        $("#" + ID).removeClass("disabled");
    }
}

function Disable(ID) {
    if ($("." + ID)) {
        $("." + ID).addClass("disabled");
    }

    if ($("#" + ID)) {
        $("#" + ID).addClass("disabled");
    }
}

function getPapel(element) {
    var substrStart = $(element).attr('class').indexOf('_') + 1;
    return $(element).attr('class').substring(substrStart, $(element).attr('class').indexOf(' ', substrStart) == -1 ? $(element).attr('class').length : $(element).attr('class').indexOf(' '));
}

function VerificaCheck(element) {
    var papel = getPapel($(element));

    var totalCheckboxes = $("#" + $(element).closest('table')[0].attributes['Id'].value).find($('[class^=checkChildren_' + getPapel($(element)) + ']').find("[type='checkbox']")).length;
    var totalCheckboxesMarcados = $("#" + $(element).closest('table')[0].attributes['Id'].value).find($('[class^=checkChildren_' + getPapel($(element)) + ']').find("[type='checkbox']:checked")).length;

    if (totalCheckboxes == totalCheckboxesMarcados) {
        $("#" + $(element).closest('table')[0].attributes['Id'].value).find($(".checkMaster_" + papel).find("[type='checkbox']"))[0].checked = true;
        //  $(".checkMaster_" + papel).find("[type='checkbox']")[0].checked = true;
    } else {
        $("#" + $(element).closest('table')[0].attributes['Id'].value).find($(".checkMaster_" + papel).find("[type='checkbox']"))[0].checked = false;
        // $(".checkMaster_" + papel).find("[type='checkbox']")[0].checked = false;
    }
}

$(document).ready(function () {
    var __defaultPostBack = __doPostBack;
    __doPostBack = function (sender, args) {

        $("#updLoading2").show();

        __defaultPostBack(sender, args);
    }

    obtemTamanho();
    ajusteMenu(h, w, y);
});


function teste() {
    obtemTamanho();
    ajusteMenu(h, w, y);
}

function visualizarSelecaoPapel() {
    $("#selecaoPapel").dialog({
        resizable: false,
        width: 360,
        modal: true,
        show: "explode",
        hide: "explode"
    });
    $("#selecaoPapel").width(350);
    return false;
};

function imprimirConteudo(idSeletor) {
    telaImpressao = window.open();

    telaImpressao.document.write(document.getElementById(idSeletor).innerHTML.replace(/<a.*href="(.*?)">.*<\/a>/g, ''));
    telaImpressao.window.print();
    telaImpressao.window.close();
}

// Verifica o codigo selecionado no Combobox de Papel e Altera o Label Contexto de acordo com a escolha
function verificaPapelUsuario(papel) {
    var codigo = papel.val();

    $(".txbValorDeContexto").val("");
    $(".valorDeContexto").hide();
    $(".cmbUtilizaBiometria").val("");
    $(".utilizaBiometria").hide();

    switch (codigo) {
        case "1":
            $(".lblValorDeContexto").text("Cód. Prestador");
            $(".valorDeContexto").show();
            $(".utilizaBiometria").show();
            break;
        case "2":
            $(".lblValorDeContexto").text("Cód. Beneficiário");
            $(".valorDeContexto").show();
            break;
        case "3":
            $(".lblValorDeContexto").text("Cód. Contrato");
            $(".valorDeContexto").show();
            break;
        case "4":
        case "5":
            $(".valorDeContexto").hide();
            break;
    }
}

function cmbAIStatus_TextChanged(sender) {
    //if (component.Text == "N") {
    //    .Visible = true;
    //    .Visible = true;
    //    .Text = String.Empty;
    //    .Visible = true;
    //    .Visible = true;
    //    .Text = String.Empty;
    //    .Enabled = false;
    //    .Text = "0";
    //    .Enabled = false;
    //    .Text = "0";
    //} else {
    //    .Visible = false;
    //    .Visible = false;
    //    .Visible = false;
    //    .Visible = false;
    //    .Enabled = true;
    //    .Enabled = true;
    //}

    if (sender.value === "N") {
        $("#lblMotivoNegativa").show();
        $("#txbMotivoNegativa").show();
        $("#txbMotivoNegativa").val('');
        $("#lblJustificativaNegativa").show();
        $("#txbJustificativaNegativa").show();
        $("#txbJustificativaNegativa").val('');
        $("#txbAIQtdeAutorizada").attr('disabled', 'disabled');
        $("#txbAIQtdeAutorizada").val('');
        $("#txbAIValorAutorizado").attr('disabled', 'disabled');
        $("#txbAIValorAutorizado").val('');
    } else if (sender === "A") {
        var valor = $("#cphConteudo_txbAIQtdeSolicitada").val();
        $("#txbAIQtdeAutorizada").val(valor);
    } else {
        cmbAIStatus_TextChanged_Hide(sender.value);
    }
}

function cmbAIStatus_TextChanged_Hide(sender) {
    $("#txbMotivoNegativa").hide();
    $("#lblMotivoNegativa").hide();
    $("#lblJustificativaNegativa").hide();
    $("#txbJustificativaNegativa").hide();
    $("#txbAIQtdeAutorizada").removeAttr('disabled');
    $("#txbAIValorAutorizado").removeAttr('disabled');
    $("#txbAIValorAutorizado").val(sender);
}

//** INICIO - FUNÇÕES MODAL / ALERT **/

//Instanciação de uma modal já exitente na Page
function buildGenericModal(id, cut, complete) {
    var newId = id;
    if (cut == 'true') {
        $('div' + id + "-cut-out").remove();
        var iDiv = document.createElement('div');
        iDiv.id = id.replace('#', '') + "-cut-out";
        iDiv.className = 'modal modal-fixed-footer';

        iDiv.innerHTML = $(id).html();
        $(id).hide;
        newId = "#" + iDiv.id;
        document.getElementsByTagName('form')[0].appendChild(iDiv);
        $(id).remove();
    }

    if (complete) {
        $(newId).modal({ complete: complete });
    } else {
        $(newId).modal();
    }
    $(newId).modal('open');
}

//Instanciação de uma modal já exitente na Page
function buildGenericModalDismissible(id) {
    $(id).modal({ dismissible: false });
    $(id).modal('open');
}

//Fecha uma modal já exitente na Page
function closeGenericModal(id) {
    modalOverlayClose();
    $(id).modal('close');
}

//Criação e instanciação de uma modal dinamicamente
//function buldModalAlert(id, title, message, style) {
//    $('div#' + id).remove();
//    var iDiv = document.createElement('div');
//    iDiv.id = id;
//    iDiv.className = 'modal modal-small';

//    iDiv.innerHTML = '<div id="title" class="modal-title" style="' + style + '">' +
//                     '<i class="modal-close material-icons right">close</i>' +
//                      title +
//                     '</div>' +
//                     '<div class="modal-content" id="modalContentAlert">' +
//                     '<p>' + message + '</p>' +
//                     '</div>' +
//                     '<div class="modal-footer">' +
//                     '<section id="acoesFiltro">' +
//                     '<button type="button" ID="btnOkCloseModal' + id + '" Class="btn modal-close right green darken-3">OK</button>' +
//                     '</section>' +
//                     '</div>';

//    document.getElementsByTagName('body')[0].appendChild(iDiv);
//    $('#' + id).modal({ startingTop: '40%' });
//    $('#' + id).modal('open');
//}

//Show Modal - Modal Já existente (simples)
function ShowModal(idModal, _dismissible) {
    $("#" + idModal).modal({ dismissible: _dismissible });
    $("#" + idModal).modal('open');
}

//Criação e instanciação de uma modal dinamicamente com redirect
function buldModalAlert(id, title, message, style, redirectCommand, dismissible, clickCommand) {
    $('div#' + id).remove();
    var iDiv = document.createElement('div');
    iDiv.id = id;
    iDiv.className = 'modal modal-small';
    var ComandOrRedirect = "";

    if (redirectCommand || clickCommand)
        ComandOrRedirect = '<a href="' + ((redirectCommand) ? redirectCommand : "#!") + '" ' + ((clickCommand) ? "onclick=" + clickCommand : "#!") + ' Class="btn modal-close right green darken-3">Ok</a>';
    else
        ComandOrRedirect = '<a class="btn modal-close right green darken-3">Ok</a>';


    iDiv.innerHTML = '<div id="title" class="modal-title" style="' + style + '">' +
                     ((dismissible) ? '<i class="modal-close material-icons right">close</i>' : "") +
                      title +
                     '</div>' +
                     '<div class="modal-content" id="modalContentAlert">' +
                     '<p>' + message + '</p>' +
                     '</div>' +
                     '<div class="modal-footer">' +
                     '<section id="acoesFiltro">' +
                     ComandOrRedirect +
                     '</section>' +
                     '</div>';

    document.getElementsByTagName('body')[0].appendChild(iDiv);
    $('#' + id).modal({ startingTop: '40%', dismissible: dismissible });
    $('#' + id).modal('open');
    // SetFocus(controlIdFocus)
}


//Tela modal de confirmação com comando para botão confirmm
//control, control.GetType(), id, "buldModalConfirm('" + id + "','" + titleModal + "','" + msgModal + "','" + style + "','"  + Dismissible.ToString().ToLower() + ",'" + ConfirmComand.Replace("'", "\\'") + "');
function buildModalConfirm(id, title, message, style, dismissible, clicConfirmComand) {
    $('div#' + id).remove();
    var iDiv = document.createElement('div');
    iDiv.id = id;
    iDiv.className = 'modal modal-small';
    var ComandoConfirm = "";

    if (clicConfirmComand)
        ComandoConfirm = '<a href="#!" onclick="' + clicConfirmComand + '" Class="btn modal-close right green darken-3">Confirmar</a>';



    iDiv.innerHTML = '<div id="title" class="modal-title" style="' + style + '">' +
                     ((dismissible) ? '<i class="modal-close material-icons right">close</i>' : "") +
                      title +
                     '</div>' +
                     '<div class="modal-content" id="modalContentAlert">' +
                     '<p>' + message + '</p>' +
                     '</div>' +
                     '<div class="modal-footer">' +
                     '<section id="acoesFiltro">' +
                     ComandoConfirm +
                     '</section>' +
                     '</div>';

    document.getElementsByTagName('body')[0].appendChild(iDiv);
    $('#' + id).modal({ startingTop: '40%', dismissible: dismissible });
    $('#' + id).modal('open');
    // SetFocus(controlIdFocus)
}

function caixaPesquisaRapidaClose() {
    $('#caixaPesquisaRapida').modal('close');
}

function caixaIncluirItemClose() {
    $('#incluirItem').modal('close');
}

function modalOverlayClose() {
    $('.modal-overlay').hide();
    return false;
}

/** FIM - FUNÇÕES MODAL / ALERT **/

function EnableElement(id) {
    if ($("." + id).length > 0) {
        $("." + id).removeClass("disabled");
        //  $("." + id).removeAttr("disabled");
        $("." + id).prop("disabled", false);
        $("." + id).removeClass('aspNetDisabled');
    }

    if ($("#" + id).length > 0) {
        $("#" + id).removeClass("disabled");
        // $("#" + id).removeAttr("disabled");
        $("#" + id).prop("disabled", false);
        $("#" + id).removeClass('aspNetDisabled');

    }
}

function DisableElement(id) {
    if ($("." + id).length > 0) {
        $("." + id).addClass("disabled");
        $("." + id).prop('disabled', true)
        $("." + id).addClass('aspNetDisabled');
    }

    if ($("#" + id).length > 0) {
        $("#" + id).addClass("disabled");
        $("#" + id).prop('disabled', true)
        $("#" + id).addClass('aspNetDisabled');
    }
}

function geraBoleto(codVenda, via) {
    var codVenda = codVenda; //0
    var via = via; //1
    var flagDetalhaJurosMultas = $("#hdfDetalharJurosMultaBNB").val();

    $.download("../Comum/Boleto_Print.aspx", "codVenda=" + codVenda + "&via=" + via + "&extrato=S&detalhaMultas=" + flagDetalhaJurosMultas, "GET");

    return false;
}


/** INICIO - FUNÇÕES QUE UTILIZAM O PICKADATE **/
function configuraDatepickerPeriodoVariado(offDiasInicial, offsetDiasFinal) {
    $('.dataInicialPeriodoVariado').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 6,
        autoClose: vCloseOnSelect,
        minDate: offDiasInicial,
        maxDate: offsetDiasFinal,
        onClose: function () {
            $(document.activeElement).blur();
        },
        onSelect: function (thingSet) {
            //console.log('Set stuff:', thingSet);

        }
    });

    $('.dataFinalPeriodoVariado').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 6,
        autoClose: vCloseOnSelect,
        minDate: offDiasInicial,
        maxDate: offsetDiasFinal,
        onClose: function () {
            $(document.activeElement).blur();
        },
        onSelect: function (thingSet) {
            //console.log('Set stuff:', thingSet); 
        }
    });
}

function ConfiguraLimiteRetroativoSolicitacao(diasRetroativos) {
    $('.dataInicialSolicitacao').datepicker({
        container: vContainer,
        showDaysInNextAndPreviousMonths: vDiasAntesDepoisDoMesAtual,
        i18n: datepicker_pt_br,
        format: vFormat, // Formato da data que aparece no input         
        yearRange: 6,
        autoClose: vCloseOnSelect,
        minDate: subDaysToDatePick(diasRetroativos),
        maxDate: new Date(),
        onClose: function () {
            $(document.activeElement).blur();
        },
        onSelect: function (thingSet) {
            //console.log('Set stuff:', thingSet); 
        }
    });

    $('.dataInicialSolicitacao').attr('diasRetroativos', diasRetroativos);
}

function subDaysToDatePick(daysToSub) {
    var minorDate;
    try {
        minorDate = new Date();
        if (isNaN(daysToSub)) {
            minorDate.setDate(minorDate.getDate() - 120);
            return minorDate
        }
        minorDate.setDate(minorDate.getDate() - daysToSub);
    } catch (e) {
        minorDate = new Date();
        minorDate.setDate(minorDate.getDate() - 120);
    }
    return minorDate;
}

function addDaysToDatePick(daysToAdd) {
    var majorDate;
    try {
        majorDate = new Date();
        if (daysToAdd.isNaN()) {
            majorDate.setDate(majorDate.getDate() + 120);
            return majorDate
        }
        majorDate.setDate(majorDate.getDate() + daysToAdd);
    } catch (e) {
        majorDate = new Date();
        majorDate.setDate(majorDate.getDate() + 120);
    }
    return majorDate;
}
/** FIM - FUNÇÕES QUE UTILIZAM O PICKDATE **/

/* BIOMETRIA FACIAL */
function inicializarVariaveis() {
    mycanvas = document.getElementById('mycanvas');
    context = mycanvas.getContext('2d');
    video = document.getElementById('video');
}

function obterTokenAcessoBiometriaFacial() {
    var token = $('#hdfTokenAcessoBiometriaFacial').val();
    /*
    if (token == '') {
        var usuario = 'infomed';
        var senha = 'infomed123';

        $.ajax({
            //url: 'https://localhost:5001/api/Usuario/login?usuario=' + usuario + '&senha=' + senha,
            url: 'http://infomedbiometriafacia.us-east-1.elasticbeanstalk.com/api/Usuario/login?usuario=' + usuario + '&senha=' + senha,
            type: 'POST',
            success: function (data) {
                console.log(data);
                if (data) {
                    var obj = JSON.parse(JSON.stringify(data));
                    token = obj.bearerToken;
                    $('#hdfTokenAcessoBiometriaFacial').val(token);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(arguments);
                //alert(" Can't do because: " + textStatus + " | " + errorThrown);
                if (XMLHttpRequest.status == 404)
                    alert(XMLHttpRequest.responseText);
            }
        });
    }
    */

    return token;
}

/* Funções para Biometria Facial*/
function iniciarWebcam() {
    inicializarVariaveis();
    context.clearRect(0, 0, 500, 380);
    $('#video').show();
    //drawShape(context, 0, 0);

    // Get access to the camera!
    if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
        // Not adding `{ audio: true }` since we only want video now
        navigator.mediaDevices.getUserMedia({ video: true }).then(function (stream) {
            //video.src = window.URL.createObjectURL(stream);
            video.srcObject = stream;
            video.play();
            mediaStream = stream;
            mediaStream.stop = function () {
                this.getAudioTracks().forEach(function (track) {
                    track.stop();
                });
                this.getVideoTracks().forEach(function (track) { //in case... :)
                    track.stop();
                });
            };

            obterTokenAcessoBiometriaFacial();
        });
    } else {

    }
    /* Legacy code below: getUserMedia 
    else if(navigator.getUserMedia) { // Standard
        navigator.getUserMedia({ video: true }, function(stream) {
            video.src = stream;
            video.play();
        }, errBack);
    } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
        navigator.webkitGetUserMedia({ video: true }, function(stream){
            video.src = window.webkitURL.createObjectURL(stream);
            video.play();
        }, errBack);
    } else if(navigator.mozGetUserMedia) { // Mozilla-prefixed
        navigator.mozGetUserMedia({ video: true }, function(stream){
            video.srcObject = stream;
            video.play();
        }, errBack);
    }*/
}

function registrarBiometriaFacial() {
    var token = obterTokenAcessoBiometriaFacial();

    context.drawImage(video, 0, 0, 500, 380);
    mediaStream.stop();
    $('#video').hide();

    var formData = new FormData();
    formData.append('IdColecao', $('#idColecao').val());
    formData.append('AplicaçãoRequisitou', $('#aplicacaoRequisitou').val());
    formData.append('UsuárioRequisitou', $('#usuarioRequisitou').val());
    formData.append('IdentificadorFace', $('#identificadorFace').val());
    formData.append('ImagemFace', dataURItoBlob(mycanvas.toDataURL()), "f" + nomeArquivo() + ".jpg");

    var dadosBiometria = {
        "IdColecao": $('#idColecao').val(),
        "AplicaçãoRequisitou": $('#aplicacaoRequisitou').val(),
        "UsuárioRequisitou": $('#usuarioRequisitou').val(),
        "IdentificadorFace": $('#identificadorFace').val(),
        "Token": token
    }
    console.log(JSON.stringify(dadosBiometria));

    $.ajax({
        //url: 'https://localhost:5001/api/ReconhecimentoFacil/Registrar',
        url: $('#urlBaseBF').val() + '/api/ReconhecimentoFacil/Registrar',
        type: 'POST',
        //dataType: 'json',
        //contentType: "multipart/form-data; boundary=----WebKitFormBoundaryQvxJtPVD9VwfnP0R",
        data: formData,//JSON.stringify(dadosBiometria),
        contentType: false,
        cache: false,
        processData: false,
        success: function (data) {
            var obj = JSON.parse(JSON.stringify(data));
            console.log(data);
            buldModalAlert('RespostaRegistroBiometriaFacial', 'ALERTA', obj.message, modalStyleAlert);
            $('.situacaoBiometriaFacial').val(obj.message);
            $('#hdfIdentificadorBeneficiarioFacial').val(obj.hash);

            if (obj.hash != '')
                registrahashBiometriaFacial();

            return true;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(arguments);
            //alert(" Can't do because: " + textStatus + " | " + errorThrown);
            return false;
        },
        beforeSend: function (xhr, settings) {
            xhr.setRequestHeader('Authorization', token);
        }

    });

    return false;
}

function validarBiometriaFacial() {
    var token = obterTokenAcessoBiometriaFacial();

    context.drawImage(video, 0, 0, 500, 380);
    mediaStream.stop();
    $('#video').hide();

    var formData = new FormData();
    formData.append('IdColecao', $('#idColecao').val());
    formData.append('AplicaçãoRequisitou', $('#aplicacaoRequisitou').val());
    formData.append('UsuárioRequisitou', $('#usuarioRequisitou').val());
    formData.append('IdentificadorFace', $('#identificadorFace').val());
    formData.append('ImagemFace', dataURItoBlob(mycanvas.toDataURL()), "f" + nomeArquivo() + ".jpg");
    formData.append('Token', $('#token').val());

    var dadosBiometria = {
        "IdColecao": $('#idColecao').val(),
        "AplicaçãoRequisitou": $('#aplicacaoRequisitou').val(),
        "UsuárioRequisitou": $('#usuarioRequisitou').val(),
        "IdentificadorFace": $('#identificadorFace').val(),
        "Token": $('#token').val()
    }
    console.log(JSON.stringify(dadosBiometria));

    $.ajax({
        //url: 'https://localhost:5001/api/ReconhecimentoFacil/Validar',
        url: $('#urlBaseBF').val() + '/api/ReconhecimentoFacil/Validar',
        type: 'POST',
        dataType: 'json',
        //contentType: "multipart/form-data; boundary=----WebKitFormBoundaryQvxJtPVD9VwfnP0R",
        data: formData,//JSON.stringify(dadosBiometria),
        contentType: false,
        cache: false,
        processData: false,
        success: function (data) {
            var obj = JSON.parse(JSON.stringify(data));
            console.log(data);
            buldModalAlert('RespostaRegistroBiometriaFacial', 'ALERTA', obj.message, modalStyleAlert);
            $('.situacaoBiometriaFacial').val(obj.message);
            $('#hdfIdentificadorBeneficiarioFacial').val(obj.hash);

            if (obj.hash != '')
                registrahashBiometriaFacial();

            return true;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(arguments);
            //alert(" Can't do because: " + textStatus + " | " + errorThrown);

            return false;
        },
        beforeSend: function (xhr, settings) {
            xhr.setRequestHeader('Authorization', token);
        }
    });

    return false;
}

function registrahashBiometriaFacial() {
    //__doPostBack('ctl00$cphConteudo$ucBiometria$lkbBiometriaFacial', '');
    $.ajax({
        url: '?RetornoAPIFacial=t',
        type: 'GET',
        success: function (data) {
            console.log(data);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(arguments);
            //alert(" Can't do because: " + textStatus + " | " + errorThrown);
        }
    });
}

function drawShape(ctx, xoff, yoff) {
    ctx.beginPath();
    ctx.lineWidth = 4;
    ctx.strokeStyle = "#FF0000";
    ctx.moveTo(447 + xoff, 103 + yoff);
    ctx.bezierCurveTo(447 + xoff, 225 + yoff, 448 + xoff, 240 + yoff, 435 + xoff, 284 + yoff);
    ctx.bezierCurveTo(415 + xoff, 353 + yoff, 364 + xoff, 390 + yoff, 319 + xoff, 390 + yoff);
    ctx.bezierCurveTo(273 + xoff, 390 + yoff, 232 + xoff, 359 + yoff, 211 + xoff, 295 + yoff);
    ctx.bezierCurveTo(194 + xoff, 243 + yoff, 198 + xoff, 224 + yoff, 201 + xoff, 103 + yoff);
    ctx.stroke();
}

function dataURItoBlob(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for (var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], { type: 'image/jpeg' });
}

function padLeft(str, max) {
    str = str.toString();
    return str.length < max ? padLeft("0" + str, max) : str;
};

function nomeArquivo() {
    var d = new Date();
    var n = d.getFullYear() + '' + padLeft(d.getMonth() + 1, 2) + '' + padLeft(d.getDate(), 2) + padLeft(d.getHours(), 2) + padLeft(d.getMinutes(), 2) + padLeft(d.getSeconds(), 2);

    return n;
}

function visualizarCaixaBiometriaFacial() {
    buildGenericModal('#caixaBiometriaFacial');

    iniciarWebcam();

    return false;
}
/* FIM BIOMETRIA FACIAL */

function visualizarCaixaBiometria() {
    $(".situacaoBiometria").val("Digital não capturada");
    buildGenericModal('#caixaBiometria');

    return false;
}

function caixaBiometriaClose() {
    $(".respostaCaptura").text("Aguardando...").css("color", "#333");
    $('#caixaBiometria').modal('close');
    return false;
}

var noSupportMessage = "Seu browser não da suporte a WebSocket!";
var ws;

function appendMessage(message) {
    $('#logBiometria').append("<p>- " + message + "</p>");
}

function abrirCadastroBiometria() {
    $('.lkbCadastraBiometria').attr('disabled', 'disabled');
    buildGenericModal('#CadastroBiometria');
}

function lerDigital(field) {
    var support = "MozWebSocket" in window ? 'MozWebSocket' : ("WebSocket" in window ? 'WebSocket' : null);
    var conectou = false;

    if (support == null) {
        appendMessage("* " + noSupportMessage + "<br/>");
        return;
    }

    appendMessage("Conectando aplicação para captura da biometria.");

    // create a new websocket and connect
    ws = new window[support]($("#hdfServidorSocket").val());

    ws.onmessage = function (evt) {
        appendMessage("Testando a biometria.");

        if (evt.data.indexOf("Erro") == -1 && evt.data != "") {
            testarBiometria(evt.data).then(function (resolve) {
                console.log("Retorno do webfinger", resolve);
                if (field == 6) {
                    $('.lkbCadastraBiometria').removeAttr('disabled');
                } else {
                    $("#hdfBiometria" + field).val(evt.data);
                    $(".digital" + field).val("Digital obtida");
                    $(".digital" + field).change();
                }
            }).catch(function (reject) {
                if (field != 6) {
                    $(".digital" + field).val("Digital incompatível");
                    $(".digital" + field).change();
                } else {
                    appendMessage("Resultado: " + reject.Mensagem);
                    buildGenericModal('#caixaBiometria');

                    setTimeout(function () {
                        $('#caixaBiometria').modal('close');
                        disconnectWebSocket();
                    }, 5000);
                }
            });
        } else {
            var mensagem = (evt.data == "") ? "Aplicação da biometria foi fechada." : evt.data.substr(4);

            visualizarCaixaBiometria();
            appendMessage(mensagem);

            $(".situacaoBiometria").val(mensagem);

            setTimeout(function () {
                disconnectWebSocket();
                caixaBiometriaClose();
            }, 4000);
        }
    };

    // when the connection is established, this method is called
    ws.onopen = function () {
        conectou = true;

        appendMessage('Aplicação conectada.');
        sendMessage();
        appendMessage('Pressione sua digital sobre o sensor biométrico.');
    };

    // when the connection is closed, this method is called
    ws.onclose = function () {
        if (conectou) {
            appendMessage('A conexão foi fechada.');
        } else {
            var mensagem = 'Não foi possível iniciar a aplicação Infomed Biometria para fazer a leitura biométrica. <br />Acesse o menu do Windows e procure por Infomed Biometria. Caso não tenha instalado <a href="' + $("#hdfServInfomedBiometria").val() + '" target="_blank">baixe aqui</a>.';
            appendMessage(mensagem);

            setTimeout(function () {
                buldModalAlert('alertaBiometria', 'ALERTA', mensagem, modalStyleAlert);
            }, 2000);
        }
    }
}

function testarBiometria(fingerData) {
    return new Promise(function(resolve, reject) { 
        var fingers = new Array();
        if ($("#hdfBiometria1").val() != "") {
            fingers.push($("#hdfBiometria1").val());
        }
        if ($("#hdfBiometria2").val() != "") {
            fingers.push($("#hdfBiometria2").val());
        }
        if ($("#hdfBiometria3").val() != "") {
            fingers.push($("#hdfBiometria3").val());
        }
        if ($("#hdfBiometria4").val() != "") {
            fingers.push($("#hdfBiometria4").val());
        }
        if ($("#hdfBiometria5").val() != "") {
            fingers.push($("#hdfBiometria5").val());
        }

        if (fingers.length == 0) {
            resolve({ Result: true });
            return;
        }
    
        var dadosBiometria = {
            "Prestador": $("#hdfPrestador").val(),
            "CodigoBeneficiario": $("#hdfCodBeneficiario").val(),
            "FingerData": fingerData,
            "Token": "ABCDE12345",
            "DriverBiometria": $("#hdfDrive").val(),
            "QualidadeFMD": "2",
            "Referencia": $("#hdfReferencia").val(),
            "TipoFMD": $("#hdfTipoFMD").val(),
            "FingerDatas": fingers
        }    

        appendMessage("Testando...");

        $.ajax({
            url: $("#hdfServidorTestar").val(),
            type: 'POST',
            dataType: 'json',
            contentType: "application/json; charset=UTF-8",
            data: JSON.stringify(dadosBiometria),
            success: function (data) {
                if (data.Result) {
                    resolve(data);
                } else {
                    reject(data);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                console.log(arguments);
            }
        });
    });
}

function connectSocketServer() {
    $(".imbCapturar").attr("disabled", "disabled");
    var support = "MozWebSocket" in window ? 'MozWebSocket' : ("WebSocket" in window ? 'WebSocket' : null);
    var conectou = false;

    if (support == null) {
        appendMessage("* " + noSupportMessage + "<br/>");
        return;
    }

    //console.log("Conectando aplicação para captura da biometria.");
    appendMessage("Conectando aplicação para captura da biometria.");

    // create a new websocket and connect
    ws = new window[support]($("#hdfServidorSocket").val());

    // when data is comming from the server, this metod is called
    ws.onmessage = function (evt) {
        //console.log(evt.data);
        appendMessage("Validando a biometria.");

        if (evt.data.indexOf("Erro") == -1 && evt.data != "") {
            enviarBiometria(evt.data);
        } else {
            var mensagem = (evt.data == "") ? "Aplicação da biometria foi fechada." : evt.data.substr(4);

            visualizarCaixaBiometria();
            appendMessage(mensagem);

            $(".situacaoBiometria").val(mensagem);

            setTimeout(function () {
                disconnectWebSocket();
                caixaBiometriaClose();
                //visualizarAlerta(3, '#', mensagem);
            }, 4000);
        }
    };

    // when the connection is established, this method is called
    ws.onopen = function () {
        conectou = true;
        //console.log("Aplicação conectada");
        appendMessage('Aplicação conectada.');
        sendMessage();
        appendMessage('Pressione sua digital sobre o sensor biométrico.');

        /*
        $('#connectButton').attr("disabled", "disabled");
        $('#disconnectButton').removeAttr("disabled");
        */
    };

    // when the connection is closed, this method is called
    ws.onclose = function () {
        if (conectou) {
            appendMessage('A conexão foi fechada.');
        } else {
            var mensagem = 'Não foi possível iniciar a aplicação Infomed Biometria para fazer a leitura biométrica. <br />Acesse o menu do Windows e procure por Infomed Biometria. Caso não tenha instalado <a href="' + $("#hdfServInfomedBiometria").val() + '" target="_blank">baixe aqui</a>.';
            appendMessage(mensagem);

            setTimeout(function () {
                buldModalAlert('alertaBiometria', 'ALERTA', mensagem, modalStyleAlert);
                //caixaBiometriaClose();
            }, 2000);
        }

        $(".imbCapturar").removeAttr("disabled");

        /*
        $('#sendButton').attr("disabled", "disabled");
        $('#connectButton').removeAttr("disabled");
        $('#disconnectButton').attr("disabled", "disabled");*/
    }
}

function sendMessage() {
    if (ws) {
        var messageBox = $("#hdfDrive").val() + "|" + $("#hdfTipoFMD").val();
        //console.log(messageBox);
        ws.send(messageBox);
        messageBox = "";
    }
}

function disconnectWebSocket() {
    if (ws) {
        ws.close();
    }
}

function connectWebSocket() {
    connectSocketServer();
}

/*
window.onload = function () {
    $('#messageInput').attr("disabled", "disabled");
    $('#sendButton').attr("disabled", "disabled");
    $('#disconnectButton').attr("disabled", "disabled");
}
*/

function enviarBiometria(fingerData) {

    var dadosBiometria = {
        "Prestador": $("#hdfPrestador").val(),
        "CodigoBeneficiario": $("#hdfCodBeneficiario").val(),
        "FingerData": fingerData,
        "Token": "ABCDE12345", // Token utilizado no Applet Java
        "DriverBiometria": $("#hdfDrive").val(),
        "QualidadeFMD": "2",
        "Referencia": $("#hdfReferencia").val(),
        "TipoFMD": $("#hdfTipoFMD").val(),
    }
    console.log(JSON.stringify(dadosBiometria));

    appendMessage("Enviando...");

    $.ajax({
        url: $("#hdfServidor").val(),
        type: 'POST',
        dataType: 'json',
        contentType: "application/json; charset=UTF-8",
        data: JSON.stringify(dadosBiometria),
        success: function (data) {
            //$('#target').html(data.msg);
            //console.log(data);

            var mensagem = "";
            var identificadorBenef = "";
            var time = 2000;
            var biometriaValida = "N";

            if (data.Mensagem.indexOf("Erro") != -1) {
                mensagem = data.Mensagem;
                visualizarCaixaBiometria();
                time = 4000;
            } else {
                mensagem = $("#hdfRegistrationMode").val() == "true" ? "Digital cadastrada" : "Digital reconhecida";
                identificadorBenef = data.Mensagem;
                biometriaValida = "S";
            }

            $(".biometriaValida").val(biometriaValida);
            $(".situacaoBiometria").val(mensagem);
            $(".identificadorBeneficiario").val(identificadorBenef);
            appendMessage("Resultado: " + mensagem);

            setTimeout(function () {
                caixaBiometriaClose();
                disconnectWebSocket();
            }, time);
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log(arguments);
            //alert(" Can't do because: " + textStatus + " | " + errorThrown);
        }
    });

    $(".imbCapturar").removeAttr("disabled");

}

///** FIM FUNÇÕES PARA BIOMETRIA **/

/** INICIO - FUNÇÕES QUE UTILIZAM API GOOGLE - MAPS **/
function caixaMaps() {
    document.getElementById("btnComoChegar").className = "btn green darken-3";
    buildGenericModal("#modalMaps");

    return false;
}

function preencheEnderecoPrestador(endereco) {
    $("#txbPara").val(endereco);
}
/** FIM - FUNÇÕES QUE UTILIZAM API GOOGLE - MAPS **/

function pesquisarEndereco() {
    $("#updLoading").show();
    var cep = $("#cphConteudo_pnlEndereco_ctl00_txbCep");

    $.get("Edicao.aspx?cep=" + cep.val(), function (dados) {
        if (dados != "") {
            var json = eval(dados);
            var index = 0;
            desabilitaCamposEndereco();

            $("#cphConteudo_pnlEndereco_ctl00_txbLogradouro").val(json.Logradouro);
            $("#cphConteudo_pnlEndereco_ctl00_txbBairro").val(json.Bairro);
            $("#cphConteudo_pnlEndereco_ctl00_txbMunicipio").val(json.Municipio);

            if (json.Estado >= 0)
                index = json.Estado;
            $("#cphConteudo_pnlEndereco_ctl00_hdfValorCombo").val(json.Estado);
            $('#cphConteudo_pnlEndereco_ctl00_cmbEstado option:eq(' + index + ')').attr('selected', true);

            if (json.Logradouro == null) {
                buldModalAlert('AlertaCEP', 'ALERTA', 'CEP não encontrado. Digitou corretamente?', modalStyleAlert);
            }
        }
    });
    $("#updLoading").hide();
    // retorna false para não acontecer o postBack
    return false;
}

function desabilitaCamposEndereco() {
    $("#cphConteudo_pnlEndereco_ctl00_txbLogradouro").attr("readonly", "readonly");
    $("#cphConteudo_pnlEndereco_ctl00_txbBairro").attr("readonly", "readonly");
    $("#cphConteudo_pnlEndereco_ctl00_txbMunicipio").attr("readonly", "readonly");
    $("#cphConteudo_pnlEndereco_ctl00_cmbEstado").attr("disabled", "disabled");
    $("#cphConteudo_pnlDadosPessoais_ctl00_txbDataNascimento").attr("readonly", "readonly");
    $("#cphConteudo_pnlDocumentos_ctl00_txbRgDataEmissao").attr("readonly", "readonly");
    $("#cphConteudo_txbDtInicial").attr("readonly", "readonly");
    $("#cphConteudo_txbDtFinal").attr("readonly", "readonly");
}

function preencheCanvasRegistroANS(registroANS) {
    var canvas = document.getElementById('canvas_registro_ans');
    var context = canvas.getContext('2d');

    context.font = '12px sans-serif';
    context.fillStyle = 'white';
    context.fillText('ANS-nº ' + registroANS, 8, 14);
}

function hideLoad() {
    $("#updLoading").hide();
    $("#updLoading2").hide();
    $("#updLoading2").remove();
}

/** ACOES CUSTOMIZADAS **/
function CarregaPagina() {
    var pagina = $("#paginaCustomizada").contents().height();
    $("#paginaCustomizada").height(pagina + 30);
}


function Count(text, maxlength) {
    var object = document.getElementById(text.id)  //get your object
    var stringReplace = object.value.replace(/</g, '{').replace(/>/g, '}');
    object.value = stringReplace;

    if (object.value.length > maxlength) {
        object.focus(); //set focus to prevent jumping
        object.value = text.value.substring(0, maxlength); //truncate the value
        object.scrollTop = object.scrollHeight; //scroll to the end to prevent jumping
        return false;
    }

    if ($('#' + text.id + '_count').length > 0) {
        $('#' + text.id + '_count').html(object.value.length + '/' + maxlength);
    } else {
        $('#' + text.id).after('<span id="' + text.id + '_count" class="count_textarea">' + object.value.length + '/' + maxlength + '</span>');
        //$('#' + text.id + '_count').css('width', $('#' + text.id).css('width'));
    }

    return true;
}

/*** Funções para o gridview antigo ***/
function verificaTotalCheckboxesMarcados(papel) {
    var totalCheckboxes = $('[class^=checkMaster_' + papel + ']').find("[type='checkbox']").length;
    var totalCheckboxesMarcados = $('[class^=checkFilho_' + papel + ']').find("[type='checkbox']:checked").length;
    if (totalCheckboxes == totalCheckboxesMarcados) {
        $(".checkMaster_" + papel).find("[type='checkbox']").attr("checked", true);
    } else {
        $(".checkMaster_" + papel).find("[type='checkbox']").attr("checked", false);
    }
}

function totalValorRecursado() {

    if ($(".valorTotalRecursado") != undefined && $(".valorTotalRecursado") != null) {
        if ($(".valorTotalRecursado").val() != undefined) {
            var totalRecursado = 0;
            $(".checkChildren_GridView").each(function () {
                if ($(this).find(":checkbox").is(":checked"))
                    totalRecursado += parseFloat($(this).parent().parent().find(".valorRecursado").val().replace(".", "").replace(",", "."));
            });
            $(".valorTotalRecursado").val(formatReal(totalRecursado));
        }
    }
}


function formatReal(mixed) {
    return number_format(mixed, 2, ",", ".");
}

function number_format(number, decimals, dec_point, thousands_sep) {

    number = (number + '')
      .replace(/[^0-9+\-Ee.]/g, '');
    var n = !isFinite(+number) ? 0 : +number,
      prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
      sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
      dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
      s = '',
      toFixedFix = function (n, prec) {
          var k = Math.pow(10, prec);
          return '' + (Math.round(n * k) / k)
            .toFixed(prec);
      };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n))
      .split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '')
      .length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1)
          .join('0');
    }
    return s.join(dec);
}

function SetFocus(id) {
    var textbox = document.getElementById(id);
    if (textbox != null) {
        textbox.focus();
    }
}

function changeText() {
    if ($('#cphConteudo_UcPesquisaRapida1_cmbCampoPesquisa').val() == "codigo") {
        var element = document.getElementById('cphConteudo_UcPesquisaRapida1_txtValorPesquisa');
        var valor = element.value;
        valor = valor.replace(/[^\s\u00BF-\u1FFF-\u2C00-\uD7FF-\u00A0\w;:\.,]+/g, "");
        element.value = valor;
    } else {
        var element = document.getElementById('cphConteudo_UcPesquisaRapida1_txtValorPesquisa');
        var valor = element.value;
        valor = $.trim(valor.replace(/[^\s\u00BF-\u1FFF-\u2C00-\uD7FF\w;:\.,]+/g, ""));
        element.value = valor;
    }
}

function proximoCampo(atual, proximo) {
    var at = document.getElementById(atual),
        px = document.getElementById(proximo);

    if (at.value.length >= at.maxLength) {
        $("#" + proximo).focus();
    }
}

function disableInternalFloatButtons() {
    $('li .btn-floating').not('.mobile-fab-tip').addClass('disabled');
}

function pageRefresh() {
    window.location.href = window.location.href;
    $('#updLoading2').show();
}

function preencheCombobox(combobox) {
    $.widget("custom.combobox", {
        _create: function () {
            this.wrapper = $("<span>")
                .addClass("custom-combobox")
                .insertAfter(this.element);

            this.element.hide();
            this._createAutocomplete();
            this._createShowAllButton();
        },

        _createAutocomplete: function () {
            var selected = this.element.children(":selected"),
                value = selected.val() ? selected.text() : "";

            this.input = $("<input type='text' size='50'>")
                .appendTo(this.wrapper)
                .val(value)
                .attr("title", "Diária")
                .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
                .autocomplete({
                    delay: 0,
                    minLength: 0,
                    source: $.proxy(this, "_source")
                })
            ;

            this.input.bind('autocompleteselect', function (event, ui) {
                ui.item.option.selected = true;
                console.log(ui.item.option.value);
                console.log(ui.item.option.index);
                $('#' + combobox + ' option').attr("selected", false);
                $('#' + combobox + ' option:eq(' + ui.item.option.index + ')').attr("selected", true);
            });

            this.input.bind('autocompletechange', function (event, ui) {

                // Selected an item, nothing to do
                if (ui.item) {
                    return;
                }

                // Search for a match (case-insensitive)
                var value = $(this).val(),
                    valueLowerCase = value.toLowerCase(),
                    valid = false;

                $(this).parent().prev().each(function () {
                    if ($(this).val().toLowerCase() === valueLowerCase) {
                        this.selected = valid = true;
                        return false;
                    }
                });

                /*
                this.element.children("option").each(function () {
                    if ($(this).text().toLowerCase() === valueLowerCase) {
                        alert($(this).text());
                        this.selected = valid = true;
                        return false;
                    }
                });
                */

                // Found a match, nothing to do
                if (valid) {
                    return;
                }

                // Remove invalid value
                $(this).val("").attr("title", "O termo " + value + " não é uma diária válida.");
                $('#' + combobox + ' option').attr("selected", false);
                /*this.input.val("")
                    .attr("title", value + " didn't match any item")
                /*.tooltip("open")*/;
                $(this).parent().prev().val("");
                //this.element.val("");                
                setInterval(function () {
                    //this.input /*.tooltip("close")*/
                    $(this).attr("title", "Diária");
                }, 2500);
            });

        },

        _createShowAllButton: function () {
            var input = this.input,
                wasOpen = false;

            $("<a>")
                .attr("tabIndex", -1)
                .attr("title", "Todas as diárias disponíveis")
            //.tooltip()
            .appendTo(this.wrapper)
                .button({
                    /*icons: {
                        primary: "ui-icon-triangle-1-s"
                    },*/
                    text: false
                })
                .removeClass("ui-corner-all")
                .addClass("custom-combobox-toggle ui-corner-right lnkPesquisa")
                .mousedown(function () {
                    wasOpen = input.autocomplete("widget").is(":visible");
                })
                .click(function () {
                    input.focus().val("");

                    // Close if already visible
                    if (wasOpen) {
                        return;
                    }

                    // Pass empty string as value to search for, displaying all results
                    input.autocomplete("search", "");
                });
        },

        _source: function (request, response) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
            response(this.element.children("option").map(function () {
                var text = $(this).text();
                if (this.value && (!request.term || matcher.test(text))) return {
                    label: text,
                    value: text,
                    option: this
                };
            }));
        },

        _destroy: function () {
            this.wrapper.remove();
            this.element.show();
        }
    });

    $("#" + combobox).combobox();

}
/*Lucas*/
function setTextBranco(campo) {
    cbo = document.getElementById(campo).value;
    document.getElementById(campo).value = "";
    document.getElementById(campo).placeholder = cbo;

}

function validaCBO(campo) {
    if (document.getElementById(campo).value == "") {
        document.getElementById(campo).value = cbo;
    }
}

function limpaDataFinal(dataIni, dataFim) {
    if (document.getElementById(dataIni.id + '_output').value == "") {
        document.getElementById(dataIni.id).value = "";
        document.getElementById(dataFim.id).value = "";
        document.getElementById(dataFim.id + '_output').value = "";
    }
}

function verificaTamanhoMin(campo1, tamanhoMin) {
    var valor = $("." + campo1);

    if (valor.val().length >= tamanhoMin) {
        valor.removeClass("invalid");
        valor.addClass("valid");
    } else {
        valor.removeClass("valid");
        valor.addClass("invalid");
    }
}

//Função responsável pela criação do autocomplete.
function CreateAutoComplete(ctrl, dados) {
    if (ctrl.length > 0) {
        $(document).ready(function () {
            //Iniciando autocomplete para o control
            $('#' + ctrl[0].id).autocomplete({ data: dados, minLength: 0 });

            //Add evento focusout
            $('#' + ctrl[0].id).focusout(function () { IfInvalidValues(ctrl, dados); });
        });
    }
}

//Função responsável por validar os dados do controle autocomplete
function IfInvalidValues(ctrl, data) {

    // array de values
    var arr = Object.keys(data);

    // Search for a match (case-insensitive)
    var value = ctrl.val();
    valueLowerCase = value.toLowerCase(),
    valid = false;

    //Laço para verificar se o array contem o valor do txtbox
    for (var i = 0; i < arr.length; i++) {
        console.log(arr[i]);
        if (arr[i].toLowerCase() === valueLowerCase) {
            valid = true;
        }
    }

    // Found a match, nothing to do
    if (valid) {
        return;
    }
    // Remove invalid value
    ctrl.val("");
}

//Limitr carcters
function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    }
}

//chama o menu lateral em telas menores que 992px
var clique = document.getElementById("btn-menu");
var menuLateral = document.getElementById("main-menu");

if (clique) {
    clique.onclick = function (e) {
        e.preventDefault();
        menuLateral.classList.toggle('toggleMenu');
    };
}

//muda a cor e ícone do menu hamburguer
$(document).ready(function () {
    $('#btn-menu').on('click', function () {
        $(this).toggleClass('fechaHamburguer');
    });
});

/*marca e desmarca o radio no menuLateral*/
$("input:radio").on("click", function (e) {
    var inp = $(this);
    if (inp.is(".theone")) {
        inp.prop("checked", false).removeClass("theone");
    } else {
        $("input:radio[name='" + inp.prop("name") + "'].theone").removeClass("theone");
        inp.addClass("theone");
    }
});

//corrige o bug do campo quantidade
function corrigeQuantidade() {

    $(document).ready(function () {
        setTimeout(function () {
            document.querySelector('.txbQuantidade').value = null;
        }, 500);
    });
}

// Extension function para converter uma string no formato de data no tipo Date (Ex.: "01/01/2001".toDate("dd/mm/yyyy hh:ii:ss")
String.prototype.toDate = function (format) {
    var normalized = this.replace(/[^a-zA-Z0-9]/g, '-');
    var normalizedFormat = format.toLowerCase().replace(/[^a-zA-Z0-9]/g, '-');
    var formatItems = normalizedFormat.split('-');
    var dateItems = normalized.split('-');

    var monthIndex = formatItems.indexOf("mm");
    var dayIndex = formatItems.indexOf("dd");
    var yearIndex = formatItems.indexOf("yyyy");
    var hourIndex = formatItems.indexOf("hh");
    var minutesIndex = formatItems.indexOf("ii");
    var secondsIndex = formatItems.indexOf("ss");

    var today = new Date();

    var year = yearIndex > -1 ? dateItems[yearIndex] : today.getFullYear();
    var month = monthIndex > -1 ? dateItems[monthIndex] - 1 : today.getMonth() - 1;
    var day = dayIndex > -1 ? dateItems[dayIndex] : today.getDate();

    var hour = hourIndex > -1 ? dateItems[hourIndex] : today.getHours();
    var minute = minutesIndex > -1 ? dateItems[minutesIndex] : today.getMinutes();
    var second = secondsIndex > -1 ? dateItems[secondsIndex] : today.getSeconds();

    return new Date(year, month, day, hour, minute, second);
};

function preencherJustificativas() {
    $(".justificativa-glosa").each(function () {
        if ($(this).closest("td").closest("tr").attr('style') != 'display: none;') {
            $(this).val($("#justificativaValor").val());
        }
    });
}

//Funcão + fonte Thermostato <INÍCIO>
function Callthermostatio(usuario_, email_, nome_operadora_, codigo_operadora_, versao_sistema_) {

    thermostatio.start({
        name: usuario_,
        email: false,

        fields: {
            codigo_operadora: codigo_operadora_,
            nome_operadora: nome_operadora_,
            versao_sistema: versao_sistema_,
            email: email_
        },

    });
}


//Funcãp Thermostato <FIM>

// A função abaixo corrige o comportamento de 'autocomplete' dos inputs no Chrome
// evitando que eles sejam erroneamente preenchidos com valores de outros input-texts
(function ($) {

    "use strict";

    $.fn.autoCompleteFix = function (opt) {
        var ro = 'readonly', settings = $.extend({
            attribute: 'autocomplete',
            trigger: {
                disable: ["off"],
                enable: ["on"]
            },
            focus: function () {
                $(this).removeAttr(ro);
            },
            force: false
        }, opt);

        $(this).each(function (i, el) {
            el = $(el);

            if (el.is('form')) {
                var force = (-1 !== $.inArray(el.attr(settings.attribute), settings.trigger.disable))
                el.find('input').autoCompleteFix({ force: force });
            } else {
                // Checagem adicionada para verificar se o elemento passado é um componente autocomplete
                // DevExpress ou se é um componente que está amrcado coma classe ignoreGoogleFix
                // Dessa fora, o fix não precisa ser aplicado nestes componentes, pois estava bugando o valor, não exibindo na interface
                var ignoreFix = false;
                var elClassList = el[0].classList;
                if (elClassList.length > 0) {
                    for (var i = 0; i < elClassList.length; i++) {
                        if (ignoreFix) continue;
                        ignoreFix = elClassList[i].startsWith("dxe") || elClassList[i] === "ignoreGoogleFix" || elClassList[i] === "el-input__inner";
                    }
                    if (ignoreFix) return;
                }
                //***********************************************************************************************************************//
                var disabled = -1 !== $.inArray(el.attr(settings.attribute), settings.trigger.disable);
                var enabled = -1 !== $.inArray(el.attr(settings.attribute), settings.trigger.enable);
                if (settings.force && !enabled || disabled)
                    el.attr(ro, ro).focus(settings.focus).val("");
            }
        });
    };
})(jQuery);

function restringirCaracteres(myfield, e, restrictionType) {
    if (!e) var e = window.event
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    var character = String.fromCharCode(code);
    // Se ESC for pressionado, remove o foco do campo
    if (code == 27) { this.blur(); return false; }
    // Ignora se outras teclas forem pressionadas
    // Comportamento estranho: 39 é a tecla arrow down, a tecla "'" e, também, a tecla DEL
    if (!e.ctrlKey && code != 9 && code != 8 && code != 36 && code != 37 && code != 38 && (code != 39 || (code == 39 && character == "'")) && code != 40) {
        if (character.match(restrictionType)) {
            return true;
        } else {
            return false;
        }
    }
}

function limparSessionStorage() {
    window.sessionStorage.removeItem('auditor_filtros');
    return false;
}

function refreshMensNaoLidas(usuario, prestador) {
    var timeInterval = document.getElementById("hiddenInterValoBuscaMsgsChat").value * 1000;
    if (timeInterval > 0) {
        verificarMensNaoLidasChatConnecta(usuario, prestador);
        setInterval(function () {
            verificarMensNaoLidasChatConnecta(usuario, prestador);
        }, timeInterval);
    }
}

function verificarMensNaoLidasChatConnecta(usuario, prestador) {
    $.get("../api/Chat/ObterDados?codigoUsuario=" + usuario + "&codPrestador=" + prestador + "&tipoChat=AP", function (dados) {
//        string codigoUsuario, string codTransacao = null, string tipoTransacao = null, string codigoChat = null, bool retornaQntMsgNaoLidas = true, string codPrestador = null, string tipoChat = null
        try {
            var qtd = 0;
            if (dados != "") {
                for (var i = 0; i < dados.length; i++) {
                    qtd += parseInt(dados[i].qtdMsgNaoLidas);
                }
            }
            if (qtd > 0) {
                $('#chatMenu i').addClass('orange-text');
            } else {
                $('#chatMenu i').removeClass('orange-text');
            }
        } catch (e) {
        }
    });
}
