﻿function jsevento(evento) {
    form1.disabled = false;
    document.getElementById("ProximoEvento").value = "";
    document.getElementById("ProximoFocus").value = "";
    document.getElementById("NomeEvento").value = evento;
    document.getElementById("NomeEventoAjax").value = "";
    document.getElementById("Ajax1").value = "";
    document.getElementById("Ajax2").value = "";
    document.getElementById("Ajax3").value = "";
    document.getElementById("Ajax4").value = "";
    document.getElementById("Ajax5").value = "";
}

function apagaIncluir() {
    for (var i = 0; i < document.all.length; i++) {
        if (document.all[i].id == "BtIncluir") {
            document.all[i].style.display = 'none';
        }
    }
}
function janelaFormLocal(Titulo, Width, Height, Url) {
    $("#dialog_janela").dialog({ resizable: true, width: Width, height: Height, modal: true, title: Titulo,
        closeOnEscape: false,
        //open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); },
        beforeClose: function (event, ui) {
            if (document.getElementById('Janela').src.indexOf("Cadastro") != -1) {
                try {
                    window.frames['Janela'].evento("Voltar");
                    return false;
                }
                catch (e)
                    { }
            } else {
                document.getElementById('Janela').src = 'branco.htm';
            }
        }
    });
    $('#dialog_janela').data('title.dialog', Titulo);
    document.getElementById('Janela').src = Url + "&TipoJanela=S";
}
function janelaFormAtualizaLocal(Titulo, Width, Height, Url, Evento) {
    $("#dialog_janela").dialog({ resizable: true, width: Width, height: Height, modal: true, title: Titulo,
        closeOnEscape: false,
        //open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); },
        beforeClose: function (event, ui) {
            if (document.getElementById('Janela').src.indexOf("Cadastro") != -1) {
                try {
                    window.frames['Janela'].evento("Voltar");
                    return false;
                }
                catch (e)
                    { }
            } else {
                document.getElementById('Janela').src = 'branco.htm';
                eval(Evento);
            }
        }
    });
    $('#dialog_janela').data('title.dialog', Titulo);
    document.getElementById('Janela').src = Url + "&TipoJanela=S";
}
function janelaTexto(Width, Height, Componente) {
    document.getElementById("texto_Janela").onkeydown = document.getElementById(Componente.value).onkeydown;
    document.getElementById('texto_Janela').value = document.getElementById(Componente.value).value;
    document.getElementById('texto_Janela').style.width = (Width - 30) + "px";
    document.getElementById('texto_Janela').style.height = (Height - 85) + "px";
    $("#dialog_texto").dialog({ resizable: true, width: Width, height: Height, modal: true, title: 'Texto',
        closeOnEscape: false,
        //open: function (event, ui) { $(".ui-dialog-titlebar-close").hide(); },
        buttons: {
            'Cancela': function () {
                $(this).dialog('close');
            },
            'Confirma': function () {
                document.getElementById(Componente.value).value = document.getElementById('texto_Janela').value;
                $(this).dialog('close');
            }
        }
    });
}

function maxLength(ta, limit) {
    if (ta.value.length >= limit) {
        ta.value = ta.value.substring(0, limit - 1);
    }
}



function janelaMensagensLocal(Titulo, Mensagem, Evento) {
    $(function () {
        $("#dialog_confirm").dialog({
            resizable: false, width: 700, modal: true,
            buttons: {
                " Ok ": function () {
                    if (Evento != "") { eval(Evento); };
                    $(this).dialog("close");
                }
            }
        });
    });
    document.getElementById('dialog_confirm').title = Titulo;
    document.getElementById('dialog_message').innerHTML = Mensagem;
}


function VoltarJanela() {
    document.getElementById('Janela').src = '';
    $("#dialog_janela").dialog('close');
}

function acionaHelp(help) {
    document.getElementById("NomeEvento").value = help;
    document.getElementById("NomeEventoAjax").value = 'HELP';
    __doPostBack('UpdatePanel2', '');
    LoadCarrega();
}

function LogOff(msg) {
    if (document.getElementById("menuInicial") != null) {
        LogOffMenu(msg);
    } else
        if (parent.document.getElementById("menuInicial") != null) {
            parent.LogOffMenu(msg);
        }
        else {
            parent.LogOff(msg);
        }
}

function AcionaJanelaOpcao(opcao, titulo, width, height, evento) {
    if (opcao != "") {
        arrayCampo = opcao.split(';');
        if (arrayCampo.length == 1) {
            var nomeConsulta = arrayCampo[0];
            if (nomeConsulta.indexOf('?') != -1) {
                if ((evento != null) && (evento != ""))
                    janelaFormAtualizaLocal(titulo, width, height, "../" + nomeConsulta + "&" + "IDSESSAO=" + GetIdSessao() + "&WidthGrid=" + width, evento);
                else
                    if (document.getElementById("TipoJanela").value == "S")
                        janelaFormLocal(titulo, width, height, "../" + nomeConsulta + "&" + "IDSESSAO=" + GetIdSessao() + "&WidthGrid=" + width);
                    else
                        janelaForm(titulo, width, height, "../" + nomeConsulta + "&" + "IDSESSAO=" + GetIdSessao() + "&WidthGrid=" + width);
            }
            else {
                if ((evento != null) && (evento != ""))
                    janelaFormAtualizaLocal(titulo, width, height, "../" + nomeConsulta + "&" + "IDSESSAO=" + GetIdSessao() + "&WidthGrid=" + width, evento);
                else
                    if (document.getElementById("TipoJanela").value == "S")
                        janelaFormLocal(titulo, width, height, "../" + nomeConsulta + "?" + "IDSESSAO=" + GetIdSessao() + "&WidthGrid=" + width);
                    else
                        janelaForm(titulo, width, height, "../" + nomeConsulta + "?" + "IDSESSAO=" + GetIdSessao() + "&WidthGrid=" + width);
            }
        } else {
            var nomeConsulta = "";
            var nomeFormulario = "";
            arrayCampo = opcao.split(';');
            if (arrayCampo.length == 2) {
                nomeConsulta = arrayCampo[0];
                nomeFormulario = arrayCampo[1];
            }
            else {
                nomeConsulta = arrayCampo[0];
            }
            if ((evento != null) && (evento != ""))
                janelaFormAtualizaLocal(titulo, width, height, "FrmConsultaFast.aspx?pagina=" + nomeConsulta + "&Formulario=" + nomeFormulario + "&IDSESSAO=" + GetIdSessao(), evento);
            else
                if (document.getElementById("TipoJanela").value == "S")
                    janelaFormLocal(titulo, width, height, "FrmConsultaFast.aspx?pagina=" + nomeConsulta + "&Formulario=" + nomeFormulario + "&IDSESSAO=" + GetIdSessao());
                else
                    janelaForm(titulo, width, height, "FrmConsultaFast.aspx?pagina=" + nomeConsulta + "&Formulario=" + nomeFormulario + "&IDSESSAO=" + GetIdSessao());
        }
    }
}

function CheckChange(obj) {
    if (obj.checked)
    { document.getElementById(obj.id + '_False').checked = false }
    else
    { document.getElementById(obj.id + '_False').checked = true };
}
function eventoAjax(evento) {
    document.getElementById("ProximoEvento").value = "";
    if (typeof (document.activeElement) != "unknown") {
        if (document.activeElement.nodeName == 'BUTTON') {
            if ((document.activeElement.attributes["OnClick"] != null) && (document.activeElement.attributes["OnClick"].nodeValue.indexOf("eventoAjax") == -1)) {
                document.getElementById("ProximoEvento").value = document.activeElement.attributes["OnClick"].nodeValue;
            }
            if ((document.activeElement.attributes["OnClick"] != null) && (document.activeElement.id == "BtCancelar")) {
                document.getElementById("ProximoEvento").value = document.activeElement.attributes["OnClick"].nodeValue;
            }
            document.getElementById("ProximoFocus").value = "";
        }
        else {
            if (document.getElementById("ProximoFocus").value != document.activeElement.id) {
                document.getElementById("ProximoFocus").value = document.activeElement.id;
            } else
                document.getElementById("ProximoFocus").value = "";
        }
    }
    else
        document.getElementById("ProximoFocus").value = "";
    document.getElementById("NomeEvento").value = evento;
    document.getElementById("NomeEventoAjax").value = evento;
    document.getElementById("Ajax1").value = "";
    document.getElementById("Ajax2").value = "";
    document.getElementById("Ajax3").value = "";
    document.getElementById("Ajax4").value = "";
    document.getElementById("Ajax5").value = "";
    if (evento == "Cancelar") {
        document.getElementById('BtCancelar').style.display = 'none';
        if ((document.getElementById('PosicaoAnt') != null) && (document.getElementById('PosicaoAnt').value != ""))
            document.getElementById('PosicaoGrid').value = document.getElementById('PosicaoAnt').value;
        //else
        //    document.getElementById("PosicaoGrid").value = "";
        document.getElementById("ProximoEvento").value = "";
        document.getElementById("StatusEdicao").value = 'N';
        document.getElementById("StatusNavega").value = '';
        evento = "Posiciona";
        document.getElementById("NomeEvento").value = evento;
        document.getElementById("NomeEventoAjax").value = evento;
    }
    if ((evento == "Incluir") && (document.getElementById("StatusEdicao").value == "S")) {
        document.getElementById("NomeEvento").value = evento;
        try {
            document.getElementById('dialog_alertjsmessage').innerHTML = msgEdicao1;
        } catch (E) {
            document.getElementById('dialog_alertjsmessage').innerHTML = 'Registro em Edição, as alterações não foram salvas, incluir um novo mesmo assim?';
        }
        $('#dialog_alertjs').dialog('open');
        return;
    }
    if ((evento == "Excluir") && (document.getElementById("StatusEdicao").value == "S")) {
        document.getElementById("NomeEvento").value = evento;
        try {
            document.getElementById('dialog_alertjsmessage').innerHTML = msgEdicao2;
        } catch (E) {
            document.getElementById('dialog_alertjsmessage').innerHTML = 'Registro em Edição, as alterações não foram salvas, excluir mesmo assim ?';
        }
        $('#dialog_alertjs').dialog('open');
        return;
    }
    else
        if (evento == "Excluir") {
            document.getElementById("NomeEvento").value = evento;
            try {
                document.getElementById('dialog_alertjsmessage').innerHTML = msgEdicao3;
            } catch (E) {
                document.getElementById('dialog_alertjsmessage').innerHTML = 'Confirma a exclusão do registro ?';
            }
            $('#dialog_alertjs').dialog('open');
            return;
        }
        else
            if (evento == "Deletar") {
                evento = "Excluir";
                document.getElementById("NomeEvento").value = evento;
                document.getElementById("NomeEventoAjax").value = evento;
            }
    if (evento == "Gravar") {
        if (document.getElementById("BtCancelar") != null) {
            document.getElementById('BtCancelar').style.display = 'none';
        }
        onSubmit();
    }
    if (evento == "Incluir") {
        document.getElementById("StatusEdicao").value = "S";
        document.getElementById('PosicaoAnt').value = document.getElementById('PosicaoGrid').value;
        document.getElementById("PosicaoGrid").value = "";
        if (document.getElementById('BtCancelar') != null)
            document.getElementById('BtCancelar').style.display = '';
    }
    __doPostBack('UpdatePanel2', '');
    LoadCarrega();
}



function SetUpperCase(sender, args) {
    sender._SetValue(args._newValue.toUpperCase());
}
function DisableGravar(sender) {
    if (document.getElementById("BtGravar") != null)
        document.getElementById("BtGravar").disabled = true;
}
function SetUpdate(sender) {
    if (document.getElementById("NomeConsulta") == null) {
        if (document.getElementById("BtIncluir") != null)
            document.getElementById("BtIncluir").disabled = true;
    }
    if (document.getElementById("BtExcluir") != null)
        document.getElementById("BtExcluir").disabled = true;
    if (document.getElementById("BtExcluirInd") != null)
        document.getElementById("BtExcluirInd").disabled = true;
    if (document.getElementById("BtGravar") != null)
        document.getElementById("BtGravar").disabled = false;
    if (document.getElementById("BAR_GridCadastro2") != null)
        document.getElementById("BAR_GridCadastro2").disabled = true;
    if (document.getElementById("GridCadastro2") != null)
        document.getElementById("GridCadastro2").disabled = true;
    if ((document.getElementById("BtCancelar") != null) && (document.getElementById("StatusEdicao").value != "S") && (document.getElementById('PosicaoAnt') != null)) {
        document.getElementById('PosicaoAnt').value = document.getElementById('PosicaoGrid').value;
        document.getElementById('BtCancelar').style.display = '';
    }
    if ((document.getElementById("BtCancelar") != null) && (document.getElementById("StatusEdicao").value == "S")) {
        document.getElementById('BtCancelar').style.display = '';
    }
    //for (var i = 0; i < document.all.length; i++) {
    //    if (document.all[i].name == 'BtExcluir')
    //        document.all[i].disabled = true;
    // }
    document.getElementById("StatusEdicao").value = "S";
    if (document.getElementById("StatusNavega") != null) {
        try {
            if (document.getElementById("StatusNavega").value != "A")
                OnChange();
        } catch (E) {
        }
        document.getElementById("StatusNavega").value = "A";
    }
}

function DesabilitarCampos() {
    for (var i = 0; i < document.all.length; i++) {
        if ((document.all[i].type == "text") ||
                (document.all[i].type == "textarea") ||
                (document.all[i].type == "select-one") ||
                (document.all[i].type == "checkbox") ||
                (document.all[i].type == "radio")) {
            document.all[i].disabled = true;
        }
    }
}

function GetIdSessao() {
    if ((document.getElementById('IDSESSAO') != null) && (document.getElementById('IDSESSAO').value != "")) {
        return document.getElementById('IDSESSAO').value;
    }
    else
        if ((parent.document.getElementById('IDSESSAO') != null) && (parent.document.getElementById('IDSESSAO').value != "")) {
            return parent.document.getElementById('IDSESSAO').value;
        }
    return '0';
}

function OnLoadForm1() {
    if ((document.getElementById('IDSESSAO') != null) && (document.getElementById('IDSESSAO').value != "")) {
        document.getElementById('IDSESSAO').value = GetIdSessao()
    }
}

function criaMascara(_RefObjeto, _Modelo) {
    var valorAtual = _RefObjeto.value;
    var valorNumerico = '';
    var nIndexModelo = 0;
    var nIndexString = 0;
    var valorFinal = '';
    var adicionarValor = true;
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) != '#') {
            valorAtual = valorAtual.replace(_Modelo.substr(i, 1), '');
        }
    }
    for (i = 0; i < valorAtual.length; i++) {
        if (!isNaN(parseFloat(valorAtual.substr(i, 1)))) {
            valorNumerico = valorNumerico + valorAtual.substr(i, 1);
        }
    }
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) == '#') {
            if (valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + valorNumerico.substr(nIndexModelo, 1);
                nIndexModelo++; nIndexString++;
            } else {
                adicionarValor = false;
            }
        } else {
            if (adicionarValor && valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + _Modelo.substr(nIndexString, 1)
                nIndexString++;
            }
        }
    }
    if (valorAtual != valorFinal)
        _RefObjeto.value = valorFinal;
}
function ChecaData(data) {
    var err = 0;
    string = data;
    if (string.length == 0) {
        return true;
    }
    var valid = "0123456789/";
    var ok = "yes";
    var temp;
    for (var i = 0; i < string.length; i++) {
        temp = "" + string.substring(i, i + 1);
        if (valid.indexOf(temp) == "-1") {
            err = 1;
        }
    }
    if (string.length != 10) {
        err = 1;
    }
    dia = string.substring(0, 2); // dia
    c = string.substring(2, 3); // '/'
    mes = string.substring(3, 5); // mes
    e = string.substring(5, 6); // '/'
    ano = string.substring(6, 10); // ano
    if (mes < 1 || mes > 12) {
        err = 1;
    }
    if (c != '/') {
        err = 1;
    }
    if (dia < 1 || dia > 31) {
        err = 1;
    }
    if (e != '/') {
        err = 1;
    }
    if (ano.length != 4) {
        err = 1;
    }
    if (mes == 4 || mes == 6 || mes == 9 || mes == 11) {
        if (dia == 31) {
            err = 1;
        }
    }
    if (mes == 2) {
        var g = parseInt(ano / 4);
        if (isNaN(g)) {
            err = 1;
        }
        if (dia > 29) {
            err = 1;
        }
        if (dia == 29 && ((ano / 4) != parseInt(ano / 4))) {
            err = 1;
        }
    }
    if (ano < 1900) {
        err = 1;
    }
    if (err == 1) {
        return false;
    } else {
        return true;
    }
}

function testedataAnt(CAMPO, data) {
    if (ChecaData(data.value)) {
        return true;
    } else {
        alert("Data inválida.");
        data.value = "";
        data.focus();
    }
}

function testedata(data) {
    if (ChecaData(data.value)) {
        return true;
    } else {
        alert("Data inválida.");
        data.value = "";
        data.focus();
    }
}


function movevalorcombo(Campo1, Campo2) {
    var conteudo = Campo1;
    var valor = conteudo.substring(0, conteudo.indexOf(";"));
    var descr = conteudo.substring(conteudo.indexOf(";") + 1, conteudo.length);
    document.all[Campo2].value = valor;
    document.all["D" + Campo2].value = descr;
}
function mostraapagacombo(Campo, mostra) {
    //     document.all["V_"+Campo].style.top  = document.all["D"+Campo].offsetTop + 20;
    //     document.all["V_"+Campo].style.left = document.all["D"+Campo].offsetLeft;

    document.all["V_" + Campo].style.width = document.all["D" + Campo].offsetWidth;
    document.all["S" + Campo].style.width = document.all["D" + Campo].offsetWidth;
    if (mostra == 0)
        document.all["V_" + Campo].style.display = "none"
    else
        document.all["V_" + Campo].style.display = "";
}

function carregacombo(Campo) {
    if (document.all["S" + Campo] != null) {
        var conteudo = document.all["S" + Campo].value;
        var valor = conteudo.substring(0, conteudo.indexOf(";"));
        var descr = conteudo.substring(conteudo.indexOf(";") + 1, conteudo.length);
        if (descr != document.all["D" + Campo].value) {
            eventoAjax(Campo);
        } else {
            mostraapagacombo(Campo, 1);
            document.all["S" + Campo].focus();
        }
    } else {
        eventoAjax(Campo);
    }

}

function PutCents(numero, tamanho) {

    if (tamanho == 0)
        return (numero);
    var i = 0;
    var y = 0;
    var numero2;
    var negativo = "N";
    if (numero.indexOf("-") != -1)
        negativo = "S";
    numero = numero.toString();
    numero = numero.replace(/[.]/g, ",");
    numero = numero.replace(/[-]/g, "");
    while ((numero.charAt(i) != ",") && (i < numero.length)) { i++; }
    if ((numero.length - i) > tamanho) {
        numero = numero.substr(0, i + (tamanho + 1));

    }
    else {
        if (tamanho == 2) {
            switch (numero.length - i) {
                case 0: numero += ",00"; break;
                case 1: numero += "00"; break;
                case 2: numero += "0"; break;
            }
        }
        if (tamanho == 3) {
            switch (numero.length - i) {
                case 0: numero += ",000"; break;
                case 1: numero += "000"; break;
                case 2: numero += "00"; break;
                case 3: numero += "0"; break;
            }
        }
        if (tamanho == 4) {
            switch (numero.length - i) {
                case 0: numero += ",0000"; break;
                case 1: numero += "0000"; break;
                case 2: numero += "000"; break;
                case 3: numero += "00"; break;
                case 4: numero += "0"; break;
            }
        }
        if (tamanho == 5) {
            switch (numero.length - i) {
                case 0: numero += ",00000"; break;
                case 1: numero += "00000"; break;
                case 2: numero += "0000"; break;
                case 3: numero += "000"; break;
                case 4: numero += "00"; break;
                case 5: numero += "0"; break;
            }
        }
        if (tamanho == 6) {
            switch (numero.length - i) {
                case 0: numero += ",000000"; break;
                case 1: numero += "000000"; break;
                case 2: numero += "00000"; break;
                case 3: numero += "0000"; break;
                case 4: numero += "000"; break;
                case 5: numero += "00"; break;
                case 6: numero += "0"; break;
            }
        }
    }
    qtdinteiros = numero.length - (tamanho + 2);
    numero2 = numero.substr(numero.length - (tamanho + 1), (tamanho + 1));
    for (var i = qtdinteiros; (i != -1); i--) {
        y++;
        if ((y == (tamanho + 1)) && (i > 0)) { numero2 = "." + numero.charAt(i) + numero2; y = 0; }
        else { numero2 = numero.charAt(i) + numero2; }
    }
    if (negativo == "S")
        numero2 = "-" + numero2;
    return (numero2);
}

function ChkNumber(campo, status, negativo, decimais) {
    var numero, digitos = "0123456789-,", Ok = true, virgula = false, virgula2 = false;
    if (negativo == false)
        digitos = "0123456789,";
    //if (decimais == 0)
    //    decimais == 2;
    if ((campo.value == "") || (campo.value == "0") || (campo.value == "0,") || (campo.value == "0,0") || (campo.value == "0,00")) {
        Ok = false;
    } else {
        numero = campo.value;
        numero = numero.toString();
        //numero = numero.replace(/[.]/g, "");
        if (numero.length > 12) {
            Ok = false;
        } else {
            //if ((digitos.indexOf(numero.charAt(0)) < 1) || (digitos.indexOf(numero.charAt(0)) > 10)) {
            //    Ok = false;
            //} else {
            for (var i = 0; ((i < numero.length) && (Ok)); i++) {
                if (numero.charAt(i) == ",") {
                    if (virgula2 == true)
                        Ok = false;
                    else
                        virgula2 = true;
                }
                if (digitos.indexOf(numero.charAt(i)) < 0) {
                    Ok = false;
                }
                if (digitos.indexOf(numero.charAt(i)) == 10) {
                    if (((numero.length - i) <= 3) && (!virgula)) {
                        virgula = true;
                    } else {
                        Ok = false;
                    }
                }
            }
            //}
        }
        if (Ok) {
            if (status) {
                campo.value = PutCents(numero, decimais);
            }
        } else {
            if (status == false) {
                var campoNovo = "";
                var teste = "N";
                virgula2 = false;
                for (var i = 1; (i <= campo.value.length); i++) {
                    if (campo.value.substr(i - 1, 1) == ",") {
                        if (virgula2 == true)
                            teste = "S";
                        else {
                            campoNovo = campoNovo + campo.value.substr(i - 1, 1);
                            virgula2 = true;
                        }
                    }
                    else {
                        if (digitos.indexOf(campo.value.substr(i - 1, 1)) != -1)
                            campoNovo = campoNovo + campo.value.substr(i - 1, 1);
                        else
                            teste = "S";
                    }
                }
                if (teste == "S") {
                    campo.value = campoNovo;
                }
            }
            else {
                campo.value = PutCents(numero, decimais);
            }
        }
    }
    if (status) {
        return Ok;
    }
}

function ChkNumber2(campo) {
    campo = campo.toString();
    campo = campo.replace(/[.]/g, "");
    campo = campo.replace(/[,]/g, ".");
    return campo;
}

function Chkvalor(campo, negativo, decimais) {
    ChkNumber(campo, true, negativo, decimais);
}


function ChkNumberTexto(campo, negativo, decimais) {
    var numero, digitos = "0123456789-,", Ok = true, virgula = false, virgula2 = false;
    if (negativo == false)
        digitos = "0123456789,";
    if ((campo == "") || (campo == "0") || (campo == "0,") || (campo == "0,0") || (campo == "0,00")) {
        Ok = false;
    } else {
        numero = campo;
        numero = numero.toString();
        numero = numero.replace(/[.]/g, "");
        if (numero.length > 12) {
            Ok = false;
        } else {
            for (var i = 0; ((i < numero.length) && (Ok)); i++) {
                if (numero.charAt(i) == ",") {
                    if (virgula2 == true)
                        Ok = false;
                    else
                        virgula2 = true;
                }
                if (digitos.indexOf(numero.charAt(i)) < 0) {
                    Ok = false;
                }
                if (digitos.indexOf(numero.charAt(i)) == 10) {
                    if (((numero.length - i) <= 3) && (!virgula)) {
                        virgula = true;
                    } else {
                        Ok = false;
                    }
                }
            }
        }
        if (Ok) {
            campo = PutCents(numero, decimais);
        }
    }
    return campo;
}

function ChkNumberGrid(campo, negativo, decimais) {
    var numero, digitos = "0123456789-,", Ok = true, virgula = false; virgula2 = false;
    if (negativo == false)
        digitos = "0123456789,";
    if ((campo == "") || (campo == "0") || (campo == "0,") || (campo == "0,0") || (campo == "0,00")) {
        Ok = false;
    } else {
        numero = campo;
        numero = numero.toString();
        numero = numero.replace(/[.]/g, ",");
        if (numero.length > 12) {
            Ok = false;
        } else {
            for (var i = 0; ((i < numero.length) && (Ok)); i++) {
                if (numero.charAt(i) == ",") {
                    if (virgula2 == true)
                        Ok = false;
                    else
                        virgula2 = true;
                }
                if (digitos.indexOf(numero.charAt(i)) < 0) {
                    Ok = false;
                }
                if (digitos.indexOf(numero.charAt(i)) == 10) {
                    if (((numero.length - i) <= 3) && (!virgula)) {
                        virgula = true;
                    } else {
                        Ok = false;
                    }
                }
            }
        }
        if (Ok) {
            campo = PutCents(numero, decimais);
        }
    }
    return campo;
}


function doGetCaretPosition(oField) {

    // Initialize
    var iCaretPos = 0;

    // IE Support
    if (document.selection) {

        // Set focus on the element
        oField.focus();

        // To get cursor position, get empty selection range
        var oSel = document.selection.createRange();

        // Move selection start to 0 position
        oSel.moveStart('character', -oField.value.length);

        // The caret position is selection length
        iCaretPos = oSel.text.length;
    }

    // Firefox support
    else if (oField.selectionStart || oField.selectionStart == '0')
        iCaretPos = oField.selectionStart;

    // Return results
    return (iCaretPos);
}


/*
**  Sets the caret (cursor) position of the specified text field.
**  Valid positions are 0-oField.length.
*/
function doSetCaretPosition(oField, iCaretPos) {

    // IE Support
    if (document.selection) {

        // Set focus on the element
        oField.focus();

        // Create empty selection range
        var oSel = document.selection.createRange();

        // Move selection start and end to 0 position
        oSel.moveStart('character', -oField.value.length);

        // Move selection start and end to desired position
        oSel.moveStart('character', iCaretPos);
        oSel.moveEnd('character', -oField.value.length + iCaretPos);
        oSel.select();
    }

    // Firefox support
    else if (oField.selectionStart || oField.selectionStart == '0') {
        oField.selectionStart = iCaretPos;
        oField.selectionEnd = iCaretPos;
        oField.focus();
    }
}


function FormataData(_RefObjeto) {
    var _Modelo = '##/##/####';
    var valorAtual = _RefObjeto.value;
    var posicao = doGetCaretPosition(_RefObjeto);
    if (valorAtual.indexOf("/") != -1) {
        var primeirabarra = valorAtual.indexOf("/");
        var segundabarra = valorAtual.lastIndexOf("/");

        if (primeirabarra > 2) {
            valorAtual = valorAtual.substr(0, 2) +
	                valorAtual.substr(primeirabarra, 8);
            posicao = 2;
        }
        else
            if (primeirabarra < 2) {
                valorAtual = "0" + valorAtual.substr(0, 1) +
	                valorAtual.substr(2, 8);
                posicao = 2;
            }
            else
                if (primeirabarra != segundabarra) {
                    if (segundabarra > 5) {
                        valorAtual = valorAtual.substr(0, 5) +
	                valorAtual.substr(segundabarra, 6);
                        posicao = 5;
                    }
                    else
                        if (segundabarra < 5) {
                            valorAtual = valorAtual.substr(0, 4) + "0" + valorAtual.substr(4, 7);
                            posicao = 5;
                        }
                }
    }
    var valorNumerico = '';
    var nIndexModelo = 0;
    var nIndexString = 0;
    var valorFinal = '';
    var adicionarValor = true;
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) != '#') {
            valorAtual = valorAtual.replace(_Modelo.substr(i, 1), '');
        }
    }
    for (i = 0; i < valorAtual.length; i++) {
        if (!isNaN(parseFloat(valorAtual.substr(i, 1)))) {
            valorNumerico = valorNumerico + valorAtual.substr(i, 1);
        }
    }
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) == '#') {
            if (valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + valorNumerico.substr(nIndexModelo, 1);
                nIndexModelo++; nIndexString++;
            }
            else {
                adicionarValor = false;
            }
        }
        else {
            if (adicionarValor && valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + _Modelo.substr(nIndexString, 1)
                nIndexString++;
            }
        }
    }
    if (_RefObjeto.value != valorFinal) {
        _RefObjeto.value = valorFinal;
        if (_RefObjeto.value.length >= 10)
            doSetCaretPosition(_RefObjeto, posicao)
        _RefObjeto.focus();
    }
    return true;
}

function FormataDataHora(_RefObjeto) {
    var _Modelo = '##/##/#### ##:##';
    var valorAtual = _RefObjeto.value;
    var posicao = doGetCaretPosition(_RefObjeto);
    if (valorAtual.indexOf("/") != -1) {
        var primeirabarra = valorAtual.indexOf("/");
        var segundabarra = valorAtual.lastIndexOf("/");

        if (primeirabarra > 2) {
            valorAtual = valorAtual.substr(0, 2) +
	                valorAtual.substr(primeirabarra, 8);
            posicao = 2;
        }
        else
            if (primeirabarra < 2) {
                valorAtual = "0" + valorAtual.substr(0, 1) +
	                valorAtual.substr(2, 8);
                posicao = 2;
            }
            else
                if (primeirabarra != segundabarra) {
                    if (segundabarra > 5) {
                        valorAtual = valorAtual.substr(0, 5) +
	                valorAtual.substr(segundabarra, 6);
                        posicao = 5;
                    }
                    else
                        if (segundabarra < 5) {
                            valorAtual = valorAtual.substr(0, 4) + "0" + valorAtual.substr(4, 7);
                            posicao = 5;
                        }
                }
    }
    var valorNumerico = '';
    var nIndexModelo = 0;
    var nIndexString = 0;
    var valorFinal = '';
    var adicionarValor = true;
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) != '#') {
            valorAtual = valorAtual.replace(_Modelo.substr(i, 1), '');
        }
    }
    for (i = 0; i < valorAtual.length; i++) {
        if (!isNaN(parseFloat(valorAtual.substr(i, 1)))) {
            valorNumerico = valorNumerico + valorAtual.substr(i, 1);
        }
    }
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) == '#') {
            if (valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + valorNumerico.substr(nIndexModelo, 1);
                nIndexModelo++; nIndexString++;
            }
            else {
                adicionarValor = false;
            }
        }
        else {
            if (adicionarValor && valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + _Modelo.substr(nIndexString, 1)
                nIndexString++;
            }
        }
    }
    if (_RefObjeto.value != valorFinal) {
        _RefObjeto.value = valorFinal;
        if (_RefObjeto.value.length >= 16)
            doSetCaretPosition(_RefObjeto, posicao)
        _RefObjeto.focus();
    }
    return true;
}


function FormataHora(_RefObjeto) {
    var _Modelo = '##:##';
    var valorAtual = _RefObjeto.value;
    var posicao = doGetCaretPosition(_RefObjeto);
    var valorNumerico = '';
    var nIndexModelo = 0;
    var nIndexString = 0;
    var valorFinal = '';
    var adicionarValor = true;
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) != '#') {
            valorAtual = valorAtual.replace(_Modelo.substr(i, 1), '');
        }
    }
    for (i = 0; i < valorAtual.length; i++) {
        if (!isNaN(parseFloat(valorAtual.substr(i, 1)))) {
            valorNumerico = valorNumerico + valorAtual.substr(i, 1);
        }
    }
    for (i = 0; i < _Modelo.length; i++) {
        if (_Modelo.substr(i, 1) == '#') {
            if (valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + valorNumerico.substr(nIndexModelo, 1);
                nIndexModelo++; nIndexString++;
            }
            else {
                adicionarValor = false;
            }
        }
        else {
            if (adicionarValor && valorNumerico.substr(nIndexModelo, 1) != '') {
                valorFinal = valorFinal + _Modelo.substr(nIndexString, 1)
                nIndexString++;
            }
        }
    }
    if (_RefObjeto.value != valorFinal) {
        _RefObjeto.value = valorFinal;
        _RefObjeto.focus();
    }
    return true;
}

$(function () {
    //all hover and click logic for buttons
    $(".fg-button:not(.ui-state-disabled)")
	.hover(
		function () {
		    $(this).addClass("ui-state-hover");
		},
		function () {
		    $(this).removeClass("ui-state-hover");
		}
	)
	.mousedown(function () {
	    $(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
	    if ($(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active')) { $(this).removeClass("ui-state-active"); }
	    else { $(this).addClass("ui-state-active"); }
	})
	.mouseup(function () {
	    if (!$(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button')) {
	        $(this).removeClass("ui-state-active");
	    }
	});
});

function acionaSearch(compo, tamanho) {
    if (compo.value == "") {
        compo.value = "%";
        compo.focus();
        compo.click();
        compo.focus();
        compo.click();
    }
    else {
        if (compo.value.length > tamanho)
            compo.value = compo.value.substring(0, tamanho);
        compo.focus();
        compo.click();
        compo.focus();
        compo.click();
    }
}

function acionaSearch2(compo) {
    document.getElementById("BuscaUsuario_Bt").focus();
    compo.value = " ";
    compo.focus();
    compo.click();
    compo.focus();
    compo.click();
    compo.value = "";
}


function createQuery(form) {
    var elements = form.elements;
    var pairs = new Array();
    for (var i = 0; i < elements.length; i++) {
        value = elements[i].value
        if (name = elements[i].name) {
            pairs.push(name + "=" + encodeURIComponent(value));
        }
        else
            if (name = elements[i].id) {
                pairs.push(name + "=" + encodeURIComponent(value));
            }
    }
    return pairs.join("&");
}


function valida_CNPJ(cgc) {
    var i;
    s = limpa_string(cgc);
    cgc = s;
    var status = true;
    if (cgc != "") {
        if ((cgc == 00000000000000) || (cgc == 00000000000191) || (cgc == 00000000000272))
            status = false;
        if (cgc == 123123123)
            status = true;
        var df, resto, dac = "";
        df = 5 * cgc.charAt(0) + 4 * cgc.charAt(1) + 3 * cgc.charAt(2) + 2 * cgc.charAt(3) + 9 * cgc.charAt(4) + 8 * cgc.charAt(5) + 7 * cgc.charAt(6) + 6 * cgc.charAt(7) + 5 * cgc.charAt(8) + 4 * cgc.charAt(9) + 3 * cgc.charAt(10) + 2 * cgc.charAt(11);
        resto = df % 11;
        dac += ((resto <= 1) ? 0 : (11 - resto));
        df = 6 * cgc.charAt(0) + 5 * cgc.charAt(1) + 4 * cgc.charAt(2) + 3 * cgc.charAt(3) + 2 * cgc.charAt(4) + 9 * cgc.charAt(5) + 8 * cgc.charAt(6) + 7 * cgc.charAt(7) + 6 * cgc.charAt(8) + 5 * cgc.charAt(9) + 4 * cgc.charAt(10) + 3 * cgc.charAt(11) + 2 * parseInt(dac);
        resto = df % 11;
        dac += ((resto <= 1) ? 0 : (11 - resto));
        status = (dac == cgc.substring(cgc.length - 2, cgc.length));
        if (!status) {
            alert('CNPJ inválido.');
            document.getElementById('cgccpf_J').focus();
        }
    }
}
function valida_CPF(numcpf) {
    x = 0;
    soma = 0;
    dig1 = 0;
    dig2 = 0;
    texto = "";
    numcpf1 = "";
    nrcpf = limpa_string(numcpf);
    var status = true;
    if (numcpf != "") {
        if ((nrcpf == '00000000000') || (nrcpf == '11111111111') || (nrcpf == '22222222222') || (nrcpf == '33333333333') || (nrcpf == '44444444444') ||
				(nrcpf == '55555555555') || (nrcpf == '66666666666') || (nrcpf == '77777777777') || (nrcpf == '88888888888') || (nrcpf == '99999999999')) {
            status = false;
        }
        len = nrcpf.length; x = len - 1;
        // var numcpf = "12345678909";
        for (var i = 0; i <= len - 3; i++) {
            y = nrcpf.substring(i, i + 1);
            soma = soma + (y * x);
            x = x - 1;
            texto = texto + y;
        }
        dig1 = 11 - (soma % 11);
        if (dig1 == 10) dig1 = 0;
        if (dig1 == 11) dig1 = 0;
        numcpf1 = nrcpf.substring(0, len - 2) + dig1;
        x = 11; soma = 0;
        for (var i = 0; i <= len - 2; i++) {
            soma = soma + (numcpf1.substring(i, i + 1) * x);
            x = x - 1;
        }
        dig2 = 11 - (soma % 11);
        if (dig2 == 10) dig2 = 0;
        if (dig2 == 11) dig2 = 0;
        //alert ("Digito Verificador : " + dig1 + "" + dig2);
        if ((dig1 + "" + dig2) == nrcpf.substring(len, len - 2)) {
            status = true;
        } else {
            status = false;
        }
        if (!status) {
            alert('CPF inválido.');
            document.getElementById('cgccpf_F').focus();
        }
    }
}
function BuscaRegistro(Data, id) {
    for (var i = 0; i < Data.length; ++i) {
        if (Data[i].id == id)
            return Data[i];
    };
    return null;
}

function Disabled(campo) {
    document.getElementById(campo).disabled = true;
    return null;
}

function Enabled(campo) {
    document.getElementById(campo).disabled = false;
    return null;
}

function AdicionarTodosAoCombo(combo) {
    document.getElementById(combo).options[0].value = "0";
    document.getElementById(combo).options[0].text = "Todos";
}

function apagaPasta(nomePastas, pasta) {
    jQuery(document).ready(function () {
        jQuery('#Tabs_' + nomePastas + ' ul li').each(function (index) {
            content_id = jQuery(this).attr('id');
            if (content_id == 'TCont' + pasta) {
                jQuery(this).hide();
            }
        });
    });
}

function mostraPasta(nomePastas, pasta) {
    jQuery(document).ready(function () {
        jQuery('#Tabs_' + nomePastas + ' ul li').each(function (index) {
            content_id = jQuery(this).attr('id');
            if (content_id == 'TCont' + pasta) {
                jQuery(this).show();
            }
        });
    });
}
function apagaColunaGrid(nomeGrid, coluna) {
    jQuery("#" + nomeGrid).jqGrid('hideCol', [coluna]);
    //jQuery("#" + nomeGrid).jqGrid('setGridParam', { shrinkToFit: true });
}
function mostraColunaGrid(nomeGrid, coluna) {
    jQuery("#" + nomeGrid).jqGrid('showCol', [coluna]);
}
function PosicionaGrid(compo, nome, item) {
    jQuery("#" + nome.id).jqGrid('setSelection', item);
    if (compo.checked) {
        if (document.getElementById('TiposDocSinis_Marcado') != null) {
            document.getElementById('TiposDocSinis_Marcado').checked = true;
            document.getElementById('TiposDocSinis_Marcado_False').checked = false;
        }
    } else {
        if (document.getElementById('TiposDocSinis_Marcado') != null) {
            document.getElementById('TiposDocSinis_Marcado').checked = false;
            document.getElementById('TiposDocSinis_Marcado_False').checked = true;
        }
    }
}

function posicionaPasta(nomePastas, pasta) {
    var $tabs = $("#" + nomePastas).tabs();
    jQuery(document).ready(function () {
        jQuery('#Tabs_' + nomePastas + ' ul li').each(function (index) {
            content_id = jQuery(this).attr('id');
            if (content_id == 'TCont' + pasta) {
                jQuery(this.parentElement.parentElement).tabs("select", index);
            }
        });
    });
}


function formatarParaMoeda(num) {
    x = 0;

    if (num < 0) {
        num = Math.abs(num);
        x = 1;
    }
    if (isNaN(num)) num = "0";
    cents = Math.floor((num * 100 + 0.5) % 100);

    num = Math.floor((num * 100 + 0.5) / 100).toString();

    if (cents < 10) cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
        num = num.substring(0, num.length - (4 * i + 3)) + '.'
               + num.substring(num.length - (4 * i + 3));
    ret = num + ',' + cents;
    if (x == 1) ret = ' - ' + ret;

    return ret;

}


