$(document).ready(function(){
    $('[data-toggle="tooltip"]').tooltip();
});
$(document).ready(function() {
    $('.format_hora').each(function() {
        $(this).mask('00:00', {clearIfNotMatch: true});
        $(this).blur(function () {
            if($(this).val() != '') {
                var hora = $(this).val().split(":");
                if (hora[0] > 24) hora[0] = 24;
                if(hora[1] > 59) hora[1] = 59;
                $(this).val(hora[0] + ':' + hora[1]);
            }
        });
    });
    $('.format_data').each(function() {
        $(this).mask('00/00/0000', {clearIfNotMatch: true});
    });

    $(".hora_inicio").blur(function() {
        compareTime($('.hora_final'), $('.hora_inicio'), '<=');
        if($('.total_horas').length != 0) {
            diferencaHoras($('.hora_inicio').val(),$('.hora_final').val(), $('.total_horas'));
        }
    });
    $(".hora_final").blur(function() {
        compareTime($('.hora_final'), $('.hora_inicio'), '<=');
        if($('.total_horas').length != 0) {
            diferencaHoras($('.hora_inicio').val(),$('.hora_final').val(), $('.total_horas'));
        }
    });
    $(".hora_inicio2").blur(function() {
        compareTime($('.hora_final2'), $('.hora_inicio2'), '<=');
        if($('.total_horas2').length != 0) {
            diferencaHoras($('.hora_inicio2').val(),$('.hora_final2').val(), $('.total_horas2'));
        }
    });
    $(".hora_final2").blur(function() {
        compareTime($('.hora_final2'), $('.hora_inicio2'), '<=');
        if($('.total_horas2').length != 0) {
            diferencaHoras($('.hora_inicio2').val(),$('.hora_final2').val(), $('.total_horas2'));
        }
    });
    if($('.horas_implantacao').length != 0) {
        $(".horas_implantacao").blur(function() {
            compareTime($('.horas_implantacao'), $('.total_horas'), '>');
        });
        $(".total_horas").change(function() {
            compareTime($('.horas_implantacao'), $('.total_horas'), '>');
        });
    }

    $('#modal_mensagens').click(function(){
        var mensagens_idacesso_array = [];
        $('input[name^="mensagens_idacesso_array"]').each(function() {
            mensagens_idacesso_array.push($(this).val());
        });

        var mensagens_idcliente = $('#mensagens_idcliente').val();
        var mensagens_idfuncionario = $('#mensagens_idfuncionario').val();
        
        $.ajax({
            type: 'POST',
            data: {'id_mensagens':JSON.stringify(mensagens_idacesso_array), 
                   'id_cliente':mensagens_idcliente,
                   'id_funcionario':mensagens_idfuncionario},
            url: createUrl('dadosAcesso/esconderModalMensagens'),
            success: function () {
                $('#mensagem_suporte').hide();
            }
        });
     });
});

function updateHoraFinal() {
    var situacao = $("#Atendimentos_ATD_SITUACAO").val();
    if(situacao != "A"){
        $('#Atendimentos_ATD_HORAFINAL').siblings('label[for="Atendimentos_ATD_HORAFINAL"]').html('Hora final <span class="required">*</span>');
        $('#Atendimentos_ATD_TOTALHORAS').siblings('label[for="Atendimentos_ATD_TOTALHORAS"]').html('Total horas <span class="required">*</span>');
    } else {
        $('#Atendimentos_ATD_HORAFINAL').siblings('label[for="Atendimentos_ATD_HORAFINAL"]').html('Hora final');
        $('#Atendimentos_ATD_TOTALHORAS').siblings('label[for="Atendimentos_ATD_TOTALHORAS"]').html('Total horas');
    }
}
$(document).on('change', '#Atendimentos_ATD_SITUACAO', updateHoraFinal);
$(document).ready(updateHoraFinal);

$(document).ready(function() {
    $('form').valida({
        autocomplete: 'off',
        tag: 'div',
        validate: 'novalidate',
        messages: {
            submit: 'Aguarde ...',
            required: 'Este campo é obrigatório',
            invalid: 'Campo com dados inválidos',
            textarea_help: 'Digitados <span class="at-counter">{0}</span> de {1} caracteres'
        },
        use_filter: true,
        before_validate: null,
        after_validate: null
    });
    $('.ui-multiselect').find('.connected-list').removeAttr('style');
    $('.ui-multiselect').find('.ui-widget-header').prop('style', 'height: 50px;');
    $('.ui-multiselect').css({marginBottom: 10, marginTop: 5});
    if($(".search-form").length > 0 && $('.grid-view > table').length > 0) {
        if($('table').find('td').length > 1)
            $(".search-form").hide();
    }
    if($('.frm_col.col_2').length > 0) {
        PendenciasAtividades();
        $(window).resize(PendenciasAtividades);
    }
});
$(document).ready(function(){
    try {
        if(!top.GetBarExpanded()) {
            top.FoldFrame(top.GetBarExpanded());
            $('.navbar-toggle').addClass('collapsed');
        }
    } catch (e) {
        $('.navbar-toggle').remove();
    }
});
function SwitchLeftFrame() {
    if (typeof (top.GetBarExpanded) != "undefined") {
        top.FoldFrame(!top.GetBarExpanded());
        $('.navbar-toggle').toggleClass('collapsed');
    }
}
function ExpandLeftFrame(f) {
    var i = document.getElementById("imgLeftFrameSwitcher");
    if (i) {
        re = /(bar_)(.+)(.gif)$/;
        i.src = i.src.replace(re, "$1" + (f ? "close" : "open") + "$3");
        top.FoldFrame(f);
    }
}
function SetExpandLeftFrame() {
    try {
        if (top.document && top.document.getElementById('pageIframe')) {
            document.getElementsByTagName('body')[0].className += ' iframe';
        }
        if (top && top.leftFrame && typeof (top.GetBarExpanded) != "undefined") {
            ExpandLeftFrame(top.GetBarExpanded());
        }
    } catch (e) {
        console.log(e);
    }
}
function showClientes(show) {
    if (document.getElementById('div-atividades') != undefined) {
        document.getElementById('div-atividades').style.display = 'none';
    }
    if (document.getElementById('div-endereco-cobranca') != undefined) {
        document.getElementById('div-endereco-cobranca').style.display = 'none';
    }
    if (document.getElementById('div-documentos') != undefined) {
        document.getElementById('div-documentos').style.display = 'none';
    }
    if (document.getElementById('div-vincular-cliente') != undefined) {
        document.getElementById('div-vincular-cliente').style.display = 'none';
    }
    document.getElementById(show).style.display = 'block';
}
function showHide(objShowHide) {
    d = document;
    layer = "";
    if (d.getElementById)
        layer1 = d.getElementById(objShowHide).style;
    else if (d.layers)
        layer1 = document.layers[objShowHide];
    else
        return 1;
    if (layer1.display == "")
        layer1.display = "none";
    if (layer1.display != "none")
        layer1.display = "none";
    else
        layer1.display = "block";
}

function TrocaTipoPessoa(Campo, TipoPessoa) {
    if (Campo == 'CLI') {
        var div = 'Clientes_CLI_CNPJCPF';
    } else if (Campo == 'INT') {
        var div = 'Interessados_INT_CPF_CNPJ';
    }
    if (TipoPessoa == 'C' || TipoPessoa == 'E' || TipoPessoa == 'S' || TipoPessoa == 'P' || TipoPessoa == 'J') {
        document.getElementById(div).setAttribute("onKeyPress", "return FormataCnpj(this,event)");
        document.getElementById(div).setAttribute("maxlength", "18");
    } else if (TipoPessoa == 'F') {
        document.getElementById(div).setAttribute("onKeyPress", "return FormataCpf(this,event)");
        document.getElementById(div).setAttribute("maxlength", "14");
    } else if (TipoPessoa == 'R' || TipoPessoa == '') {
        document.getElementById(div).removeAttribute("onKeyPress");
    }
}
function SomenteNumero(e) {
    var tecla = (window.event) ? event.keyCode : e.which;
    if ((tecla > 47 && tecla < 58))
        return true;
    else {
        if (tecla == 8 || tecla == 0)
            return true;
        else
            return false;
    }
}
function MascaraMoeda(objTextBox, SeparadorMilesimo, SeparadorDecimal, e) {
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    //var whichCode = (window.Event) ? e.which : e.keyCode;
    var whichCode = (window.addEventListener) ? e.which : e.keyCode;
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc
    if ((objTextBox.value.length >= objTextBox.maxLength) && (whichCode != 13) && (whichCode != 8))
        whichCode = 1;
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8) || (whichCode == 9))
        return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave


    if (strCheck.indexOf(key) == -1)
        return false; // Chave inválida
    len = objTextBox.value.length;
    for (i = 0; i < len; i++)
        if ((objTextBox.value.charAt(i) != '0') && (objTextBox.value.charAt(i) != SeparadorDecimal))
            break;
    aux = '';
    for (; i < len; i++)
        if (strCheck.indexOf(objTextBox.value.charAt(i)) != -1)
            aux += objTextBox.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0)
        objTextBox.value = '';
    if (len == 1)
        objTextBox.value = '0' + SeparadorDecimal + '0' + aux;
    if (len == 2)
        objTextBox.value = '0' + SeparadorDecimal + aux;
    if (len > 2) {
        aux2 = '';
        for (j = 0, i = len - 3; i >= 0; i--) {
            if (j == 3) {
                aux2 += SeparadorMilesimo;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        objTextBox.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
            objTextBox.value += aux2.charAt(i);
        objTextBox.value += SeparadorDecimal + aux.substr(len - 2, len);
    }
    return false;
}
function FormataCep(Campo, teclapres) {
    var strCheck = '0123456789';
    var whichCode = (window.addEventListener) ? teclapres.which : teclapres.keyCode;
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc
    if ((Campo.value.length > Campo.maxLength) && (whichCode != 13) && (whichCode != 8))
        whichCode = 1;
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8) || (whichCode == 9))
        return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave

    if (strCheck.indexOf(key) == -1) {
        return false; // Chave inválida
    } else {
        var tecla = teclapres.keyCode;
        var vr = new String(Campo.value);
        vr = vr.replace("-", "");
        tam = vr.length + 1;
        if (tecla != 8) {
            if (tam == 6)
                Campo.value = vr.substr(0, 5) + '-' + vr.substr(5, 5);
        }
    }
}
function FormataTelefone(Campo, teclapres) {
    var strCheck = '0123456789';
    var whichCode = (window.addEventListener) ? teclapres.which : teclapres.keyCode;
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc
    if ((Campo.value.length > Campo.maxLength) && (whichCode != 13) && (whichCode != 8))
        whichCode = 1;
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8) || (whichCode == 9))
        return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave


    if (strCheck.indexOf(key) == -1) {
        return false; // Chave inválida
    } else {
        if (teclapres.keyCode != 8) {
            var vr = new String(Campo.value);
            vr = vr.replace("-", "");
            tam = vr.length;
            if (tam == 2) {
                Campo.value = "(" + Campo.value + ")";
            }
            if (tam == 3)
                if (Campo.value.charAt(0) == "(")
                    Campo.value += " )";
            if (tam == 8)
                Campo.value += "-";
        }
    }
}
function FormataCnpj(Campo, teclapres) {
    var strCheck = '0123456789';
    var whichCode = (window.addEventListener) ? teclapres.which : teclapres.keyCode;
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc
    if ((Campo.value.length > Campo.maxLength) && (whichCode != 13) && (whichCode != 8))
        whichCode = 1;
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8) || (whichCode == 9))
        return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave


    if (strCheck.indexOf(key) == -1) {
        return false; // Chave inválida
    } else {
        var tecla = teclapres.keyCode;
        var vr = new String(Campo.value);
        vr = vr.replace(".", "");
        vr = vr.replace("/", "");
        vr = vr.replace("-", "");
        tam = vr.length + 1;
        if (tecla != 14) {
            if (tam == 3)
                Campo.value = vr.substr(0, 2) + '.';
            if (tam == 6)
                Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 5) + '.';
            if (tam == 10)
                Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(6, 3) + '/';
            if (tam == 15)
                Campo.value = vr.substr(0, 2) + '.' + vr.substr(2, 3) + '.' + vr.substr(6, 3) + '/' + vr.substr(9, 4) + '-' + vr.substr(13, 2);
        }
    }
}
function FormataCpf(Campo, teclapres) {
    var strCheck = '0123456789';
    var whichCode = (window.addEventListener) ? teclapres.which : teclapres.keyCode;
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc
    if ((Campo.value.length > Campo.maxLength) && (whichCode != 13) && (whichCode != 8))
        whichCode = 1;
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8) || (whichCode == 9))
        return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave


    if (strCheck.indexOf(key) == -1) {
        return false; // Chave inválida
    } else {
        var tecla = teclapres.keyCode;
        var vr = new String(Campo.value);
        vr = vr.replace(".", "");
        vr = vr.replace("/", "");
        vr = vr.replace("-", "");
        tam = vr.length + 1;
        if (tecla != 14) {
            if (tam == 4)
                Campo.value = vr.substr(0, 3) + '.';
            if (tam == 7)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.';
            if (tam == 11)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-';
            if (tam == 16)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-' + vr.substr(9, 2);
        }
    }
}
function FormataCpfMultiplos(Campo, teclapres) {
    var strCheck = '0123456789';
    var whichCode = (window.addEventListener) ? teclapres.which : teclapres.keyCode;
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc
    if ((Campo.value.length > Campo.maxLength) && (whichCode != 13) && (whichCode != 8))
        whichCode = 1;
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8) || (whichCode == 9))
        return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave

    if (strCheck.indexOf(key) == -1) {
        return false; // Chave inválida
    } else {
        var tecla = teclapres.keyCode;
        var vr = new String(Campo.value);
        vr = vr.replace(".", "");
        vr = vr.replace("/", "");
        vr = vr.replace("-", "");
        tam = vr.length + 1;
        if (tecla != 14) {
            if (tam == 4)
                Campo.value = vr.substr(0, 3) + '.';
            if (tam == 7)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.';
            if (tam == 11)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-';

            if (tam == 13)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-' + vr.substr(10, 2) + ' / ' + vr.substr(14, 3);
            if (tam == 18)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-' + vr.substr(10, 2) + ' / ' + vr.substr(14, 3) + '.' + vr.substr(18, 3);
            if (tam == 22)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-' + vr.substr(10, 2) + ' / ' + vr.substr(14, 3) + '.' + vr.substr(18, 3) + '.' + vr.substr(22, 3);
            if (tam == 26)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-' + vr.substr(10, 2) + ' / ' + vr.substr(14, 3) + '.' + vr.substr(18, 3) + '.' + vr.substr(22, 3) + '-' + vr.substr(26, 2);

            if (tam == 29)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-' + vr.substr(10, 2) + ' / ' + vr.substr(14, 3) + '.' + vr.substr(18, 3) + '.' + vr.substr(22, 3) + '-' + vr.substr(26, 2) + ' / ' + vr.substr(31, 3);
            if (tam == 35)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-' + vr.substr(10, 2) + ' / ' + vr.substr(14, 3) + '.' + vr.substr(18, 3) + '.' + vr.substr(22, 3) + '-' + vr.substr(26, 2) + ' / ' + vr.substr(31, 3) + '.' + vr.substr(35, 3);
            if (tam == 39)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-' + vr.substr(10, 2) + ' / ' + vr.substr(14, 3) + '.' + vr.substr(18, 3) + '.' + vr.substr(22, 3) + '-' + vr.substr(26, 2) + ' / ' + vr.substr(31, 3) + '.' + vr.substr(35, 3) + '.' + vr.substr(39, 3);
            if (tam == 43)
                Campo.value = vr.substr(0, 3) + '.' + vr.substr(3, 3) + '.' + vr.substr(7, 3) + '-' + vr.substr(10, 2) + ' / ' + vr.substr(14, 3) + '.' + vr.substr(18, 3) + '.' + vr.substr(22, 3) + '-' + vr.substr(26, 2) + ' / ' + vr.substr(31, 3) + '.' + vr.substr(35, 3) + '.' + vr.substr(39, 3) + '-' + vr.substr(42, 2);
        }
    }
}
function FormataData(Campo, teclapres) {
    var strCheck = '0123456789';
    var whichCode = (window.addEventListener) ? teclapres.which : teclapres.keyCode;
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc
    if ((Campo.value.length > Campo.maxLength) && (whichCode != 13) && (whichCode != 8))
        whichCode = 1;
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8) || (whichCode == 9))
        return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave


    if (strCheck.indexOf(key) == -1) {
        return false; // Chave inválida
    } else {
        var tecla = teclapres.keyCode;
        var vr = new String(Campo.value);
        vr = vr.replace("/", "");
        vr = vr.replace("/", "");
        vr = vr.replace("/", "");
        tam = vr.length + 1;
        if (tecla != 8 && tecla != 8) {
            if (tam > 0 && tam < 2)
                Campo.value = vr.substr(0, 2);
            if (tam > 2 && tam < 4)
                Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, 2);
            if (tam > 4 && tam < 7)
                Campo.value = vr.substr(0, 2) + '/' + vr.substr(2, 2) + '/' + vr.substr(4, 7);
        }
    }
}
function FormataHora(Campo, teclapres) {
    var strCheck = '0123456789';
    var whichCode = (window.addEventListener) ? teclapres.which : teclapres.keyCode;
    // 13=enter, 8=backspace as demais retornam 0(zero)
    // whichCode==0 faz com que seja possivel usar todas as teclas como delete, setas, etc
    if ((Campo.value.length > Campo.maxLength) && (whichCode != 13) && (whichCode != 8))
        whichCode = 1;
    if ((whichCode == 13) || (whichCode == 0) || (whichCode == 8) || (whichCode == 9))
        return true;
    key = String.fromCharCode(whichCode); // Valor para o código da Chave


    if (strCheck.indexOf(key) == -1) {
        return false; // Chave inválida
    } else {
        var tecla = teclapres.keyCode;
        var vr = new String(Campo.value);
        vr = vr.replace(":", "");
        vr = vr.replace(":", "");
        vr = vr.replace(":", "");
        tam = vr.length + 1;
        if (tecla != 8 && tecla != 8) {
            if (tam > 0 && tam < 2)
                Campo.value = vr.substr(0, 2);
            if (tam > 2 && tam < 4)
                Campo.value = vr.substr(0, 2) + ':' + vr.substr(2, 2);
        }
    }
}
function diferencaHoras(aHoraini, aHoraFim, aHoraTotal) {
    var horatotal = '00:00';
    if ((aHoraini != '') && (aHoraini != '__:__:__') && (aHoraFim != '') && (aHoraFim != '__:__:__')) {

        var aHoraini = aHoraini + ':00';
        var aHoraFim = aHoraFim + ':00';
        var hora1 = aHoraini.substring(0, aHoraini.indexOf(":"));
        var hora2 = aHoraFim.substring(0, aHoraFim.indexOf(":"));
        var minuto1 = aHoraini.substring(aHoraini.indexOf(":") + 1, aHoraini.lastIndexOf(":"));
        var minuto2 = aHoraFim.substring(aHoraFim.indexOf(":") + 1, aHoraFim.lastIndexOf(":"));
        var segundo1 = aHoraini.substring(aHoraini.lastIndexOf(":") + 1, aHoraini.length);
        var segundo2 = aHoraFim.substring(aHoraFim.lastIndexOf(":") + 1, aHoraFim.length);

        var soma1 = 0, soma2 = 0;

        soma1 = (hora1 * 3600) + (minuto1 * 60) + segundo1;
        soma2 = (hora2 * 3600) + (minuto2 * 60) + segundo2;
        //alert(soma1);
        //alert(soma2);

        var difseg = 0;
        if (soma1 > soma2)
            difseg = soma1 - soma2;
        else
            difseg = soma2 - soma1;

        //alert(difseg);
        var difmin = parseInt(difseg / 100 / 60);
        var difhora = 0;

        difhora = parseInt(difmin / 60); //divisao
        difmin = parseInt(difmin % 60); //resto

        //alert(difmin);
        if (difhora < 10)
            horatotal = '0' + difhora.toString() + ':';
        else
            horatotal = difhora.toString() + ':';

        if (difmin < 10)
            horatotal = horatotal + '0' + difmin.toString() + '';
        else
            horatotal = horatotal + difmin.toString() + '';

    }
    $(aHoraTotal).val(horatotal);
}
function converteMoedaFloat(valor) {
    valor = valor.replace(".", "");
    valor = valor.replace(",", ".");
    valor = parseFloat(valor);
    return valor;
}
function formataMoeda(numero, casasDecimais, separadorDecimal, separadorMilhar, unidadeMoeda) {
    casasDecimais = isNaN(casasDecimais = Math.abs(casasDecimais)) ? 2 : casasDecimais;
    separadorDecimal = separadorDecimal == undefined ? "," : separadorDecimal;
    separadorMilhar = separadorMilhar == undefined ? "." : separadorMilhar;
    unidadeMoeda = unidadeMoeda == undefined ? "" : unidadeMoeda + " ";
    var sinal = numero < 0 ? "-" : "";
    var parteInteira = parseInt(numero = Math.abs(+numero || 0).toFixed(casasDecimais)) + "";

    var j = (j = parteInteira.length) > 3 ? j % 3 : 0;
    return unidadeMoeda + sinal + (j ? parteInteira.substr(0, j) + separadorMilhar : "") + parteInteira.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + separadorMilhar) + (casasDecimais ? separadorDecimal + Math.abs(numero - parteInteira).toFixed(casasDecimais).slice(2) : "");
}
function SomaValores(div) {
    var total = 0;
    var theOddOnes = document.getElementsByClassName(div);
    var i;
    for (i = 0; i < theOddOnes.length; i++) {
        if (theOddOnes[i].value != '') {
            total = total + converteMoedaFloat(theOddOnes[i].value);
        }
    }

    div_total = document.getElementById('total');
    div_total.innerHTML = '<strong>Valor total: ' + formataMoeda(total, 2, ',', '.', 'R$ ') + '<strong>';
}
function valorMinimotabela() {
    var data = new FormData();
    fields = $('#contratos-form').serializeArray();
    $.each(fields, function(i, field){
        data.append(field.name, field.value);
    });
    $.ajax({
        url: createUrl('contratos/DynamicMinimoTabela'),
        type: 'POST',
        data: data,
        processData: false,
        contentType: false,
        success: function (data) {
            $('#valorminimo').html(data);
        }
    });
}
function documentosFiscais() {
    var data = new FormData();
    fields = $('#contratos-form').serializeArray();
    $.each(fields, function(i, field){
        data.append(field.name, field.value);
    });
    $.ajax({
        url: createUrl('contratos/documentosFiscais'),
        type: 'POST',
        data: data,
        processData: false,
        contentType: false,
        success: function(data) {
            var selected = $($("#Contratos_IdsDocumentosFiscais")).val();
            $("#Contratos_IdsDocumentosFiscais").html(data);
            selectField('Contratos_IdsDocumentosFiscais', selected);
            jQuery("#Contratos_IdsDocumentosFiscais").multiselect("destroy").multiselect({sortable:false,searchable:true});
            if($(document).find("#Contratos_IdsDocumentosFiscais option").length == 0) {
                $(document).find("label[for=Contratos_IdsDocumentosFiscais] span.required").hide();
            } else {
                $(document).find("label[for=Contratos_IdsDocumentosFiscais] span.required").show();
            }
        }
    });
}
function maximohorasImplantacao() {
    var data = new FormData();
    fields = $('#contratos-form').serializeArray();
    $.each(fields, function(i, field){
        data.append(field.name, field.value);
    });
    $.ajax({
        url: createUrl('contratos/DynamicHorasImplantacao'),
        type: 'POST',
        data: data,
        processData: false,
        contentType: false,
        success: function (data) {
            $('#horasmaximo').html(data);
        }
    });
}
function ContratoSemValorImplantacao() {
    if($("#Contratos_COT_COBRADAIMPLANTACAO").val() == 1) {
        $('#Contratos_COT_VLRIMPLANTACAO').parent().show();
    } else {
        $('#Contratos_COT_VLRIMPLANTACAO').val('');
        $('#Contratos_COT_VLRIMPLANTACAO').parent().hide();
    }
}
function moduloMobile() {
    var data = new FormData();
    fields = $('#contratos-form').serializeArray();
    $.each(fields, function(i, field){
        data.append(field.name, field.value);
    });
    $.ajax({
        url: createUrl('contratos/moduloMobile'),
        type: 'POST',
        data: data,
        processData: false,
        contentType: false,
        success: function (data) {
            data = JSON.parse(data);
            if(data.mobile == 1) {
                $('#Contratos_COT_USUARIOS_MOBILE').parent().show();
            } else {
                $('#Contratos_COT_USUARIOS_MOBILE').val('');
                $('#Contratos_COT_USUARIOS_MOBILE').parent().hide();
            }
        }
    });
}
function StatusCliente(status) {
    switch (status) {
        case 'A':
            return 'Cliente Ativo';
        break;      
        case 'I':
            return 'Cliente Inativo';
        break;   
        case 'FN':
            return 'Fechamento Negativo';
        break; 
        case 'FP':
            return 'Fechamento Positivo';
        break;      
        case 'N':
            return 'Em Negociação';
        break;   
        case 'NP':
            return 'Negociação Postergada';
        break; 
        case 'P':
            return 'Prospecto';
        break; 
        case 'AG':
            return 'Aguardando';
        break; 
        case 'O':
            return 'Outros';
        break; 
        case 'AI':
            return 'Aguardando Inativação';
        break; 
        case 'D':
            return 'Demonstração';
        break; 
        case 'CV':
            return 'Cliente Conveniado';
        break; 
        default:
            return status;
    }
}

function TipoCliente(tipo) {
    switch (tipo) {
        case 'C':
            return 'Contador';
        break;      
        case 'E':
            return 'Entidades de Classe';
        break;   
        case 'S':
            return 'Escola';
        break; 
        case 'F':
            return 'Física';
        break; 
        case 'J':
            return 'Jurídica';
        break; 
        case 'P':
            return 'Parceiro';
        break; 
        case 'R':
            return 'Produtor Rural';
        break; 
        case 'A':
            return 'Aguardando';
        break; 
        default:
            return tipo;
    }
}
function JustificativaObrigatoria() {
    var data = new FormData();
    fields = $('#contratos-form').serializeArray();
    $.each(fields, function(i, field){
        data.append(field.name, field.value);
    });
    $.ajax({
        url: createUrl('contratos/DynamicJustificativaObrigatoria'),
        type: 'POST',
        data: data,
        processData: false,
        contentType: false,
        success: function (data) {
            if(data == 1) {
                if (
                    $('#labelJustificativa').siblings('.required').length == 0 &&
                    $('#labelJustificativa').children('.required').length == 0
                ) {
                    $('#labelJustificativa').html('Justificativa <span class="required">*</span>');
                }
            } else {
                $('#labelJustificativa').html('Justificativa');
            }
        }
    });
}
function addPrint() {
    $.ajax({
        url: createUrl('prints/form'),
        type: 'GET',
        success: function (data) {
            $('#prints').append(data);
        }
    });
}
function addArquivo() {
    $.ajax({
        url: createUrl('arquivos/inputs'),
        type: 'GET',
        success: function (data) {
            $('#arquivos').append(data);
            $('#arquivos').find('input[type=file]:last').focus();
        }
    });
}
function removerArquivo(id) {
    if(confirm('Tem certeza que deseja excluir este arquivo?')) {
        $("#arquivo" + id).remove();
    } else {
        $(this).parents('.arquivo_form').find('input[type=file').focus();
    }
    return false;
}
function removerPrint(id) {
    $("#print" + id).remove();
}
function getBaseUrl() {
    return $('input[name=base_uri]').val();
}
function createUrl(action, params) {
    if(params === undefined || params === "") {
        params = {};
    }
    var url = getBaseUrl() + '/index.php?r=' + action;
    
    params = $.param(params);
    return params.length > 0 ? url + '&'+ params : url;
}
function createAssetsUrl(asset) {
    return getBaseUrl() + '/' + asset;
}
function horaCorreta(id) {
    $('#'+id).mask('00:00', {clearIfNotMatch: true});
    $('#'+id).blur(function () {
        if($(this).val() != '') {
            var hora = $(this).val().split(":");
            if (hora[0] > 24) hora[0] = 24;
            if(hora[1] > 59) hora[1] = 59;
            $(this).val(hora[0] + ':' + hora[1]);
        }
    });
}
function FormataHoraTrabalhada(id, reverse) {
    if(reverse == true) {
        $('#'+id).mask('##00:00', {reverse: true, clearIfNotMatch: true});
    }  else {
        $('#'+id).mask('00:00', {clearIfNotMatch: true});
    }
    $('#'+id).blur(function () {
        if($(this).val() != '') {
            var hora = $(this).val().split(":");
            if(hora[1] > 59) hora[1] = 59;
            $(this).val(hora[0] + ':' + hora[1]);
        }
    });
}
function getLabel(id) {
    var label = $('label[for="'+id+'"]');
    if(label.length <= 0) {
        var parentElem = $(this).parents('label');

        if(parentElem.length > 0) {
            label = parentElem;
        }
    }

    if(label.length <= 0) {
        var parentElem = $(this).parent();

        if(parentElem.find('label').length > 0) {
            label = parentElem.find('label');
        }
    }
    return label;
}
function getLabelText(id) {
    var label = getLabel(id);
    var labelText = label.text();
    labelText = labelText.replace('*', '');
    return $.trim(labelText);
}
function compareTime(begin, end, operator) {
    if(operator == '') {
        operator = '>';
    } else if(operator != '<' && operator != '>' && operator != '>=' && operator != '<=') {
        operator = '>';
    }
    var begin_label = getLabelText($(begin).prop('id'));
    var operatorText;

    var error = false;

    if($(begin).val() != '' && $(end).val() != '') {
        var horaInicial = Number($(begin).val().split(':')[0]);
        var minutoInicial = Number($(begin).val().split(':')[1]);
        var horaFinal = Number($(end).val().split(':')[0]);
        var minutoFinal = Number($(end).val().split(':')[1]);

        if(operator == '>') {
            operatorText = 'maior que';
            if(horaInicial > horaFinal) {
                error = true;
            } else if (horaInicial == horaFinal && minutoInicial > minutoFinal) {
                error = true;
            }
        } else if(operator == '<') {
            operatorText = 'menor que';
            if(horaInicial < horaFinal) {
                error = true;
            } else if (horaInicial == horaFinal && minutoInicial < minutoFinal) {
                error = true;
            }
        } else if(operator == '>=') {
            operatorText = 'maior ou igual a';
            if(horaInicial > horaFinal) {
                error = true;
            } else if (horaInicial == horaFinal && minutoInicial >= minutoFinal) {
                error = true;
            }
        } else if(operator == '<=') {
            operatorText = 'menor ou igual a';
            if(horaInicial < horaFinal) {
                error = true;
            } else if (horaInicial == horaFinal && minutoInicial <= minutoFinal) {
                error = true;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }

    var row;
    if($(begin).parents('.form-group').length != 0) {
        row = $(begin).parents('.form-group');
    } else {
        row = $(begin).parents('.row');
    }

    if(error) {
        var message = begin_label+' não pode ser '+operatorText+' "'+$(end).val()+'".';

        $(begin).removeClass("error");
        $(row).find(".time-validation").remove();

        $(begin).addClass("error");
        $(row).append("<div class=\"errorMessage time-validation\">"+message+"</div>");
    } else {
        $(begin).removeClass("error");
        $(row).find(".time-validation").remove();
    }
}
function PendenciasAtividades() {
    var offsetLeft =  $(".frm_col.col_1").width();
    var parentWidth = $('.frm_col.col_2').parent("form").width();
    var width = parentWidth - offsetLeft;
    if(width < 450)
        width = "100%";
    $('.frm_col.col_2').css({
        width: width
    });
}
function btnSearchScroll() {
    var scrollTop = $(window).scrollTop();
    var offsetTop = $(".search-form").offset().top - 60;
    var offsetBottom = offsetTop + $(".search-form").height() - 80;
    var btn = $(".search-form").find("#search_button");
    if ($(".search-form").children('.form').hasClass('large-sections')) {
        var leftOffset = 864;
    } else {
        var leftOffset = 664;
    }
    btn.css({
        left: leftOffset,
    });

    if ((leftOffset + btn.width()) < $(window).width()) {
        if(scrollTop > offsetBottom) {
            btn.css({
                position: "absolute",
                top: 130
            });
        } else if(scrollTop > offsetTop) {
            btn.css({
                position: "fixed",
                top: 130,
            });
        } else {
            btn.css({
                position: "fixed",
                top: 130,
            });
        }
    } else {
        if((scrollTop + $(window).height()) > (offsetBottom + 160)) {
            btn.css({
                position: "absolute",
                top: offsetBottom + 30,
                left: ($(window).width() / 2 - btn.width() / 2)
            });
        } else {
            btn.css({
                position: "fixed",
                top: offsetTop,
                left: ($(window).width() / 2 - btn.width() / 2)
            });
        }
    }
    if(btn.attr("name") == "yt1") {
        parent = $(document).find("#yw3");
        var offsetTop = parent.offset().top + parent.height() + 39;
        btn.css({
            position: "absolute",
            top: offsetTop
        });
    }
}
function reloadFrame() {
    updateUrl($('input[name="frame_src"]').val());
    if(parent.frames["workFrame"] != undefined) {
        parent.frames["workFrame"].location.href = $('input[name="frame_src"]').val();
    } else {
        window.location.href = $('input[name="frame_src"]').val();
    }
}
function redir(url) {
    if(parent.frames["workFrame"] != undefined) {
        parent.frames["workFrame"].location.href = url;
    } else {
        window.location.href = url;
    }
}
function focusSearch() {
    if($(".search-form").css('display') != 'none') {
        if($('.focus_toggle').length > 0) {
            $('.focus_toggle').first().focus();
        } else {
            $('.search-form').find('select, input[type=text]').first().focus();
        }
    }
}
function updateUrl(params) {

    if(params.indexOf('://') == -1) {
        var urn = $('input[name="base_urn"]').val();
        var uri = getBaseUrl();

        if(urn != '/' && params.indexOf(urn) != -1 && uri.indexOf(urn) != -1) {
            params = params.replace(urn, "");
        }

        while(params.indexOf('/index.php') != -1) {
            params = params.replace("/index.php", "index.php");
        }

        params = uri + params;
    }
    $('input[name="frame_src"]').val(params);
    $('.update_url').each(function() {
        var href = params.replace($(this).data('url'), $(this).data('replace'));
        $(this).prop('href', href);
    });
    if($("#abrir_telacheia").length > 0){
        $("#abrir_telacheia").prop('href', params.replace("atendimentos/tecnico", "atendimentos/telacheia").replace("atendimentos%2Ftecnico", "atendimentos/telacheia"));
    }
    return params;
}
function updated() {
    $("html, body").animate({ scrollTop: 0 }, "slow");
    $("#admin-grid > table").stickyTableHeaders({fixedOffset: 130});
    $('#admin-grid > table').find('.tableFloatingHeaderOriginal').delegate('a', 'click', function() {
        updateUrl($(this).prop('href'));
        return true;
    });
    $(document).delegate('.pager a', 'click', function() {
        updateUrl($(this).prop('href'));
        return true;
    });
    if($('.search-form').css("display") == 'none') {
        $(".search-form").find("#search_button").hide();
        $(".summary").show();
    } else if($('.search-form').css("display") != 'none') {
        $(".summary").hide();
        $(".search-form").find("#search_button").show();
    }
    if($(".tool_tip").length !== 0) {
        try {
            $(".tool_tip").qtip({position:{my: "middle left", at:"middle right",viewport:$(window)},style:{tip:{corner:true}}});
        } catch(e) {
            console.log('Erro: '. e);
        }
    }
    $(document).ready(function(){
        $('[data-toggle="tooltip"]').tooltip();
    });
    if($('.grid-view.scrollable').length > 0) {
        $('.grid-view.scrollable table').on('scroll', scrollableTableSize);
        $(window).on('scroll', scrollableTableSize);
        $(window).on('resize', scrollableTableSize);
        $(document).on('ready', scrollableTableSize);
        scrollableTableSize();
    }
    
    if($('#form_envio').hasClass('ignore-hide-on-empty')) {
        $('#form_envio').removeClass('ignore-hide-on-empty');
    } else {
        if($(document).find('.show-search-on-empty').length > 0 || $(document).find('#admin-grid .no-results').length > 0) {
            var form = document.querySelector("div#form_envio");
            if (form != null) {
                form.style.display = "block";
            }
        }
    }
}
function toggleSearch() {
    if($('.search-form').css("display") != 'none') {
        $(".search-form").find("#search_button").hide();
        $(".summary").show();
        $(document).find(".tableFloatingHeaderOriginal").removeClass('search_open');
    } else if($('.search-form').css("display") == 'none') {
        $(".summary").hide();
        $(".search-form").find("#search_button").show();
        $(document).find(".tableFloatingHeaderOriginal").addClass('search_open');
    }
    $(document).find('table').stickyTableHeaders('destroy');
    $("html, body").animate({ scrollTop: 0 }, "slow");
    $('.search-form').slideToggle('slow', function() {
        if($('#form_envio').length > 0) {
            $('#form_envio').addClass('ignore-hide-on-empty');
        }
        updated();
        focusSearch();
    });

    $(".search-form").find("#search_button").removeAttr('disabled').prop('disabled', false).html("<i class='fa fa-search'></i>Pesquisar");
}
$(document).ready(function() {
    if($(".search-form").length > 0 && !($(".form > .search-form").length > 0 )) {
        btnSearchScroll();
        $(window).scroll(btnSearchScroll);
        $(window).resize(btnSearchScroll);

        $(document).delegate('.search-button', 'click', function() {
            toggleSearch();
            btnSearchScroll();
            return false;
        });
        $('.search-form form').on('submit', function() {

            $('.keys').prop("title", "index.php?" + $(this).serialize());
            updateUrl("/index.php?" + $(this).serialize());
            toggleSearch();
            if($('.grid-view').length) {
                $.fn.yiiGridView.update($('.grid-view').prop('id'), {
                    data: $(this).serialize()
                });
            } else {
                return true;
            }
            return false;
        });
        if($(".search-form").css('display') != 'none')
            focusSearch();
    }
    if($('.pager a').length > 0) {
        $(document).delegate('.pager a', 'click', function() {
            if($('.search-form').css("display") != 'none') {
                $(".search-form").find("#search_button").hide();
                $('.search-form').slideToggle();
            }
            updateUrl($(this).prop('href'));
            if($('#form_envio').length > 0) {
                $('#form_envio').addClass('ignore-hide-on-empty');
            }
            updated();
            return true;
        });
    } else {
        $(".summary").css({bottom: 0});
    }
});
$(document).ready(function() {
    $(document).find("#admin-grid > table").stickyTableHeaders({fixedOffset: 130});
    $('#admin-grid > table').find('.tableFloatingHeaderOriginal').delegate('a', 'click', function() {
        updateUrl($(this).prop('href'));
        return true;
    });
});
var animationController = function animationController() {
    var timeout = null;
    var delayBy = 200;

    var pub = {};

    var actualAnimationStart = function actualAnimationStart() {
        if(!$("#loading").hasClass("false") && $(".select2-active").length == 0) {
            $('#loading').show();
        }
    };

    var actualAnimationStop = function actualAnimationStop() {
        $('#loading').removeClass('false');
        $('#loading').hide();
        if($('.pager a').length == 0)
            $(".summary").css({bottom: 0});
    };

    pub.startAnimation = function animationController$startAnimation()  {
        timeout = setTimeout(actualAnimationStart, delayBy);
    };

    pub.stopAnimation = function animationController$stopAnimation() {
        clearTimeout(timeout);
        actualAnimationStop();
    }
    return pub;
}();

$(document).ready(function() {
    $(document).ajaxStart(animationController.startAnimation);
    $(document).ajaxStop(animationController.stopAnimation);
});

$(document).ready(function() {
    $('img[src="'+getBaseUrl()+'/assets_custom/img/blank.gif"]').parent('a').remove();
});
$(document).ready(function() {
    $('.maskMoeda').mask('000.000.000.000.000,00', {reverse: true});
    $(".maskMoedaAllowNegative").maskMoney({
        allowNegative: true,
        allowZero: true,
        thousands:'.',
        decimal:',',
        affixesStay: false
    });
    var SPMaskBehavior = function (val) {
      return val.replace(/\D/g, '').length === 11 ? '(00)00000-0000' : '(00)0000-00009';
    },
    spOptions = {
        clearIfNotMatch: true,
        onKeyPress: function(val, e, field, options) {
            field.mask(SPMaskBehavior.apply({}, arguments), options);
        }
    };
    $('.mask_telefone').mask(SPMaskBehavior, spOptions);

    var SPMaskBehaviorFiltro = function (val) {
        var length = val.replace(/\D/g, '').length;
        if(length < 9)
            return '0000-00009';
        if(length === 9)
            return '00000-00009';
        if(length === 10)
            return '(00)0000-00009';
        return '(00)00000-0000';
    },
    spOptions = {
        onKeyPress: function(val, e, field, options) {
            field.mask(SPMaskBehaviorFiltro.apply({}, arguments), options);
        }
    };

    $('.mask_telefone_filtro').mask(SPMaskBehaviorFiltro, spOptions);
    $('.mask-cpf').mask('000.000.000-00', {clearIfNotMatch: true});
    $('.mask-cnpj').mask('00.000.000/0000-00', {clearIfNotMatch: true});
    if($('.mask-cnpjcpf').length > 0) {
        var options =  {
            onKeyPress: function(doc, e, field, options){
              var masks = ['000.000.000-009', '00.000.000/0000-00'];
                mask = (doc.length<15) ? masks[0] : masks[1];
              $('.mask-cnpjcpf').mask(mask, options);
            },
            clearIfNotMatch: true
        };
        if($('.mask-cnpjcpf').val().length > 14) {
            $('.mask-cnpjcpf').mask('00.000.000/0000-00', options);
        } else {
            $('.mask-cnpjcpf').mask('000.000.000-009', options);
        }
    }

    $('#Atendimentos_ATD_HORASIMPLANTACAO').mask('00:00', {clearIfNotMatch: true});
});
$(document).on('click', '.close-alert', function(event) {
    $(this).parent().hide();
});
jQuery.extend (String.prototype, {
    camelize: function () {
        return this.replace(/(?:^|\s)\w/g, function(match) {
            return match.toUpperCase();
        });
    },
    toUserName: function() {
        var name = $.trim(this).toLowerCase().split(" ");
        if(name.length == 0) {
          return;
        }
        if(name.length == 1) {
          return name[0].removeNonAlpha().removeDiacritics();
        }
        return name[0].removeDiacritics().removeNonAlpha() + '.' + name[name.length-1].removeDiacritics().removeNonAlpha();
    },
    removeDiacritics: function () {
        changes = defaultDiacriticsRemovalMap;
        var newStr = this;
        for(var i=0; i<changes.length; i++) {
            var newStr = newStr.replace(changes[i].letters, changes[i].base);
        }
        return newStr;
    },
    removeNonAlpha: function() {
        var str = this;
        str = str.replace(/[^a-zA-Z]+/g, '');
        return str;
    }
});
$(document).ready(function() {
    $(".mailtolower").blur(function() {
      $(this).val($.trim($(this).val().toLowerCase().removeDiacritics()));
    });
});
var defaultDiacriticsRemovalMap = [
    {'base':'A', 'letters':/[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g},
    {'base':'AA','letters':/[\uA732]/g},
    {'base':'AE','letters':/[\u00C6\u01FC\u01E2]/g},
    {'base':'AO','letters':/[\uA734]/g},
    {'base':'AU','letters':/[\uA736]/g},
    {'base':'AV','letters':/[\uA738\uA73A]/g},
    {'base':'AY','letters':/[\uA73C]/g},
    {'base':'B', 'letters':/[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g},
    {'base':'C', 'letters':/[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g},
    {'base':'D', 'letters':/[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g},
    {'base':'DZ','letters':/[\u01F1\u01C4]/g},
    {'base':'Dz','letters':/[\u01F2\u01C5]/g},
    {'base':'E', 'letters':/[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g},
    {'base':'F', 'letters':/[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g},
    {'base':'G', 'letters':/[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g},
    {'base':'H', 'letters':/[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g},
    {'base':'I', 'letters':/[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g},
    {'base':'J', 'letters':/[\u004A\u24BF\uFF2A\u0134\u0248]/g},
    {'base':'K', 'letters':/[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g},
    {'base':'L', 'letters':/[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g},
    {'base':'LJ','letters':/[\u01C7]/g},
    {'base':'Lj','letters':/[\u01C8]/g},
    {'base':'M', 'letters':/[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g},
    {'base':'N', 'letters':/[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g},
    {'base':'NJ','letters':/[\u01CA]/g},
    {'base':'Nj','letters':/[\u01CB]/g},
    {'base':'O', 'letters':/[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g},
    {'base':'OI','letters':/[\u01A2]/g},
    {'base':'OO','letters':/[\uA74E]/g},
    {'base':'OU','letters':/[\u0222]/g},
    {'base':'P', 'letters':/[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g},
    {'base':'Q', 'letters':/[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g},
    {'base':'R', 'letters':/[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g},
    {'base':'S', 'letters':/[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g},
    {'base':'T', 'letters':/[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g},
    {'base':'TZ','letters':/[\uA728]/g},
    {'base':'U', 'letters':/[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g},
    {'base':'V', 'letters':/[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g},
    {'base':'VY','letters':/[\uA760]/g},
    {'base':'W', 'letters':/[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g},
    {'base':'X', 'letters':/[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g},
    {'base':'Y', 'letters':/[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g},
    {'base':'Z', 'letters':/[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g},
    {'base':'a', 'letters':/[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g},
    {'base':'aa','letters':/[\uA733]/g},
    {'base':'ae','letters':/[\u00E6\u01FD\u01E3]/g},
    {'base':'ao','letters':/[\uA735]/g},
    {'base':'au','letters':/[\uA737]/g},
    {'base':'av','letters':/[\uA739\uA73B]/g},
    {'base':'ay','letters':/[\uA73D]/g},
    {'base':'b', 'letters':/[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g},
    {'base':'c', 'letters':/[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g},
    {'base':'d', 'letters':/[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g},
    {'base':'dz','letters':/[\u01F3\u01C6]/g},
    {'base':'e', 'letters':/[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g},
    {'base':'f', 'letters':/[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g},
    {'base':'g', 'letters':/[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g},
    {'base':'h', 'letters':/[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g},
    {'base':'hv','letters':/[\u0195]/g},
    {'base':'i', 'letters':/[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g},
    {'base':'j', 'letters':/[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g},
    {'base':'k', 'letters':/[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g},
    {'base':'l', 'letters':/[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g},
    {'base':'lj','letters':/[\u01C9]/g},
    {'base':'m', 'letters':/[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g},
    {'base':'n', 'letters':/[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g},
    {'base':'nj','letters':/[\u01CC]/g},
    {'base':'o', 'letters':/[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g},
    {'base':'oi','letters':/[\u01A3]/g},
    {'base':'ou','letters':/[\u0223]/g},
    {'base':'oo','letters':/[\uA74F]/g},
    {'base':'p','letters':/[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g},
    {'base':'q','letters':/[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g},
    {'base':'r','letters':/[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g},
    {'base':'s','letters':/[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g},
    {'base':'t','letters':/[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g},
    {'base':'tz','letters':/[\uA729]/g},
    {'base':'u','letters':/[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g},
    {'base':'v','letters':/[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g},
    {'base':'vy','letters':/[\uA761]/g},
    {'base':'w','letters':/[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g},
    {'base':'x','letters':/[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g},
    {'base':'y','letters':/[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g},
    {'base':'z','letters':/[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g}
];
function selectField(field, options) {
    if(options == null || options.length == 0)
        return;
    if(jQuery.isArray(options)) {
        $(options).each(function(index, el) {
            $('#' +field+' option[value='+el+']').prop('selected', true);
        });
    } else {
        $('#' +field+' option[value='+options+']').prop('selected', true);
    }
}
$(document).ready(function() {
    $('.toggle_atendimentos_update').click(function() {
        event.preventDefault();
        $('.'+$(this).data('toggle')).toggle();
        return false;
    });
    $('.toggle_historico_alteracoes').click(function() {
        event.preventDefault();
        $('.'+$(this).data('toggle')).toggle();
        return false;
    });
});
function scrollableTableSize() {
    $(".grid-view.scrollable table > *").width($(".grid-view.scrollable table").width() + $(".grid-view.scrollable table").scrollLeft());
    $(".grid-view.scrollable table > tbody").height($(window).height() - 215);
}
$(document).ready(function() {
    if($('.grid-view.scrollable').length > 0) {
        $('.grid-view.scrollable table').on('scroll', scrollableTableSize);
        $(window).on('scroll', scrollableTableSize);
        $(window).on('resize', scrollableTableSize);
        $(document).on('ready', scrollableTableSize);
    }
});

$(document).ready(function(){

    var exportar = $(".exportar");
    var csv = $(".exportarCsv");
    var txt = $(".exportarTxt");
    var pdf = $(".exportarPdf");

    exportar.on('click', function(e){

        var frame = $("input[name=frame_src]").val();
        $(this).attr('href', frame+"&exportar=1");
        $(this).css('pointer-events', 'none');
        $('html').css('cursor', 'wait');

        setTimeout(function(){
            $('.exportar').css('pointer-events', 'auto');
        }, 30000);

        setTimeout(function(){
            $('html').css('cursor', 'default');
        }, 10000);
    });

    $(document).on("mousedown", '.exportar', function(e) {
        if (e.which == 2) {
            e.preventDefault();
            e.stopPropagation();
            alert("Comando inválido!");
            return false;
        } else {
            return true;
        }
    });

    csv.on('click', function(){
        var frame = $("input[name=frame_src]").val();
        $(this).attr('href', frame+"&exportar=1&format=csv");

        $(this).css('pointer-events', 'none');
        $('html').css('cursor', 'wait');

        setTimeout(function(){
            $('.exportarCsv').css('pointer-events', 'auto');
        }, 10000);

        setTimeout(function(){
            $('html').css('cursor', 'default');
        }, 5000);
    });

    $(document).on("mousedown", '.exportarCsv', function(e) {
        if (e.which == 2) {
            e.preventDefault();
            e.stopPropagation();
            alert("Comando inválido!");
            return false;
        } else {
            return true;
        }
    });

    txt.on('click', function(){

        var frame = $("input[name=frame_src]").val();
        $(this).attr('href', frame+"&exportar=1&format=txt");

        $(this).css('pointer-events', 'none');
        $('html').css('cursor', 'wait');

        setTimeout(function(){
            $('.exportarTxt').css('pointer-events', 'auto');
        }, 10000);

        setTimeout(function(){
            $('html').css('cursor', 'default');
        }, 5000);
    });

    $(document).on("mousedown", '.exportarTxt', function(e) {
        if (e.which == 2) {
            e.preventDefault();
            e.stopPropagation();
            alert("Comando inválido!");
            return false;
        } else {
            return true;
        }
    });

    pdf.on('click', function(){

        var frame = $("input[name=frame_src]").val();
        $(this).attr('href', frame+"&exportar=1&format=pdf");

        $(this).css('pointer-events', 'none');
        $('html').css('cursor', 'wait');

        setTimeout(function(){
            $('.exportarPdf').css('pointer-events', 'auto');
        }, 30000);

        setTimeout(function(){
            $('html').css('cursor', 'default');
        }, 10000);
    });

    $(document).on("mousedown", '.exportarPdf', function(e) {
        if (e.which == 2) {
            e.preventDefault();
            e.stopPropagation();
            alert("Comando inválido!");
            return false;
        } else {
            return true;
        }
    });
});

function createUID() {
    // http://www.ietf.org/rfc/rfc4122.txt
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23];

    var uuid = s.join("");
    return uuid;
}

$(document).on("change", "input[type='file']", function () {
    var fileInput = $(this);
    var maxSize = fileInput.data('max-size');
    if (maxSize != undefined && maxSize != '') {
        if (fileInput.get(0).files.length){
            var fileSize = fileInput.get(0).files[0].size;
            if (fileSize > maxSize) {
                alert('Os arquivos anexados não podem ter mais de 15 MB!');
                fileInput.val("");
                return false;
            }
        } else {
            return false;
        }
    }
});