//barra de Status
window.status = 'Desenvolvido por Wheb Sistemas';

var mozilla = !document.all;

function replaceAll(string, car1, car2){
    var index = string.indexOf(car1);
    while(index != -1){
        string = string.replace(car1, car2);
        index = string.indexOf(car1);
    }
    return string;
}

function formataCasas(fld, milSep, decSep, e, maxLength, mascara){
    var selectedText = document.selection;
    if (selectedText.type == 'Text') {
        fld.value = '';
        return;
    }
    var sep = 0;
    var key = '';
    var i = j = 0;
    var len = len2 = 0;
    var strCheck = '0123456789';
    var aux = aux2 = '';
    var count = mascara.length-1;
    var numCasa = 0;
    while(mascara.charAt(count) != '.'){
        count--;
        numCasa++;
    }
    var whichCode = (window.Event) ? e.which : e.keyCode;

    if (whichCode == 13 || whichCode == 8 || whichCode == 0)
        return true;  // Enter //backspace // delete
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1)
        return false;  // Not a valid key
    len = fld.value.length;
    if(maxLength != null)
        if(len>=maxLength)
            return false;
    for(i = 0; i < len; i++)
        if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep))
            break;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i))!=-1)
            aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    if (len == 0)
        fld.value = '';
    else{
        if(len <= numCasa){
            fld.value = '0'+decSep;
            for(z=len;z<numCasa;z++)
                fld.value +='0';
            fld.value += aux;
        }
    }
    if (len > numCasa) {
        aux2 = '';
        for (j = 0, i = len - (numCasa+1); i >= 0; i--) {
            if (j == 3) {
                aux2 += milSep;
                j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
        }
        fld.value = '';
        len2 = aux2.length;
        for (i = len2 - 1; i >= 0; i--)
            fld.value += aux2.charAt(i);
        fld.value += decSep + aux.substr(len - numCasa, len);
    }
    return false;
}

function aceitaSomenteNumeros(campo){
    var valor = campo.value;
    if(valor == "" || valor == null)
        return;
    var regExp = new RegExp(/-?\d+(,\d)?\d*/g);
    var retorno = false;
    try{
        retorno = regExp.exec(valor)[0].toString().length == valor.toString().length;
    }catch(erro){}
    if(!retorno){
        alert("Este campo aceita somente valores numericos!");
        campo.focus();
        return false;
    }else{
        return true;
    }
}

function formataNumeroComVirgula(fld, e,maxLength,outros) {
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13 || whichCode == 8 || whichCode == 0)
        return true;  // Enter //backspace // delete
    var selectedText = document.selection;
    if(selectedText == undefined){
        try{
            selectedText = fld.selectionStart != fld.selectionEnd ? true : undefined;
        }catch(erro){}
    }
    var tipo = undefined;
    try{
        tipo = document.selection == undefined ?  fld.type : selectedText.type;
    }catch(erro){}

    if (selectedText != undefined && tipo != undefined && tipo.toUpperCase() == 'TEXT'){
        fld.value = '';
    }
    var sep = 0;
    var key = '';
    var i = j = z = 0;
    var len = len2 = 0;
    if(outros == undefined)
        outros = '';
    var strCheck = '0123456789,'+outros;
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13 || whichCode == 8 || whichCode == 0)
        return true;  // Enter //backspace // delete
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1)
        return false;  // Not a valid key
    len = fld.value.length;
    if(maxLength != null)
        if(len>=maxLength)
            return false;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i))!=-1)
            aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    aux2='';
    for (j=0; j<len-1;j++) {
        aux2 += aux.charAt(j);
    }
    fld.value = '';
    len2 = aux2.length;
    for (j =0; j<=len2; j++)
        fld.value += aux2.charAt(j);
}

function formataNumero(fld, e,maxLength,outros) {
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13 || whichCode == 8 || whichCode == 0)
        return true;  // Enter //backspace // delete
    var selectedText = document.selection;
    if(selectedText == undefined){
        try{
            selectedText = fld.selectionStart != fld.selectionEnd ? true : undefined;
        }catch(erro){}
    }
    var tipo = undefined;
    try{
        tipo = document.selection == undefined ?  fld.type : selectedText.type;
    }catch(erro){}

    if (selectedText != undefined && tipo != undefined && tipo.toUpperCase() == 'TEXT'){
        fld.value = '';
    }
    var sep = 0;
    var key = '';
    var i = j = z = 0;
    var len = len2 = 0;
    if(outros == undefined)
        outros = '';
    var strCheck = '0123456789'+outros;
    var aux = aux2 = '';
    var whichCode = (window.Event) ? e.which : e.keyCode;
    if (whichCode == 13 || whichCode == 8 || whichCode == 0)
        return true;  // Enter //backspace // delete
    key = String.fromCharCode(whichCode);  // Get key value from key code
    if (strCheck.indexOf(key) == -1)
        return false;  // Not a valid key
    len = fld.value.length;
    if(maxLength != null)
        if(len>=maxLength)
            return false;
    aux = '';
    for(; i < len; i++)
        if (strCheck.indexOf(fld.value.charAt(i))!=-1)
            aux += fld.value.charAt(i);
    aux += key;
    len = aux.length;
    aux2='';
    for (j=0; j<len-1;j++) {
        aux2 += aux.charAt(j);
    }
    fld.value = '';
    len2 = aux2.length;
    for (j =0; j<=len2; j++)
        fld.value += aux2.charAt(j);
}

//Juli - 01/09/06
//formata um numero conforme as casas decimais passadas
function formataCasasDecimais(numero,qtdDec){
    try{
        var num = numero.toString();
        var indVirgula = num.indexOf('.');
        if(indVirgula != -1){
            if(qtdDec != 0)
                qtdDec++;
            num = num.substr(0,indVirgula) + num.substr(indVirgula,qtdDec);
        }
        return num;
    }catch(error){
        error.message();
    }
}


function adicionaZero(fld,e,mascara){
    var count = mascara.length-1; // Retira #
    var numCasa = 0;
    while(mascara.charAt(count) != '.'){
        count--;
        numCasa++;
    }
    if(fld.value.length == 0 || fld.value.charAt(0) == ',')
        fld.value = 0 + fld.value;
    var lengthValor = fld.value.length;
    if(fld.value.indexOf(',') < 0 ){
        fld.value = fld.value + ',';
        for(i=0; i< numCasa; i++)
            fld.value = fld.value + '0';
    }else{
        posVir   = fld.value.indexOf(',');
        vlPosVir = fld.value.substr(posVir+1,lengthValor-posVir);
        if(vlPosVir.indexOf(',') >= 0){
            alert('Valor Inválido !!! -> '+fld.value+' <-');
            fld.value = '';
            fld.focus();
        }else{
            dif = numCasa - vlPosVir.length;
            for(i=0; i< dif; i++)
                fld.value = fld.value +'0';
        }
    }
    try{
        fld.value = fld.value.substr(0,fld.value.indexOf(',')+(numCasa+1));
    }catch(error){}
}

/*Utilizar quando for pegar um valor de um Input antes de realizar o calculo*/
function formataNumeroHtmltoJS(valor){
    valor = valor.replace(/\./g,'');
    valor = valor.replace(/\,/g,'.');
    return valor;
}
/*Utilizar quando for devolver um valor para um Input depois de realizar o calculo*/
function formataNumeroJStoHtml(valor){
    valor = valor+'';
    valor = valor.replace(/\./g,',');
    return valor;
}

//gera uma data
function geraData(fld){
    var data  = new Date();
    var day   = data.getDate()
    var month = data.getMonth()+1
    if(month<10)
        month = '0'+month;
    if(day < 10)
        day = '0'+day;
    var year  = data.getFullYear()
    if(fld.size < 14)
        fld.value = day + "/" + month + "/" + year;
    else{
        var hours   = data.getHours()
        var minutes = data.getMinutes()
        var seconds = data.getSeconds();
        if(minutes < 10)
            minutes = '0'+minutes;
        if(seconds<10)
            seconds = '0'+seconds;
        fld.value = day + "/" + month + "/" + year +" "+ hours + ":" + minutes + ":" +seconds;
    }
}

/**
 Juliane - 14/07/2007
 Function para abrir uma janela de login
 @param a ação a ser excutada após o login ok
 */
function abrirLogin(acao){
    if((getCookie("trocouUsuario") == "false") || (getCookie("trocouUsuario") == ''))
        novaWindow('wheb_loginAlternativo.jsp?action='+acao,'Janela' ,'','200','230');
    else
        link(acao);
}
//função para seleção de menu
var restore = 0;
if (restore) selObj.selectedIndex=0;
function jumpMenu(selObj,link,target){ //v3.0
    var targ    = "parent.frames['"+target+"']";
    eval(targ+".location=link+selObj.options[selObj.selectedIndex].value");
}

//abri nova janela
var filha = ''

function novaWindowMenuBar(theURL,winName,features,height, width) {
    features += "height=" + height + ",innerHeight=" + height;
    features += ",width=" + width + ",innerWidth=" + width;
    if (window.screen) {
        var ah = screen.availHeight - 30;
        var aw = screen.availWidth - 10;

        var xc = (aw - width) / 2;
        var yc = (ah - height) / 2;

        features += ",left=" + xc + ",screenX=" + xc;
        features += ",top=" + yc + ",screenY=" + yc;

    }
    features += ",menuBar=yes,status";
    filha = window.open(theURL,winName,features);
}


function novaWindowToolbar(theURL,winName,features,height, width) {
    features += "height=" + height + ",innerHeight=" + height;
    features += ",width=" + width + ",innerWidth=" + width;
    if (window.screen) {
        var ah = screen.availHeight - 30;
        var aw = screen.availWidth - 10;

        var xc = (aw - width) / 2;
        var yc = (ah - height) / 2;

        features += ",left=" + xc + ",screenX=" + xc;
        features += ",top=" + yc + ",screenY=" + yc;
        features += ",toolbar=yes";
    }
    features += ",menuBar=no,status";
    filha = window.open(theURL,winName,features);
}
function novaWindow(theURL,winName,features,height, width) {
    features += "height=" + height + ",innerHeight=" + height;
    features += ",width=" + width + ",innerWidth=" + width;
    if (window.screen) {
        var ah = screen.availHeight - 30;
        var aw = screen.availWidth - 10;

        var xc = (aw - width) / 2;
        var yc = (ah - height) / 2;

        features += ",left=" + xc + ",screenX=" + xc;
        features += ",top=" + yc + ",screenY=" + yc;
    }
    features += ",menuBar=no,status";
    filha = window.open(theURL,winName,features);
}
/*Abre uma janela ocupando toda a tela*/
function novaWindowFS(theURL,winName) {
    features = "fullscreen";
    filha = window.open(theURL,winName,features);
}
/*Abre uma janela ocupando toda a tela com propriedades*/
function novaWindowMax(theURL,winName,features) {
    var height = screen.height-85;
    var width  = screen.width-10;
    features += "height=" + height + ",innerHeight=" + height;
    features += ",width=" + width + ",innerWidth=" + width;
    features += ",left=" + 0 + ",screenX=" + 0;
    features += ",top=" + 0 + ",screenY=" + 0;
    features += ",menuBar=no,status";
    filha = window.open(theURL,winName,features);
    return filha;
}

/*Abre uma janela maximizada com todas as propriedades*/
function novaWindowMaximizada(theURL,winName) {
    features = '';
    features += "height=" + window.screen.availHeight + ",innerHeight=" + window.screen.availHeight;
    features += ",width=" + window.screen.availWidth  + ",innerWidth=" + window.screen.availWidth ;
    features += ",left=" + 0 + ",screenX=" + 0;
    features += ",top=" + 0 + ",screenY=" + 0;
    features += ",menubar=YES, titlebar=YES, toolbar=YES, location=YES, directories=YES, status=YES, resizable=YES";
    filha = window.open(theURL,winName,features);
}



function windowFullScreen(url){
    //Checa se tiver bloqueador pop-up abre janela normal senão janela fullscreen fechando a que chamou

    //var janela = window.open(url,"janela","fullscreen");
    var janela = novaWindowMax(url,"janela",'');

    if(janela == null){
        window.location.href=url;
    }else{
        fecharJanelaAtual();
    }
}

function fecharJanelaAtual(){
    //fecha a janela atual sem pedir confirmação
    janela = top;
    janela.opener = top;
    janela.close();
}


function mostraWindowFilha(){
    if(filha!='' && filha != undefined){
        try{
            filha.focus();
        }catch(Error){
            filha = '';
        }
    }
}

//confirma escolha
/*function confirmaEscolha(mensagem,acao,form){
   if(confirm(mensagem)){
        if(form)
                enviar(form,acao);
        else
                link(acao);
   }
}*/

function confirmaEscolha(mensagem, acao, executarLinkPrincipal){
    if(confirm(mensagem))
        if(executarLinkPrincipal)
            linkPrincipal(acao);
        else
            link(acao);
}

/*function verificaResolucao(){
    if(screen.width==640){
        alert('Resolução Mínima Redomendável 800x600');
    }else{
        document.write('<link rel="stylesheet" type="text/css" href="bibliotecas/css/estilo_Padrao.css">');
    }
}*/

function encerraCom(link,opcao){
    tam   = link.length;
    tamOp = opcao.length;
    if(link.substr(tam-tamOp,tam) == opcao)
        return true;
    return false;
}

function getLargura(){
    largura = '800';
    if (parseInt(navigator.appVersion)>3) {
        if (navigator.appName=="Netscape")
            largura = window.innerWidth;
        if (navigator.appName.indexOf("Microsoft")!=-1)
            largura = document.body.offsetWidth;
    }
    return largura;
}

function getLarguraComp(componente){
    largura = componente.style.width;
    if(!largura > 0 )
        return componente.offsetHeight;
    return parseInt(largura.substr(0,largura.length-2));
}
function getAltura(){
    altura = '600';
    if (parseInt(navigator.appVersion)>3) {
        if (navigator.appName=="Netscape")
            altura = window.innerHeight;
        if (navigator.appName.indexOf("Microsoft")!=-1)
            altura = document.body.offsetHeight;
    }
    return  altura;
}

function getAlturaComp(componente){
    altura = componente.style.height;
    if(!altura > 0 )
        return componente.offsetHeight;
    return parseInt(altura.substr(0,altura.length-2));
}

var IE = document.all?true:false
if (!IE) document.captureEvents(Event.MOUSEMOVE)
// Variavies Temporarias
var tempX = 0
var tempY = 0
// Pega X e Y do mouse
function getMouseXY(e) {
    if (IE) { // grab the x-y pos.s if browser is IE
        tempX = event.clientX + document.body.scrollLeft
        tempY = event.clientY + document.body.scrollTop
    } else {  // grab the x-y pos.s if browser is NS
        tempX = e.pageX
        tempY = e.pageY
    }
    if (tempX < 0){
        tempX = 0
        }
    if (tempY < 0){
        tempY = 0
        }
    return false;
}

function getMouseX(e){
    var tempX = 0;
    if (IE) { // grab the x-y pos.s if browser is IE
        tempX = event.clientX + document.body.scrollLeft
    } else {  // grab the x-y pos.s if browser is NS
        tempX = e.pageX
    }
    return tempX;
}

function getMouseY(e){
    var tempY = 0;
    if (IE) { // grab the x-y pos.s if browser is IE
        tempY = event.clientY + document.body.scrollTop
    } else {  // grab the x-y pos.s if browser is NS
        tempY = e.pageY
    }
    return tempY;
}

function ativaModal(e){
    if((getLargura() < getMouseX()) ||
        (getMouseX() < 0) ||
        (getMouseY() < 0) ||
        (getAltura() < getMouseY()))
        window.focus();
}

function ativaPopUpMenu(a){
    try{
        menu = document.getElementById('popUpMenu');
        if(menu == undefined)
            menu = parent.document.getElementById('popUpMenu');
        if(menu.style.height == '10px'){
            difFrame = 0;
            if(a != undefined)
                difFrame = parseInt(a.substr(0,(a.length-2)))-25;
            getMouseXY();
            menu.style.top = ((tempY+10)+difFrame)+"px";
            menu.style.left = (tempX-10)+"px";
            menu.style.visibility = "visible";
        }
        return false;
    }catch(error){}
}

/*Inicio Seleciona Linha com o Mouse*/
classeAnt = '';
function marcaLinha(elemento){
    classeAnt = elemento.className;
    elemento.className = 'Selecao';
}

function desmarcaLinha(elemento){
    elemento.className = classeAnt;
}
/*Fim Seleciona Linha com o Mouse*/
/*Inicio alinha a Direita ao Receber Focus*/
classAnt = '';
function alinhaDireita(evt){
    evt.className = classAnt;
}
function alinhaEsquerda(evt){
    evt.select();
    classAnt = evt.className;
    if(classAnt.indexOf('Obrigatorio') >= 0 )
        evt.className = 'Obrigatorio';
    else
        evt.className = 'Text';
}
/*Fim do alinha A Direita ao Receber Focus*/
function validaCnpj(e){
    texto = 'CNPJ Inválido';
    cnpj = e.value
    if(cnpj.length == 0)
        return;
    var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais;
    digitos_iguais = 1;
    if (cnpj.length < 14 && cnpj.length < 15){
        alert(texto);
        e.focus();
        return false;
    }
    for (i = 0; i < cnpj.length - 1; i++)
        if (cnpj.charAt(i) != cnpj.charAt(i + 1)){
            digitos_iguais = 0;
            break;
        }
    if (!digitos_iguais){
        tamanho = cnpj.length - 2
        numeros = cnpj.substring(0,tamanho);
        digitos = cnpj.substring(tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--){
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                pos = 9;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(0)){
            alert(texto);
            e.focus();
            return false;
        }
        tamanho = tamanho + 1;
        numeros = cnpj.substring(0,tamanho);
        soma = 0;
        pos = tamanho - 7;
        for (i = tamanho; i >= 1; i--){
            soma += numeros.charAt(tamanho - i) * pos--;
            if (pos < 2)
                pos = 9;
        }
        resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
        if (resultado != digitos.charAt(1)){
            alert(texto);
            e.focus();
            return false;
        }
        return true;
    }
    else{
        e.focus();
        alert(texto);
        return false;
    }
}
/*Executa a função Javascript passada como parâmetro no envento onEnter*/
function onEnterFuncao(evento,nmFuncaoJS){
    var whichCode = evento.keyCode;
    if(whichCode == 13)
        eval(nmFuncaoJS);
}

function onEnterWindow(theURL,winName,features,height, width,evento){
    var whichCode = evento.keyCode;
    if(whichCode == 13){
        novaWindow(theURL,winName,features,height, width);
    }
}
//executa link
function link(link) {
    location.href= link;
}
//executa link no frame pai
function linkPai(link) {
    parent.location.href= link;
}
//executa link Target
function linkTarget(link, target) {
    if(link == '' || link == 'null'){
        desativaBotao('btnDetGrid');
        return;
    }
    if(link.indexOf("getCookie") > 0){
        link = executaCookies("", link);
    }
    var frame = target;
    try{
        if(parent.frames[frame] != undefined)
            parent.frames[frame].window.location = link;
        else
            self.frames[frame].window.location = link;
    }catch(error){
        try{
            document.frames[frame].window.location = link;
        }catch(error){
            try{
                opener.frames[frame].window.location = link;
            }catch(error){
                try{
                    parent.parent.frames[frame].window.location = link;
                }catch(error){
                    try{
                        window.parent.parent.location.href  = link;
                    }catch(error){
                    //setErros(error);
                    }
                }
            }
        }
    }
}
/** Juli - 29/05/2007
 Funcao criada para executar os getCookies
 Motivo - em alguns links a funcao getCookie não era reconhecida
 */
function executaCookies(todoTexto, texto){
    if(texto.indexOf("'+getCookie(") > 0){
        //armazenar a primeira parte do texto
        todoTexto += texto.substr(0, texto.indexOf("'+getCookie("));
        //buscar a posição inicial do cookie
        var ini = texto.indexOf("'+getCookie(") + 2;
        //buscar a posição final do cookie
        var fim = texto.indexOf(")+'")+1;
        //pegar somente o cookie
        var aux	= texto.substr(ini, fim - ini);
        //executar o cookie e armazenar no texto
        todoTexto += eval(aux);
        //buscar o texto final para procurar mais funções getCookies
        texto = texto.substr(fim+2);
        //se o texto possuir getCookie então é chamada a função recursivamente
        if(texto.indexOf("'+getCookie(") > 0)
            return executaCookies(todoTexto, texto);
        else
            return todoTexto + texto;
    }
}

//executa link
function linkPrincipal(link) {
    top.window.location = link;
}
function setaFocus(nmCampo){
    if(getComponente('cabErro') == null || getComponente('cabErro').style.visibility == 'hidden'){
        if(getCookie('setarFocus') == 'true' || getCookie('setarFocus') == undefined || getCookie('setarFocus') == '' ){
            if(getComponente(nmCampo) != null){
                ativaBotao(nmCampo);
                getComponente(nmCampo).focus();
            }
        }
    }
}

/* Setar focus no campo informado */
function setaFocusCampo(nmCampo){  
    if(getComponente('cabErro') == null || getComponente('cabErro').style.visibility == 'hidden'){
        if(getCookie('setarFocus') == 'true' || getCookie('setarFocus') == undefined || getCookie('setarFocus') == '' ){
            if(getComponente(nmCampo) != null){
                getComponente(nmCampo).focus();
            }
        }
    }
}

//elimina ctrl + v
function verificaCtrl_V(evento,campo){
    if(evento.ctrlKey && evento.keyCode == 86){
        return false;
    }
}

function ehAlfaNumerico(e,campo){
    teclasInvalidas = '0123456789';
    valor = campo.value;
    size  = campo.value.length;
    saida = '';
    retorno = true;
    for(i=0; i<size; i++){
        if(teclasInvalidas.indexOf(valor.substr(i,1)) < 0)
            saida+=valor.substr(i,1);
        else
            retorno = false;
    }
    campo.value = saida;
    return retorno;
}

//Verifica se contem apenas digitos
function ehDigitos(evento){
    return ((evento.keyCode > 47) && (evento.keyCode < 58)); // números de 0 a 9
}

//Põe a primeira  Letra do Nome em maiusculo e o restante em minusculo
function formataSubstantivos(campo, e){

    var nome = campo.value;
    var i;

    var frase      = nome.substr(0,1).toUpperCase();
    var ehPrimeira = false;

    for(i=1; i <= nome.length; i++) {
        if(nome.substr(i,1) != " "){
            if(ehPrimeira){
                frase += nome.substr(i,1).toUpperCase();
                ehPrimeira = false;
            }else
                frase += nome.substr(i,1).toLowerCase();
        }else{
            ehPrimeira = true;
            frase += nome.substr(i,1);
        }
    }
    campo.value = frase;
}

/*function (nmFrame){
    var frame = '';
    if(!isNaN(nmFrame)) //retorna true se o nrFrame for numérico
        nmFrame = 'frame_'+nmFrame;
    try{
        frame = self.frames[nmFrame];
    }catch(error){
        try{
            frame = parent.frames[nmFrame];
        }catch(error){
            try{
                frame = top.frames[nmFrame];
            }catch(error){
                try{
                    frame = window.opener.frames[nmFrame];
                }catch(error){
                    try{
                        frame = window.opener.parent.frames[nmFrame];
                    }catch(error){}
                }
            }
        }
    }
    return frame;
}*/
function getFrame(nrFrame){
    if(nrFrame == '')
        return this;
    if(!isNaN(nrFrame)) //retorna true se o nrFrame for numérico
        nrFrame = 'frame_'+nrFrame;
    var formulario = self.frames[nrFrame];
    if(formulario == undefined){
        formulario = parent.frames[nrFrame];
        if(formulario == undefined){
            formulario = top.frames[nrFrame];
            if(formulario == undefined){
                formulario = parent.self.frames[nrFrame];
                if(formulario == undefined && window.opener){
                    formulario = window.opener.self.frames[nrFrame];
                    if(formulario == undefined){
                        formulario = window.opener.parent.frames[nrFrame];
                    }
                }
            }
        }
    }
    return formulario;
}

function getFrameReq(nrFrame){
    var nmFrameReq = 'frame_req_'+nrFrame;
    if(nrFrame == '')
        return this;
    var formulario = getFrame(nrFrame).frames[nmFrameReq];
    return formulario;
}


function getComponente(id,nmFrame){
    var componente = '';
    if(nmFrame != '' && nmFrame != undefined){
        var frame = getFrame(nmFrame);
        if(frame)
            componente = frame.document.getElementById(id);
    }else{
        try{
            componente = document.getElementById(id);
            if(componente == null)
                componente = parent.document.getElementById(id);
            if(componente == null){
                try{
                    componente = window.opener.document.getElementById(id);
                }catch(error){}
            }
        }catch(error){
            alert(error.message + 'Id ->'+id);
        }
    }
    return componente;
}

function ocultaComponente(componente){
    try{
        componente.style.display = 'none';
    }catch(error){
        alert(error.message);
    }
}
function mostraComponente(componente){
    try{
        componente.style.display = 'block';
    }catch(error){
        alert(error.message);
    }
}

function maximizaComponente(componente,altura){
    try{
        componente.style.height = getAlturaComp(componente) + altura;
    }catch(error){
        alert(error.message);
    }
}
function minimizaComponente(componente,altura){
    try{
        componente.style.height = getAlturaComp(componente) - altura;
    }catch(error){
        alert(error.message);
    }
}
function fechaJanela(){
    top.window.close();
}
function fechaJanelaConf(mensagem){
    if(confirm(mensagem)){
        fechaJanela();
    }
}
function MostraDiv(state,id,alt){
    var DivRef;
    if(id != '')
        DivRef = getComponente(id);
    if(alt != undefined && alt != ''){
        id = 1;
        DivRef = alt;
    }
    var IfrRef = getComponente('DivMestra');
    if( IfrRef == null){
        IfrRef = getComponente("DivMestra_paginaLayer");
        if(IfrRef == null){
            IfrRef = getComponente('DivMestra_'+id);
            if(IfrRef == null){
                criaDivMestra(id);
                IfrRef = getComponente('DivMestra_'+id);
            }
        }
    }
    if(state){
        if(alt != undefined && alt != ''){
            IfrRef.style.width   = DivRef.Container.style.width;
            IfrRef.style.height  = DivRef.Container.style.height;
            IfrRef.style.top     = DivRef.Container.style.top;
            IfrRef.style.left    = DivRef.Container.style.left;
        }else{
            IfrRef.style.width   = DivRef.offsetWidth;
            IfrRef.style.height  = DivRef.offsetHeight;
            IfrRef.style.top     = DivRef.offsetTop;
            IfrRef.style.left    = DivRef.offsetLeft;
        }
        IfrRef.style.zIndex  = DivRef.style.zIndex - 1;
        IfrRef.style.display = "block";
    }else{
        IfrRef.style.display = "none";
    }
}
function diminuirPX(var1,var2){
    var1 = parseInt(var1.substr(0,var1.length-2));
    var2 = parseInt(var2.substr(0,var2.length-2));
    return ((var1)-(var2));
}
function somarPX(var1,var2){
    var1 = parseInt(var1.substr(0,var1.length-2));
    var2 = parseInt(var2.substr(0,var2.length-2));
    return ((var1)+(var2));
}
function criaDivMestra(id){
    iframe                  = document.createElement("iframe");
    if( id != undefined)
        iframe.id               = 'DivMestra_'+id;
    else
        iframe.id               = 'DivMestra';
    iframe.style.position   = 'absolute';
    iframe.src              = 'javascript:false;';
    iframe.style.top        = '0px';
    iframe.style.left       = '0px';
    iframe.style.display    = 'block';
    iframe.style.width      = '0px';
    iframe.style.height     = '0px';
    iframe.style.zIndex     = '1000';
    if(parent){
        try{
            parent.document.body.appendChild(iframe);
        }catch(err){
            document.body.appendChild(iframe);
        }
    }else
        document.body.appendChild(iframe);
}

function fecharOnEsc(evento){
    var whichCode = (window.Event) ? evento.which : evento.keyCode;
    if(whichCode == 27)
        window.close();
}

/* Converte RGB para o formato maluco Delphi ($00ABCD12)
   Eduardo Paniz Mallmann - 11/01/2007 */
function RGBtoDELPHI(corRGB){
    if(corRGB.substr(0,1) == "#")
        return "$00" + corRGB.substr(5,2) + corRGB.substr(3,2) + corRGB.substr(1,2);
    else
        return "$00" + corRGB.substr(4,2) + corRGB.substr(2,2) + corRGB.substr(0,2);
}

/* Converte Delphi em RGB
   Eduardo Paniz Mallmann - 11/01/2007 */
function DELPHItoRGB(corDELPHI){
    if(corDELPHI.substr(0,2) == 'CL' || corDELPHI.substr(0,2) == 'cl')
        return corDELPHI.substr(2,corDELPHI.length);
    return "#" + corDELPHI.substr(7,2) + corDELPHI.substr(5,2) + corDELPHI.substr(3,2);
}

function formataTexto(format,value){

    format = format.split("");
    value = value.split("");
    var tamValue = value.length;
    var tamMaks = format.length;
    var msks = ".,/-";
    var retorna = "";
    i = 0;
    j = 0;
    while(tamValue != j){

        if( msks.indexOf(format[i]) >= 0 ){
            retorna = retorna +  format[i];
            if(format[i] == value[j]){

                j++;
            }
        }
        else{
            retorna = retorna+ value[j];
            j++;

        }

        i++;
    }

    return retorna ;

}
function isCPF(campo){
    teste = new Array();
    obj = campo.value;
    var D1,D2,D1calc,D2calc,aux;
    var j = 0;
    var counter = 0;

    if(obj.length > 0 && obj.length < 8){
        alert('CPF inválido');
        campo.focus();
        return false;
    }

    for(i=0;i<obj.length;i++){
        if(!isNaN(obj.substring(i,i+1))){
            teste[j] = obj.substring(i,i+1);
            j++;
        }
    }
    aux = teste[0];
    for(i=0;i<teste.length;i++){
        if(teste[i] == aux){
            counter++;
        }
    }
    if(counter == teste.length){
        return false;
    }

    D1 = teste[j-2];
    D2 = teste[j-1];
    D1calc = 0;
    D2calc = 0;
    var loop = j-2;
    for(i=0;i<loop;i++){
        D1calc += Number(teste[i])*(10-i);
        D2calc += Number(teste[i])*(11-i);
    }
    D1calc = (D1calc*10)%11;
    if(D1calc == 10){
        D1calc=0
        };
    D2calc = ((D2calc+(2*D1calc))*10)%11;
    if(D2calc == 10){
        D2calc=0
        };
    if(D1 == D1calc && D2 == D2calc){
        return true;
    }else{
        alert('CPF inválido');
        campo.focus();
        return false;
    }
}

/**
 * Função que retorna a idade
 * Eder J. Silva - 10/01/2007
 */
function obterIdade(dataNasc){

    var data  = new Date();
    var dia   = data.getDate()
    var mes   = data.getMonth()+1
    var ano   = data.getYear()

    if(mes<10)
        month = '0'+mes;

    if(dia < 10)
        dia = '0'+dia;

    diaNasc = dataNasc.substr(0,2);
    mesNasc = dataNasc.substr(3,2);
    anoNasc = dataNasc.substr(6,4);
    if(dataNasc != ""){
        idade = ano - anoNasc;
        if(mes < mesNasc)
            idade --;
        else
        if (mes = mesNasc)
            if(dia < diaNasc)
                idade--;
    }else
        idade = ' ';
    return idade;
}
function getMaiorValor(vl_1,vl_2){
    return vl_1 > vl_2 ? vl_1 : vl_2;
}
function obtemValorSelecionadoRadio(name){
    valor = 'comp = document.all.'+name ;

    eval(valor);
    for (i=comp.length-1; i > -1; i--){

        if (comp[i].checked)
            return (comp[i].value);
    }
    return "";
}

/** Function para remover os espaços - (Ana)*/
function trimTotalAjax(string){

    var i = 0;
    var final = '';
    var ant = false;
    while (i < string.length) {
        if (string.charCodeAt(i)!=13){
            if (string.charCodeAt(i)== 32 || string.charCodeAt(i)==10) {
                if (!ant){
                    final  += string.charAt(i);
                    ant     = true;
                }
            }else{
                final += string.charAt(i);
                ant = false;
            }
        }
        i++;
    }
    return final ;
}
function minimizaIframeMenu(){
    if(getComponente('menu'))
        getComponente('menu').style.height = '25px';
}
function maximizaIframeMenu(){
    if(getComponente('bodyMenu')){
        getComponente('bodyMenu').style.background = '';
        getComponente('bodyMenu').style.backgroundColor = 'transparent';
    }
    if(getComponente('menu'))
        getComponente('menu').style.height = '100%';
}

/* Este método é chamado quando um localizador usa AJAX. Ele chama os métodos para montar o nmColunas, vlColunas, myData e myColumns
   Atualiza também o grid com as novas informações - Eduardo - 07/05/2007 */
var objAux = null;
var atualizaValoresGridAjax = function(ret){
    try{
        antesAtualizarGrid();
    }catch(erro){}
    //Juli-18/07/07 tratamento para quando tiver mais de um grid na mesma página
    objAux = objAux == null ? obj : objAux;
    montarMyColumns(ret.myColumns);
    montarMyData(ret.myData);
    montarNmColunas(ret.nmColunas);
    montarVlColunas(ret.vlColunas);
    objAux.setLinhasSelec([0]);
    objAux.setMarcadorTexto(parseInt(ret.nrRegIn+1), 10);
    if(ret.sobrescreverLinhasPintadas)
        obj.setSobrescreverLinhasPintadas();
    objAux.atualizarGrid();
    montarCoresLinhaGrid(ret.corLinhaGrid);
    objAux.setarFocus();
    fazerPaginacaoAjax(ret);
    try{
        ocultaProcessando();
        depoisGridAtualizado();
    }catch(error){}
}

function montarCoresLinhaGrid(linhas){
    if(linhas == undefined)
        return;
    for(var i = 0; i < linhas.length; i++){
        if(linhas[i][0] != '')
            obj.getLinha(i).style.color      = linhas[i][0];
        if(linhas[i][1] != '')
            obj.getLinha(i).style.background = linhas[i][1];
    }
}

function montarMyColumns(valores){
    myColumns = new Array();
    for(var i = 0; i < valores.length; i++)
        myColumns[myColumns.length] = valores[i].replace(/\"/g, '');
    objAux.setCabecalhoTexto(myColumns);
    objAux.setQtdColunas(myColumns.length);
}

function montarMyData(valores){
    myData = new Array();
    for(var i = 0; i < valores.length; i++){
        var arrayAux = new Array();
        for(var j = 0; j < valores[i].length; j++)
            arrayAux[arrayAux.length] = valores[i][j].replace(/\"/g, '');
        myData[myData.length] = arrayAux;
    }
    objAux.setCelulaTexto(myData);
    objAux.setQtdLinhas(myData.length);
}

function montarNmColunas(valores){
    nmColunas = new Array();
    for(var i = 0; i < valores.length; i++)
        nmColunas[nmColunas.length] = valores[i].replace(/\"/g, '');
}

function montarVlColunas(valores){
    vlColunas = new Array();
    for(var i = 0; i < valores.length; i++){
        var arrayAux = new Array();
        for(var j = 0; j < valores[i].length; j++)
            arrayAux[arrayAux.length] = valores[i][j].replace(/\"/g, '');
        vlColunas[vlColunas.length] = arrayAux;
    }
}

/*  Função para verificar o tamanho do div da paginação e se deve deixá-lo visível ou não. É chamado depois que o grid foi atualizado.
    Eduardo - 10/05/2007 */
function fazerPaginacaoAjax(ret){
    try{
        var aux = getComponente("divResultado").style.height;
        var alturaDiv = parseInt(aux.substr(0, aux.indexOf("px")));
        if(ret.ehFazerPag){
            getComponente("divPag").style.visibility = "";
            getComponente("divPag").style.display = "";
            if(getComponente("divResultado").style.position == "absolute"){
                getComponente("divPag").style.position = "absolute";
                getComponente("divPag").style.top = (getAltura() - 78) + "px";
            }
            getComponente("divPag").innerHTML = montarInnerHTMLPaginacao(ret);
            if(alturaDiv == ret.alturaDiv)
                getComponente("divResultado").style.height = (alturaDiv - 20) + "px";
        }else{
            getComponente("divPag").style.visibility = "hidden";
            getComponente("divPag").style.display = "none";
            if((alturaDiv + 20) == ret.alturaDiv)
                getComponente("divResultado").style.height = (alturaDiv + 20) + "px";
        }
    }catch(error){}
}
/*  Função para criar a paginação do grid com ajax. Eduardo - 11/05/2007 */
function montarInnerHTMLPaginacao(ret){
    try{
        var qtPaginas = parseInt((ret.qtTotReg / ret.qtRegPag) + 1);
        var paginaAtual = parseInt((ret.nrRegIn / ret.qtRegPag) + 1);
        var posSelec = paginaAtual;
        var paginacao = "<font id=\"FonteNormal\">Páginas de Resultado: (" + paginaAtual + " / " + qtPaginas +")</font> ";
        var proximo = parseInt(ret.nrRegIn);
        if(qtPaginas <= 10){
            proximo = 0;
            paginaAtual = 1;
        }else{
            posSelec = 1;
            if(proximo < 0)
                proximo = 0;
            if(proximo > 0){
                var menos = proximo-(10*ret.qtRegPag);
                if(menos < 0)
                    menos = 0;
                paginacao += "<a href=\"javascript:; dwrAction.setNrRegistroInicio("+menos+"); dwrAction.setClickPaginacao('S'); localizadorPadrao_localizar()\"><b>Menos </b>";
            }
        }
        for(var i = 1; i <= 10; i++){
            if(ret.qtTotReg > proximo){
                var label = paginaAtual++;
                if(i == posSelec)
                    label = "<b>" + label + "</b>";
                var qtIni = parseInt(proximo+1);
                var qtFim = parseInt(proximo+ret.qtRegPag);
                var title = "Registros de " + qtIni + " à  " + qtFim;
                paginacao += "<a href=\"javascript:; dwrAction.setNrRegistroInicio("+proximo+"); dwrAction.setClickPaginacao('S'); localizadorPadrao_localizar()\" "+title+" >| " + label + " </a>";

            }
            proximo += ret.qtRegPag;
        }
        if(ret.qtTotReg > proximo)
            paginacao += "<a href=\"javascript:; dwrAction.setNrRegistroInicio("+proximo+"); dwrAction.setClickPaginacao('S'); localizadorPadrao_localizar()\"> | <b>Mais</b></a>";
        paginacao += "<font id=\"FonteNormal\"> | Ir para página: </font><input onkeypress=\"if(event.keyCode == 13) restringeNrPaginaPaginacao(this.value, " + qtPaginas + ", "+ret.qtRegPag+")\" id=\"nrPagina\" type=\"text\" size=\"3\" style=\"height: 16px;\">";
        dwrAction.setNrRegistroInicio(0);
        return paginacao;
    }catch(erro){
        setErros(erro);
    }
}
/* Método para fazer a paginação a partir de uma página digitada, ou seja, pula para o número da página digitada */
function restringeNrPaginaPaginacao(valorDigitado, qtPaginas, qtRegPag){
    if(valorDigitado > qtPaginas || valorDigitado < 1 || isNaN(getComponente("nrPagina").value)){
        alert("Valor fora da faixa");
        return false;
    }
    var nrRegistro = (valorDigitado * qtRegPag) - qtRegPag;
    dwrAction.setNrRegistroInicio(nrRegistro);
    dwrAction.setClickPaginacao('S');
    mostraProcessando();
    localizar();
}
/*
   Método para mostrar a mensagem de processando no meio da tela. Este é o que chama o AJAX para executar as funções.
   ocultarImagemAuto -> passar true se deseja ocultar a imagem em outra parte do código. Caso seja false ou não seja passado parâmetro, o ajax esconde a imagem
   ehAjax      -> passar false se desejar mostrar a imagem quando não utilizar uma requisição AJAX
   imageSrc -> caminho de uma imagem diferente da padrão

   Eduardo - 11/05/2007
 */
function mostraProcessando(ocultarImagemAuto,ehAjax, imageSrc){
    ehAjax = (ehAjax == undefined ? true : ehAjax);
    var loadingImage;
    if(imageSrc)
        loadingImage = imageSrc;
    else
        loadingImage = "icones/aguarde.gif";
    if(ehAjax)
        dwr.engine.setPreHook(carregaImagem(loadingImage));
    else
        carregaImagem(loadingImage);
    if(ocultarImagemAuto == undefined || ocultarImagemAuto){
        dwr.engine.setPostHook(function(){
            $('disabledImageZone').style.visibility = 'hidden';
        });
    }
}

function carregaImagem(loadingImage){
    var disabledImageZone = getComponente('disabledImageZone');
    if (!disabledImageZone) {
        var localiz = getCookie("index_localizador") != undefined && getCookie("index_localizador") != null && getCookie("index_localizador") > -1;
        var nrFrame = localiz ? getCookie("index_localizador") : getCookie("frame");
        var documento = getComponente("frame_"+nrFrame);
        if(documento)
            documento = documento.document == undefined ? document : documento.document;
        else
            documento = document;
        disabledImageZone = documento.createElement('div');
        disabledImageZone.setAttribute('id', 'disabledImageZone');
        disabledImageZone.style.position = "absolute";
        disabledImageZone.style.zIndex = "1000";
        disabledImageZone.style.width = "100%";
        disabledImageZone.style.height = "100%";
        var imageZone = documento.createElement('img');
        imageZone.setAttribute('id','imageZone');
        imageZone.setAttribute('src',loadingImage);
        imageZone.style.position = "absolute";
        imageZone.style.top = "0px";
        imageZone.style.right = "0px";
        disabledImageZone.style.top = (getAltura()/2 - imageZone.getAttribute('height') / 2) + "px";
        disabledImageZone.style.right = (getLargura()/2 - imageZone.getAttribute('width') / 2) + "px";
        disabledImageZone.appendChild(imageZone);
        documento.body.appendChild(disabledImageZone);
    } else {
        disabledImageZone.src = loadingImage;
        disabledImageZone.style.visibility = 'visible';
        disabledImageZone.style.display    = 'block';
    }
}

function ocultaProcessando(){
    var imagem = getComponente('disabledImageZone');
    if(imagem){
        imagem.style.visibility = 'hidden';
        imagem.style.display    = 'none';
    }
}
/* Método que retornar um parâmetro de uma função. Passa-se o número do parâmetro como 'parâmetro da função'
   Wheb Sistemas Eduardo Paniz Mallmann */
function getParametroFuncao(posicao){
    try{
        return parametrosFuncao[posicao-1];
    }catch(erro){
        return null;
    }
}
/* Método que retornar um parâmetro do menu do sistema. Passa-se o número do parâmetro como 'parâmetro da função'
   Wheb Sistemas Eduardo Paniz Mallmann */
function getParametroMenuSistema(posicao){
    try{
        return parametrosMenuSistema[posicao-1];
    }catch(erro){
        return null;
    }
}
/**
 *  Juli - 10/05/2007
 *  Mostra a versão do sistema pressionando as teclas ctrl  + espaço
 */
function verificarVersao(evento){
    if(evento.ctrlKey && evento.keyCode == 32){
        novaWindow('sobre.html','Sobre','',260, 282);

    }
}
function trim(valor){
    return valor.replace(/\s/g, "");
}
function verificarTamanhoGrid(nrFrame, tamanho){
    try{
        if(tamanho == undefined)
            tamanho = 0;
        var tab = getComponente("dsTabela_"+nrFrame);
        var compens = getComponente("div_pag_"+nrFrame, nrFrame) ? 40 : 25
        compens -= getComponente("dsTabela_"+nrFrame) ? 0 : 20;
        getComponente("todoGrid").style.height = getAltura()-compens - tamanho;
        try{
            obj.setarFocus();
        }catch(erro){}
    }catch(error){}
}
/** Função para tratamento de código inválido
 *   @param o nome do componente do código
 *   @param o nome do componente da descrição
 */
function  trataCodigoInvalido(comp, dsComp){
    alert("Código inválido");
    setaFocus(comp);
    getComponente(comp).select();
    getComponente(dsComp).value = "";
}
var dtInicioLogin = '';
var dtFimLogin    = '';
function marcaInicioLogin(event){
    var cdBarras = getComponente("nmUsuario").value;
    if(cdBarras.length < 2 && event.keyCode != 8){
        dtInicioLogin = '';
    }
    if(dtInicioLogin == '')
        dtInicioLogin = new Date();
}

function efetuaLogin(form){
    dtFimLogin = new Date();
    var acao = form.action;
    if(dtInicioLogin != '' && dtFimLogin.getTime() - dtInicioLogin.getTime() < 250)
        acao+='?cdBarras=S';
    else
        acao+='?cdBarras=N';
    dtInicioLogin = '';
    form.action = acao;
}
function executaJSSe(condicao,nmFuncaoVerdade,nmFuncaoFalso){
    if(eval(condicao))
        eval(nmFuncaoVerdade);
    else
        eval(nmFuncaoFalso);
}
function arrayContains(lista,nmCampo){
    var retorno = false;
    for(var i=0; i < lista.length; i++){
        if(lista[i] == nmCampo){
            retorno = true;
            break;
        }
    }
    return retorno;
}

function includeCss(arquivo){
    var novo    = document.createElement("<link>");
    novo.setAttribute('type', 'text/css');
    novo.setAttribute('rel', 'stylesheet');
    novo.setAttribute('href', arquivo);
    window.document.getElementsByTagName('head')[0].appendChild(novo);
}
function getEstilos(){
    var estilos = montarEstilos();
    for(var i=0; i < estilos.length; i++)
        includeCss(estilos[i]);
}


function verificaAtalhosSistema(evento){
    /*Chama Evento Parametros da Função*/
    if(evento.shiftKey && evento.keyCode == 118){
        novaWindow('montarPastaParametrosFuncaoUsuario.action', 'parametros', '', 600,600);
    }else if(evento.shiftKey && evento.keyCode == 116){
        novaWindow('carregarAdmSistema.action?cdFuncaoCdPerfil=6001_@atual', 'parametros', '', 600,800);
    }
}

/*Passar como parâmetro a mascara
N - somente número
C - qualquer caracter

Ex: (NN) NNNN-NNNN
 */

function formataCampoTexto(campo, mask, evt) {

    if(document.all) // Internet Explorer
        key = evt.keyCode;
    else // Nestcape
        key = evt.which;

    if (key == 8)
        return true;
    string = campo.value;
    i = string.length;

    if (i < mask.length) {
        if (mask.charAt(i) == 'N') {
            return (key > 47 && key < 58);
        } else {
            if (mask.charAt(i) == 'C') {
                return true;
            }
            for (c = i; c < mask.length; c++) {
                if (mask.charAt(c) != 'N' && mask.charAt(c) != 'C')
                    campo.value = campo.value + mask.charAt(c);
                else if (mask.charAt(c) == 'C'){
                    return true;
                } else {
                    return (key > 47 && key < 58);
                }
            }
        }
    } else
        return false;
}

function atualizarMenu(){
    getFrame('menu').remontarMenu();
}

function limpaEspaco(campo, evento){
    var valor = campo.value;
    var  i = 0;
    var final = '';
    var ant = false;
    while (i < valor.length) {
        if (valor.charCodeAt(i)!=13){
            if (valor.charCodeAt(i)== 32 || valor.charCodeAt(i) == 10) {
                if (!ant){
                    ant     = true;
                    campo.value = final;
                }
            }else{
                final += valor.charAt(i);
                ant = false;
            }
        }
        i++;
    }
}