
/**** Início das funções referentes ao dbGrid *****/
var SelectedLine = -1;
var Operation = '';

function SetOperation(fOperation)
  {
    Operation = fOperation;
  }

function ConfirmLine(fTable, fLine)
  {
    var elements_line = document.getElementById(fLine).getElementsByTagName("input");
	//var elements_line = document.getElementById(fLine);
	var elements_label = document.getElementById(fLine).getElementsByTagName("label");
	var k=0;
	for (i=0; i < elements_line.length; i++)
	  {
	  	//alert('Label: '+elements_label.display);
		if((elements_line[i].type == 'text') || (elements_line[i].type == 'button'))
		  {
			//var conteudo = elements_line[i].value;
			var conteudo = elements_line[i].getAttribute('value');
			
			
			elements_line[i].style.visibility='hidden';
			
			var label_do_campo = document.getElementById('label_'+elements_line[i].id);
			if(label_do_campo != null)
			  {
			  	/* se label já existe, remove ele para ser criado novamente */
			    label_do_campo.parentNode.removeChild(label_do_campo);
				label_do_campo = null;	
			  }
			  
			
			if(label_do_campo == null)
			  {
			    var novo_label = document.createElement('label');
				novo_label.id = 'label_'+elements_line[i].id;
				novo_label.style.display = 'block';
				novo_label.innerHTML = conteudo;
				elements_line[i].parentNode.appendChild(novo_label);	
				
			  }
			k++;
		  }
	  }
	/* Botão OK*/
	buttons = document.getElementById(fLine).getElementsByTagName("button");
	for (i=0; i < buttons.length; i++)
	  {
	    if(buttons[i].id == 'ok')
		  buttons[i].style.visibility='hidden';
	  }

  }
  
function UpdateLine(fTable, fLine)
  {
	var elements_line = document.getElementById(fLine).getElementsByTagName("input");
	var elements_label = document.getElementById(fLine).getElementsByTagName("label");
	var k=0;
	for (i=0; i < elements_line.length; i++)
	  {
		if((elements_line[i].type == 'text') || (elements_line[i].value == 'ok'))
		  {
			elements_line[i].style.visibility='';
			if(elements_label[k])
			  {
			    elements_label[k].style.display = 'none';
			  }
			k++;
		  }
	  }
	/* Botão OK*/
	buttons = document.getElementById(fLine).getElementsByTagName("button");
	for (i=0; i < buttons.length; i++)
	  {
	    if(buttons[i].id == 'ok')
		  buttons[i].style.visibility='';
	  }
  }
  
function SelectLine(fTable, fLine)
  {
	var new_background = '#09f';
	var old_background = '#f3f3f3';
	
	var ChangeBackground = true;
	if( fLine == SelectedLine )
	  {
	    //UpdateLine(fTable, fLine);
	  }
	else
	  {
	    SelectedLine = fLine;
	  }
	  
	var elements_line = document.getElementById(fLine).getElementsByTagName("td");
	var lines = document.getElementById(fTable).getElementsByTagName("tr");
	/* troca a linha selecionada por fundo vermelho*/
	for(i=0;i<elements_line.length;i++)
	  {
		if(old_background == new_background) 
		  {
		    ChangeBackground = false; 
		  }
	    elements_line[i].style.background = new_background;
	  }
	for(i=1;i <=lines.length-1;i++)
	  {
		if( (lines[i].id != fLine) && (lines[i].id.length >=1) &&  (ChangeBackground == true) )
		  {
	        var actual_line = lines[i].getElementsByTagName("td");

		    for(k=0;k<actual_line.length;k++)
			  {
			    actual_line[k].style.background = old_background;
			  }
		  }
	  }
	DisableButtonsGrid( document.getElementById('ok') );
	
  }
  
function ExcludeLine(fTable, fLine) 
  {
  	if (confirm('Confirma a exclusão deste item? ')) 
	  {
  		var TableBody = fTable.getElementsByTagName('TBody')[0]; 
  		var linha_apagar = document.getElementById(fLine); 
  		TableBody.removeChild( linha_apagar );
	  }
  }
  
function AddLine(fTable)
  {
  	var nr_aleatorio = RandomNumber();
	var tabela = document.getElementById(fTable);
	TableBody = tabela.getElementsByTagName('TBody')[0];
	var new_line = document.createElement( 'TR' );
	new_line.setAttribute('id', tabela.id+'_row_'+nr_aleatorio);
	TableBody.appendChild(new_line);
	
	return new_line.id;
  }  
  
function AddCell(fTable, fLine)
  {
  	
	var nr_aleatorio = RandomNumber();
  	var nome_cel = document.createElement( 'TD' );
	var line = document.getElementById(fLine); 
	nome_cel.setAttribute('id', fTable+'_'+fLine+'_td_'+nr_aleatorio);
	line.appendChild(nome_cel);
	
	
	return nome_cel.id;
  }
  
function AddField(fCell, fArgs)
  {
    
	var celula = document.getElementById(fCell);
	var nr_aleatorio = RandomNumber();
	var novo_campo = document.createElement('input');
	
	if(fArgs['type'] == 'display')
	  {
	    var novo_id = 'display_'+fArgs['id'];	
		novo_campo.setAttribute('disabled', 'true');
	  }
	else
	  {
	    if( fArgs['id'].length > 0 )
		  var novo_id = fArgs['id'];
		else
		  var novo_id = fCell+'_'+'_field_'+nr_aleatorio;	
	  }
	
	 
	novo_campo.setAttribute('type', fArgs['type']);
	
	novo_campo.setAttribute('size', fArgs['size']);
	if( fArgs['nome_busca'].length > 0 )
	  novo_campo.setAttribute('nome_busca', fArgs['nome_busca']);
	if( fArgs['readonly'].length > 0 )
	  novo_campo.setAttribute('readonly', fArgs['readonly']);
	
	if( fArgs['onkeypress'].length > 0 )
	  novo_campo.onkeypress = function(event) { eval(fArgs['onkeypress']) }
	if( fArgs['onkeyup'].length > 0 )
	  novo_campo.onkeyup = function(event) { eval(fArgs['onkeyup']) } 
	if( fArgs['onkeydown'].length > 0 )
	  novo_campo.onkeydown = function(event) { eval(fArgs['onkeydown']) }  
	
	if( fArgs['name'].length > 0 )
	  novo_campo.setAttribute('name', fArgs['name']);
	
	novo_campo.setAttribute('id', novo_id);
	
	//if( fArgs['value'].length > 0 )
	  novo_campo.setAttribute('value', fArgs['value']);
	celula.appendChild(novo_campo);
	
	
	
	
	return novo_id;
	
		
  }

function RandomNumber() 
  { 
	var superior = 32141232; 
	var inferior = 199; 
	var numPosibilidades = superior - inferior; 
	aleat = Math.random() * numPosibilidades; 
	return Math.round( aleat);
  }

function CriaCampoDbGrid(fOwner, fOptions)
  {
  	alert('Esta função foi excluida acidentalmente. CriaCampoDbGrid!!!')
  }
 

function FocoPrimeiroCampo(fForm)
  {
  	var campos = $(fForm).getElementsByTagName('input');
	for(i=0;i<campos.length;i++)
	  if( (campos[i].disabled == false) && (campos[i].type != 'hidden') && (foco == null) )
	    {
		  var foco = campos[i];	
		}
	foco.focus();
  }
function DisableButtonsGrid(fOwner)
  {
	var button_add = document.getElementById('add');
	var button_edit = document.getElementById('edit');
	var button_delete = document.getElementById('delete');
	
	var button_ok = document.getElementById('ok');
	if(Operation == 'add')
	  {
		button_add.disabled = true;
		button_edit.disabled = true;
		button_delete.disabled = false;
		
		
	  }
	if(Operation == 'edit')
	  {
		button_add.disabled = true;
		button_edit.disabled = true;
		button_delete.disabled = false;

	  }
	if(Operation == 'delete')
	  {
		button_add.disabled = false;
		button_edit.disabled = false;
		button_delete.disabled = false;
	  }
	if(Operation == 'ok')
	  {
		button_add.disabled = false;
		button_edit.disabled = false;
		button_delete.disabled = false;
		
	  }
  }
  
/***** Fim das funções referentes ao dbGrid *****/



/**** Início das funções referentes ao Incremental Search *****/
var LinkSelected = -1;

function KeyRegister(fParam)
  {
	if(LinkSelected == -1)
	   {
	     LinkSelected = 0;
		 var linha_anterior = null; 
	   }
	 else
	  {
		var linha_anterior = document.getElementById("resultline"+(LinkSelected) ) ;
	  }
	  
    if((fParam == 'up') && (LinkSelected > 0) ) 
	  {  
		if(document.getElementById("resultline"+(LinkSelected-1) ) != null)
		  {
		    LinkSelected--;
		  }
	  }
	if(fParam == 'down')
	  {
		if(document.getElementById("resultline"+(LinkSelected+1) ) != null)
		  {
		    LinkSelected++;
		  }
	  }
	 
	 var line = document.getElementById("resultline"+LinkSelected);
	 if(line != null) 
	   { 
	     line.setAttribute("className","dif");
	   }
	 if(linha_anterior != null) { linha_anterior.setAttribute("className", ""); }
	 if(fParam == 'select')
	  {
	    document.getElementById("link_"+LinkSelected).click();
	  }
  }
  
  
function SearchInDatabase(fTargetField, fTargetFileProcess, fHost, fDatabaseServerType, fDatabaseFile, fUsername, fPassword, fSQL, fFieldReturn, fFieldWhere, fTargetFieldValue)
  {
	  
	//var fKey = event.keyCode;
	var fKey = window.getKeyCode();
	/* se foi pressionada a tecla pra baixo ou direira */
	if( (fKey == 40) || (fKey == 39) )
	  {
		KeyRegister('down');
	  }
	/* se foi pressionada a tecla pra cima ou esquerda */
	else if((fKey == 38) || (fKey == 37)) 
	  {
		KeyRegister('up');
	  }
	if(fKey == 13) 
	  {
		KeyRegister('select');
	  }
	else if( (fKey != 38) && (fKey != 37) && (fKey != 40) && (fKey != 39) && (fKey != 13) ) 
	  {
		LinkSelected = -1;
		var fFieldValue = document.getElementById(fTargetField).value; 
		var div_result = document.getElementById("search_"+fTargetField);   
		if(div_result == null)
		  {
			var elimina_div_tempo = null;
			var target_field = document.getElementById(fTargetField);
			var no_anterior = target_field.parentNode;
			var body_page = document.getElementsByTagName('body')[0]; 
			var div_result = document.createElement("div");
			with (div_result)
			  {
				setAttribute('id', 'search_'+fTargetField)
				setAttribute('width', '150%')
				style.top = target_field.offsetTop+15;
				style.left = target_field.offsetLeft+3;
				style.display = 'block';
				style.visible = '';
				style.position = 'absolute';
				target_field.parentNode.appendChild(div_result);   
			  }
			var elimina_div_tempo = window.setInterval(function() { RemoveDivIncrementalPorTempo(div_result); }, 5000);
		  }
		/* Inicializa o objeto ajax*/
		InitializeAjax();
		LoadSearch(div_result, fTargetFileProcess, fHost, fDatabaseServerType, fDatabaseFile, fUsername, fPassword, fSQL, fFieldReturn, fFieldWhere, fFieldValue, fTargetField, fTargetFieldValue );
		
	  }
  }
  
function RemoveDivIncrementalPorTempo(fDiv)
  {
    if(LinkSelected < 1)
	  if(fDiv != null)
	    if(fDiv.parentNode != null)
		  fDiv.parentNode.removeChild(fDiv); 	
  }
  

  
  
function LoadSearch(fTargetSearch, fTargetFileProcess, fHost, fDatabaseServerType, fDatabaseFile, fUsername, fPassword, fSQL, fFieldReturn, fFieldWhere, fFieldValue, fTargetFieldDescription, fTargetFieldValue)
  {
	fTargetSearch.innerHTML='Carregando...';
	var n = "?incremental_search=true&host="+fHost+"&databaseservertype="+fDatabaseServerType+"&username="+fUsername+"&password="+fPassword+"&sql="+fSQL+"&fieldreturn="+fFieldReturn+"&fieldwhere="+fFieldWhere+"&database_file="+fDatabaseFile+"&field_value="+fFieldValue+"&target_search="+fTargetFieldDescription+"&target_field_value="+fTargetFieldValue;
	xmlhttp.open("POST", fTargetFileProcess+n,true);
	
	xmlhttp.onreadystatechange=function() {

        if (xmlhttp.readyState==4){
            var texto=xmlhttp.responseText;
			
            //Desfaz o urlencode
            texto=texto.replace(/\+/g," ")
            texto=unescape(texto);
			ExtraiScript(texto);
            //Exibe o texto no div conteúdo
            fTargetSearch.innerHTML=texto
        }
     }
    xmlhttp.send(null);
  }


function ReturnValues(fField, fValue)
  {
	var campo = document.getElementById(fField).value = fValue;
  }

function RemoveDiv(fDiv)
  {
	var div_remove = document.getElementById("search_"+fDiv);
	div_remove.parentNode.removeChild(div_remove);
  }

function SetValue(fFieldId, fValue)
  {
    
	var fieldss = document.getElementsByTagName('input');
	alert(fieldss.length);
  }


function InitializeAjax()
  {
    try
	  {
    	xmlhttp = new XMLHttpRequest();
	  }
	catch(ee)
	  {
        try
	      {
        	xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      	  }
		catch(e)
	  	  {
        	try
		  	  {
            	xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
          	  }
			catch(E)
		  	  {
            	xmlhttp = false;
        	  }
    	  }
  	  }  
  }
/**** Fim das funções referentes ao Incremental Search *****/

/**** Início das funções referentes a Telas de baixa *****/
function TelaBaixa(fOwner, fCodTelaConsulta, fCodRegistro, fCodTelaLancamento)
  {
	
	var fLeft = fOwner.offsetLeft;
	var fTop = fOwner.offsetTop;
	CriaDivTelaBaixa(fTop, fLeft, 'red', 'black'); 
	var div_alvo = document.getElementById('div_telabaixa');
	div_alvo.onclick =  function() { }
	
	var n ='monta_tela_baixa=S&cod_tela_consulta='+fCodTelaConsulta+'&cod_registro='+fCodRegistro+'&nome_tela_lancamento='+fCodTelaLancamento;
	executa_funcao_ambiente('extras/screen/tela.baixa.php', n, div_alvo.id, '')
	
  }

function CriaDivTelaBaixa(fTop, fLeft, fBackgroundColor, fFontColor)
  {
  	
	//var fOwner = document.getElementById('div_alerta');
	CriaLightBox('show');
	var fOwner = document.getElementById('div_conteudo');
	if(document.getElementById('div_telabaixa') == null)
	  {
	    var new_div = document.createElement("div");
	  }
	else
	  {
	  	var new_div = document.getElementById('div_telabaixa');
	  }
	with (new_div)
	  {
		setAttribute('id', 'div_telabaixa');
		setAttribute('width', '500px');
		style.top = fTop;
		style.left = fLeft;
		style.display = 'block';
		style.background = fBackgroundColor;
		style.color = fFontColor;
		style.padding = '3px';
		style.visible = '';
		style.position = 'absolute';
		fOwner.parentNode.appendChild(new_div);   
	  }
	
	
  }
  
function RemoveElement(fIdElement)
  {
    if( document.getElementById(fIdElement) != null)
	  {
		var elemento = document.getElementById(fIdElement);
		elemento.parentNode.removeChild(elemento);	
	  }
	CriaLightBox('hidden');
	
	/* Submete novamente o formulário de geração do relatorio */
	/*if( document.getElementById('button_visualiza') != null)
	  {
	    document.getElementById('button_visualiza').click();
	  } */

  }
  
function ReSubmitForm()
  {
    if( document.getElementById('button_visualiza') != null)
	  {
	    document.getElementById('button_visualiza').click();
	  }	
  }

  
  
/***** Fim das funções referentes a Telas de baixa **** */



/****  Início das funções referentes a classe screen *****/


function CreateDivSearchAlert(fObject, fType, fInitialText)
  {
  	
	if(fType == 'create')
	  {
	    CreateDiv(fObject, 'bottom', "#f00", "#fff", fInitialText);
		
		var campo = document.getElementById('div_child_'+fObject.id);
		
		//campo.innerHTML = fInitialText;
		
		//var oculta_div = window.setTimeout(function () { CreateDivSearchAlert(fObject, 'delete', ''); }, 2000);
	  }
	if(fType == 'delete')
	  {
	    var campo = document.getElementById('div_child_'+fObject.id);
		campo.parentNode.removeChild(campo);	
	  }
     	
  }
  
function ExibirOcultarElemento(fIdDiv)
  {
	var div = document.getElementById(fIdDiv);
  	if( div != null)
	  {
	    if( div.style.display == 'block')
	      div.style.display = 'none';
        else 
	      div.style.display = 'block';	
	  }
	  
  }
  

  
function CreateDiv(fParentField, fPosition, fBackgroundColor, fFontColor, fInicialText)
  {
  	var line_factor = 0;
	var new_div = document.createElement("div");
	var factor = 0;
	if(fPosition == 'top')
	  line_factor = -15; 
	if(fPosition == 'bottom')
	  line_factor = 35;
  	with (new_div)
	  {
		style.position = 'absolute';
		setAttribute('id', 'div_child_'+fParentField.id)
		setAttribute('width', '500px');
		style.top = fParentField.parentNode.offsetTop+line_factor+$('tabela_manutencao_cadastro').offsetTop;
		style.left = fParentField.parentNode.offsetLeft+10;
		style.display = 'block';
		style.background = fBackgroundColor;
		style.color = fFontColor;
		style.padding = '3px';
		style.visible = '';
		
		innerHTML = fInicialText;
		fParentField.parentNode.appendChild(new_div);
		   
	  }
	   
  }

   
function DisabledFields(fForm, fDisabled, fAction)
  {
    var form_elements = document.getElementById(fForm).getElementsByTagName("input");  
	var textareas = document.getElementById(fForm).getElementsByTagName("textarea");
	var campo_chave = 0;
    for(i=0; i<form_elements.length;i++)
	  {
	  	
	  	if( (fAction == 'I') || (fAction == 'A')  )
	      form_elements[i].disabled = fDisabled;
		if( (fAction == 'C') && (form_elements[i].campo_chave != 'S') ) 
		  form_elements[i].disabled = true;
		  
		  
		if( (fAction == 'C') && (form_elements[i].getAttribute("campo_chave") == 'S') 
		 || (fAction == 'A') && (form_elements[i].campo_chave == 'S')
		)
		  {
		    form_elements[i].disabled = false;
		  }
	   
	    if (form_elements[i].getAttribute("campo_chave") == 'S')
		  form_elements[i].focus();     

		  
	  }

	  

	for(i=0; i<textareas.length;i++)
	  {
		if( (fAction == 'I') || (fAction == 'A')  )
	      textareas[i].disabled = fDisabled	
		if(fAction == 'C')
		  textareas[i].disabled = true;
		if( (fAction == 'C') && (form_elements[i].campo_chave == 'S') )
		  textareas[i].disabled = false;
	  } 
  }
 
 

	
	
  
function BuscaRegistroPorCodigo(fEvent,fOwner, fNomeBusca, fTargetFileProcess)
  {
    
	/** Função para preencher o display com o valor de uma busca **/
	var fKey = window.getKeyCode(fEvent);
	
	//var fKey = fEvent.keyCode;
	if( ((fKey == 13) || (fKey == 9)) && (fOwner.value != '0')) 
	  {
		var fTargetSearch = document.getElementById('div_alerta');	
		
		
		CreateDivSearchAlert(fOwner, 'create', 'Buscando registro...');
		
		
//		alert('campo owner chave: '+fOwner.id);
		var n = "?fast_search=true&nome_busca="+fNomeBusca+"&valor_chave="+fOwner.value+"&campo_owner="+fOwner.id;
		
		xmlhttp.open("POST", fTargetFileProcess+n,true);
		
		xmlhttp.onreadystatechange=function() {
	
	        if (xmlhttp.readyState==4){
	            var texto=xmlhttp.responseText
	            //Desfaz o urlencode
	            texto=texto.replace(/\+/g," ")
	            texto=unescape(texto)
				ExtraiScript(texto);
	            //Exibe o texto no div conteúdo
	            fTargetSearch.innerHTML=texto
	        }
	     }
	    xmlhttp.send(null);
		
	  }
	else if ( (fKey == 13) && (fOwner.value == '0') )
	  {
	  	
		var url = "busca.php?busca="+fOwner.getAttribute('nome_busca')+"&retorna_codigo="+fOwner.id+"&retorna_nome=display_"+fOwner.getAttribute('id')+'&campo_retorno_id='+fOwner.getAttribute('id'); 
		/* var url = "busca.lancamentos.php?tela_lcto="+fOwner.getAttribute('cod_tela')+"&modelo_busca=lcto_auto&campo="+fOwner.getAttribute('name'); */
		janela_consulta = window.open(url,"janela1","width=750,height=550,scrollbars=YES, resizable=YES");
		janela_consulta.focus();
	  }
	
	
	
  }

function aleatorio()
  { 
    var inferior = 1;
	var superior = 128472;
    numPossibilidades = superior - inferior 
    aleat = Math.random() * numPossibilidades 
    aleat = Math.floor(aleat) 
    return parseInt(inferior) + aleat 
  }

/******    Funções para manipular tela p/ upload de arquivos     ********/
function SetarDocumentoUpload(fValue)
  {
  	var campo = document.getElementById('_UPLOAD_DOCUMENTOS');
	
	
	var campo_arquivos_ja_gravados = document.getElementById('arquivos_ja_gravados');
	campo_arquivos_ja_gravados.innerHTML += "<br />[<a href=\"#\">Excluir</a>]"+fValue;
	campo.value = campo.value+'|'+fValue;
	
	alert(campo.value);
  }
  
  
/** Função para preencher a tela com registros **/

function PreencheRegistroTela(evento, fOwner, fTargetFileProcess)
  {
  	
	//alert(key);
	//var obj = $(fOwner);
	//var fKey = key;
	
	var fKey = window.getKeyCode(evento);
	
	if( (fKey == 13) && (fOwner.value.length > 0) && (fOwner.value != '0') )
	  {
		var fValue = fOwner.value;
		var fCodTela = fOwner.getAttribute('cod_tela') ;	  	
		CreateDivSearchAlert(fOwner, 'create', 'Buscando registro...');
		
		if(fValue != '0')
	      {
		    var fAction = document.getElementById('tipo_acao').value;
			if( (fAction == 'A') || (fAction == 'C') || (fAction == 'X') )
			  {
			    var fTarget = document.getElementById('div_alerta');
			    fTarget.innerHTML = '<span class="carregando"><img src="img/loading.gif">Carregando registro...</span>'; //'Carregando registro...';
			    var n = "?preenche_registro_tela="+fCodTela+"&registro="+fValue+'&owner='+fOwner.id;
				
			    xmlhttp.open("POST", fTargetFileProcess+n,true);
			
			    xmlhttp.onreadystatechange=function() 
			      {
		            if (xmlhttp.readyState==4)
				      {
					    LimpaCamposTela();
		                var texto=xmlhttp.responseText
		                //Desfaz o urlencode
		                texto=texto.replace(/\+/g," ")
		                texto=unescape(texto);
					    ExtraiScript(texto);
		                //Exibe o texto no div conteúdo
		                fTarget.innerHTML=texto
		              }
		           }
		        xmlhttp.send(null);	
			  }
			
	      }
		if(fValue == '0')
		  {
		  	alert('Implementar a busca por telinha');
		  }

      }
	//if( (fKey == 13) && (fOwner.value.length > 0) && (fOwner.value == '0') )
	
	if( (fKey == 13) && (fOwner.value.length > 0) && (fOwner.value == '0') )
	  {
	  	/*alert('Tem que buscar o zero :-)'); */
		 var url = "busca.lancamentos.php?tela_lcto="+fOwner.getAttribute('cod_tela')+"&modelo_busca=lcto_auto&campo="+fOwner.getAttribute('name')+'&campo_retorno_id='+fOwner.getAttribute('id'); 
		/* var url = "busca.lancamentos.php?tela_lcto="+fOwner.getAttribute('cod_tela')+"&modelo_busca=lcto_auto&campo="+fOwner.getAttribute('name'); */
		janela_consulta = window.open(url,"janela1","width=750,height=550,scrollbars=YES, resizable=YES");
		janela_consulta.focus(); 
	  }
	/*alert(fKey); */
	
  }
  
  
function SelecionaRegistroParaAlteracao(fValue)
  {
  	var componentes = window.opener.document.getElementsByTagName('input');
	for(i=0; i< componentes.length; i++)
	  //if(componentes[i].campo_chave == 'S')
	  if(componentes[i].getAttribute('campo_chave') == 'S')
	    {
		  componentes[i].value = fValue;
		  componentes[i].focus();	
		}
	     
    
	window.close();
  }
function CrudButtonsControl(fFormId, fAction)
  {
  	
	if( (fAction == 'I') || (fAction == 'A') ||  (fAction == 'C') ||  (fAction == 'X') )
	  {
	  	document.getElementById('tipo_acao').value = fAction;
		
		if(fAction != 'C')
		  {
		  	document.getElementById('include_button').disabled = true;
			document.getElementById('update_button').disabled = true;
			document.getElementById('read_button').disabled = true;
			document.getElementById('delete_button').disabled = true;
			
		    document.getElementById('button_confirma').disabled = false;
			document.getElementById('button_cancela').disabled = false;	
			
			/* Limpa os campos de arquivos p/ upload */
			
			document.getElementById('_UPLOAD_DOCUMENTOS_NOMEUSER').value = '';
			document.getElementById('_UPLOAD_DOCUMENTOS').value = '';
			if( document.getElementById('arquivos_ja_gravados') != null)
			  document.getElementById('arquivos_ja_gravados').innerHTML = "<p style=\"width: auto;\"><strong>Arquivos anexados</strong>(<label id=\"numero_arquivos\">0</label></p>)";
			
		  }
	
		DisabledFields(fFormId, false, fAction );
		FormUploadControl();
	    document.getElementById('caixa_upload').style.display = 'block';
		
		
	  }
	if( (fAction == 'CONFIRM') || (fAction == 'CANCEL') )
	  {
	  	document.getElementById('include_button').disabled = false;
		document.getElementById('update_button').disabled = false;
		document.getElementById('read_button').disabled = false;
		document.getElementById('delete_button').disabled = false;
		
		document.getElementById('button_confirma').disabled = true;
		document.getElementById('button_cancela').disabled = true;
	  }
	
  }
  
function FormUploadControl()
  {
  	if(document.getElementById('form_upload') != null)
	  {
	  	DisabledFields('form_upload', false, 'I' );
	  }
  }


function LimpaCamposTela()
  {
  	/* Função utilizada para limpar os campos da tela, antes de preencher com novos dados da busca */
  	var campos = document.getElementsByTagName('input');
	for(i=0; i< campos.length; i++)
	  {
	  	if( (campos[i].type == 'text') || (campos[i].type == 'textarea') )
		  campos[i].value = '';
		/* se for campo checkbox, então desmarca como default */
		if(campos[i].type == 'checkbox')
		  campos[i].checked = false;
	  }
  }


function VerificaData(fCampo) 
{
	//var digData = fdigData.value.replace(/'/'/g,"");
	var digData = fCampo.value;
	if(fCampo.value.length > 1)
	  {
	    var bissexto = 0;
	    var data = digData; 
	    var tam = data.length;
	    var ano = data.substr(6,4)
		// T final
		if (tam == 8)
		  {
		    if(ano > 69)
			  ano = '19'+ano;
			else
			  ano = '20'+ano;
			tam = 10;	
		  }
	    if (tam == 10) 
	    {
	        var dia = data.substr(0,2)
	        var mes = data.substr(3,2)
	        //var ano = data.substr(6,4)
			//alert('dia:'+dia+' mês:'+mes+' ano:'+ano);
	        if ((ano > 1900)||(ano < 2100))
	        {
	            switch (mes) 
	            {
	                case '01':
	                case '03':
	                case '05':
	                case '07':
	                case '08':
	                case '10':
	                case '12':
	                    if  (dia <= 31) 
	                    {
	                        return true;
	                    }
	                    break
	                
	                case '04':        
	                case '06':
	                case '09':
	                case '11':
	                    if  (dia <= 30) 
	                    {
	                        return true;
	                    }
	                    break
	                case '02':
	                    /* Validando ano Bissexto / fevereiro / dia */ 
	                    if ((ano % 4 == 0) || (ano % 100 == 0) || (ano % 400 == 0)) 
	                    { 
	                        bissexto = 1; 
	                    } 
	                    if ((bissexto == 1) && (dia <= 29)) 
	                    { 
	                        return true;                 
	                    } 
	                    if ((bissexto != 1) && (dia <= 28)) 
	                    { 
	                        return true; 
	                    }            
	                    break                        
	            }
	        }
	    }    
	    alert("Data inválida: "+data+".");
		fCampo.focus();
	    return false;	
	  }
    
}

/**** Função para buscar lista telefônica ****/

function CriaLightBox(fAction)
  {
	if(fAction == 'show')
	  {
	    //var corpo = document.getElementById('corpo');
		var corpo = document.getElementsByTagName('body')[0];
		if (corpo == null)
		  alert('Não achou a tag body');
		if( document.getElementById('lightbox_ofcweb') == null)
		  {
			var new_div = document.createElement("div");
		  	with (new_div)
			  {				
				setAttribute('id', 'lightbox_ofcweb');
				style.height = corpo.offsetHeight+'px';
				corpo.appendChild(new_div);
			  }	
	        TestaEmbaixo('hidden', "lightbox_ofcweb");
		  }	
		
	  }
	else if(fAction == 'hidden')
	  {
	    
		TestaEmbaixo('show', "lightbox_ofcweb");
		//var div_lightbox = document.getElementById('lightbox_ofcweb');
		var div_lightbox = $('lightbox_ofcweb');
		
		
		if(div_lightbox != null)
		  div_lightbox.parentNode.removeChild(div_lightbox);	
	  }
    
  }


  
function ShowMessage(fMsg)
  {
  	
	CriaLightBox('show');
	
	/* Cria div p/ comportar a mensagem de texto */
	var corpo = document.getElementById('corpo');
	var new_showmessage = document.createElement("div");
  	with (new_showmessage)
	  {
		setAttribute('id', 'showmessage');
		new_showmessage.innerHTML = fMsg+'<br>';
		style.backgroundColor = '#fff';
		
		style.top = '25%';
		style.left = '27%';
		style.position = 'absolute';
		style.width = '45%';
		style.height = '30%';
		style.border= '3px solid #000';
		style.zIndex= '100000';
		
		corpo.appendChild(new_showmessage);
	  }	
	var botao_ok = document.createElement("a");
	new_showmessage.appendChild(botao_ok);
	with (botao_ok)
	  {
		innerHTML = 'OK';
		setAttribute('id', 'ok_showmessage');
		setAttribute('href', '#');
	    style.border = '1px solid #000';
		style.position = 'absolute';
		style.textDecoration = 'none';
		style.color = '#0099FF';
		style.top = '80%';
		style.left = '90%';
		
	  }
    botao_ok.onclick = function() { CriaLightBox('hidden'); botao_ok.parentNode.parentNode.removeChild(botao_ok.parentNode); return false;}
	
  }
  
  
  
function TestaEmbaixo(fAction, fOwner)
  {
  	
	var x = document.getElementById(fOwner);
	if(x != null)
	  {
	    if(fAction == 'hidden')
		  {
			//x.style.display = "block";
		    if(!x.ieFix)
			  x.ieFix = hitTest(x, document.getElementsByTagName("a"));
		    for(var i = x.ieFix.length; i; x.ieFix[--i].style.visibility = "hidden");
			  {
			  	}
		    
			x.ieFix = hitTest(x, document.getElementsByTagName("select"));
		    for(var i = x.ieFix.length; i; x.ieFix[--i].style.visibility = "hidden");
			  {
			  	}
		     x.ieFix = null;
		  }
		else if(fAction == 'show')
		  {
		    //x.style.display = "block";
		    if(!x.ieFix)
			  x.ieFix = hitTest(x, document.getElementsByTagName("a"));
		    for(var i = x.ieFix.length; i; x.ieFix[--i].style.visibility = "");	
			
			x.ieFix = hitTest(x, document.getElementsByTagName("select"));
		    for(var i = x.ieFix.length; i; x.ieFix[--i].style.visibility = "");
			x.ieFix = null;				
		  }	
	  }
	
  }
function BuscaListaTelefonica(event, fOwner, fDivDestino)
  {
	CriaLightBox('show');
	//if( (document.getElementById('div_child_' + fOwner.id) == null) && (fDivDestino == null) )
	if( (document.getElementById('div_lista_telefonica') == null) && (fDivDestino == null) )
	  {
		var new_div = document.createElement("div");
	  	with (new_div)
		  {
			setAttribute('id', 'div_lista_telefonica')
			style.zIndex = '999999';
			fOwner.parentNode.appendChild(new_div);
			
		  }
		
	  }
	if(fDivDestino != null)
	  var div_criada = document.getElementById(fDivDestino);
	else
	  var div_criada = document.getElementById('div_lista_telefonica');
	div_criada.style.textAlign = 'left';
	div_criada.style.zIndex = '999999';
	div_criada.innerHTML = "Buscando lista telefônica...";
		    
	var n = "?cliente="+fOwner.value;
	xmlhttp.open("GET", 'extras/lista_telefonica/lista.telefonica.php'+n,true);
			
    xmlhttp.onreadystatechange=function() 
      {
        if (xmlhttp.readyState==4)
	      {
		    
            var texto=xmlhttp.responseText
            //Desfaz o urlencode
            texto=texto.replace(/\+/g," ")
            texto=unescape(texto);
		    ExtraiScript(texto);
            //Exibe o texto no div conteúdo
            div_criada.innerHTML=texto
          }
       }
    xmlhttp.send(null);	
	
  }


function SempreAtiva()
  {
    /* Mexi p/ não chamar no meu APACHe.....o valr correto é 120000 (dois minutos)*/
    //var chama_sempre_ativa = window.setInterval( function() { ReativarSession(); } , 1200000);
  }

function ReativarSession()
  {
	var html_tag = document.getElementsByTagName('body')[0];
	var nova_div = document.createElement('div');
	with (nova_div)
	  {
	  	setAttribute('id', 'renova_sessao');
		innerHTML = 'Aguarde... renovando sessão';
	  }
	html_tag.appendChild(nova_div);
	
	var n = "?cliente="
	xmlhttp.open("GET", 'extras/keep_alive/keep.alive.php'+n,true);
	xmlhttp.onreadystatechange=function() 
      {
        if (xmlhttp.readyState==4)
	      {
			nova_div.parentNode.removeChild(nova_div);
          }
       }
	xmlhttp.send(null);	
  }


function $(fObjeto)
  {
  	var obj = document.getElementById(fObjeto);
	
	return obj;
  }

function AplicarFiltro(fForm)
  {
	var campos = '';
	var alvo = 'grid_registros';
	var cod_tela = 0;
	
	
	for(i=0; i < fForm.elements.length;i++)
	  {
	  	var filtro = '^display';
		padrao = new RegExp(filtro);
		testar = padrao.test(fForm.elements[i].id);
	    /* Ignora elementos fieldset */
		if( (fForm.elements[i].tagName.toLowerCase() != 'fieldset') && (testar == false) )
		if( (fForm.elements[i].type != 'fieldset') && (fForm.elements[i].value.length > 0) && (fForm.elements[i].type != 'button') ) 
		  {
			//alert(fForm.elements[i].id+" "+fForm.elements[i].getAttribute('NOME_BUSCA') );
			if( (fForm.elements[i].getAttribute('NOME_BUSCA') != '') && (fForm.elements[i].getAttribute('NOME_BUSCA') != null))
			  campos += fForm.elements[i].name.replace("campo_", "") + '_AVALIAUNICO'+ "="+ fForm.elements[i].value+"&" ;
			else
			  campos += fForm.elements[i].name.replace("campo_", "") + "="+ fForm.elements[i].value+"&" ;
		  } 
		  
	  }
	cod_tela = $('_cod_tela').value;
	
	campos = '_cod_tela='+cod_tela+'&'+campos;
	var corpo = document.getElementsByTagName('body')[0];
	var div_ajax_simplificado = document.createElement('div');
	with (div_ajax_simplificado)
	  {
	  	id='div_ajax_simplificado';
		innerHTML = 'Aguarde, aplicando filtro.';
	  }
	corpo.appendChild(div_ajax_simplificado);
	
    xmlhttp.open("GET", 'extras/screen/aplica.filtro.php'+'?'+campos,true);
    xmlhttp.onreadystatechange=function() 
	  {
        if (xmlhttp.readyState==4){
			//Lê o texto
            var texto=xmlhttp.responseText
            //Desfaz o urlencode
            texto=texto.replace(/\+/g," ")
            texto=unescape(texto)
            //Exibe o texto no div conteúdo
            var conteudo=document.getElementById(alvo)
            conteudo.innerHTML=texto;
			div_ajax_simplificado.parentNode.removeChild(div_ajax_simplificado);
			ExtraiScript(texto);
        }
      }
    xmlhttp.send(null)
	
  }
  
  
function GridRegistrosSeleciona(fLine)
  {
    //CriaLightBox('show');
	var celulas = fLine.getElementsByTagName('td');
	var nome_celulas = $('tabela_registros_inicial').getElementsByTagName('th');
	var todos_os_campos = '';
	
	var teste = document.getElementsByTagName('input');
	
	for(i=0; i < teste.length;i++)
	  {
	  	/* Converte todos os Id's p/ minusculo..senão dá problema no FF*/
		teste[i].id = teste[i].id.toLowerCase();
	  }
	
	for(i=0; i < celulas.length; i++)
	  {
		var nome_campo = null;
	    /* varre o link, pra ver se não tem nenhum img ou link */
		var elimina_img = nome_celulas[i].getElementsByTagName('a');
		for(k=0; k< elimina_img.length; k++)
		  {
			nome_campo = elimina_img[k].innerHTML;
		  }
		if(nome_campo == null)
		  var nome_campo = nome_celulas[i].innerHTML.replace(/\ /g, '');
		else
		  var nome_campo = nome_campo.replace(/\ /g, '');

		var campo = $(nome_campo);
		if( (campo != null) && (campo.type == 'checkbox') )
		  {
		    var valor_check = celulas[i].innerHTML.replace(/^\ /g, '');
			//alert(valor_check);
			if( (valor_check.toLowerCase() == '<img src="img/check.gif">' ) || (valor_check == 's') )
			  {
			  	campo.value = 'S'; 
				campo.checked = true;
			  }	
			else
			  campo.checked = false;
		  }
		else if( campo != null )
		  {
		    campo.value = celulas[i].innerHTML.replace(/^\ /g, '');	
		  }
		  
		/* pega valor de chave */
		if(campo.getAttribute('campo_chave') == 'S')
		  {
		  	var valor_chave = campo.value;
			var tela = campo.getAttribute('_cod_tela');
		  }
		  
	  } 
	ExibirOcultarElemento('div_manutencao_registro');
	$('tipo_acao').value = 'A';
	$('aba_listagem_principal').style.display = 'none';
	HabilitarForm('A', 'manutencao_cadastro', false);
	
	/* Força a seleção da primeira aba do registro */
	$('container_abas_internas').getElementsByTagName('a')[0].onclick();
	
	/* Retorna as opções do cadastro/lançamento via JSON*/
	RetornaOpcoesCadastro(tela, valor_chave);
	
	
	
	
  }

function RetornaOpcoesCadastro(fCodTela, fValorChave)
  {
  
	var p_buttons = $('cadastro_botoes_avancado');
	p_buttons.innerHTML = 'Carregando opções...';
	xmlhttp.open("GET", 'extras/screen/json.opcoes.tela.php?'+'tela='+fCodTela+'&chave='+fValorChave+'&aleat='+aleatorio(),true);
    xmlhttp.onreadystatechange=function() 
	  {
	    if (xmlhttp.readyState==4)
		  {
	        p_buttons.innerHTML = '';
			var texto=xmlhttp.responseText
			//alert(texto)
			eval( 'obj_Json = '+texto)
			//alert(obj_Json.length)
			for(i=0; i<obj_Json.length;i++ )
			  {
				p_buttons.innerHTML += obj_Json[i];
			  }
	      }
      }
     xmlhttp.send(null)
  }
  
function GridExcluirRegistro()
  {
  	if(confirm('Deseja realmente excluir este registro?') == true)
	  {
		$('tipo_acao').value = 'X';
		$('manutencao_salvar_registro').click();
	  }
  } 

function GridReordenar(fOrdem)
  {
	var combo = $('_combobox_filtro_ordem_campo');
	var head = $('head_'+fOrdem);
	head.innerHTML = 'Ordenando resultados...';
	if(combo.value == (fOrdem+1 ))
	  {
	    var combo_ordenacao = $('_combobox_filtro_ordenacao');
		if(combo_ordenacao.selectedIndex == 1)
		  combo_ordenacao.selectedIndex = 0;
		else
		  combo_ordenacao.selectedIndex = 1;	
	  } 
	else
	  {
	    combo.selectedIndex = fOrdem;
	  }	
	AplicarFiltroOnTheFly();
  }
  
function GetDadosGridInterno(fNomeGrid)
  {
  	
	/* TEM Q REMOVER ISSO AQUI...É SÓ NO TESTE*/
	var div= document.getElementById('div_ajax_simplificado');
	if(div != null)
	  div.parentNode.removeChild(div);
	/* FIM DE REMOVER*/
	var tela = document.getElementById('controle').value;
	var campos_form = document.getElementById('manutencao_cadastro').getElementsByTagName('input');
	for(i=0; i<campos_form.length;i++)
	  {
	  	if(campos_form[i].getAttribute('campo_chave') == 'S')
		  var valor = campos_form[i].value;
	  }
	var corpo = document.getElementsByTagName('body')[0];
	var div_ajax_simplificado = document.createElement('div');
	var gridBody = $(fNomeGrid);
	//alert(gridBody.parentNode.offsetTop);
	with (div_ajax_simplificado)
	  {
	  	id='div_ajax_simplificado';
		style.top = gridBody.parentNode.offsetTop;
		style.position = 'relative';
		innerHTML = 'Aguarde, preenchendo dados do grid.';
		 
	  }
	gridBody.parentNode.appendChild(div_ajax_simplificado);
	
	
      
	
	var parametro = 'campo='+fNomeGrid+'&tela='+tela+'&value='+valor;
	
	xmlhttp.open("GET", 'extras/screen/dbgrid.preenchimento.php'+'?'+parametro+'&aleat='+aleatorio(),true);
	
    xmlhttp.onreadystatechange=function() 
	  {
	    if (xmlhttp.readyState==4)
		  {
			//Lê o texto
	        var texto=xmlhttp.responseText
			
	        //Desfaz o urlencode
	        texto=texto.replace(/\+/g," ")
	        texto=unescape(texto)
	        //Exibe o texto no div conteúdo
	        var conteudo=div_ajax_simplificado;
	        conteudo.innerHTML=texto;
			div_ajax_simplificado.parentNode.removeChild(div_ajax_simplificado);
			ExtraiScript(texto);
	    }
    }
    xmlhttp.send(null)
  }
  
function HabilitarForm(fOperacao,fForm, fHabilitar)
  {
  	if(fHabilitar == false)
	  var Desabilitar = true;
	else
	  var Desabilitar = false;
	  
	if( (Desabilitar == false) && ($('container_abas_internas').getElementsByTagName('a')[0] != null) )
	  $('container_abas_internas').getElementsByTagName('a')[0].onclick();
	$('tipo_acao').value = fOperacao;
	enterAsTab(fForm);
	var campos_form = $(fForm).getElementsByTagName('input');
	for(i=0; i< campos_form.length; i++)
	  {
		if(( (fOperacao == 'A') || (fOperacao == 'I') ) && (campos_form[i].getAttribute('campo_chave') == 'S') )
		  {
		    campos_form[i+1].disabled = Desabilitar;
			if(Desabilitar == false)
			  campos_form[i+1].focus();	
			if(fOperacao == 'I')
			  campos_form[i].value = '';
		  }
		else if ( (campos_form[i].getAttribute('campo_chave') != 'S') && (campos_form[i].getAttribute('readonly') != true) ) 
		  campos_form[i].disabled = Desabilitar; 
		
		//alert(campos_form[i].getAttribute('readonly'));
		if( (fOperacao == 'I')  && (campos_form[i].getAttribute('readonly') == true) )
		  campos_form[i].value = '';
	  }
	/* TextArea */
	var campos_textarea_form = $(fForm).getElementsByTagName('textarea');
	for(i=0; i< campos_textarea_form.length; i++)
	  {
	    campos_textarea_form[i].disabled = Desabilitar; 	
	  }  
	if(Desabilitar == true)  
	  $('botoes_cadastro').style.display = 'none';
	else
	  $('botoes_cadastro').style.display = 'block';
	  
	var botoes_cadastro = $('botao_acoes_registro').getElementsByTagName('button');
	for(i=0; i<botoes_cadastro.length;i++)
	  {
	    if(Desabilitar == false)
		  botoes_cadastro[i].setAttribute('disabled', 'true');	
		else
		  botoes_cadastro[i].removeAttribute('disabled');
	  }
	    
	
  }
  
function VerificaLog()
  {
  	var tela = $('controle').value;
	var campos_form = $('manutencao_cadastro').getElementsByTagName('input');
	for(i=0; i<campos_form.length;i++)
	  {
	  	if(campos_form[i].getAttribute('campo_chave') == 'S')
		  var registro = campos_form[i].value;
	  }
	var url = "extras/screen/exibe.log.registro.php?"+"tela="+tela+"&registro="+registro; 
	janela_consulta = window.open(url,"janela_logs","width=550,height=350,scrollbars=YES, resizable=YES");
	janela_consulta.focus(); 
	
  }
function GridRegistroContextMenu(fEvent)
  {
	var corpo = document.getElementsByTagName('body')[0];
	var div_contexto = document.createElement('div');
	var texto_contexto = '';
	with (div_contexto)
	  {
	  	id='menu_contexto';
		style.position = 'absolute';
		style.top = fEvent.clientY;
		style.left = fEvent.clientX;
		texto_contexto += '<ul>';
		texto_contexto += '<li><a href="incluir">+</a>Incluir</li>';
		texto_contexto += '<li><a href="Alterar">+</a>Alterar</li>';
		texto_contexto += '<li><a href="Excluir">-</a>Excluir</li>';
		texto_contexto += '<li><a href="Consultar">^</a>Consultar</li>';
		texto_contexto += '</ul>';
		innerHTML = texto_contexto;
		onmousedown = function() { corpo.removeChild(div_contexto); }
	  }
	corpo.appendChild(div_contexto);
  }  
  
  
function ControlaVoltarListagem()
  {
	if( $('botoes_cadastro').style.display == 'block' )
	  {
	    if( confirm('Deseja abandonar a edição deste registro?') )
		  {
		    ExibirOcultarElemento('botoes_cadastro');
			ExibirOcultarElemento('aba_listagem_principal'); 
			ExibirOcultarElemento('div_manutencao_registro');
				
		  }	
	  }
	else
	  {
	    ExibirOcultarElemento('aba_listagem_principal'); 
		ExibirOcultarElemento('div_manutencao_registro');	
	  }
	
  }
function SelecionaAba(fIdComponente)
  {
  	var elemento_selecionado = $(fIdComponente);
	with (elemento_selecionado)
	  {
	  	setAttribute('className', 'abas_grandes_selecionada');
		setAttribute('class', 'abas_grandes_selecionada');
	  }
	var container_elementos = $('container_orelha_abas').getElementsByTagName('span');
	for(i=0; i < container_elementos.length; i++)
	  if(container_elementos[i].id != fIdComponente)
	    {
		  with (container_elementos[i])
		    {
			  setAttribute('className', 'abas_grandes');
			  setAttribute('class', 'abas_grandes');	
			}
		}
  } 
 

function SelecionaAbaInterna(fOwner, fIdAba)
  {
	var PaiAbinhas = $(fIdAba);
	
	var AbasTela = $('div_manutencao_registro').getElementsByTagName('div');
	//alert(AbasTela.length)
	var filtro = '^tab_interna_';
	padrao = new RegExp(filtro);
	for(i=0; i< AbasTela.length; i++)
	  {
	  	testar = padrao.test(AbasTela[i].id);
		if(testar)
		  {
		  	if(AbasTela[i].id == fIdAba)
			  AbasTela[i].style.display = 'block';
			else  
			  AbasTela[i].style.display = 'none';
		  }
	  }
	links_container = $('container_abas_internas').getElementsByTagName('a');
	for(i=0; i<links_container.length; i++ )
	  {
	    links_container[i].setAttribute('className', 'abas_internas_nao_selecionada');
		links_container[i].setAttribute('class', 'abas_internas_nao_selecionada');	
	  }
	fOwner.setAttribute('className', 'abas_internas_selecionada');
	fOwner.setAttribute('class', 'abas_internas_selecionada');
	if(fIdAba == 'tab_interna_documentos_anexados')
	  VerificaDocumentos(fIdAba.replace(/tab_interna_/, ''));
	else
	  VerificaDbGrids(fIdAba.replace(/tab_interna_/, ''));
  }
 
function UploadDoc(fField)
  {
  	var form_manutencao = $('manutencao_cadastro').getElementsByTagName('input');
	for(i=0;i<form_manutencao.length;i++)
	  {
	  	if(form_manutencao[i].getAttribute('campo_chave') == 'S')
		  var chave = form_manutencao[i].value;
		if( (form_manutencao[i].getAttribute('_cod_tela') != null) && (form_manutencao[i].getAttribute('_cod_tela').length > 0) )
		  var tela = form_manutencao[i].getAttribute('_cod_tela');
	  }
	 
	/* cria alerta p/ usuário q está fazendo upload */
	var div_alerta_upload = document.createElement('div');
	with( div_alerta_upload )
	  {
	  	id='div_alerta_upload';
		innerHTML = 'Aguarde, fazendo o upload do arquivo...';
	  } 
	$('corpo').appendChild(div_alerta_upload);  
	
	var form_upload = $('form_upload');
	var ParentOwner = fField.parentNode;
	form_upload.appendChild(fField);
	$('upload_cod_registro_arquivo').value = chave;
	form_upload.submit();
	ParentOwner.appendChild(fField);
  }

function VerificaDocumentos(fAba)
  {
  	var form_manutencao = $('manutencao_cadastro').getElementsByTagName('input');
	var table_documentos = $('table_documentos');
	for(i=0;i<form_manutencao.length;i++)
	  {
	  	if(form_manutencao[i].getAttribute('campo_chave') == 'S')
		  var chave = form_manutencao[i].value;
		if( (form_manutencao[i].getAttribute('_cod_tela') != null) && (form_manutencao[i].getAttribute('_cod_tela').length > 0) )
		  var tela = form_manutencao[i].getAttribute('_cod_tela');
	  }
	xmlhttp.open("GET", 'extras/screen/lista.documentos.php?'+'tela='+tela+'&chave='+chave+'&aleat='+aleatorio(),true);
    xmlhttp.onreadystatechange=function() 
	  {
	    if (xmlhttp.readyState==4)
		  {
	        var texto=xmlhttp.responseText
			//alert(texto)
			eval( 'obj_Json = '+texto)
			var retornar = '';
			
			/* remove todas as linhas do dbGrid */
			/*for(var i = table_documentos.rows.length; i--;)
			  {
			  	if( (table_documentos.rows[i].parentNode != null) && (table_documentos.rows[i].parentNode.tagName != 'THEAD') )
				  table_documentos.deleteRow(i);
			  	//alert('removeu');
			  } */
			/* remove todas as linhas do dbGrid */
			 while (table_documentos.rows.length > 0)
		       {
				 table_documentos.deleteRow(0); 
			   }
			for(i=0; i<obj_Json.length;i++ )
			  {
				var linha = table_documentos.insertRow(-1);
				var campo_arquivo = linha.insertCell(0);
				var campo_data = linha.insertCell(1);
				var campo_hora = linha.insertCell(2);
				var campo_usuario = linha.insertCell(3);
				
				campo_data.innerHTML = obj_Json[i].data;
				campo_hora.innerHTML = obj_Json[i].hora;
				 
				campo_arquivo.innerHTML = obj_Json[i].arquivo_nome_usuario;
				campo_usuario.innerHTML = obj_Json[i].usuario;
			  }
	      }
      }
     xmlhttp.send(null)
  }
  
  
function CadListaBloquetos(fOwner)
  {
  	var chave = '';
	var form_m = $('manutencao_cadastro').getElementsByTagName('input');
	for(i=0;i<form_m.length;i++)
	  if(form_m[i].getAttribute('CAMPO_CHAVE') == 'S')
	    var chave = form_m[i].value;   
	//alert(fOwner.id);
	xmlhttp.open("GET", 'extras/screen/extras.lista.bloquetos.php?cr='+chave+'&aleat='+aleatorio(),true);
	xmlhttp.onreadystatechange=function() 
	  {
	    if (xmlhttp.readyState==4)
		  {
	        var texto=xmlhttp.responseText
			//alert(texto);
			eval( 'obj_Json = '+texto)
			var retornar = '';
			if(obj_Json.length>0)
			  {
			  	var destino = $('tab_interna_'+fOwner.id);
				var new_table = document.createElement('table');
				destino.appendChild(new_table);
				//var linha = new_table.insertRow(0);
				//var cel_a = linha.insertCell(0);
				//cel_a.innerHTML = 'asdasdasd';
				//new_table.insertRow(0);
				//new_table.insertRow(0); 
			  }
			  
			  
			for(i=0; i<obj_Json.length;i++ )
			  {
				
				var nome_campos = obj_Json[i].nome_campos;
				
				if(i==0)
				  {
				    var linha = new_table.insertRow(-1);
					for(j=0;j<nome_campos.length;j++)
					  {
					    
						var head_celula = linha.insertCell(-1);
						head_celula.innerHTML = nome_campos[j];	
					  }	
				  }
				var linha = new_table.insertRow(-1);
				for(j=0;j<nome_campos.length;j++)
				  {
				    var cel_a = linha.insertCell(-1);
					cel_a.innerHTML = obj_Json[i][ nome_campos[j] ];	
				  }
				
				/*for(j=0;j<obj_Json[i].length;j++)
				  {
				    var cel_a = linha.insertCell(0);
					cel_a.innerHTML = obj_Json[i][0];
					var cel_b = linha.insertCell(0);
					cel_b.innerHTML = obj_Json[i]['VALORPARCELA'];
					
					//var nome_campos = obj_Json[i].nome_campos.split(",");
					var nome_campos = obj_Json[i].nome_campos;
					alert(nome_campos[0]);
				  }*/
				//var cel_a = linha.insertCell(0);
				//alert(obj_Json[0].VALORPARCELA)
				//GetDadosGridInterno(obj_Json[i]);
			  }
	      }
      }
     xmlhttp.send(null)
  }
function RemoverArquivo(fOwner, fArquivoUsuario, fArquivoFisico, fVerify)
  {
	
	
	if(confirm('Deseja realmente excluir o arquivo '+fArquivoUsuario+'?'))
	  {
		xmlhttp.open("GET", 'extras/documento_upload/excluir_doc.php?doc='+fArquivoFisico+'&verify='+fVerify+'&aleat='+aleatorio(),true);
		xmlhttp.onreadystatechange=function() 
		  {
		  	if (xmlhttp.readyState==4)
			  {
			  	alert(xmlhttp.responseText);
				$('table_documentos').deleteRow(fOwner.parentNode.parentNode.rowIndex);
			  }
		  }
		xmlhttp.send(null)	
		return false;
	  }
	else
	  {
	  	return false;
	  }
  }
function VerificaDbGrids(fAba)
  {
	/* Só executa se foi passado aba maior q 0*/
	if(fAba > 0)
	  {
	    xmlhttp.open("GET", 'extras/screen/dbgrid.preenchimento.php?'+'busca_grids_aba='+fAba+'&aleat='+aleatorio(),true);
		xmlhttp.onreadystatechange=function() 
		  {
		    if (xmlhttp.readyState==4)
			  {
		        var texto=xmlhttp.responseText
				eval( 'obj_Json = '+texto)
				for(i=0; i<obj_Json.length;i++ )
				  {
					GetDadosGridInterno(obj_Json[i]);
				  }
		      }
		  }
		 xmlhttp.send(null)	
	  }
	
  }
  
function SalvaFiltroPadrao(fForm)
  {
	alert(MontaValores(fForm.id, ''));
	var elemento_destino = document.createElement('span');
	with (elemento_destino)
	  {
	  	innerHTML = 'Enviando informações';
		id="elemento_destino_post";
	  }
	document.getElementsByTagName('body')[0].appendChild(elemento_destino);
	EnviaForm('extras/screen/salva.filtro.usuario.php', 'elemento_destino_post', fForm.id, '');
  }
function PostaForm(fFormId)
  {
  	var fForm = $(fFormId);
	var elemento_destino = document.createElement('span');
	with (elemento_destino)
	  {
	  	innerHTML = 'Enviando informações';
		id="elemento_destino_post";
	  }
	document.getElementsByTagName('body')[0].appendChild(elemento_destino);
	var enviou_form = EnviaForm(fForm.getAttribute('action'), 'elemento_destino_post', fFormId, '');
	
	//alert(enviou_form) ;
	/*if(   )
	  return true;
	else
	  return false; */
	
	var chama_sempre_ativa = window.setTimeout( function() { AplicarFiltroOnTheFly(); } , 500);
	return enviou_form;
	
  }

function AplicarFiltroOnTheFly()
  {
	var teste = $('form_opcoes_filtro');
	AplicarFiltro(teste);
  }
 
function Paginacao(fSkip)
  {
  	$('_skip_registros').value = fSkip;
	
	AplicarFiltroOnTheFly();
	//fLink.setAttribute('className', 'paginacao_cadastro_selecionado');
	//fLink.setAttribute('class', 'paginacao_cadastro_selecionado');
  }

function EmiteBloquetoUnico(fCodBloqueto)
  {
  	janela=window.open("extras/bloqueto/bloqueto.php?id=" + fCodBloqueto ,"","width=550,height=450,scrollbars=yes, resizable=yes")
  }
  
function ContasReceberEmiteBloqueto()
  {
    campos = $('manutencao_cadastro').getElementsByTagName('input');
	for(i=0; i< campos.length; i++)
	  if(campos[i].getAttribute('CAMPO_CHAVE') == 'S')
	    var registro = campos[i].value;
	//alert(registro);
	janela=window.open("extras/bloqueto/bloqueto.php?cr=" + registro ,"","width=550,height=450,scrollbars=yes, resizable=yes")	
  }
  
  
function ContasReceberCriaBaixa(fTelaLancamento)
  {
	var form_manut = $('manutencao_cadastro').getElementsByTagName('input');
	for(i=0;i<form_manut.length;i++)
	  {
	    if(form_manut[i].getAttribute('_cod_tela') > 0 )
		  var cod_tela = form_manut[i].getAttribute('_cod_tela');
		if(form_manut[i].getAttribute('campo_chave') == 'S') 
		  var cod_registro = form_manut[i].value;
		
	  }
	var n ='monta_tela_baixa=S&cod_tela_consulta='+cod_tela+'&cod_registro='+cod_registro+'&nome_tela_lancamento='+fTelaLancamento;
	janela=window.open("extras/screen/tela.baixa.php?"+n ,"","width=750,height=350,scrollbars=yes, resizable=yes")

  }
function ContasReceberEstornar()
  {
  	var form_manut = $('manutencao_cadastro').getElementsByTagName('input');
	for(i=0;i<form_manut.length;i++)
	  {
	    if(form_manut[i].getAttribute('_cod_tela') > 0 )
		  var cod_tela = form_manut[i].getAttribute('_cod_tela');
		if(form_manut[i].getAttribute('campo_chave') == 'S') 
		  var cod_registro = form_manut[i].value;
		
	  }
	var n ='monta_tela_baixa=S&cod_tela_consulta='+cod_tela+'&cod_registro='+cod_registro+'&tipo_lcto=cr';
	janela=window.open("extras/financeiro/estorno.php?"+n ,"","width=750,height=350,scrollbars=yes, resizable=yes")
  }

//Para visualizar os componentes encima dos select do Internet Explorer :-S
hitTest = function(o, l){
    function getOffset(o){
        for(var r = {l: o.offsetLeft, t: o.offsetTop, r: o.offsetWidth, b: o.offsetHeight};
            o = o.offsetParent; r.l += o.offsetLeft, r.t += o.offsetTop);
        return r.r += r.l, r.b += r.t, r;
    }
    for(var b, s, r = [], a = getOffset(o), j = isNaN(l.length), i = (j ? l = [l] : l).length; i;
        b = getOffset(l[--i]), (a.l == b.l || (a.l > b.l ? a.l <= b.r : b.l <= a.r))
        && (a.t == b.t || (a.t > b.t ? a.t <= b.b : b.t <= a.b)) && (r[r.length] = l[i]));
    return j ? !!r.length : r;
};

var BuscaIncrementalSelecionada = 0;

function ControlaClassBuscaIncremental(fEvent, fSelecionar)
  {
    var selecionar = $('buscainc'+fSelecionar);
	if(selecionar != null)
	  {
	    var todos_links = selecionar.parentNode.getElementsByTagName('a');
		for(i=0; i<todos_links.length;i++)
		  {
		    todos_links[i].setAttribute('className', '');
			todos_links[i].setAttribute('class', '');	
		  }
		selecionar.setAttribute('className', 'busca_link_selecionado');	
		selecionar.setAttribute('class', 'busca_link_selecionado');	
	  }
	
  }
function BuscaIncremental(fEvent, fOwner)
  {
    /* Seta para cima */
	if( (fEvent.keyCode == 40) )
	  {
	    if($('buscainc'+(BuscaIncrementalSelecionada+1)) != null )
		  {
		  	BuscaIncrementalSelecionada++;
		    ControlaClassBuscaIncremental(fEvent, BuscaIncrementalSelecionada);
		  }
	  }
	/* Seta para baixo */  
	if( (fEvent.keyCode == 38) )
	  {
		if($('buscainc'+(BuscaIncrementalSelecionada-1)) != null )
		  {
		  	BuscaIncrementalSelecionada--;
			ControlaClassBuscaIncremental(fEvent, BuscaIncrementalSelecionada);
		  }
		
	  }
	/* Enter */  
	if( (fEvent.keyCode == 13) )
	  {
		$('buscainc'+BuscaIncrementalSelecionada).onclick(); 
	  }
	if( ((fEvent.keyCode > 50) && (fOwner.value.length > 0) ) ||(fEvent.keyCode == 8)  )
	  {
	    BuscaIncrementalSelecionada=0;
		var campo_codigo = fOwner.id.replace(/display/g, "");
		var value_search = fOwner.value;
		var nome_busca = fOwner.getAttribute('NOME_BUSCA');
		xmlhttp.open("POST", caminho_ofcweb+'class.telas.php?fast_search_model2=S&value_search='+value_search+'&search='+nome_busca,true);
		xmlhttp.onreadystatechange=function() 
		  {
	        if (xmlhttp.readyState==4){
	            var texto=xmlhttp.responseText
	            texto=unescape(texto)
				ExtraiScript(texto);
				//var campo_codigo = $(nome_campo_codigo).value = 
	            //$('div_alerta').innerHTML=texto;
				
				eval( 'obj_Json = '+texto)
				var retornar = '';
				for(i=0; i<obj_Json.length;i++ )
				  {
				  	if(i==0)
					  retornar += "<a href=\"#\" class=\"busca_link_selecionado\" id=\"buscainc"+i+"\" onClick=\"$('"+ campo_codigo+"').value='"+obj_Json[i][0]+"'; $('"+ fOwner.id+"').value='"+obj_Json[i][1]+"'; parentNode.parentNode.removeChild(parentNode); return false;\">"+obj_Json[i]['exibir_browser']+'</a>';
					else
					  retornar += "<a href=\"#\" id=\"buscainc"+i+"\" onClick=\"$('"+ campo_codigo+"').value='"+obj_Json[i][0]+"'; $('"+ fOwner.id+"').value='"+obj_Json[i][1]+"'; parentNode.parentNode.removeChild(parentNode); return false;\">"+obj_Json[i]['exibir_browser']+'</a>';
				  }
				if( $('div_busca_incremental') == null)
				  var div_busca = document.createElement('div');
				else
				  var div_busca = $('div_busca_incremental');
				  
				//
				with (div_busca)
				  {
				  	id='div_busca_incremental';
					innerHTML = retornar;
					style.position = 'absolute';
					style.display = 'block';
					setAttribute('width', '500px');
					
					if( ($('filtro_relatorio_opcoes') != null ) && ($('filtro_relatorio_opcoes').style.display == 'block') )
					  {
					    div_busca.style.top = fOwner.parentNode.offsetTop+35+$('tabela_opcoes_filtro').offsetTop+20;
						div_busca.style.left = fOwner.parentNode.offsetLeft+10;  	
					  }
					else
					  {
						div_busca.style.top = fOwner.parentNode.offsetTop+35+$('tabela_manutencao_cadastro').offsetTop;
						div_busca.style.left = fOwner.parentNode.offsetLeft+10;		
					  }
					fOwner.parentNode.appendChild(div_busca);
					style.padding = '3px';
					style.visible = '';
					div_busca.onblur = function() { RemoveBuscaIncremental(); }
					
				  }
				//alert( (div_busca.offsetTop) );
				
				//document.getElementsByTagName('body')[0].appendChild(div_busca);
	        }
	     }
	    xmlhttp.send(null);	
	  }
	
	
  }
  

function RemoveBuscaIncremental()
  {
  	var div_busca = $('div_busca_incremental');
	//alert(div_busca)
	if(div_busca != null)
	  {
	    var remove_div_busca = window.setTimeout( function() {  div_busca.parentNode.removeChild(div_busca); } , 500);	
	  }
	  
  }

function MarcaTodasCheckbox(fMarcar)
  {
  	var checks = document.getElementsByTagName("input");
	for(i=0; i < checks.length; i++)
	  {
		if(checks[i].type == 'checkbox')
	      checks[i].checked = fMarcar ;
	  }
  }
/** Função para capturar o evento de tecla crossbrowser **/  
this.getKeyCode = function(ev)
  {
  	
	if(ev) 
	  { //Moz
	    return ev.keyCode;
	  }
	if(window.event) 
	  { //IE
		return window.event.keyCode;

	  }
  }


/****  Fim das funções referentes a classe screen *****/
caminho_ofcweb = '/';
caminho_ofcweb_url = 'http://www.ofcweb.com.br/';
