/* NUGET: BEGIN LICENSE TEXT
 *
 * Microsoft grants you the right to use these script files for the sole
 * purpose of either: (i) interacting through your browser with the Microsoft
 * website or online service, subject to the applicable licensing or use
 * terms; or (ii) using the files as included with a Microsoft product subject
 * to that product's license terms. Microsoft reserves all other rights to the
 * files not expressly granted by Microsoft, whether by implication, estoppel
 * or otherwise. Insofar as a script file is dual licensed under GPL,
 * Microsoft neither took the code under GPL nor distributes it thereunder but
 * under the terms set out in this paragraph. All notices and licenses
 * below are for informational purposes only.
 *
 * NUGET: END LICENSE TEXT */
/*
** Unobtrusive Ajax support library for jQuery
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
(function(a){var b="unobtrusiveAjaxClick",d="unobtrusiveAjaxClickTarget",h="unobtrusiveValidation";function c(d,b){var a=window,c=(d||"").split(".");while(a&&c.length)a=a[c.shift()];if(typeof a==="function")return a;b.push(d);return Function.constructor.apply(null,b)}function e(a){return a==="GET"||a==="POST"}function g(b,a){!e(a)&&b.setRequestHeader("X-HTTP-Method-Override",a)}function i(c,b,e){var d;if(e.indexOf("application/x-javascript")!==-1)return;d=(c.getAttribute("data-ajax-mode")||"").toUpperCase();a(c.getAttribute("data-ajax-update")).each(function(f,c){var e;switch(d){case"BEFORE":e=c.firstChild;a("<div />").html(b).contents().each(function(){c.insertBefore(this,e)});break;case"AFTER":a("<div />").html(b).contents().each(function(){c.appendChild(this)});break;case"REPLACE-WITH":a(c).replaceWith(b);break;default:a(c).html(b)}})}function f(b,d){var j,k,f,h;j=b.getAttribute("data-ajax-confirm");if(j&&!window.confirm(j))return;k=a(b.getAttribute("data-ajax-loading"));h=parseInt(b.getAttribute("data-ajax-loading-duration"),10)||0;a.extend(d,{type:b.getAttribute("data-ajax-method")||undefined,url:b.getAttribute("data-ajax-url")||undefined,cache:!!b.getAttribute("data-ajax-cache"),beforeSend:function(d){var a;g(d,f);a=c(b.getAttribute("data-ajax-begin"),["xhr"]).apply(b,arguments);a!==false&&k.show(h);return a},complete:function(){k.hide(h);c(b.getAttribute("data-ajax-complete"),["xhr","status"]).apply(b,arguments)},success:function(a,e,d){i(b,a,d.getResponseHeader("Content-Type")||"text/html");c(b.getAttribute("data-ajax-success"),["data","status","xhr"]).apply(b,arguments)},error:function(){c(b.getAttribute("data-ajax-failure"),["xhr","status","error"]).apply(b,arguments)}});d.data.push({name:"X-Requested-With",value:"XMLHttpRequest"});f=d.type.toUpperCase();if(!e(f)){d.type="POST";d.data.push({name:"X-HTTP-Method-Override",value:f})}a.ajax(d)}function j(c){var b=a(c).data(h);return!b||!b.validate||b.validate()}a(document).on("click","a[data-ajax=true]",function(a){a.preventDefault();f(this,{url:this.href,type:"GET",data:[]})});a(document).on("click","form[data-ajax=true] input[type=image]",function(c){var g=c.target.name,e=a(c.target),f=a(e.parents("form")[0]),d=e.offset();f.data(b,[{name:g+".x",value:Math.round(c.pageX-d.left)},{name:g+".y",value:Math.round(c.pageY-d.top)}]);setTimeout(function(){f.removeData(b)},0)});a(document).on("click","form[data-ajax=true] :submit",function(e){var g=e.currentTarget.name,f=a(e.target),c=a(f.parents("form")[0]);c.data(b,g?[{name:g,value:e.currentTarget.value}]:[]);c.data(d,f);setTimeout(function(){c.removeData(b);c.removeData(d)},0)});a(document).on("submit","form[data-ajax=true]",function(h){var e=a(this).data(b)||[],c=a(this).data(d),g=c&&c.hasClass("cancel");h.preventDefault();if(!g&&!j(this))return;f(this,{url:this.action,type:this.method||"GET",data:e.concat(a(this).serializeArray())})})})(jQuery);;
var controleAjaxConsulta = [];
var filtroExecutado = {};
var GridRowsPerPage;

$(document).ready(function () {
    resolverMvcGridRelacon();
    resolverTooltip();
    if (jQuery.isEmptyObject(filtroExecutado)) {
        $("#divEntidade").html('<label class="control-label">Entidade</label><select class="form-control" disabled readonly><option selected>Selecione um Município</option></select>');
    }
    Co_InicializarBinds();

    resolverMascaras();

    window.setTimeout(resolverDatePicker, 300);
});

function resolverDatePicker() {
    var dt = $("#dtPeriodoVigenciaDe").data('date');
    $("#dtPeriodoVigenciaDe").val(dt);
    var ate = $("#dtPeriodoVigenciaAte").data('date');
    $("#dtPeriodoVigenciaAte").val(ate);
}
function Co_InicializarBinds() {    
    $('#btnEnviarConsulta').on('click', function (e) {
        Co_EnviarFormulario(e);
        Co_btnOcultaDiv_Changed(this, e);
    });
    
    $('.widget-header').on('click', function (e) {
        if ($(e.target).hasClass("fa-chevron-down")) {
            e.stopPropagation();
        }
        showOrHideWidgetBox('.widget-box');
        Co_MostrarMensagem_Changed();
    });
    $('#btnLimparConsulta').on('click', function (e) {
        e.preventDefault();
        Co_LimparFormulario();
    });
}

function Co_btnOcultaDiv_Changed(s, e) {
    if ($(s).attr("id") == "btnEnviarConsulta") {        
        $("#divResultado").css("display", "block");
        $(".widget-toolbar > a > i").removeClass("fa-chevron-up");
        $(".widget-toolbar > a > i").addClass("fa-chevron-down");
        $(".widget-body").css("display", "none");
        $(".widget-box").addClass("collapsed");
        $("#exibirForm1").css("display", "none");
        $("#exibirForm2").css("display", "block");
    }
}

function Co_EnviarFormulario(event) {
    event.preventDefault();
    event.stopPropagation();

    var formData = $("#formConsulta").serializeObject();
    if (GridRowsPerPage != null) {
        formData.nrRegPorPagina = parseInt(GridRowsPerPage);
    }
    else {
        formData.nrRegPorPagina = 20;
    }
    $.extend(formData, { flFiltroExecutado: true, nrOrdem: 0, nrPagina: 1 });

    formData.idMunicipio = $("#Municipio_idMunicipio").val();
    formData.idEsfera = $("#Esfera_idEsfera").val();
    formData.idEstruturaAdministrativa = $("#EstruturaAdministracao_idEstruturaDeAdministracao").val();
    formData.idNaturezaJuridica = $("#NaturezaJuridica_idNaturezaJuridica").val();
    formData.idEntidade = $("#idPessoa").val();

    formData.vlRecursosPropriosDe = $("#vlContrapartida").val();
    formData.vlRecursosPropriosAte = $("#vlContrapartidaAte").val();

    formData.vlValorConvenioDe = $("#vlRepasse").val();
    formData.vlValorConvenioAte = $("#vlRepasseAte").val();

    formData.nrConvenio = $("#nrConvenio").val();

    $('#loadingConsulta').show();
    $('#divResultado').html('');

    if (controleAjaxConsulta["pesquisa"] != null) {
        controleAjaxConsulta["pesquisa"].abort();
    }

    controleAjaxConsulta["pesquisa"] = $.ajax({
        url: baseUrl + 'Convenios/ConveniosConsulta/Pesquisa',
        data: formData,
        method: "POST",
        success: function (data) {
            Co_SuccessGridConsulta(data, formData);
        }, error: function (data) {
            $('#divResultado').html('<div class="alert alert-danger" style="margin-bottom:0px;">Não foi possível carregar a consulta</div>');
            $('#loadingConsulta').hide();
        }
    })
    .done(function () {
        $('table:not(.stacktable)', '#divResultado').cardtable();
    });
}

function Co_LimparFormulario() {
    $('#loadingConsulta').show();

    window.setTimeout(function () {
        $('input').val('');

        $("#divEntidade").html('<label class="control-label">Entidade</label><select class="form-control" disabled readonly><option selected>Selecione um Município</option></select>');
        $("#divResultado").empty();

        $("select").each(function () {
            var elem = $(this);
            $(elem).find("option:selected").each(function () {
                $(this).removeAttr("selected");
            });
            $(elem).find("option:first").attr('selected', 'selected');
        });

        Todos_Modify(baseUrl + "ConveniosConsulta/Modify");
    }, 1);

    var newUrl = getPathFromUrl();
    History.replaceState({ state: 1 }, "Consulta - TCE-PR", newUrl);
    filtroExecutado = null;

    $('#loadingConsulta').hide();
}


function Co_MostrarMensagem_Changed() {
    if ($(".widget-toolbar > a > i").hasClass("fa-chevron-up")) {
        $("#exibirForm1").css("display", "block");
        $("#exibirForm2").css("display", "none");
    }
    else {
        $("#exibirForm1").css("display", "none");
        $("#exibirForm2").css("display", "block");
    }
}

function Co_SuccessGridConsulta(data, formData) {
    $('#divResultado').html(data);
    filtroExecutado = formData;
    var filtro = btoa(JSON.stringify(formData));
    History.replaceState({ state: 1 }, "Consulta - TCE-PR", "?f=" + filtro);

    $('#loadingConsulta').hide();
    resolverMvcGridRelacon();
}
;
//Variavel auxiliar para uso no ajax.
var controleAjax = [];

$(document).ready(function () {
    resolverMvcGrid();
    resolverMascaras();
    resolverBugs();
    resolverImpressaoMVCGrid();
    resolverPlugins();
});

var qtipStyle = {
    classes: 'qtip-dark qtip-tce'
};

var mascarasGeral = {
    mascaraCPF: "000.000.000-00",
    mascaraCPF2: "000.000.000-00#",
    mascaraCNPJ: "00.000.000/0000-00",
    mascaraRG: "0.000.000-AA",
    mascaraRG2: "00.000.000-AA",
    mascaraTelefone: '(00) 0000-00009',
    mascaraTelefone2: '(00) 00000-0000',
    mascaraMoeda: 'R$ #.##0,00', //jquery.mask
    mascaraMoeda2: { prefix: 'R$ ', decimal: ",", thousands: "." }, //jquery.maskmoney
    mascaraMoeda3: { decimal: ",", thousands: "." }, //jquery.maskmoney
    mascaraMoeda2casasDecimais: { decimal: ",", thousands: ".", precision: 2 }, //jquery.maskmoney
    mascaraMoeda3casasDecimais: { decimal: ",", thousands: ".", precision: 3 }, //jquery.maskmoney
    mascaraMoeda4casasDecimais: { decimal: ",", thousands: ".", precision: 4 }, //jquery.maskmoney
    mascaraMoeda5casasDecimais: { decimal: ",", thousands: ".", precision: 5 }, //jquery.maskmoney
    mascaraNumero: '00000000000000',
    mascaraData: '00/00/0000',
    mascaraDatePicker: {
        format: "dd/mm/yyyy",
        language: "pt-BR",
        daysOfWeekHighlighted: "0,6",
        todayHighlight: true
    },
    mascaraDatePickerMesAno: {
        format: "MM/yyyy",
        startView: 1,
        minViewMode: 1,
        language: "pt-BR",
    }
};

function resolverPlugins() {
    resolverTooltip();
    resolverExpander();
    resolverSwitch();
    resolverNoty();
    resolverChosen();
    resolverPainelAjax('body');
    resolverModalWide();
}

function resolverModalWide() {
    $("body").on("show.bs.modal", ".modal-wide", function () {
        var height = $(window).height() - 200;
        $(this).find(".modal-body").css("max-height", height);
    });
}

function resolverSwitch() {
    $('.inputSwitch').each(function () {
        $(this).bootstrapSwitch({
            state: $(this).data('state'),
            size: $(this).data('size'),
            readonly: $(this).data('readonly'),
            onColor: $(this).data('on-color'),
            offColor: $(this).data('off-color'),
            onText: $(this).data('on-label'),
            offText: $(this).data('off-label'),
            labelText: $(this).data('text-label')
        });
    });

    $('body').on('switchChange.bootstrapSwitch', '.inputSwitch', function (event, state) {
        if (state) {
            $(this).attr("checked", "checked");
        } else {
            $(this).removeAttr("checked", "checked");
        }
    });
}

function resolverImpressaoMVCGrid() {
    $('body').on('click', '.panel-heading a.fa-print[data-toggle=popup]', function (e) {
        window.open($(this).attr('href'), "Imprimir", "width=950, height=650");
        return false;
    });
}

function resolverMascaras() {
    $('.maskDate').datepicker(mascarasGeral.mascaraDatePicker);
    $('.maskDate').mask(mascarasGeral.mascaraData, { placeholder: "__/__/____" });
    $('.maskDate2').datepicker(mascarasGeral.mascaraDatePickerMesAno, { placeholder: "Mês/Ano" });
    $('.input-daterange input').mask(mascarasGeral.mascaraData, { placeholder: "__/__/____" });
    $('.input-daterange').datepicker(mascarasGeral.mascaraDatePicker);
    $('.maskNumber').mask(mascarasGeral.mascaraNumero);
    $('.maskMoney').maskMoney(mascarasGeral.mascaraMoeda2);
    $('.maskMoneySemR').maskMoney(mascarasGeral.mascaraMoeda3);
    $('.maskMoney2CasasDecimais').maskMoney(mascarasGeral.mascaraMoeda2casasDecimais);
    $('.maskMoney3CasasDecimais').maskMoney(mascarasGeral.mascaraMoeda3casasDecimais);
    $('.maskMoney4CasasDecimais').maskMoney(mascarasGeral.mascaraMoeda4casasDecimais);
    $('.maskMoney5CasasDecimais').maskMoney(mascarasGeral.mascaraMoeda5casasDecimais);
    $('.maskCPF').mask(mascarasGeral.mascaraCPF);
    $('.maskCNPJ').mask(mascarasGeral.mascaraCNPJ);
    $('.maskCPFCNPJ').mask(mascarasGeral.mascaraCPF, {
        onKeyPress: function (texto, e, field, options) {
            var textoSemFormatacao = RemoveDocumentoFormat(texto);
            mask = (textoSemFormatacao.length > 11) ? mascarasGeral.mascaraCNPJ : mascarasGeral.mascaraCPF2;
            $('.maskCPFCNPJ').mask(mask, options);
        }
    });
    $('.maskRG').mask(mascarasGeral.mascaraRG, {
        onKeyPress: function (texto, e, field, options) {
            var textoSemFormatacao = RemoveDocumentoFormat(texto);
            mask = (textoSemFormatacao.length < 9) ? mascarasGeral.mascaraRG : mascarasGeral.mascaraRG2;
            $('.maskRG').mask(mask, options);
        }
    });
    $('.maskTelefone').mask(mascarasGeral.mascaraTelefone, {
        onKeyPress: function (texto, e, field, options) {
            var textoSemFormatacao = RemoveDocumentoFormat(texto);
            mask = (textoSemFormatacao.length < 11) ? mascarasGeral.mascaraTelefone : mascarasGeral.mascaraTelefone2;
            $('.maskTelefone').mask(mask, options);
        }
    });

    $('body').on('focusout', '.maskCPFCNPJ', function (e) {

        var documento = RemoveDocumentoFormat($(this).val());
        $(this).unmask();

        if (documento.length > 11) {
            if (documento.length < 14) {
                documento = leftZeroPad(parseInt(documento), 14);
            }

            $(this).val(documento);
            $(this).mask(mascarasGeral.mascaraCNPJ);
        }
        else {
            if (documento.length >= 9) {
                documento = leftZeroPad(parseInt(documento), 11);
            }

            $(this).val(documento);
            $(this).mask(mascarasGeral.mascaraCPF);
        }
    });
}

function resolverBugs() {
    //Resolvendo bug do min e max em campos number
    $('body').off('change, focusout', 'input[type=number]');
    $('body').on('change, focusout', 'input[type=number]', function (e) {
        var valorInput = parseInt($(this).val());

        if (!isNaN(valorInput)) {
            if ($(this).is('[min]')) {
                if (valorInput < parseInt($(this).attr('min'))) {
                    $(this).val('');
                }
            }

            if ($(this).is('[max]')) {
                if (valorInput > parseInt($(this).attr('max'))) {
                    $(this).val('');
                }
            }

        } else {
            $(this).val('');
        }
    });
}

function RemoveDocumentoFormat(doc) {
    if (doc.length > 0) {
        return doc.replace(/\./g, "").replace(/\-/g, "").replace(/\//g, "").replace(/\(/g, "").replace(/\)/g, "").replace(/\ /g, "");
    } else {
        return "";
    }
}

function leftZeroPad(numero, numZeros) {
    var n = Math.abs(numero);
    var zeros = Math.max(0, numZeros - n.toString().length);
    var zeroString = Math.pow(10, zeros).toString().substr(1);
    if (numero < 0) {
        zeroString = '-' + zeroString;
    }

    return zeroString + n;
}

function resolverExpander() {
    $('.colunaContratoLicitacaoObjeto').expander({
        expandText: '...',//' &raquo;',
        expandPrefix: ' ',
        userCollapseText: ' &laquo;',
        userCollapsePrefix: ' ',
        widow: 0,
        slicePoint: 50
    });
}

function resolverTooltip() {
    $('[title][data-placement=BottomLeft]').qtip({
        style: qtipStyle,
        position: {
            at: 'bottom center',
            my: 'top right'
        }
    });
    $('[title][data-placement=BottomCenter]').qtip({
        style: qtipStyle,
        position: {
            at: 'bottom center',
            my: 'top center'
        }
    });
    $('[title][data-placement=BottomRight]').qtip({
        style: qtipStyle,
        position: {
            at: 'bottom center',
            my: 'top left'
        }
    });
    $('[title][data-placement=TopLeft]').qtip({
        style: qtipStyle,
        position: {
            at: 'top center',
            my: 'bottom right'
        }
    });
    $('[title][data-placement=TopCenter]').qtip({
        style: qtipStyle,
        position: {
            at: 'top center',
            my: 'bottom center'
        }
    });
    $('[title][data-placement=TopRight]').qtip({
        style: qtipStyle,
        position: {
            at: 'top center',
            my: 'bottom left'
        }
    });


    $('.mvc-grid-header[title]').each(function () {
        var title = $(this).attr('title');
        if (title.length > 0) {
            $('.mvc-grid-header-title', this).append('&nbsp;<i class="fa fa-question-circle" title="' + title + '"></i>');
            $('i', this).qtip({ //topright
                style: qtipStyle,
                position: {
                    at: 'top center',
                    my: 'bottom left'
                }
            });
        }
        $(this).removeAttr('title');
    });

}

function resolverMvcGrid() {
    $('.mvc-grid').mvcgrid({
        reloadStarted: resolverMvcGrid_ReloadStarted,
        reloadEnded: resolverMvcGrid_ReloadEnded
    });
}

function resolverMvcGrid_ReloadStarted(g) {
    if ($('#loadingConsulta')) {
        $('#loadingConsulta').show();
    }
}
function resolverMvcGrid_ReloadEnded(g) {
    window.setTimeout(function () {

        $('.atalhos a', $(g.element).closest(".panel.panel-default")).each(function (e) {
            if ($(this).attr("href").indexOf("tipoExibicao=") > 0) {
                var linkSegmentos = $(this).attr("href").split('?');
                var linkPartes = linkSegmentos[1].split('&');
                var tipoExibicao = "";

                for (var iq in linkPartes) {
                    if (linkPartes[iq].indexOf('tipoExibicao=') >= 0) {
                        tipoExibicao = linkPartes[iq];
                        break;
                    }
                }

                var linkNovoPartes = g.gridQuery.split('&');
                var linkNovo = linkSegmentos[0] + "?";
                var linkNovoItens = [];

                for (var iq in linkNovoPartes) {
                    if (linkNovoPartes[iq].indexOf('tipoExibicao=') < 0) {
                        linkNovo += linkNovoPartes[iq] + '&';
                    }
                }

                linkNovo += tipoExibicao;

                $(this).attr('href', linkNovo);

            }
        });

        //Esperando renderizar
        resolverExpander();
        resolverTooltip();
        if ($('#loadingConsulta')) {
            $('#loadingConsulta').hide();
        }
    }, 2);
}


function dataBRtoFormData(data) {
    //Converte data formato pt-br para formato padrão serialização
    var newdata = data;
    //console.log(data);

    if (data.length > 0 && data.indexOf('/') > 0) {
        var time = "00:00:00";

        if (data.indexOf(':') > 0) {
            data = data.replace('T', ' ');
            time = data.split(' ')[1];
            data = data.split(' ')[0];
        }

        data = data.split('/');
        newdata = data[2] + '-' + data[1] + '-' + data[0] + 'T' + time;
        //console.log(data);
        //console.log(newdata);

    }
    return newdata;
}

//Funções jquery
$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

/* Crud */
function resolverNoty() {
    if (CONST_TIPO_REQUEST != null && CONST_MENSAGEM_REQUEST != null) {
        CONST_TIPO_REQUEST = parseInt(CONST_TIPO_REQUEST);

        if (CONST_TIPO_REQUEST > 0 && CONST_MENSAGEM_REQUEST.length) {
            var tipo = "";

            switch (CONST_TIPO_REQUEST) {
                case 1:
                    tipo = tipoNoty.sucesso;
                    break;
                case 2:
                    tipo = tipoNoty.erro;
                    break;
                case 3:
                    tipo = tipoNoty.alerta;
                    break;
                default:
                    tipo = tipoNoty.informativo;
                    break;
            }

            exibirMensagemNoty(CONST_MENSAGEM_REQUEST, tipo);

            CONST_MENSAGEM_REQUEST = null;
            CONST_TIPO_REQUEST = null;
        }
    }

    $('body').on('click', 'a[data-confirm]', function () {
        var texto = $(this).data('confirm');
        var url = $(this).attr('href');

        noty({
            layout: 'center',
            theme: 'defaultTheme',
            type: 'confirm',
            text: texto,
            killer: true,
            buttons: [
            {
                addClass: 'btn btn-primary', text: 'Excluir', onClick: function ($noty) {
                    $noty.close();
                    document.location.href = url;
                }
            },
            {
                addClass: 'btn btn-danger', text: 'Cancelar', onClick: function ($noty) {
                    $noty.close();
                }
            }
            ]
        });
        return false;
    });
}

var tipoNoty = {
    erro: "error",
    sucesso: "success",
    alerta: "warning",
    informativo: "information"
};

function exibirMensagemNoty(texto, tipo) {
    noty({
        layout: 'topRight',
        theme: 'defaultTheme',
        type: tipo,
        text: texto,
        animation: {
            open: "animated flipInX",
            close: "animated flipOutX"
        },
        timeout: 5000
    });
}

function resolverChosen() {
    //chosen ajax
    $('select.ajax-chosen-select').each(function () {
        var urlAjax = $(this).data('url');
        var maxSelected = $(this).data('maxselected');

        if (maxSelected != null)
            maxSelected = parseInt(maxSelected);
        
        $(this).ajaxChosen({
            type: 'POST',
            url: urlAjax,
            dataType: 'json',
            minTermLength: 2,
            afterTypeDelay: 200,
            keepTypingMsg: "Continue digitando...",
            lookingForMsg: "procurando por"
        }, function (data) {
            var results = [];

            $.each(data, function (i, val) {
                results.push({ value: val.value, text: val.text });
            });

            return results;
        }, {
            width: "100%",
            max_selected_options: maxSelected || 100,
            no_results_text: "Nenhum item encontrado"
        });
    });

    //chosen normal
    $('select.chosen-select').each(function () {

        var maxSelected = $(this).data('maxselected');

        if (maxSelected != null)
            maxSelected = parseInt(maxSelected);

        $(this).chosen({ width: "100%", no_results_text: "Nenhum item encontrado", max_selected_options: maxSelected || 100 }).change(function (s, e) {
            var idSelect = $(this).attr('id');
            var totalItensSituacao = $("option", this).length - 1;
            var totalSelecionadosSituacao = $("option:selected:not(#" + idSelect + " option:first-child)", this).length;

            if (e.deselected != null && e.deselected != "-1") {
                //Desmarcou um item
                if (totalSelecionadosSituacao == 0) {
                    //Nenhum item selecionado é equivale a todos selecionados
                    $(this).val("-1");
                    $("option:first-child", this).attr('disabled', 'disabled');
                }
            }
            else if (e.selected != null && e.selected != "-1") {
                //Marcou um item
                if (totalSelecionadosSituacao == totalItensSituacao) {
                    //Selecionou tudo, mostra apenas o todos
                    //Co_LimparMultiSelect(false);
                    $("option", this).removeAttr('disabled').removeAttr('selected');
                    $(this).val("-1");
                    $("option:first-child", this).attr('disabled', 'disabled');
                } else {
                    //Desmarca o todos
                    $("option:first-child", this).removeAttr('disabled').removeAttr('selected');
                }
            } else {
                //Desmarca todas as opções selecionadas e marca o todos
                //Co_LimparMultiSelect(false);
                $("option", this).removeAttr('disabled').removeAttr('selected');
                $(this).val("-1");
                $("option:first-child", this).attr('disabled', 'disabled');
            }
            $(this).trigger("chosen:updated");
        });
    });
}

function resolverPainelAjax(seletorContainer) {
    //Informe o seletor do pai dos paineis que serão resolvidos
    $('.panel-ajax', seletorContainer).each(function (e) {

        var executou = $(this).data('vlmd-expnaj') || $(this).attr('data-vlmd-expnaj');

        executou = executou != undefined && executou != null && executou != '' && executou != 'undefined';
        $(this).data('vlmd-expnaj', 'sepaj');

        if (!executou) {

            var url = $(this).data('url') || $(this).attr('data-url');
            var target = '#' + $(this).attr('id');

            controleAjax[target] = $.ajax({
                url: url,
                async: true,
                type: "POST",
                success: function (data) {
                    $(target).replaceWith(data);
                    resolverPlugins();
                    resolverMvcGrid();
                },
                error: function (data) {
                    $('.panel-body', target).html(data);
                }, complete: function () {
                    controleAjax[target] = null;
                }
            });

        }
    });
}

;
/*!
 * jQuery Expander Plugin - v1.4.14 - 2014-10-05
 * http://plugins.learningjquery.com/expander/
 * Copyright (c) 2014 Karl Swedberg
 * Licensed MIT (http://www.opensource.org/licenses/mit-license.php)
 */
!function(a){a.expander={version:"1.4.14",defaults:{slicePoint:100,sliceOn:null,preserveWords:!0,showWordCount:!1,wordCountText:" ({{count}} words)",widow:4,expandText:"read more",expandPrefix:"&hellip; ",expandAfterSummary:!1,wordEnd:/(&(?:[^;]+;)?|[0-9a-zA-Z\u00C0-\u0100]+|[^\u0000-\u007F]+)$/,summaryClass:"summary",detailClass:"details",moreClass:"read-more",lessClass:"read-less",moreLinkClass:"more-link",lessLinkClass:"less-link",collapseTimer:0,expandEffect:"slideDown",expandSpeed:250,collapseEffect:"slideUp",collapseSpeed:200,userCollapse:!0,userCollapseText:"read less",userCollapsePrefix:" ",onSlice:null,beforeExpand:null,afterExpand:null,onCollapse:null,afterCollapse:null}},a.fn.expander=function(b){function c(a,b){var c="span",d=a.summary,e=q.exec(d),f=e?e[2].toLowerCase():"";return b?(c="div",e&&"a"!==f&&!a.expandAfterSummary?d=d.replace(q,a.moreLabel+"$1"):d+=a.moreLabel,d='<div class="'+a.summaryClass+'">'+d+"</div>"):d+=a.moreLabel,[d," <",c+' class="'+a.detailClass+'"',">",a.details,"</"+c+">"].join("")}function d(a,b){var c='<span class="'+a.moreClass+'">'+a.expandPrefix;return a.showWordCount?a.wordCountText=a.wordCountText.replace(/\{\{count\}\}/,b.replace(n,"").replace(/\&(?:amp|nbsp);/g,"").replace(/(?:^\s+|\s+$)/,"").match(/\w+/g).length):a.wordCountText="",c+='<a href="#" class="'+a.moreLinkClass+'">'+a.expandText+a.wordCountText+"</a></span>"}function e(b,c){return b.lastIndexOf("<")>b.lastIndexOf(">")&&(b=b.slice(0,b.lastIndexOf("<"))),c&&(b=b.replace(m,"")),a.trim(b)}function f(a,b){b.stop(!0,!0)[a.collapseEffect](a.collapseSpeed,function(){var c=b.prev("span."+a.moreClass).show();c.length||b.parent().children("div."+a.summaryClass).show().find("span."+a.moreClass).show(),a.afterCollapse&&a.afterCollapse.call(b)})}function g(b,c,d){b.collapseTimer&&(j=setTimeout(function(){f(b,c),a.isFunction(b.onCollapse)&&b.onCollapse.call(d,!1)},b.collapseTimer))}function h(b){var c="ExpandMoreHere374216623",d=b.summaryText.replace(b.sliceOn,c);d=a("<div>"+d+"</div>").text();var e=d.indexOf(c),f=b.summaryText.indexOf(b.sliceOn);return-1!==e&&e<b.slicePoint&&(b.summaryText=b.allHtml.slice(0,f)),b}var i="init";"string"==typeof b&&(i=b,b={});var j,k=a.extend({},a.expander.defaults,b),l=/^<(?:area|br|col|embed|hr|img|input|link|meta|param).*>$/i,m=k.wordEnd,n=/<\/?(\w+)[^>]*>/g,o=/<(\w+)[^>]*>/g,p=/<\/(\w+)>/g,q=/(<\/([^>]+)>)\s*$/,r=/^(<[^>]+>)+.?/,s=/\s\s+/g,t=function(b){return a.trim(b||"").replace(s," ")},u={init:function(){this.each(function(){var b,i,m,q,s,u,v,w,x,y,z,A,B,C,D,E=[],F=[],G="",H={},I=this,J=a(this),K=a([]),L=a.extend({},k,J.data("expander")||a.meta&&J.data()||{}),M=!!J.find("."+L.detailClass).length,N=!!J.find("*").filter(function(){var b=a(this).css("display");return/^block|table|list/.test(b)}).length,O=N?"div":"span",P=O+"."+L.detailClass,Q=L.moreClass+"",R=L.lessClass+"",S=L.expandSpeed||0,T=t(J.html()),U=T.slice(0,L.slicePoint);if(L.moreSelector="span."+Q.split(" ").join("."),L.lessSelector="span."+R.split(" ").join("."),!a.data(this,"expanderInit")){for(a.data(this,"expanderInit",!0),a.data(this,"expander",L),a.each(["onSlice","beforeExpand","afterExpand","onCollapse","afterCollapse"],function(b,c){H[c]=a.isFunction(L[c])}),U=e(U),s=U.replace(n,"").length;s<L.slicePoint;)q=T.charAt(U.length),"<"===q&&(q=T.slice(U.length).match(r)[0]),U+=q,s++;for(L.sliceOn&&(D=h({sliceOn:L.sliceOn,slicePoint:L.slicePoint,allHtml:T,summaryText:U}),U=D.summaryText),U=e(U,L.preserveWords&&T.slice(U.length).length),u=U.match(o)||[],v=U.match(p)||[],m=[],a.each(u,function(a,b){l.test(b)||m.push(b)}),u=m,i=v.length,b=0;i>b;b++)v[b]=v[b].replace(p,"$1");if(a.each(u,function(b,c){var d=c.replace(o,"$1"),e=a.inArray(d,v);-1===e?(E.push(c),F.push("</"+d+">")):v.splice(e,1)}),F.reverse(),M)x=J.find(P).remove().html(),U=J.html(),T=U+x,w="";else{if(x=T.slice(U.length),y=a.trim(x.replace(n,"")),""===y||y.split(/\s+/).length<L.widow)return;w=F.pop()||"",U+=F.join(""),x=E.join("")+x}L.moreLabel=J.find(L.moreSelector).length?"":d(L,x),N?x=T:"&"===U.charAt(U.length-1)&&(G=/^[#\w\d\\]+;/.exec(x),G&&(x=x.slice(G[0].length),U+=G[0])),U+=w,L.summary=U,L.details=x,L.lastCloseTag=w,H.onSlice&&(m=L.onSlice.call(I,L),L=m&&m.details?m:L),z=c(L,N),J.html(z),B=J.find(P),C=J.find(L.moreSelector),"slideUp"===L.collapseEffect&&"slideDown"!==L.expandEffect||J.is(":hidden")?B.css({display:"none"}):B[L.collapseEffect](0),K=J.find("div."+L.summaryClass),A=function(a){a.preventDefault(),C.hide(),K.hide(),H.beforeExpand&&L.beforeExpand.call(I),B.stop(!1,!0)[L.expandEffect](S,function(){B.css({zoom:""}),H.afterExpand&&L.afterExpand.call(I),g(L,B,I)})},C.find("a").unbind("click.expander").bind("click.expander",A),L.userCollapse&&!J.find(L.lessSelector).length&&J.find(P).append('<span class="'+L.lessClass+'">'+L.userCollapsePrefix+'<a href="#" class="'+L.lessLinkClass+'">'+L.userCollapseText+"</a></span>"),J.find(L.lessSelector+" a").unbind("click.expander").bind("click.expander",function(b){b.preventDefault(),clearTimeout(j);var c=a(this).closest(P);f(L,c),H.onCollapse&&L.onCollapse.call(I,!0)})}})},destroy:function(){this.each(function(){var b,c,d=a(this);d.data("expanderInit")&&(b=a.extend({},d.data("expander")||{},k),c=d.find("."+b.detailClass).contents(),d.removeData("expanderInit"),d.removeData("expander"),d.find(b.moreSelector).remove(),d.find("."+b.summaryClass).remove(),d.find("."+b.detailClass).after(c).remove(),d.find(b.lessSelector).remove())})}};return u[i]&&u[i].call(this),this},a.fn.expander.defaults=a.expander.defaults}(jQuery);;
function resolverMvcGridTab() {
    $(".tabbable .mvc-grid").mvcgrid({
        reloadStarted: resolverMvcGridTab_ReloadStarted,
        reloadEnded: resolverMvcGridTab_ReloadEnded
    });
}

function resolverMvcGridTab_ReloadStarted(g) {
    var target = $('.tabbable ul.nav li.active a').attr('href');
    var tabLoading = $('#tabLoadingBase').clone().removeAttr('id').show();
    $(target).append('<div class="tabAjaxContent"></div>');
    $(target).prepend(tabLoading);

    $(target + " .tabAjaxContent").hide();
}

function resolverMvcGridTab_ReloadEnded(g) {    
    var target = $('.tabbable ul.nav li.active a').attr('href');
    $(".tabLoading", target).remove();    
    $(target + " .tabAjaxContent").show();
    resolverMvcGrid_ReloadEnded(g);
}

function resolverMvcGridRelacon() {
    $('.mvc-grid').mvcgrid({
        reloadStarted: resolverMvcGridRelacon_ReloadStarted,
        reloadEnded: resolverMvcGridRelacon_ReloadEnded,
        reloadFailed: resolverMvcGridRelacon_ReloadFailed
    });
}

function resolverMvcGridRelacon_ReloadStarted(g) {
    if ($('#loadingConsulta')) {
        $('#loadingConsulta').show();
    }
}
function resolverMvcGridRelacon_ReloadFailed(g) {
    if ($('#divResultado')) {
        $('#divResultado').html('<div class="alert alert-danger" style="margin-bottom:0px;">Não foi possível carregar a consulta</div>');
    }
    if ($('#loadingConsulta')) {
        $('#loadingConsulta').hide();
    }
}

function resolverMvcGridRelacon_ReloadEnded(g) {
    window.setTimeout(function () {
        //$('.atalhos a', $(g.element).closest(".panel.panel-default")).each(function (e) {
        $('.atalhos a', $(g.element).closest(".panel-default")).each(function (e) {
            if ($(this).attr("href").indexOf("tipoExibicao=") > 0) {
                var linkSegmentos = $(this).attr("href").split('?');
                var linkPartes = linkSegmentos[1].split('&');
                var tipoExibicao = "";

                for (var iq in linkPartes) {
                    if (linkPartes[iq].indexOf('tipoExibicao=') >= 0) {
                        tipoExibicao = linkPartes[iq];
                        break;
                    }
                }

                var linkNovoPartes = g.gridQuery.split('&');
                var linkNovo = linkSegmentos[0] + "?";
                var linkNovoItens = [];

                for (var iq in linkNovoPartes) {
                    if (linkNovoPartes[iq].indexOf('tipoExibicao=') < 0) {
                        linkNovo += linkNovoPartes[iq] + '&';
                    }
                }

                linkNovo += tipoExibicao;

                $(this).attr('href', linkNovo);

            }
        });
        //Esperando renderizar
        resolverExpander();
        resolverTooltip();
        if ($('#loadingConsulta')) {
            $('#loadingConsulta').hide();
        }
    }, 5);
}

function showOrHideWidgetBox(elem) {
    if ($(elem).hasClass('collapsed')) {
        showWidgetBox(elem);
    } else {
        hideWidgetBox(elem);
    }
}

function showWidgetBox(elem) {
    $(elem).widget_box('show');
}

function hideWidgetBox(elem) {
    $(elem).widget_box('hide');
}

function zerosDecimais(elem) {
    if (elem != null && elem != undefined) {
        var str = elem;
        var valorReal = str.split(",")[0];
        var valorDecimal = str.substr(str.indexOf(",") + 1);
        var valorDeCorte = valorDecimal.slice(-1);
        
        for (i = 0; i = valorDecimal.length; i++) {
            if (valorDeCorte == 0) {
                valorDecimal = valorDecimal.substring(0, valorDecimal.length - 1);
                valorDeCorte = valorDecimal.slice(-1);
            } else {
                break;
            }
        }

        var resultado;

        if (valorDecimal != null && valorDecimal != undefined && valorDecimal != "") {
            resultado = valorReal + "," + valorDecimal;
        } else {
            resultado = valorReal;
        }

        return resultado;
    }

}


/**
 *
 * Helper function to extract the URL between the last / and before ?   
 * If url is www.example.com/file.php?f_id=55 this function will return file.php  
 * pseudo code: edit to match your url settings  
 **/
function refineUrl() {
    //get full url
    var url = window.location.href;
    //get url after/  
    var value = url.substring(url.lastIndexOf('/') + 1);
    //get the part after before ?
    value = value.split("?")[0];
    return value;
}

function getPathFromUrl() {
    var url = window.location.href;
    return url.split("?")[0];
}


function configurarNumeros() {
    $(".numero").on('change keyup', function (e) {        
        // Setas direcionais (37 a 40)
        if (e.keyCode < 37 || e.keyCode > 40) {
            var resultado = $(this).val().replace(/[^0-9]/g, '');
            $(this).val(resultado);
        } else {
            return true;
        }
    });
};
