var campo_data = '';
var status_cadastro = '';
x = 0;
y = 0;
if (window.Event)
document.captureEvents (Event.MOUSEUP);
function nocontextmenu()
{
 user = fn_pega_cookie("COK_TX_LOGIN");

 if (user.indexOf('rcpd') == -1)
 {
 	event.cancelBubble = true
 	event.returnValue = false;
 	return false;
 }
}
function norightclick(e)
{
	if (fn_ie())
	{
	    X = event.clientX;
	    Y = event.clientY;
	}
	else
	{
	    X = e.clientX;
	    Y = e.clientY;
	}
}

if (document.layers)
document.captureEvents(Event.MOUSEDOWN);
document.oncontextmenu = nocontextmenu;
document.onmousedown = norightclick;
document.onmouseup = norightclick;

//----- Desabilita Select
function disableselect (e)
{
	return true;
}
function reEnable()
{
	return true;
}

//document.onselectstart=new Function ("return false")

if (window.sidebar)
{
	//document.onmousedown=disableselect;
	document.onclick=reEnable;
}

//-------------------------

function fn_acessa(tipo_acesso)
    {
            width =  ((window.screen.width-12)/100)*100;
            height = ((window.screen.height-150)/100)*100;
               //alert('ok');
            var dt=new Date();
            nocache=dt.getSeconds()+''+dt.getMilliseconds();
            top.name = '';
            fn_tipo_visualizacao();
            if (tipo_acesso == 'S')
                window.location = 'principal.php?tp=' + tipo_acesso;
            else
                window.location = 'principal.php';
                //sistema = window.open('principal.php', "SAM" + nocache, "top = 0,left=0,width=" + width + ",height=" + height + ",fullscreen=0, toolbar=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1");
    }

function fn_tipo_visualizacao()
    {
        fn_cria_cookie('SS_TP_VISUALIZACAO',document.body.clientWidth+'x'+document.body.clientHeight,'7');
    }

function fn_mOvr(src,clrOver)
    {
             if (!src.contains(event.fromElement))
                    {
                    src.style.cursor = 'hand';
                             if (src.bgColor != '#d6d6d6')
                        src.bgColor = clrOver;
            }
     }
function fn_mOut(src,clrIn)
    {
        if (!src.contains(event.toElement))
                    {
                     src.style.cursor = 'default';
                     if (src.bgColor != '#d6d6d6')
                         src.bgColor = clrIn;
            }
     }
function fn_mClk(src)
    {
               if (src.bgColor != '#d6d6d6')
                       {
                         selecionado.bgColor = '#ffffff'
                         selecionado.id = 'ant';
                         src.id = 'selecionado';
                         src.bgColor = '#D6D6D6';
                         ant.bgColor = '#ffffff';
                       }
    }

function fn_seleciona_modulo(linha,qtd_modulos)
{
    for (a=0;a<qtd_modulos;a++)
    {
    	div = document.getElementById('modulo_'+a);
        if (div.id != linha.id)
        {
        	if(div.className.indexOf('_selecionado') != -1)
            	div.className = div.className.replace('_selecionado','');
        }
    }
    if(linha.className.indexOf('_selecionado') == -1)
        linha.className=linha.className + '_selecionado';
}

function fn_seleciona_tela(linha,qtd_telas)
{
    for (a=0;a<qtd_telas;a++)
    {
    	div = document.getElementById('tela_'+a);
        if (div.id != linha.id)
        {
        	if(div.className.indexOf('_selecionado') != -1)
            	div.className = div.className.replace('_selecionado','');
        }
    }
    if(linha.className.indexOf('_selecionado') == -1)
        linha.className=linha.className + '_selecionado';
}

function fn_foco_linha(linha)
{
	if (linha.className.indexOf('_selecionado') == -1)
    {
    	if(linha.className.length>6)
	        linha.className = linha.className.replace('_foco','');
	    else
	        linha.className=linha.className+'_foco';
    }
}

function fn_seleciona(linha,x,check,pasta_images)
{
	linha.className = linha.className.replace('_foco','');
    if(linha.className.length>6)
        linha.className = linha.className.replace('_selecionado','_foco');
    else
        linha.className=linha.className+'_selecionado';

    imagem = x.src.substring(x.src.lastIndexOf('/')+1,x.src.length);
    formulario = document.forms[0];
    if (imagem != 'check1.gif')
        {
            x.src = pasta_images + '/check1.gif';
            fn_check('ON',check,formulario);
        }
    else
        {
            x.src = pasta_images + '/check0.gif';
            fn_check('',check,formulario);
        }
    if (formulario.VAR_TELA_PAI.value != '')
    {
    	if (formulario.VAR_CHAVE.value == '')
	        parent.fn_tira_botao('');
	    else
	        parent.fn_tira_botao('none');
    }
}

function fn_check(valor,campo,formulario)
{
    selecionados = '';

    if (campo.value != '')
    {
	    if (valor == 'ON')
	        {
	            formulario.VAR_CHAVE.value += ',' + campo.value + '';
	        }
	    else
	        {
	            selecionados = formulario.VAR_CHAVE.value.replace(',' + campo.value,'');
	            formulario.VAR_CHAVE.value = selecionados;
	        }
    }
}

function fn_seleciona_linha(campo,formulario)
{
    formulario.VAR_CHAVE.value += ',' + campo.value + '';
    parent.fn_tira_botao('none');
    parent.fn_edita_filhos(window);
}

function fn_seleciona_todos(formulario,pasta_images)
{
    fn_seleciona(grid,formulario.IMGCK_TODOS,formulario.CK_TODOS,pasta_images);

    cont = 0;
    for (x=0;x<document.images.length;x++)
        {
            if (document.images[x].name != '')
                {
                    document.images[x].src = document.IMGCK_TODOS.src;
                    imagem = document.images[x].src.substring(document.images[x].src.lastIndexOf('/')+1,document.images[x].src.length);
                    check = document.images[x].name.replace('IMG','');
                    eval('check = formulario.' + check + ';');
                    if (imagem != 'check1.gif' && check.name != 'CK_TODOS')
                    {
                        formulario.VAR_CHAVE.value = '';
                        fn_check('',check,formulario);
                        eval('tr = tr_' + (cont-1));
                        tr.className=tr.className.substring(0,6);
                    }
                    else
                    {
                        if (check.name != 'CK_TODOS')
                        {
                        	fn_check('ON',check,formulario);
                        	eval('tr = tr_' + (cont-1));
                            if (tr.className != tr.className.substring(0,6)+'_selecionado')
                           	  	tr.className=tr.className+'_selecionado';
                        }
                    }
                    cont++;
                }
        }
		if (document.getElementById("menu") != null)
		{
	        menu.innerHTML = '';
		}

	    if (formulario.VAR_TELA_PAI.value != '')
	    {
	        if (formulario.VAR_CHAVE.value == '')
	            parent.fn_tira_botao('');
	        else
	            parent.fn_tira_botao('none');
	    }
}

function fn_apaga(formulario,ck_lista)
{
    atualiza_centro = 'S';
    if (formulario.VAR_CHAVE.value == '' || formulario.VAR_CHAVE.value.indexOf(',novo') != -1)
    {
        fn_msg('Nenhum item selecionado para exclusão !');
    }
    else
    {
        if (confirm(fn_mostra_texto('Você tem certeza de que deseja excluir esse(s) registro(s) ?')))
        {
            if ((top.name.substring(0,5) == 'FILHO' || top.name.substring(0,6) == '2FILHO') && ck_lista == 'S')
            {
                formulario.target = 'frGravacao';
                atualiza_centro = 'N';
            }

            formulario.action = 'apaga.php?VAR_CK_LISTA=' + atualiza_centro;
            formulario.submit();
            formulario.action = '';

            if (atualiza_centro != 'N')
               window.close();
        }
     }
}

var_campo_focus = '';
function fn_altera_campo(campo,formulario,tipo_campo)
{
	var_campo_focus = campo;
    if(formulario.VAR_ALTERACAO.value.indexOf(",|" + campo.name + "|")==-1)
    {
      formulario.VAR_ALTERACAO.value += ",|" + campo.name + "|";
    }
}

fecha_janela = false;
ck_atualiza = 'S';
function fn_grava(formulario)
{
    erros = '';

    if (formulario.VAR_CHAVE.value == 'novo')
    {
        var iediv = window.document.getElementById('div_calendario');
        if (!(ieMat = window.document.getElementById('div_gravando')))
	       var ieMat = window.document.createElement('div');
        ieMat.setAttribute("id","div_gravando");
        ieMat.style.width=65;
        ieMat.style.height=15;

        iediv.insertBefore(ieMat,iediv.firstChild);
        iediv.style.display = '';
        iediv.style.top=Y;
        iediv.style.left=X;
        iediv.className='foco';

        document.getElementById("div_gravando").innerText = 'Gravando...';
		setTimeout('document.getElementById("div_gravando").style.display = "none";',1000);
    }

    for (x=0;x<formulario.elements.length;x++)
        {
            if (formulario.elements[x].value == '' && formulario.VAR_OBRIGATORIOS.value.indexOf('#' + formulario.elements[x].name + '#') != -1)
                erros += '\n' + CAMPOS['#' + formulario.elements[x].name + '#'];
        }

    if (erros != '')
        fn_msg('Atenção: É obrigatório o preenchimento dos campos abaixo' + erros);
    else
        {
            if (formulario.VAR_ALTERACAO.value != '' || formulario.VAR_CHAVE.value == 'novo')
                {
                	comp = '';
                	if (ck_atualiza == 'N')
                    	comp = '?VAR_CK_ATUALIZA=N';

                    formulario.action = 'grava.php' + comp;

                    if (top.name.substring(0,5) == 'FILHO' && !(top.frMenu))
                            formulario.target = 'frGravacao';
                    else
                        fecha_janela = true;

                    if (ck_atualiza == 'N')
                    {						
                        formulario.target = 'frPost';
                    }

                    if (top.name.substring(0,6) == '2FILHO')
                        formulario.target = '';

                    if (fn_verifica_campos())
                        {
							user = fn_pega_cookie("COK_TX_LOGIN");
							//if (user == 'bruno.rcpd')
							//formulario.target = '_blank';

                            formulario.submit();

                            ck_atualiza = '';

                            if (formulario.VAR_CHAVE.value != 'novo')
                                {
                                    formulario.VAR_ALTERACAO.value = '';
                                    formulario.target = 'frPost';
                                    formulario.action = '';
                                }

                            if (top.name.substring(0,5) == 'FILHO' && (fecha_janela))
                                window.close();
                        }


                }
            else
                {
                    fn_msg('Não houve alteração !');
                }
        }
}

function fn_volta(tela,localizacao)
{
    if (!localizacao)
        localizacao = '';

    nome = '#' + window.name;
    if (nome.indexOf('FILHO') > 0)
    	window.close();
    else
        window.location = localizacao + 'cadastro.php?VAR_TELA=' + tela;
}

function fn_verifica_alteracao(formulario)
{
    if (formulario.VAR_ALTERACAO.value != '' && formulario.action == '')
        if (confirm(fn_mostra_texto('Atenção: Ocorreram alterações nesse registro. Deseja gravar as informações alteradas ?')))
            {
            	ck_atualiza = 'N';
                fn_grava(formulario);
            }
}

var_aba = '';
var_qtd_abas = 0;
function fn_teclas(qtd_abas,aba)
{
    // 13 = enter      // 83 = s
    // 8 <=           // 32 =>
    // 67 C            // 27 ESC
    // 69 E           // 46 DEL

    var_aba = aba;
    var_qtd_abas = qtd_abas;
    if (event.ctrlKey)
        {
        	if (event.keyCode == 32 || event.keyCode == 8)
            {

                aba = 'webfxtab_tabPane'+aba;
	            aba = fn_pega_cookie(aba);
	            prox_aba = Number(aba)+1;
	            prox_aba = (prox_aba > qtd_abas) ? 0 : prox_aba;
	            ant_aba = Number(aba)-1;
	            ant_aba = (ant_aba < 0) ? qtd_abas : ant_aba;
            }

            if (event.keyCode == 32)
                tp1.setSelectedIndex(prox_aba)

            if (event.keyCode == 8)
                tp1.setSelectedIndex(ant_aba)

            if (event.keyCode == 83)
            {
                window.focus();
                fn_grava(document.forms[0]);
                var_campo_focus.select();
            }
        }
    if (event.keyCode == 9)
    {
    	event.cancelBubble = true
		event.returnValue = false;
    }
}

function fn_teclas_lista()
{
    if (event.ctrlKey)
    {
        if (event.keyCode == 38 || event.keyCode == 40)  //    /\ = 38 & \/ = 40
        {
            coluna = var_campo_focus.getAttribute('coluna');
            formulario = document.forms[0];

            ativo = false;
            if (event.keyCode == 38)
            {
                for (a=(formulario.elements.length-1);a>=0;a--)
                {
                	coluna_atual = formulario.elements[a].getAttribute('coluna');

                	if (ativo && coluna_atual == coluna && var_campo_focus.type == formulario.elements[a].type && var_campo_focus.size == formulario.elements[a].size)
                    {
                    	formulario.elements[a].focus();
	                    event.cancelBubble = true
	                    event.returnValue = false;
	                    return true;
	                    break;
                    }
                	if (var_campo_focus.name == formulario.elements[a].name)
                    	ativo = true;
                }
                ativo = true;
                for (a=(formulario.elements.length-1);a>=0;a--)
                {
                	coluna_atual = formulario.elements[a].getAttribute('coluna');

                	if (ativo && coluna_atual == coluna && var_campo_focus.type == formulario.elements[a].type && var_campo_focus.size == formulario.elements[a].size)
                    {
                    	formulario.elements[a].focus();
	                    event.cancelBubble = true
	                    event.returnValue = false;
	                    return true;
	                    break;
                    }
                }
            }
            if (event.keyCode == 40)
            {
                for (a=0;a<formulario.elements.length;a++)
                {
                	coluna_atual = formulario.elements[a].getAttribute('coluna');

                	if (ativo && coluna_atual == coluna && var_campo_focus.type == formulario.elements[a].type && var_campo_focus.size == formulario.elements[a].size)
                    {
                    	formulario.elements[a].focus();
	                    event.cancelBubble = true
	                    event.returnValue = false;
	                    return true;
	                    break;
                    }
                	if (var_campo_focus.name == formulario.elements[a].name)
                    	ativo = true;
                }
                ativo = true;
                for (a=0;a<formulario.elements.length;a++)
                {
                	coluna_atual = formulario.elements[a].getAttribute('coluna');

                	if (ativo && coluna_atual == coluna && var_campo_focus.type == formulario.elements[a].type && var_campo_focus.size == formulario.elements[a].size)
                    {
                    	formulario.elements[a].focus();
	                    event.cancelBubble = true
	                    event.returnValue = false;
	                    return true;
	                    break;
                    }
                }
            }
        }
        if (event.keyCode == 83)
        {
        	window.focus();
            parent.fn_ok_filhos(window);
        }
        if (event.keyCode == 69)
        {
        	window.focus();
            event.cancelBubble = true
            event.returnValue = false;
            parent.fn_edita_filhos(window);
        }
        if (event.keyCode == 46)
	    {
	       fn_apaga(window.fSelecao,'S');
	    }
    }
    if (event.keyCode == 27)
    {
       parent.fn_cancela_filho(window);
    }
    if (event.keyCode == 9)
    {
    	event.cancelBubble = true
		event.returnValue = false;
    }
}

function fn_novo(url,localizacao)
    {
        if (!localizacao)
            localizacao = '';

        window.location = localizacao + 'edit.php?VAR_CHAVE=novo' + url;
    }

function fn_abre_aba(codigo)
{
	if (ar_abas[codigo] != undefined)
    {
	    for (b=0;b<ar_abas[codigo].length;b++)
	    {
	        if (ar_abas[codigo][b] != undefined)
	        {
	            nome_frame = 'frSelecao' + ar_abas[codigo][b];
                iframe = document.getElementById(nome_frame);

	            if (iframe != null)
	            {
	                if (iframe.src == '')
	                    fn_atualiza_grid(nome_frame);
	            }
	        }
	    }
    }
}

function fn_atualiza_grid(nome_frame)
{
	iframe = document.getElementById(nome_frame);
    src2 = iframe.getAttribute('src2');
    iframe.src = src2;
}

function fn_edita_grava_filho(cont_campos)
{
	if (cont_campos > 0)
    {
    	span_editar   = document.getElementById('span_editar_' + cont_campos);
	    span_incluir  = document.getElementById('span_incluir_' + cont_campos);
	    span_gravar   = document.getElementById('span_gravar_' + cont_campos);
	    span_cancelar = document.getElementById('span_cancelar_' + cont_campos);

        if (span_editar != null)
        {
        	if (span_editar.style.display == '')
            {
            	span_editar.style.display = 'none';
                span_gravar.style.display = '';
	        	span_cancelar.style.display = '';
            }
            else
            {
                span_editar.style.display = '';
                span_gravar.style.display = 'none';
	        	span_cancelar.style.display = 'none';
            }
        }

        if (span_incluir != null)
        {
        	if (span_incluir.style.display == '')
            {
            	span_incluir.style.display = 'none';
                span_gravar.style.display = '';
	        	span_cancelar.style.display = '';
            }
            else
            {
                span_incluir.style.display = '';
                span_gravar.style.display = 'none';
	        	span_cancelar.style.display = 'none';
            }
        }
    }
}

function fn_edita_filho(variaveis,modo,complemento,texto)
{
    if (modo != 'P')
        {
            tela =variaveis.substring(variaveis.indexOf('=')+1,variaveis.indexOf('&'));
            tela_formatada = tela.replace('.','_');
            tela_formatada = tela_formatada.replace('.','_');
            tela_formatada = tela_formatada.replace('.','_');

            var dt=new Date();
            nocache=dt.getSeconds()+''+dt.getMilliseconds();
            largura = (fn_pega_cookie('cok_width' + tela) != null) ? fn_pega_cookie('cok_width' + tela) : '580';
            altura  = (fn_pega_cookie('cok_height' + tela)!= null) ? fn_pega_cookie('cok_height' + tela) : '550';

            configuracoes  = complemento;
            configuracoes += (configuracoes.indexOf('top') == -1) ? ",top=0" : "";
            configuracoes += (configuracoes.indexOf('left') == -1) ? ",left=0" : "";
            configuracoes += (configuracoes.indexOf('status') == -1) ? ",status=1" : "";
            configuracoes += (configuracoes.indexOf('resizable') == -1) ? ",resizable=1" : "";
            configuracoes += (complemento.indexOf('width') == -1  || fn_pega_cookie('cok_width' + tela) != null) ? ",width=" + largura : "";
            configuracoes += (complemento.indexOf('height') == -1 || fn_pega_cookie('cok_height' + tela)!= null) ? ",height=" + altura : "";

            if (complemento.indexOf('width=') != -1)
            {
                parte1 = complemento.substring(complemento.indexOf('width=')+6,complemento.lenght) + ',';
                pos1   = parte1.indexOf(',');
                width = parte1.substring(0,pos1);
                parte2 = complemento.substring(complemento.indexOf('height=')+7,complemento.lenght) + ',';
                pos2   = parte2.indexOf(',');
                height = parte2.substring(0,pos2);
                variaveis += '&TAM='+width+'X'+height;
            }
            else
                variaveis += '&TAM='+largura+'X'+altura;

            nome_tela = (top.name.substring(0,5) == 'FILHO') ? '2FILHO' + nocache : 'FILHO' + nocache;

            pagina = window.open(variaveis,nome_tela,configuracoes);
        }
    else
        {
            chave = variaveis.substring(variaveis.indexOf('VAR_CHAVE')+10,variaveis.indexOf('VAR_TELA_PAI')-1);
            campo = fn_pega_cookie('cok_lookup');

            comando  = '';
            comando += "if(!fn_procura_item('" + chave + "',top.opener.document.forms[0]." + campo + ")){";
            comando += "top.opener.document.forms[0]." + campo + ".length++;";
            comando += "top.opener.document.forms[0]." + campo + ".options[top.opener.document.forms[0]." + campo + ".length-1].value = '" + chave + "';";
            comando += "top.opener.document.forms[0]." + campo + ".options[top.opener.document.forms[0]." + campo + ".length-1].text = '" + texto + "';";
            comando += "top.opener.document.forms[0]." + campo + ".selectedIndex = top.opener.document.forms[0]." + campo + ".length-1;";
            comando += "}";
            comando += "top.opener.document.forms[0]." + campo + ".onchange();";

            eval(comando);
            top.close();
        }
}

function fn_insere_filhos(frame,variaveis,modo,complemento,texto,cont_campos)
{
	if (frame.src == '')
    {
    	src2 = frame.getAttribute('src2');
    	frame.src = src2;
    }

    if (qtd = prompt(fn_mostra_texto('Quantidade de Itens a inserir:'),'1'))
        {
            if (qtd > 1)
                {
                	fn_edita_grava_filho(cont_campos);
                    fn_tira_botao('none');
                    frame.document.fSelecao.VAR_QTD_NOVO.value = qtd;
                    frame.document.fSelecao.VAR_CHAVE.value = 'novo';
                    frame.document.fSelecao.target = '';
                    frame.document.fSelecao.submit();
                    frame.document.fSelecao.target = 'frPost';
                }
            else
                {
                    with(frame)
                    {
                    	fn_edita_filho(variaveis,modo,complemento,texto);
                    }
                }
        }
}

function fn_edita_filhos(frame)
{
	local = frame.location;
    local = local.toString();
    local = local.substring(local.indexOf('&VAR_SEQ_CAMPO=')+15,local.length);
    seq_campo = local.substring(0,local.indexOf('&'));
    fn_edita_grava_filho(seq_campo);

    frame.document.fSelecao.target = '';
    frame.document.fSelecao.submit();
    frame.document.fSelecao.target = 'frPost';
    fn_tira_botao('none');
}

function fn_cancela_filho(frame)
{
	local = frame.location;
    local = local.toString();
    local = local.substring(local.indexOf('&VAR_SEQ_CAMPO=')+15,local.length);
    seq_campo = local.substring(0,local.indexOf('&'));
    fn_edita_grava_filho(seq_campo);

    frame.document.fSelecao.action = '';
    frame.document.fSelecao.target = '';
    frame.document.fSelecao.VAR_CHAVE.value = '';
    frame.document.fSelecao.submit();
    frame.document.fSelecao.target = 'frPost';
    fn_tira_botao('');
}

function fn_ok_filhos(frame)
{
	local = frame.location;
    local = local.toString();
    local = local.substring(local.indexOf('&VAR_SEQ_CAMPO=')+15,local.length);
    seq_campo = local.substring(0,local.indexOf('&'));
    fn_edita_grava_filho(seq_campo);
    fn_tira_botao('');


    if (frame.document.fSelecao.VAR_ALTERACAO.value != '')
        {
            frame.document.fSelecao.action = 'grava_filho.php';
            frame.document.fSelecao.submit();
        }

    frame.document.fSelecao.action = '';
    frame.document.fSelecao.target = '';
    frame.document.fSelecao.VAR_CHAVE.value = '';

    if (fn_ie())
    	frame.document.fSelecao.submit();
    else
    	frame.history.go(-1);

    frame.document.fSelecao.target = 'frPost';
}

function fn_personaliza(frame,tela)
    {
        with (frame)
            {
                largura = (fn_pega_cookie('cok_widthPERSONALIZA') != null) ? fn_pega_cookie('cok_widthPERSONALIZA') : '750';
                altura  = (fn_pega_cookie('cok_heightPERSONALIZA')!= null) ? fn_pega_cookie('cok_heightPERSONALIZA') : '320';
                personalizacao = window.open('personaliza.php?VAR_TELA=' + tela,'PERSONALIZA','top = 0,left=0,width='+largura+',height='+altura+',fullscreen=0, toolbar=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1');
            }
    }

function fn_verifica_data(data)
{
    dia  = (data.substring(0,2));
    mes  = (data.substring(3,5));
    ano  = (data.substring(6,10));

    situacao = "";
    if ((dia < 01)||(dia < 01 || dia > 30) && (  mes == 04 || mes == 06 || mes == 09 || mes == 11 ) || dia > 31)
        situacao = "falsa";
    if (mes < 01 || mes > 12 )
        situacao = "falsa";
    if (mes == 02 && ( dia < 01 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4))))
        situacao = "falsa";
    if (ano>2100 || ano<1800)
        situacao = "falsa";
    if (data == "")
        situacao = "falsa";
    if (data.length < 10 || data.indexOf('//') != -1)
        situacao = "falsa";
    if (situacao == "falsa" && data != '')
        return false;
    else
        return true;
}

function fn_verifica_hora(hora)
{

    situacao = "";
    if (hora != '' && (hora.substring(0,2) > 24 || hora.substring(0,2) < 0))
        situacao = "falsa";
    if (hora != '' && (hora.substring(3,5) > 59 || hora.substring(3,5) < 0))
        situacao = "falsa";
    if (hora.length < 5 || data.indexOf('::') != -1)
        situacao = "falsa";
    if (situacao == "falsa" && data != '')
        return false;
    else
        return true;
}

function fn_verifica_numerico(valor)
{
    numeros = "1234567890.,-";
    retorno = true;
    qtd_virg = 0;
    for (x=0;x<valor.length;x++)
        {
            if (valor.charAt(x) == ",")
                qtd_virg += 1;
            if (numeros.indexOf(valor.charAt(x)) == -1)
                retorno =  false;
        }
    if (qtd_virg > 1)
        return false;

    return retorno;
}

function fn_valida_data(campo)
{

	function verifica_inteiro(s)
	{
	    for (i = 0; i < s.length; i++)
	    {
	        var c = s.charAt(i);
	        if (((c < "0") || (c > "9"))) return false;
	    }

	    return true;
	}

	function stripCharsInBag(s, bag)
	{
	    returnString = "";
	    for (i = 0; i < s.length; i++)
	    {
	        var c = s.charAt(i);
	        if (bag.indexOf(c) == -1) returnString += c;
	    }

	    return returnString;
	}

	function daysInFebruary (year)
	{
	    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
	}
	function DaysArray(n)
	{
	    for (var i = 1; i <= n; i++)
	    {
	        this[i] = 31
	        if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
	        if (i==2) {this[i] = 29}
	    }
	   return this
	}

	function isDate(dtStr)
	{
	    var minYear=1900;
	    var maxYear=2100;
	    var dtCh = "/"
	    var daysInMonth = DaysArray(12);
	    var pos1=dtStr.indexOf(dtCh);
	    var pos2=dtStr.indexOf(dtCh,pos1+1)
	    var strDay=dtStr.substring(0,pos1)
	    var strMonth=dtStr.substring(pos1+1,pos2)
	    var strYear=dtStr.substring(pos2+1)
	    strYr=strYear;

	    if (strDay.charAt(0)=="0" && strDay.length>1)
	        strDay=strDay.substring(1)
	    if (strMonth.charAt(0)=="0" && strMonth.length>1)
	        strMonth=strMonth.substring(1)
	    for (var i = 1; i <= 3; i++)
	    {
	        if (strYr.charAt(0)=="0" && strYr.length>1)
	            strYr=strYr.substring(1)
	    }
	    month=parseInt(strMonth)
	    day=parseInt(strDay)
	    year=parseInt(strYr)
	    if (pos1==-1 || pos2==-1){
	        alert(fn_mostra_texto("O formato da data deve ser : dd/mm/yyyy"))
	        return false
	    }
	    if (strMonth.length<1 || month<1 || month>12)
	    {
	        alert(fn_mostra_texto("Mes invalido"))
	        return false
	    }
	    if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month])
	    {
	        alert(fn_mostra_texto("Dia invalido"))
	        return false
	    }
	    if (strYear.length != 4 || year==0 || year<minYear || year>maxYear)
	    {
	        alert(fn_mostra_texto("Ano invalido, deve ser entre ")+minYear+" "+fn_mostra_texto('e')+" "+maxYear)
	        return false
	    }
	    if (dtStr.indexOf(dtCh,pos2+1)!=-1 || verifica_inteiro(stripCharsInBag(dtStr, dtCh))==false)
	    {
	        alert(fn_mostra_texto("Data invalida"));
	        return false
	    }

	    return true
	}

	//#######################################################################################################
	if (campo.value!='')
	{
	    if (isDate(campo.value)==false)
	    {
			campo.focus();
			return false
	    }
	}
    return true
}

function fn_formata_data(campo)
{
    if (fn_ie())
        var tecla = event.keyCode;
    else
    {
        var tecla = 8;
    }
    
    var pesquisados = ',1,2,3,4,5,6,7,8,9,0,/,';
    if ((tecla >= 96 && tecla <= 105) || tecla == 111 || (tecla >= 48 && tecla <= 57) || tecla == 193 || tecla == 46 || tecla == 8)
    {
        data = new Date();
        dia = data.getDate();
        dia = (dia < 10) ? '0' + dia : dia;
        mes = data.getMonth() + 1;
        mes = (mes < 10) ? '0' + mes : mes;
        ano = data.getUTCFullYear();

        if (campo.value.indexOf('//') != -1)
            campo.value = campo.value.replace('//','/');

        if (campo.value.length == 1 && campo.value > 3)
            campo.value = '0' + campo.value + '/';

        if (campo.value.length == 2 && campo.value.substring(campo.value.length-1,campo.value.length) == '/')
            campo.value = '0' + campo.value;

        if (campo.value.length == 2 && campo.value.substring(campo.value.length-1,campo.value.length) != '/')
            campo.value = campo.value + '/';

        if (campo.value.length == 4 && campo.value.substring(3,4) > 1)
            campo.value = campo.value.substring(0,3) + '0' + campo.value.substring(3,4) + '/' + ano;

        if (campo.value.length == 5 && campo.value.substring(campo.value.length-1,campo.value.length) == '/')
            campo.value = campo.value.substring(0,campo.value.length-2) + '0' + campo.value.substring(campo.value.length-2,campo.value.length) + ano;

        if (campo.value.length == 5 && campo.value.substring(campo.value.length-1,campo.value.length) != '/')
            campo.value = campo.value + '/' + ano;

        if (campo.value.length == 10)
        {
        	if (fn_valida_data(campo))
            {
	            campo.onchange();
	            campo_hora = document.getElementById('HR_' + campo.name);
	            if (campo_hora != undefined)
	                campo_hora.focus();
            }
            else
            	campo.value = '';
        }
    }
    else
    {
        ultimo = ',' + campo.value.substring(campo.value.length-1,campo.value.length) + ',';
        if (pesquisados.indexOf(ultimo) == -1)
            campo.value = campo.value.substring(0,campo.value.length-1);
    }
}

function fn_formata_hora(campo,campo_data)
{
    if (fn_ie())
        var tecla = event.keyCode;
    else
    {
        var tecla = 8;
    }
    
    var pesquisados = ',1,2,3,4,5,6,7,8,9,0,:,';
    if ((tecla >= 96 && tecla <= 105) || (tecla >= 48 && tecla <= 57) || tecla == 191 || tecla == 46 || tecla == 8)
    {
        data   = new Date();
        dia = data.getDate();
        dia = (dia < 10) ? '0' + dia : dia;
        mes = data.getMonth() + 1;
        mes = (mes < 10) ? '0' + mes : mes;
        ano = data.getUTCFullYear();
        hora   = data.getHours();
        minuto = data.getMinutes();

        if (campo_data)
        {
            if (campo_data.value == '')
                campo_data.value = dia + '/' + mes + '/' + ano;
        }

        campo.value = campo.value.replace('::',':');

        if (campo.value.length == 1 && campo.value > 2)
            campo.value = '0' + campo.value + ':';

        if (campo.value.length == 2 && campo.value.substring(campo.value.length-1,campo.value.length) == ':')
            campo.value = '0' + campo.value;

        if (campo.value.length == 2 && campo.value.substring(campo.value.length-1,campo.value.length) != ':')
            campo.value = campo.value + ':';

        if (campo.value.length == 4 && campo.value.substring(3,4) > 5)
            campo.value = campo.value.substring(0,3) + '0' + campo.value.substring(3,4);

	if (campo.value.length == 5)
	{
	    if (campo.value.indexOf(":") == -1)
	    {
	    	campo.value = '';
	    }
	    else
	        campo.onchange();
	}
    }
    else
    {
        ultimo = ',' + campo.value.substring(campo.value.length-1,campo.value.length) + ',';
        if (pesquisados.indexOf(ultimo) == -1)
            campo.value = campo.value.substring(0,campo.value.length-1);
    }
}

function fn_formata_data_hora(campo)
{
    data = new Date();
    mes = data.getMonth() + 1;
    mes = (mes < 10) ? '0' + mes : mes;
    ano = data.getYear();

    if (campo.value.length == 2)
        campo.value += '/' + mes + '/' + ano;

    if (campo.value.length == 10)
        campo.value += ' ';

    if (campo.value.length == 13 || campo.value.length == 16)
        campo.value += ':';

    campo.onchange();
}

function fn_formata_valor(campo)
{
    valor        = (campo.value*1);
    valor       = (valor+0.0006);
    valor_final = Math.round(valor*100)/100;
    campo.value = valor_final;

    if (campo.value.indexOf('.')!=-1)
    {
        qtd = campo.value.length-(campo.value.indexOf('.')+1);

        if (qtd<2)
            campo.value = campo.value + '0';
    }
    else
    {
        campo.value = campo.value + '.' + '00';
        campo.value = campo.value.replace('NaN','0');
    }
    campo.value = campo.value.replace('.',',');
}

function fn_ordenacao(campo,valor_cookie,nome_cookie)
{
    campo_ordenacao = valor_cookie;

    if (campo.indexOf(' desc,') != -1 && campo.indexOf('-') == -1)
        {
            campo_ordenacao = valor_cookie.replace(campo.replace(' desc,','')+',',campo);
        }
    else if (campo.indexOf('-') != -1)
        {
            campo_ordenacao = valor_cookie.replace(campo.substring(1,campo.length),'');
        }
    else
        {
            campo_ordenacao += campo;
        }

    fn_remove_cookie(nome_cookie);
    fn_cria_cookie(nome_cookie,campo_ordenacao,'1');

    window.history.go(0);
    //fSelecao.target = '';
    //fSelecao.submit();
    //fSelecao.target = 'frPost';
}

function fn_cria_cookie(nome,valor,qtd_dias)
{
    expira = "";
    if (qtd_dias)
        {
            d = new Date();
            d.setTime( d.getTime() + qtd_dias * 24 * 60 * 60 * 1000 );
            expira = "; expires=" + d.toGMTString();
        }
    document.cookie = nome + "=" + valor + expira + "; path=/";
}
   /*
function fn_pega_cookie(nome)
{

    var re = new RegExp( "(\;|^)[^;]*(" + nome + ")\=([^;]*)(;|$)" );
    var res = re.exec( document.cookie );
    if (res != null || fn_ie() == false)
    	return res[3];
    else
    {
    	var xml="manipula_cookies.php?acao=pega&variavel=" + nome;
	    if (window.ActiveXObject)
	       	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	    else if (document.implementation && document.implementation.createDocument)
	    	var xmlDoc= document.implementation.createDocument("","doc",null);

	    xmlDoc.async = false;

	    if (typeof xmlDoc!="undefined")
	    	xmlDoc.load(xml);

        if (xmlDoc.getElementsByTagName("cookies").length == 0)
        	return null;
        else
        {
   	    	cookies = xmlDoc.getElementsByTagName("cookies")[0];
        	cookie = cookies.childNodes[0];

        	return  cookie.getAttribute("valor");
        }
    }
}  */

function fn_pega_cookie(nome)
{

    var re = new RegExp( "(\;|^)[^;]*(" + nome + ")\=([^;]*)(;|$)" );
    var res = re.exec( document.cookie );
    if (res != null)
    	return res[3];
    else
    {
    	var xml="manipula_cookies.php?acao=pega&variavel=" + nome;

	    if( window.ActiveXObject && /Win/.test(navigator.userAgent) )
        {
	       	var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

            xmlDoc.async = false;
            xmlDoc.load(xml);

            if (xmlDoc.getElementsByTagName("cookies").length == 0)
        	return null;
	        else
	        {
	            cookies = xmlDoc.getElementsByTagName("cookies")[0];
	            cookie = cookies.childNodes[0];

	            return  cookie.getAttribute("valor");
	        }
        }
        else if( document.implementation && document.implementation.createDocument )
	    {
	        xmlDoc = document.implementation.createDocument("", "", null);
	        xmlDoc.load(xml);

	        xmlDoc.onload = function()
	        {
            	if (xmlDoc.getElementsByTagName("cookies").length == 0)
	            	return null;
	            else
	            {
                	cookies = xmlDoc.getElementsByTagName("cookies")[0];
	                cookie = cookies.childNodes[0];

	                return  cookie.getAttribute("valor");
	            }
	        }
        }
	    else
	    {
	      return false;
	    }
    }
}

function fn_remove_cookie(nome)
{
    fn_cria_cookie(nome,'null','1');
}

function fn_tamanho_janela(tela)
{
    fn_cria_cookie('cok_width' + tela,document.body.offsetWidth,7);
    fn_cria_cookie('cok_height'+ tela,document.body.offsetHeight,7);
}

function fn_paginacao(qtd_registros_total,qtd_registros_exibicao,pagina_atual,qtd_paginas,qtd_registros_pagina,codigo_campo)
{
	formulario = document.forms[0];
    eval('formulario.VAR_QTD_REGISTROS_PAGINA'+codigo_campo+'.value = qtd_registros_pagina;');
    document.getElementById('total_registros'+codigo_campo).innerHTML   = qtd_registros_exibicao;
    document.getElementById('qtd_total'+codigo_campo).innerHTML         = qtd_registros_total;
    eval('formulario.VAR_PAGINA'+codigo_campo+'.value  = pagina_atual;');
    eval('formulario.qtd_pagina'+codigo_campo+'.value     = qtd_paginas;');
    document.getElementById('qtd_pagina2'+codigo_campo).innerHTML       = qtd_paginas;
}

function fn_muda_pagina(tipo,frame,nome_cookie,codigo_campo)
{
    frame.document.fSelecao.target = '';
    formulario = document.forms[0];
    eval('v_var_pagina = formulario.VAR_PAGINA' + codigo_campo + ';');
    eval('v_qtd_pagina = formulario.qtd_pagina' + codigo_campo + ';');

    pagina = '';
    if (tipo == '<')
        {
            if ((Number(v_var_pagina.value)-1) >= 0)
                pagina = Number(v_var_pagina.value)-1;
        }
    if (tipo == '<<')
        pagina = '1';
    if (tipo == '>')
        {
            if ((Number(v_var_pagina.value)+1) <= (Number(v_qtd_pagina.value)))
            {

                pagina = Number(v_var_pagina.value)+1;
            }
        }
    if (tipo == '>>')
        {
            if ((Number(v_qtd_pagina.value)) > 0)
                pagina = v_qtd_pagina.value;
        }

    fn_remove_cookie(nome_cookie);
    fn_cria_cookie(nome_cookie,pagina,'1');
    frame.history.go(0);
}

function fn_ck_pesquisa(check,nome_cookie,frame,pasta_images)
{
    imagem = fPesquisa.img_pesquisa.src.substring(check.src.lastIndexOf('/')+1,check.src.length);

    if (imagem != 'check1.gif')
        {
            check.src = pasta_images + '/check1.gif';
            fn_cria_cookie(nome_cookie,'S',7);
        }
    else
        {
            check.src = pasta_images + '/check0.gif';
            fn_remove_cookie(nome_cookie);
        }
    frame.history.go(0);
}

function fn_abre_pesquisa(frame,tela,tipo)
{
    with (frame)
        {
            largura = '700';
            altura  = '400';
            arquivo = (tipo == 'A') ? 'pesquisa.php' : 'pesquisa_avancada.php';
            pesquisa = window.open(arquivo + '?VAR_TELA=' + tela,'PESQUISA_AVANCADA','top=0,left=0,width='+largura+',height='+altura+',fullscreen=0, toolbar=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1');
        }
}

function fn_altera_pesquisa(campo,valor)
{
    fn_cria_cookie(campo,valor,1);
}

function fn_limpa_pesquisa(campos,campo_pesquisa)
{
    fn_remove_cookie(campos);
    fn_remove_cookie(campos);
    fn_remove_cookie(campo_pesquisa.name);
    campo_pesquisa.value = '';
    document.fPesquisa.submit();
}

function fn_mostra_todos(nome_cookie,frame,codigo_campo)
{
	formulario = document.forms[0];
    eval('v_var_pagina = formulario.VAR_PAGINA'+codigo_campo+';');

    valor = '';
    if (v_var_pagina.value != '0')
        {
            if (confirm(fn_mostra_texto('Caso existam muitos registros, o processo de seleção podera ficar muito lento. Deseja continuar ?')))
                {
                    valor = '0';
                    document.getElementById('mostra_todos'+codigo_campo).innerText = fn_mostra_texto('Mostrar com paginação');
                }
        }
    else
        {
            valor = '1';
            document.getElementById('mostra_todos'+codigo_campo).innerText = fn_mostra_texto('Mostrar todos');
        }

    v_var_pagina.value = valor;
    fn_remove_cookie(nome_cookie);
    fn_cria_cookie(nome_cookie,v_var_pagina.value,'1');
    frame.history.go(0);
}

function fn_legendas(tela,frame)
{
    with (frame)
        {
            legendas = window.open('legendas.php?VAR_TELA=' + tela,'LEGENDAS','top=0,left=0,width=250,height=310,fullscreen=0, toolbar=0,directories=0,status=1,menubar=0,scrollbars=1,resizable=1');
        }
}

function fn_filtra_legenda(tela,descricao,nome_cookie,valor_cookie)
{
    valor = tela+'|'+descricao;
    //valor_cookie = '';
   // valor_cookie = fn_pega_cookie(nome_cookie);

    //fn_remove_cookie(nome_cookie);
    fn_cria_cookie(nome_cookie,'null','1');
    if (valor_cookie)
        {
            if (valor_cookie.indexOf(valor) == -1)
                fn_cria_cookie(nome_cookie,valor,'1');
        }
    else
                fn_cria_cookie(nome_cookie,valor,'1');

    top.opener.history.go(0);
    window.close();
}

function fn_ie()
{
	navegador = navigator.appName;
    navegador = navegador.toLowerCase();

	if (navegador.indexOf('internet explorer')!=-1)
    	return true;
    else
    	return false;
}

function fn_envia(de,para,todos)
{
        indice = 0;
        codigos = '';
        for (i=de.options.length-1;i>=0;i--)
            {
                     if ((de.options[i].selected && todos != 'S' || todos == 'S') && de.options[i].text != '')
                             {
                                para.options.length++;
                                para.options[para.options.length-1].text = de.options[i].text;
                                para.options[para.options.length-1].value = de.options[i].value;
                                indice = para.options.length-1;
                                codigos += ',' + de.options[i].value;

                                if (fn_ie())
                                	de.options.remove(i);
                                else
                                	de.options[i].text = '';
                             }
            }
        document.fRelaciona.VAR_CODIGOS.value = codigos;
        document.fRelaciona.submit();
        document.fRelaciona.VAR_CODIGOS.value = '';
        document.fRelaciona.VAR_TIPO.value  = '';
        document.fRelaciona.VAR_CAMPO.value = '';

        para.selectedIndex = indice;
}

function fn_altera_campos()
{
    for (a=0;a<fCadastro.elements.length;a++)
        {
            if (fCadastro.elements[a].type != 'hidden' && fCadastro.elements[a].value != '' && fCadastro.VAR_CHAVE.value == 'novo')
                fn_altera_campo(fCadastro.elements[a],fCadastro);
        }
}

function fn_tamanho_lista(frame,tipo)
{
	var iframes = document.getElementsByTagName("iframe");

    for (A=0;A<iframes.length;A++)
    {
    	if (frame.name == iframes[A].getAttribute('name'))
        	frame = iframes[A];
    }

    if (tipo == '+')
    	altura = parseFloat(frame.getAttribute('height'))+15;
    else
    	altura = parseFloat(frame.getAttribute('height'))-15;

    frame.setAttribute("height",altura);
    tela = frame.getAttribute('name');
    tela = tela.substring(9,tela.length);
    tela = tela.replace('_','.');
    tela = tela.replace('_','.');
    fn_cria_cookie('cok_heightLISTA'+ tela,altura,7);
}

var_altura = 0;
var_posicao_inicialY = 0;
var_posicao_inicial_filhoY = 0;
var_frame = '';

function fn_tamanho_lista_inicia(frame)
{
	if (fn_ie())
    {
    	var_altura = document.getElementById(frame.name).height;
    	var_posicao_inicialY = parseFloat(event.clientY);
    	var_frame = frame;
    }
}
function fn_tamanho_lista_altera()
{

    var_posicao_inicial_filhoY = 0;
    if (var_posicao_inicialY > 0)
    {
        muda = (parseFloat(event.clientY) - parseFloat(var_posicao_inicialY));

        //if (muda>0)
        //{
            tam_atual = (parseFloat(var_altura) + parseFloat(muda));
            document.getElementById(var_frame.name).height = tam_atual;
       // }
       // else
       // {
       // 	tam_atual =
       // }
    }
    else
    {
        if (var_frame != '')
        {
            var_posicao_inicialY = parseFloat(event.clientY);
            var_altura = document.getElementById(var_frame.name).height;
        }
    }
}
function fn_tamanho_lista_altera_filho()
{
	var_posicao_inicialY = 0;
	if (var_posicao_inicial_filhoY > 0)
	{
	    muda = (parseFloat(var_frame.event.clientY) - parseFloat(var_posicao_inicial_filhoY));
	    tam_atual = (parseFloat(var_altura) + parseFloat(muda));
	    document.getElementById(var_frame.name).height = tam_atual;
	}
	else
	{
	    if (var_frame != '')
	    {
	        var_posicao_inicial_filhoY = parseFloat(var_frame.event.clientY);
	        var_altura = document.getElementById(var_frame.name).height;
	    }
	}
}

function fn_tamanho_lista_fim()
{
	if (var_frame != '')
	{
	altura = document.getElementById(var_frame.name).height;
	frame = var_frame.name.replace('frSelecao','');
    fn_cria_cookie('cok_heightLISTA' + frame,altura,7);
	}

	var_altura = 0;
	var_posicao_inicialY = 0;
	var_posicao_inicial_filhoY = 0;
	var_frame = '';
}

function fn_botao_especifico(formulario,link,ck_multiplo,destino,abertura)
{
	// ck_multiplo
    // S = Sim
    // N = Não
    // T = Tanto faz

    ok = false;    ;

    if (ck_multiplo == 'T')
    {
    	ok = true;
    }
    else
    {
    	if (formulario.VAR_CHAVE.value == '')
        {
            fn_msg('Atenção. Nenhum item selecionado !');
        }
    	else
        {
            if (ck_multiplo == 'S')
                {
                    ok = true;
                }
            else
                {
                    if (formulario.VAR_CHAVE.value.indexOf(',') != formulario.VAR_CHAVE.value.lastIndexOf(','))
                        {
                            fn_msg('Atenção. Selecione apenas um item !');
                        }
                    else
                        {
                            ok = true;
                        }
                }
        }
    }

    if (ok)
    {
        if (destino == '_blank')
            {
                abertura += '';
                window.open('about:blank','ESPECIFICO',abertura);
                destino = 'ESPECIFICO';
            }
        destino_antigo = formulario.target;
        link_antigo = formulario.action;

        formulario.target = destino;
        formulario.action = link;

        formulario.submit();
        formulario.target = destino_antigo;
        formulario.action = link_antigo;

    }
}

function fn_pesquisa_combo(evento,formulario,campo,cod_lookup,where_campo_pai,local_arquivo)
{
    if (campo.value != '' && (evento == 17 || evento == 13))// || evento >= 65 && evento <= 90 ||evento >= 97 && evento <= 105 || evento >= 48 && evento <= 57)
        {
            if (where_campo_pai != '' && where_campo_pai != 'P')
                {
                    aspas = "|";
                    eval('tipo_select = (' + where_campo_pai.substring(where_campo_pai.indexOf("=")+1,where_campo_pai.length) + '.type == "hidden" || ' + where_campo_pai.substring(where_campo_pai.indexOf("=")+1,where_campo_pai.length) + '.type == "text") ? "" : "' + '['+where_campo_pai.substring(where_campo_pai.indexOf('=')+1,where_campo_pai.length)+'.selectedIndex]";');
                    eval('where_campo_pai="' + where_campo_pai.substring(0,where_campo_pai.indexOf('=')+1) + aspas + '"+' +  where_campo_pai.substring(where_campo_pai.indexOf('=')+1,where_campo_pai.length) + tipo_select + '.value +"' + aspas + '"');
                }

            if (campo.value.length > 4)
                campo.size = campo.value.length -4;

            nome_campo = campo.name.substring(3,campo.name.length);
            nome_tela = window.name.toString();
            tabela_filha = (top.name.substring(0,3) != '' || where_campo_pai == 'P' || nome_tela.indexOf('frSelecao') != -1) ? "S" : "N";

            campo_pai = '';
            if (where_campo_pai != 'P')
                {
                    campo_pai = (where_campo_pai != '') ? "S" : "";
                    fn_cria_cookie('cok_where_pai',where_campo_pai,1);
                }
            formulario.action  = (local_arquivo) ? local_arquivo : '';
            formulario.action += 'pesquisa_lookup.php?VAR_CAMPO=document.' + formulario.name + '.' + nome_campo + '&VAR_VALOR=' + campo.value + '&VAR_CAMPO_PAI=' + campo_pai + '&VAR_LOOKUP=' + cod_lookup + '&VAR_CK_FILHO=' + tabela_filha;
            target_antigo = formulario.target;

            if (nome_tela.indexOf('frSelecao') == -1)
                formulario.target = 'frGravacao';
            else
                formulario.target = 'frGravacao_lista';
            formulario.submit();
            formulario.action = '';
            formulario.target = target_antigo;
            formulario.target = 'frPost';
        }
}

function fn_abre_combo(campo,cod_lookup,where_campo_pai,local_arquivo)
{
    if (campo.disabled)
    {
        alert(fn_mostra_texto('Atenção, este campo não esta disponível para alteração.'));
        return '';
    }
    nome_form = document.forms[0].name;
    valor = '';
    campo_pai = '';
    if (where_campo_pai != '' && where_campo_pai != 'P')
        {
            where_campo_pai = where_campo_pai.replace('AND ','AND TABELA.');
            campo_pai = (where_campo_pai != '') ? "S" : "";
            campo_where = where_campo_pai.substring(0,where_campo_pai.indexOf('='));

            valor = where_campo_pai.substring(where_campo_pai.indexOf('=')+1,where_campo_pai.length);

            eval('valor=' + valor + '.value;');
            where = campo_where + '=|' + valor + '|';
            where_campo_pai = where;
        }
    if (where_campo_pai != '' && where_campo_pai != 'P')
        fn_cria_cookie('cok_where_pai',where_campo_pai,1);

    fn_cria_cookie('cok_lookup',campo.name,1);
    local_arquivo = (local_arquivo) ? local_arquivo : '';
    window.open(local_arquivo + 'cadastro.php?VAR_TELA=' + cod_lookup + '&VAR_CK_PESQUISA=S' + '&VAR_CK_CAMPO_PAI=' + campo_pai,'COMBO','top=0,left=0,status=1,scrollbars=1,resizable=1');
}

function fn_msg(mensagem)
{
    if (mensagem != '')
        alert(fn_mostra_texto(mensagem));
}

function fn_procura_item(valor,campo)
{
    qtd=campo.options.length;
    achou=false;
    for (x=0 ; x< qtd; x++)
        {
            if (campo.options[x].value == valor)
                {
                    achou=true;
                    campo.selectedIndex=x;
                }
        }
    if (!achou)
       campo.selectedIndex=0;

    return achou;
}

var ck_alterando_filho = false;
var procura_filho = '';
function fn_altera_filho(formulario,cd_lookup,campo_filho,nm_campo_pai)
{
	if (ck_alterando_filho == false)
    {
    	ck_alterando_filho = true;
	    formulario.action = 'altera_filho.php?VAR_LOOKUP=' + cd_lookup + '&VAR_CAMPO=' + campo_filho + '&VAR_CAMPO_PAI=' + nm_campo_pai;
	    formulario.target = 'frGravacao';
	    formulario.submit();
	    formulario.action = '';
	    formulario.target = 'frPost';
    }
    else
    {
    	clearTimeout(procura_filho);
    	procura_filho = setTimeout('fn_altera_filho('+formulario.name+',"'+cd_lookup+'","'+campo_filho+'","'+nm_campo_pai+'")',1000);
    }
}

function fn_word(path)
	{
    	path = (path) ? path : '';
        tipo = 'w';
        if (confirm(fn_mostra_texto('Deseja fazer download do arquivo ?')))
        	tipo = 'wd';
    	endereco = path + 'relatorio.php?VAR_TIPO_TELA=' + tipo + '&PHPSESSID=' + fn_pega_cookie('PHPSESSID');
        window.open(endereco, "WORD", "top=0,left=0,titlebar=0,width=750,height=550,toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1")
    }

function fn_excel(path)
	{
    	path = (path) ? path : '';
        tipo = 'e';
        if (confirm(fn_mostra_texto('Deseja fazer download do arquivo ?')))
         	tipo = 'ed';
    	endereco = path + 'relatorio.php?VAR_TIPO_TELA=' + tipo + '&PHPSESSID=' + fn_pega_cookie('PHPSESSID');
        window.open(endereco, "EXCEL", "top=0,left=0,titlebar=0,width=750,height=550,toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1")
    }

function fn_pdf(path)
{
    path = (path) ? path : '';
    endereco = path + 'relatorio.php?VAR_TIPO_TELA=p&PHPSESSID=' + fn_pega_cookie('PHPSESSID');
    window.open(endereco, "PDF", "top=0,left=0,titlebar=0,width=750,height=550,toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1")
}

function fn_imprimi(path)
{
	window.print();
    //path = (path) ? path : '';
    //endereco = path + 'relatorio.php?VAR_TIPO_TELA=i&PHPSESSID=' + fn_pega_cookie('PHPSESSID');
    //window.open(endereco, "IMPRESSAO", "top=0,left=0,titlebar=0,width=750,height=550,toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1")
}

function fn_salva_relatorio()
{
    descricao = '';
    if (descricao = prompt(fn_mostra_texto('Descrição do Relatório'),fn_mostra_texto('Meu relatório')))
        {
            localizacao = window.location;
            localizacao = localizacao.toString();
            endereco    = localizacao + '&VAR_SALVA_RELATORIO=S';
            fn_cria_cookie('COK_DESCRICAO_RELATORIO',descricao,1);
            window.location = endereco;
         }
}

function fn_config_relatorio(tela,relatorio)
{
    localizacao = window.location;
    localizacao = localizacao.toString();
    tipo = (localizacao.indexOf('relatorio_lista.php') != -1) ? "L" : "E";
    window.open("personaliza_relatorio.php?VAR_TELA=" + tela + "&VAR_TIPO=" + tipo + "&VAR_RELATORIO=" + relatorio, "CONFIGURACAO", "top=0,left=0,titlebar=0,width=750,height=550,toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1")
}

function MM_preloadImages()
{
    var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore()
{
    var i,x,a=document.MM_sr;
    for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d)
{
    var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
    if(!(x=d[n])&&d.all)
        x=d.all[n];
    for (i=0;!x&&i<d.forms.length;i++)
        x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++)
        x=MM_findObj(n,d.layers[i].document);
    if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage()
{
    var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array;
    for(i=0;i<(a.length-2);i+=3)
    if ((x=MM_findObj(a[i]))!=null)
        document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];
}

function fn_abre_relatorio(tela,codigo)
{
    width  = window.screen.width-15;
    height = window.screen.height-105;
    endereco = 'relatorio_lista.php?VAR_TIPO_TELA=r&VAR_TELA=' + tela + '&VAR_RELATORIO=' + codigo;
    relatorio = window.open(endereco, "RELATORIO", "top=0,left=0,titlebar=0,width=" + width + ",height=" + height + ",toolbar=0,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1")
}

function fn_abre_calendario(variaveis)
{
    nome_campo = variaveis.substring(variaveis.lastIndexOf('.')+1,variaveis.length);

    if (document.getElementById(nome_campo).disabled || document.getElementById(nome_campo).readOnly)
    {
        alert(fn_mostra_texto('Atenção, este campo não esta disponível para alteração.'));
        return '';
    }

    if (window.name.substring(0,9) == 'frSelecao')
    {
        janela = parent;
        janela_tit = window.name+'.';
    }
    else
    {
        janela = window;
        janela_tit = '';
    }

    variaveis = variaveis.replace('=','='+janela_tit)

    poslarg=0;
    posalt=0;
    if (fn_ie())
    {
        poslarg = janela.document.body.clientWidth;
        posalt  = janela.document.body.clientHeight;


        larg = 185;
        alt = 155;
    }
    else
    {
        poslarg = janela.innerWidth;
        posalt  = janela.innerHeight;
        larg = 172;
        alt = 149;
    }

    if (window.name.substring(0,9) == 'frSelecao')
    {
    	left = (poslarg/2)-(larg/2);
        topo = (posalt/2)-(alt/2);
    }
    else
    {
	    if ((X-100)<0)
	        left = 0;
	    else
	    {
	        if (((X-100)+larg)>poslarg)
	            left =  (poslarg-larg);
	        else
	            left = (X-100);
	    }
	    topo = ((Y+alt)>posalt) ? (posalt-alt) : Y;
   	}

    var iediv = janela.document.getElementById('div_calendario');
    if (!(ieMat = janela.document.getElementById('frData')))
	   var ieMat = janela.document.createElement('iframe');
	ieMat.setAttribute("id","frData");
    ieMat.setAttribute("name","frData");
    ieMat.style.width=larg;
	ieMat.style.height=alt;
	ieMat.src=(variaveis.indexOf('?')==-1) ? 'calendario.php?'+variaveis : variaveis;
	iediv.insertBefore(ieMat,iediv.firstChild);
	iediv.style.display = '';
	iediv.style.top=topo;
	iediv.style.left=left;
	iediv.style.zIndex="99";
}

function fn_envia_email(path,complemento)
{
    path = (path) ? path : '';
    endereco = path + 'relatorio.php?VAR_TIPO_TELA=m&PHPSESSID=' + fn_pega_cookie('PHPSESSID') + complemento;
    relatorio = window.open(endereco, "EMAIL", "top=0,left=0,titlebar=0,width=750,height=390,toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=0,resizable=1")
}

function fn_seleciona_email(email,tipo,linha)
{
    virg_para = (top.top.opener.relatorio.relatorio.fEnvia.VAR_PARA.value != '') ? ',' : '';
    virg_cc   = (top.top.opener.relatorio.relatorio.fEnvia.VAR_COPIA.value != '') ? ',' : '';
    virg_bcc  = (top.top.opener.relatorio.relatorio.fEnvia.VAR_COPIA_OCULTA.value != '') ? ',' : '';

    linha.className = 'texto_selecionado';

    if (tipo == 'para')
        if (top.top.opener.relatorio.relatorio.fEnvia.VAR_PARA.value.indexOf(email) == -1)
            top.top.opener.relatorio.relatorio.fEnvia.VAR_PARA.value +=  virg_para + email;
    if (tipo == 'cc')
        if (top.top.opener.relatorio.relatorio.fEnvia.VAR_COPIA.value.indexOf(email) == -1)
            top.top.opener.relatorio.relatorio.fEnvia.VAR_COPIA.value += virg_cc + email;
    if (tipo == 'bcc')
        if (top.top.opener.relatorio.relatorio.fEnvia.VAR_COPIA_OCULTA.value.indexOf(email) == -1)
            top.top.opener.relatorio.relatorio.fEnvia.VAR_COPIA_OCULTA.value += virg_bcc + email;
}

function fn_esqueci_senha()
{
    fLogin.VAR_REENVIO.value = 'OK';
    fLogin.submit();
}

function fn_apaga_imagem(codigo,campo,tipo)
{
    if (confirm(fn_mostra_texto('Você tem certeza que deseja excluir esta imagem ?')))
    {
        if (window.name.indexOf('frSelecao') == -1)
            frGravacao.location = 'apaga_arquivo.php?VAR_CAMPO=' + campo + '&VAR_ARQUIVO=' + codigo + '&VAR_TIPO=' + tipo;
        else
            frGravacao_lista.location = 'apaga_arquivo.php?VAR_CAMPO=' + campo + '&VAR_ARQUIVO=' + codigo + '&VAR_TIPO=' + tipo;
    }
}

function fn_abre_imagem(imagem)
{
    relatorio = window.open(imagem, "IMAGEM", "top=0,left=0,titlebar=0,width=490,height=390,toolbar=0,location=0,directories=0,status=1,menubar=0,scrollbars=0,resizable=1")
}

function fn_agrupa(var_pagina,check,nome_cookie,frame,pasta_images)
{
    imagem = fPesquisa.img_agrupa.src.substring(check.src.lastIndexOf('/')+1,check.src.length);

    if (imagem != 'check1.gif')
        {
            check.src = pasta_images + '/check1.gif';
            fn_cria_cookie(nome_cookie,'S',7);
        }
    else
        {
            check.src = pasta_images + '/check0.gif';
            fn_remove_cookie(nome_cookie);
        }
    var_pagina.value = 1;
    var_pagina.onchange();
    frame.history.go(0);
}

function fn_cor_foco()
{
    for (a=0;a<document.forms.length;a++)
    {
        for (b=0;b<document.forms[a].elements.length;b++)
        {
            if(document.forms[a].elements[b].type!="button" && document.forms[a].elements[b].type!="submit" && document.forms[a].elements[b].type!="hidden" && (document.forms[a].elements[b].type))
            {
                document.forms[a].elements[document.forms[a].elements[b].name].onfocus = function() {this.className = 'foco'; var_campo_focus = this;};
                document.forms[a].elements[document.forms[a].elements[b].name].onblur  = function() {this.className = ''};
            }
        }
    }
}

function fn_muda_tamanho()
{
if (parent)
{
	if (window.name == 'frMenu' || window.name == 'frCentro')
    {
        fn_remove_cookie('SS_TP_VISUALIZACAO');
    	fn_cria_cookie('SS_TP_VISUALIZACAO',parent.document.body.clientWidth+'x'+parent.document.body.clientHeight,'7');
        //top.frJs.fn_atualizar();
    }
}
}

function fn_menu_grid(tela)
{
	if (event.button == 2)
    {
    	eval('menu.innerHTML = parent.menu' + tela + '.innerHTML;');
    	menu.style.left=X;;
        menu.style.top=Y;;
       	menu.style.visibility="visible";
    }
    else
    {
        menu.style.visibility="hidden";
    }
}

function fn_tab(campo,formulario)
{

	if (event.keyCode == 9)
    {
        aba = 'webfxtab_tabPane'+var_aba;
        aba = fn_pega_cookie(aba);

	    prox_aba = Number(aba)+1;
	    prox_aba = (prox_aba > var_qtd_abas) ? 0 : prox_aba;
	    ant_aba = Number(aba)-1;
	    ant_aba = (ant_aba < 0) ? var_qtd_abas : ant_aba;

        index = campo.getAttribute('tabindex');
        grupo = campo.getAttribute('grupo');

        if (event.shiftKey)
        {
        	for (a=formulario.elements.length-1;a>=0;a--)
	        {
	            if (formulario.elements[a].type != 'hidden' && formulario.elements[a].disabled != true)
	            {
	                index_atual = formulario.elements[a].getAttribute('tabindex');
	                grupo_atual = formulario.elements[a].getAttribute('grupo');
	                if (index_atual < index)
	                {
	                    if (grupo_atual != grupo)
	                    {
	                        tp1.setSelectedIndex(ant_aba);
	                        formulario.elements[a].focus();
                            if(formulario.elements[a].type == 'text')
                            	formulario.elements[a].select();
	                    }
	                    else
	                    {
	                        formulario.elements[a].focus();
                            if(formulario.elements[a].type == 'text')
                            	formulario.elements[a].select();
	                    }
	                    return true;
	                    break;
	                }
	            }
            }
        }
        else
        {
            for (a=0;a<formulario.elements.length;a++)
	        {
	            if (formulario.elements[a].type != 'hidden' && formulario.elements[a].disabled != true)
	            {
	                index_atual = formulario.elements[a].getAttribute('tabindex');
	                grupo_atual = formulario.elements[a].getAttribute('grupo');
	                if (index_atual > index)
	                {
	                    if (grupo_atual != grupo)
	                    {
	                        tp1.setSelectedIndex(prox_aba);
	                        formulario.elements[a].focus();
                            if(formulario.elements[a].type == 'text')
                            	formulario.elements[a].select();
	                    }
	                    else
	                    {
	                        formulario.elements[a].focus();
                            if(formulario.elements[a].type == 'text')
                            	formulario.elements[a].select();
	                    }
	                    return true;
	                    break;
	                }
	            }
	            if((formulario.elements.length-1) == a)
	            {
	                prox_aba = 0;;
                    index = 0;
                    a = -1;
	            }
	        }
        }
    }
}

function fn_grupo_relatorio(tabela,nome_cookie)
{
    if (tabela.style.display == '')
    {
    	tabela.style.display = 'none';
        fn_cria_cookie(nome_cookie,'S',1);
    }
    else
    {
	    tabela.style.display = '';
        fn_remove_cookie(nome_cookie);
    }
}

function fn_abre_fecha_grupo_menu(divs,telas)
{
	if (divs != '')
    {
    	div_menu = new Array();
        eval(divs);
        div_tela = new Array();
        eval(telas);

        for (a=0;a<div_menu.length;a++)
        {
        	nome_cookie = 'tela_' + div_tela[a];
        	if (div_menu[a].style.display == '')
            {
            	div_menu[a].style.display = 'none';
                fn_cria_cookie(nome_cookie,'S',1);
            }
			else
            {
            	div_menu[a].style.display = '';
                fn_remove_cookie(nome_cookie,'S',1);
            }
        }
    }
}

function fn_autentica_sistema(local,chave,login)
{
    localizacao_centro = top.frCentro.location;
    localizacao_centro = localizacao_centro.toString();
    localizacao_centro = localizacao_centro.replace(';','*PONTOEVIRG*');

    if (localizacao_centro.indexOf('centro.php') == -1)
        {
            localizacao_menu = top.frMenu.location;
            localizacao_menu = localizacao_menu.toString();
            modulo = localizacao_menu.substring(localizacao_menu.indexOf('=')+1,localizacao_menu.length);
            fn_cria_cookie('cok_localizacao_centro' + modulo,localizacao_centro,1);
        }
    top.frPost.location = 'login_sistema.php?local='+local;
	//window.open('login_sistema.php?local='+local,'login','');
}

function fn_tira_botao(tipo)
{
	div1 = document.getElementById('botoes_bottom');
    div2 = document.getElementById('botoes_top');

	div1.style.display = tipo;
    div2.style.display = tipo;
}

function fn_tamanho_memo(campo,tam)
{
	if (campo.value.length > tam)
    	alert(fn_mostra_texto('Atenção: O campo que está sendo alterado possui o tamanho máximo de ')+tam+' '+fn_mostra_texto('caracteres')+'.\n'+fn_mostra_texto('Até o momento, já foram escritos nele')+' '+campo.value.length+' '+fn_mostra_texto('caracteres')+'.');
}

function fn_verifica_popup()
{
	var pop = window.open("about:blank","_blank","width=10,height=100,top=0,left=0");
	
	if (null == pop || true == pop.closed)
	{   
		alert(fn_mostra_texto("ATENÇÃO! Seu computador possui anti-popups")+'!\n\n'+fn_mostra_texto("Isso fará com que alguns recursos do sistema não funcionem perfeitamente."));
		return false;
	} 
	else 
	{  
		pop.close();
		return true;
	}
}

function fn_inicia_campo_html(nome_campo)
{
	var sBasePath = document.location.href.substring(0,document.location.href.lastIndexOf('_samples')) ;
	var oFCKeditor = new FCKeditor(nome_campo) ;
	oFCKeditor.BasePath	= 'fckeditor/' ;
	oFCKeditor.ReplaceTextarea() ;
}

function fn_mostra_texto(texto)
{
	texto_pesq = texto.toUpperCase();

	if (ar_dicionario[texto_pesq] != '' && ar_dicionario[texto_pesq] != undefined)
		return ar_dicionario[texto_pesq];
	else
		return texto;
}