
/* 
Função: NVL
Inserida: 17/07/2007
Ultima alteração: 
Propósito: Similar ao NVL do ORACLE
- p1 = Parametro 1
- p2 = Parametro 2 que será retornado caso o primeiro seja nulo
*/
		
function nvl(p1,p2) {
	return (!p1)?p2:p1;
}


/* 
Função: Limpa PLACA
Inserida: 19/01/2006 15:48
Ultima alteração: 19/01/2006 15:48
Propósito: Parâmetros
- fld = campo PLACA a ser formatado
Chamada
- Deve ser colocada no evento onBlur
*/
		
function f_placa(fld) {
	fld.value = (fld.value.replace('-','')).toUpperCase();	
}

/* 
Função: Verifica Separador Numerico
Inserida: 19/01/2006 15:49
Ultima alteração: 19/01/2006 15:49
Propósito: f_verifica_separador(fld) : Verifica o separador de um campo numérico, se o usuario digitar ',' substitui por '.'
	* variáveis *
	  - fld : Objeto
	* chamada *
    f_verifica_separador(this);
*/
		
function f_verifica_separador(fld){
	if ((fld.value).indexOf(',') != -1) {
	  fld.value = fld.value.substr(0,fld.value.length - 1);
	  fld.value = fld.value + '.';
    }
	if(isNaN(fld.value)) {
	  alert("Digite somente números neste campo.");
	  fld.value = fld.value.substr(0,fld.value.length - 1);
    }
}

/* 
Função: Habilitar Botão
Inserida: 19/01/2006 15:50
Ultima alteração: 19/01/2006 15:51
Propósito: Função: Habilita botão
Propósito: Habilita o botão
*/
		
function f_habilitar_botao( p_botao, p_evo_click) {
	try {
		v_img = eval("document.getElementById('img_"+ p_botao + "')");
		v_botao = eval("document.getElementById('btn_"+p_botao+"')");
		v_img.src   		= '/_imagens/botoes/16x16/' + p_botao + '.gif'; 
		v_botao.onclick	    = function() { eval(p_evo_click);              };	
		v_botao.disabled = false;
	} catch(e) {
		with(parent) {
                                        try{
			v_img = document.getElementById('img_'+ p_botao );
			v_botao = document.getElementById('btn_'+p_botao);
			v_img.src   		= '/_imagens/botoes/16x16/' + p_botao + '.gif'; 
			v_botao.onclick	    = function() { eval(p_evo_click);              };	
			v_botao.disabled = false; 
                                         }catch(e) {}
		}
	}
}

/* 
Função: Desabilitar Botão
Inserida: 19/01/2006 15:51
Ultima alteração: 19/01/2006 15:51
Propósito: Desabilita um botao
*/
		
function f_desabilitar_botao( p_botao ) {
	try {
		v_img   		 = document.getElementById('img_'+ p_botao);
		v_botao          = document.getElementById('btn_'+p_botao);
		v_img.src   	 = '/_imagens/botoes/16x16/' + p_botao + '_disable.gif'; 
		v_botao.onclick	 = '';
		v_botao.disabled = true;
	} catch(e) {
		with(parent) {
			v_img   	     = document.getElementById('img_'+ p_botao);
			v_botao 	     = document.getElementById('btn_'+p_botao);
		    v_img.src   	 = '/_imagens/botoes/16x16/' + p_botao + '_disable.gif'; 
			v_botao.onclick	 = '';
			v_botao.disabled = true;
		}
	}
}

/* 
Função: Formata Número Decimal
Inserida: 19/01/2006 15:52
Ultima alteração: 23/11/2006 08:27
Propósito: Filtra a entrada de dados para apenas numeros, com "," ou "."
Ex: onKeyPress="return f_formata_numero_decimal(this)"
*/
		
function f_formata_numero_decimal(objeto, p_event) {
	var k = -1;
	if(f_formata_numero_decimal.arguments.length == 2) {
		ev = p_event;
	}
	if (window.event && window.event.keyCode) {
		k = window.event.keyCode;
	} else {
		if(p_event) {
			k = p_event.charCode;
		}
		if(k == 0) {
			k = -1;
		}
	}
	if(k == 44 && ((window.event) || (objeto.value.indexOf('.') == -1))) {
		k = 46;
		if(window.event) {
			window.event.keyCode = 46;
		} else {
			return false;
		}
		if(document.selection)
			document.selection.createRange().text = '';
	}
	//objeto.value += '.';
	return (k > -1 ? ((k > 47 && k < 58) || (k == 8 || (k == 46 && objeto.value.indexOf('.') == -1 ))) : true);
}

/* 
Função: Verifica Tipo do Campo
Inserida: 19/01/2006 15:53
Ultima alteração: 19/01/2006 15:53
Propósito: Retorno TRUE se o campo é controlado pela função CONTROLA CAMPOS
*/
		
function f_verifica_tipo( p_campo ) {
	switch( p_campo.type ) {
		case 'text' : 
		case 'select-one' : 
		case 'select-multiple' : 
		case 'textarea' : 
		case 'password' : 
			return true;
		default :	
			return false;
	}
}

/* 
Função: Show Hint
Inserida: 19/01/2006 15:54
Ultima alteração: 19/01/2006 15:54
Propósito: Mostra um hint, só funciona em IE.
*/
		
function show_popup(current,e,comentario) {
	var oPopup = window.createPopup();
	var oPopupBody = oPopup.document.body;
	oPopupBody.style.backgroundColor = "lightyellow";
	oPopupBody.style.border = "solid black 1px";    
	oPopupBody.style.fontFamily = "Verdana, Geneva, Arial, Helvetica, sans-serif";
	oPopupBody.style.fontSize = "10px";
	oPopupBody.scroll = "yes";
	
	var altura = 1;
	var largura = 320;
	var deslocamento = (parseInt(current.offsetHeight)+5);
	
	if (comentario.length > 45)
	  altura = Math.ceil(comentario.length/45);
	else
	  largura = Math.ceil(comentario.length * 8);
	 
	oPopupBody.innerHTML = comentario; 
	
	if ((current.type == 'select-one') || (current.type == 'select-multiple')) {
	   if (altura == 1)
		   deslocamento = -1*(parseInt(current.offsetHeight)+5);
	   else
		   deslocamento = -1*(parseInt(current.offsetHeight)+(10*altura));
	}
	
	oPopup.show(0, deslocamento, largura, 15*altura, current);
}

/* 
Função: Hide Hint
Inserida: 19/01/2006 15:55
Ultima alteração: 19/01/2006 15:55
Propósito: Oculta um Hint da função show_popup
*/
		
function showhide(fld){
	var campo = document.createElement("tr");
	campo = eval(fld);
	if(campo.style.display == 'none')
		campo.style.display ='';
	else
		campo.style.display ='none';
	return false;
}

/* 
Função: Maskara de Formatação
Inserida: 19/01/2006 15:56
Ultima alteração: 24/10/2006 09:29
Propósito: Formata um campo de acordo com uma maskara pré-determinada.
0 indica caracteres somente numericos
X indica caracteres alfa numericos
Ex: 
Formatação de datas
onKeyPress="return f_formata(this, '00/00/0000')
*/
		
function f_formata(obj, p_event, p_mask) {
	if(obj.readOnly || obj.disabled)
		return;
	if(f_formata.arguments.length == 2) {
		mask = p_event;
	} else {
		mask = p_mask;
		ev = p_event;
	}
	var k = -1;
	var v_tipos = '0XxAa';
	if (window.event && window.event.keyCode ) {
		k = window.event.keyCode;
	} else {
		if(f_formata.arguments.length != 2) {
			k = ev.charCode;
			if(k == 0) {
				return true;
			}
		}
	}
	while (v_tipos.indexOf(mask.substring(obj.value.length, obj.value.length+1)) == -1 && obj.value.length < mask.length) {
		obj.value = obj.value + mask.substring(obj.value.length, obj.value.length+1);
	}
	var v_numeros = '0123456789';
	var v_letras_maius = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
	if(document.selection)
		document.selection.createRange().text = '';
	if(mask.substring(obj.value.length, obj.value.length+1) == '0') {
		ret = (k > -1 ? (v_numeros.indexOf(String.fromCharCode(k)) != -1) : true);
	} else if (mask.substring(obj.value.length, obj.value.length+1) == 'x') {
		//permite somente a entrada de letras, permanecendo maiusculas ou minusculas conforme o usuario digitar
		ret = (k > -1 ? (v_letras_maius.indexOf(String.fromCharCode(k).toUpperCase()) != -1) : true);
	} else if (mask.substring(obj.value.length, obj.value.length+1) == 'X') {
		//permite somente a entrada de letras, tornando todas maiusculas
		if (window.event && window.event.keyCode ) {
			window.event.keyCode = String.fromCharCode(k).toUpperCase().charCodeAt(0);
		} else if(f_formata.arguments.length != 2) {
			ev.charCode = String.fromCharCode(k).toUpperCase().charCodeAt(0);
		}
		ret = (k > -1 ? (v_letras_maius.indexOf(String.fromCharCode(k).toUpperCase()) != -1) : true);
	} else if (mask.substring(obj.value.length, obj.value.length+1) == 'a') {
		//permite entradas alfa-numericas, permanecendo maiusculas ou minusculas conforme o usuario digitar
		ret = true;
	} else if (mask.substring(obj.value.length, obj.value.length+1) == 'A') {
		//permite entradas alfa-numericas, tornando todas maiusculas
		if (window.event && window.event.keyCode ) {
			window.event.keyCode = String.fromCharCode(k).toUpperCase().charCodeAt(0);
		} else if(f_formata.arguments.length != 2) {
			ev.charCode = String.fromCharCode(k).toUpperCase().charCodeAt(0);
		}
		ret = true;
	} 

	return ((!(obj.value.length>(mask.length-1)))&&ret);
}

function FCKeditor_OnComplete( editorInstance )
{
    editorInstance.Events.AttachEvent( 'OnStatusChange', f_fckeditor_readonly ) ;
}

var counter = 0 ;

function f_fckeditor_readonly( editorInstance )
{
  if (FCK_STATUS_COMPLETE == 2) {
	  try {
		 window[oEditor.Name + '___Frame'].document.getElementById('xEditingArea').childNodes[0].style.visibility = 'hidden';
		 window[oEditor.Name + '___Frame'].focus();
	  } catch(e) {}
	  
  }
}


/* 
Função: Desabilita Todos os Campos
Inserida: 19/01/2006 15:56
Ultima alteração: 02/08/2006 16:12
Propósito: Desabilita todos os campos do formulário
*/
		
function f_desabilita_todos_campos( ) {
	for(var i=0;i<document.forms[0].elements.length;i++) {
		var v_elem = document.forms[0].elements[i];
		if(!v_elem.getAttribute('sempre_ativo') || v_elem.getAttribute('sempre_ativo') != 1) {
			v_elem.disabled = true;
			if(v_elem.getAttribute("rte") == 1)
				disableRTE(document.forms[ 0 ].elements[ i ].name);
			if(v_elem.getAttribute("fckeditor") == 1) {
				try {
					window[oEditor.Name + '___Frame'].document.getElementById('xEditingArea').childNodes[0].style.visibility = 'hidden';
					window[oEditor.Name + '___Frame'].focus();			   
				} catch(e) {
					oEditor = FCKeditorAPI.GetInstance(v_elem.name);
					FCKeditor_OnComplete( oEditor ); 
				}
			}
		}
	} 
}


/* 
Função: Habilita Todos os campos
Inserida: 19/01/2006 15:58
Ultima alteração: 02/08/2006 16:12
Propósito: Habilita Todos os campos do formulário
*/
		
function f_habilita_todos_campos( ) {
	var v_focus = true;
	for(var i=0;i<document.forms[0].elements.length;i++) {	
		var v_elem = document.forms[0].elements[i];
		if (!v_elem.getAttribute('ativo') || v_elem.getAttribute('ativo') != 0) {
			v_elem.disabled = false;
			if(v_elem.getAttribute("rte") == 1)
				enableRTE(v_elem.name);
			if(v_elem.getAttribute("fckeditor") == 1)
				window[oEditor.Name + '___Frame'].document.getElementById('xEditingArea').childNodes[0].style.visibility = 'visible';		
		}
		if(((v_elem.type == 'select-multiple') || (v_elem.type == 'select-one') || (v_elem.type == 'text')) && v_focus && !v_elem.disabled && !v_elem.readOnly) {
			try {
				v_elem.focus();
				v_focus = false;
			} catch(e) {}
		}
	}	
}

function f_form_select() {
	var v_focus = true;
	for(var i=0;i<document.forms[0].elements.length;i++) {	
		var v_elem = document.forms[0].elements[i];
		if(((v_elem.type == 'select-multiple') || (v_elem.type == 'select-one') || (v_elem.type == 'text')) && v_focus && !v_elem.disabled && !v_elem.readOnly) {
			try {
				v_elem.select();
				v_focus = false;
			} catch(e) {}
		}
	}	
}

/* 
Função: Limpar Campos
Inserida: 19/01/2006 15:59
Ultima alteração: 02/08/2006 16:11
Propósito: Limpa todos os campos
*/
		
function f_limpar_campos() {
	for(var i=0;i<document.forms[0].elements.length;i++) {
		var v_elem = document.forms[0].elements[i];
		if (!v_elem.getAttribute("fixo")) {
			switch (v_elem.type) {
				case 'select-one':
				case 'select-multiple':
				case 'hidden':
				case 'text': 
				case 'textarea':
					v_elem.value = '';
					break;
				case 'checkbox':
				case 'radio':
					v_elem.checked = false;
					break;
			}
			if(v_elem.getAttribute("rte") == 1)
				enableDesignMode(v_elem.name, '', v_elem.disabled);
			if(v_elem.getAttribute("fckeditor") == 1)
			   FCKeditorAPI.GetInstance(v_elem.name).Commands.GetCommand('NewPage').Execute();
		}
	}	
}

/* 
Função: Controla Campos
Inserida: 19/01/2006 16:03
Ultima alteração: 21/09/2006 11:39
Propósito: f_controla_campos(num_forms) : Cria show messagem para os campos, inclusive pode gerar tabindex
	* variáveis *
	  - num_forms : numero de formularios da tela
	  - cria_tab_index : parâmetro deve ser passado caso o desenvolvedor desejar a criação automática do tanindex dos forms
	* chamada *
    windown.onload = function() { f_controla_campos(1); }
*/
		
function insertAfter( referenceNode, newNode ) {    
  referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}

function f_controla_campos(num_forms) {
	if(!window.event)
		return;
    var v_controla_tab_index = false;
	var args = f_controla_campos.arguments;
    if (args.length > 1) 
	   v_controla_tab_index = true;
	for (var j=0; j<num_forms; j++) {  
		for (var i=0;i<document.forms[j].elements.length;i++) {
			var v_elem = document.forms[j].elements[i];
			if(f_verifica_tipo(v_elem) && Number(v_elem.getAttribute('obrigatorio'))==1)
				v_elem.className = 'requerido_form';
			// Limpar todos os TABINDEX
			if (v_controla_tab_index)
				v_elem.tabIndex = 0;
			if (v_elem.onfocus) 
				v_elem.v_funcao_focus = v_elem.onfocus;
			v_elem.onfocus = function() { 
								if(this.v_funcao_focus)
									this.v_funcao_focus();
								if (f_verifica_tipo(this) && this.type != 'select-one' && this.type != 'select-multiple') {
									this.style.backgroundColor='#FFFFDD'; 
									this.style.color = '#000000';
								}
								if (this.getAttribute('hint')) 
								   show_popup(this,event,this.getAttribute('hint'));
							};
			if (v_controla_tab_index) 
				v_elem.tabIndex = i+1;   
			if (f_verifica_tipo(v_elem)) {
				v_elem.onhelp = function() { 
					show_popup(event.srcElement,event,event.srcElement.getAttribute('hint')); 
				}
				if (v_elem.onblur)
					v_elem.v_funcao_blur = v_elem.onblur;
					v_elem.onblur = function() { 
										if(this.v_funcao_blur)
											this.v_funcao_blur();
										this.style.backgroundColor='';
										this.style.color = '';
										window.status = '';
									};
			}
		}	
	}
	window.status = ''; 
}

/* 
Função: Marca Checks
Inserida: 19/01/2006 16:28
Ultima alteração: 19/01/2006 16:28
Propósito: Marca todos os itens de um check group
*/
		
function f_marca_todos( p_check_name ) {
  for (var i = 0;i<document.forms[0].elements.length; i++) {		
    if ( (document.forms[0].elements[i].type == 'checkbox') && (p_check_name == document.forms[0].elements[i].name) )
       document.forms[0].elements[i].checked = true;	
  }
}

/* 
Função: Inicializa Abas
Inserida: 19/01/2006 16:29
Ultima alteração: 28/09/2006 19:01
Propósito: Inicializa uma tabela para conter abas
*/
		
function initAbas(v_id, v_aba_inicial, p_ativa_crtl_tab) {
	var tbl = document.getElementById(v_id);
	var abas = tbl.rows[0].cells
	var nro_abas = abas.length;
	var corpos = new Array();
	for(var i=0;i<tbl.rows.length;i++) {
		if(i!=0) {
			corpos[corpos.length] = tbl.rows[i];
			tbl.rows[i].cells[0].className = 'td_aba_corpo';
		}
	}
	var nro_corpos = corpos.length;
	if (nro_abas < nro_corpos) {
//		alert("O numero de abas é menor que o numero de corpos!");
	}
	for(var i=0;i<abas.length;i++) {
		if (i < nro_corpos) {
			if(v_aba_inicial == i) {
				abas[i].className = 'td_aba_up';
			} else {
				abas[i].className = 'td_aba_down';
			}
			abas[i].f_old = abas[i].onclick;
			abas[i].onclick = function() {
				mudaAba(corpos, abas, this);
				if(this.f_old) 
					this.f_old(event);
			}
		} else {
			abas[i].className = 'td_aba_none';
		}
	}
	for(var i=0;i<corpos.length;i++) {
		if(v_aba_inicial == i) {
			corpos[i].style.display = '';
		} else {
			corpos[i].style.display = 'none';
		}
	}
	if (p_ativa_crtl_tab) {
  	   document.onkeydown = function(event){ 
	  	if ( ((window.event)?window.event:event).ctrlKey ) // caso seja pressionada a tecla control
		  if (((window.event)?window.event:event).keyCode == 9) {
		  	 mudaAbaSequencia(v_id);
	 		 return false;
		  }
	    }   
   }	
}

/* 
Função: Muda Aba
Inserida: 19/01/2006 16:30
Ultima alteração: 19/01/2006 16:30
Propósito: Muda a aba atual selecionada
*/
		
function mudaAba(v_tbody, v_tr, obj) {
	tb = v_tbody;
	tr = v_tr;
	var sel = -1;
	for(var i=0;i<tr.length;i++) {
		if (i < tb.length) {
			if (tr[i] == obj) {
				sel = i;
				tr[i].className = 'td_aba_up';
			} else {
				tr[i].className = 'td_aba_down';
			}
		}
	}
	for(var i=0;i<tb.length;i++) {
		if (i == sel) {
			tb[i].style.display = '';
		} else {
			tb[i].style.display = 'none';
		}
	}			
}

/* 
Função: Mostra Erro
Inserida: 19/01/2006 16:31
Ultima alteração: 19/01/2006 16:31
Propósito: f_erro(p_mensagem, p_campo, form) : Mostra mensagem de erro e posiciona o cursor no campo que disparou o erro
	* variáveis *
	  - p_mensagem : mensagem que deve ser mostrada
	  - p_campo : campo que disparou o erro
	  - form : formulario
*/
		
function f_erro(p_mensagem, p_campo, form) {
     try {
	alert(p_mensagem);
//	if (form.MENSAGEM) 
//        form.MENSAGEM.value = p_mensagem;
	if (p_campo.type == 'select-one') 
		p_campo.focus();
	if (p_campo.type == 'text') 
		p_campo.select();
     } catch(e) {}
	return false;
}

/* 
Função: New Window
Inserida: 19/01/2006 16:32
Ultima alteração: 26/05/2006 11:56
Propósito: Exibe uma nova janela, sem as barras de ferramentas
*/
		
function NewWindow(mypage, myname, w, h, scroll) {
	mypage = mypage.replace('http%3A','http:').replace('https%3A','https:');
	if(mypage != '' && mypage.replace(/ /g, '').toLowerCase() != 'about:blank' && mypage.indexOf('/') != 0 && (mypage.indexOf('http://') != 0 && mypage.indexOf('https://') != 0)) {
		init = '';
		t = window.location.toString().split('/');
		for(var i=0;i<t.length-1;i++) {
			init += t[i]+'/';
		}
		mypage = init+mypage;
	}
	var winl = (screen.width - w) / 2;
	var wint = (screen.height - h) / 2;
	winprops = 'height='+h+',width='+w+',top='+wint+',left='+winl+',scrollbars='+scroll+',resizable,status'
	win = window.open(mypage, myname, winprops)
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}

/* 
Função: Verifica Form
Inserida: 19/01/2006 16:33
Ultima alteração: 30/10/2006 14:37
Propósito: f_verifica_form(formulario) : Verifica os dados do formulario, o que pode ser feito apenas em uma secao do form
	* variáveis *
	  - formulario : nome do formulario
	  - secao : Opcional, indica que a verificação deve ser feita apenas em uma parte do form
*/
function f_verifica_form(formulario) {
	var args=f_verifica_form.arguments;
	// Verifica apenas umas secao do formulario
	var secao = false;
	var v_formulario_valor = false;
	if (args.length == 2) secao = true;	
	for (var i = 0; i<formulario.elements.length; i++) {
		var v_elem = formulario.elements[i];
		if (!v_elem.disable) {
			// Verifica se o campo está preenchido
			if ((!secao && !v_elem.getAttribute("secao")) || args[1] == v_elem.getAttribute("secao")) {
				if (v_elem.getAttribute("texto_interno")) {
					if(v_elem.value == v_elem.getAttribute("texto_interno")) 
						v_formulario_valor = false;
					else if (v_elem.value)
						v_formulario_valor = true;
					else
						v_formulario_valor = false;
				} else if (v_elem.value)
					v_formulario_valor = true;
				else 
					v_formulario_valor = false; 
				if ((v_elem.getAttribute("obrigatorio") == 1) && (!v_formulario_valor) && (!v_elem.disable)) {
					return f_erro('O campo '+v_elem.getAttribute("display")+' '+String.fromCharCode(233)+' requerido.',v_elem, formulario);
				}
			}
			// Verifica o tipo de dado do campo
			if ((!secao && !v_elem.getAttribute("secao")) || args[1] == v_elem.getAttribute("secao")) {
				if (v_elem.value) {
					var v_display = v_elem.getAttribute("display");
					switch(String(v_elem.getAttribute("tipo")).toLowerCase().trim()) {
						case 'numerico':
							// Corrige caso o valor tenha sido digitado com ,
							v_elem.value = v_elem.value.replace(',', '.');
							if(!v_elem.value.isNumber())
								return f_erro('O valor do campo '+v_display+' deve ser num'+String.fromCharCode(233)+'rico.',v_elem, formulario);
							break;
						case 'data':
							if(!v_elem.value.substr(0,10).isDate())
								return f_erro('O valor do campo '+v_display+' deve ser uma data v'+String.fromCharCode(225)+'lida.',v_elem, formulario);
							break;
						case 'data_hora':
							if(!v_elem.value.isDataHora())
								return f_erro('O valor do campo '+v_display+' deve ser uma data e hora v'+String.fromCharCode(225)+'lida, no formato (dia/m'+String.fromCharCode(234)+'s/ano hora:minuto).',v_elem, formulario);
							break;
						case 'cpf':
							if(!v_elem.value.isCPF())
								return f_erro('O valor do campo '+v_display+' deve ser um nº v'+String.fromCharCode(225)+'lido de CPF.',v_elem, formulario);
							break;
						case 'cnpj':
							if(!v_elem.value.isCNPJ())
								return f_erro('O valor do campo '+v_display+' deve ser um CNPJ v'+String.fromCharCode(225)+'lido.',v_elem, formulario);
							break;
						case 'cnpjcpf':
						case 'cnpj_cpf':
							if(!v_elem.value.isCNPJCPF())
								return f_erro('O valor do campo '+v_display+' deve ser um CNPJ ou CPF v'+String.fromCharCode(225)+'lido.',v_elem, formulario);
							break;
						case 'email':
							if(!v_elem.value.isMail())
								return f_erro('O valor do campo '+v_display+' deve ser um e-mail.',v_elem, formulario);
							break;
						case 'placa':
							v_elem.value = v_elem.value.replace('-', '').trim();
							if(!v_elem.value.isPlaca())
								return f_erro('O valor do campo '+v_display+' deve ser uma placa v'+String.fromCharCode(225)+'lida.',v_elem, formulario)
							break;
					}
				}			
			}
		}
	}
	return true;
}

/* 
Função: Cria Botão
Inserida: 19/01/2006 16:34
Ultima alteração: 12/05/2006 11:07
Propósito: Cria objeto BUTTON em uma barra do site
variáveis:
 - p_nome -> Nome do botão, palavra unica e sem espaços ou caracteres especiais
 - p_label  -> Label do botão
 - p_click   -> Evento de click
 - p_barra  -> Função completa para inserir o botão na barra (parent.document.getElementById('barra_botoes_top').appendChild(obj))
*/
		
function f_cria_botao (p_nome, p_label, p_click, p_barra) {
	if (!p_barra) {
		p_barra = parent.document.getElementById('barra_botoes_top');
	}
	if(p_barra.id == 'barra_botoes_bottom') {
		p_barra = parent.document.getElementById('barra_botoes_bottom_sp');
	}
	// Cria o objeto BOTAO
	var obj = parent.document.createElement('button');
	if(p_label == 'Localizar') {
		obj.accessKey = 'l';
		p_label = '<u>L</u>ocalizar';
	}
	if(p_label == 'Imprimir') {
		obj.accessKey = 'p';
		p_label = 'Im<u>p</u>rimir';
	}
	if(p_label == 'Filtro') {
		obj.accessKey = 'f';
		p_label = '<u>F</u>iltro';
	}

	// Marca como temporario para o RESETA BOTOES eliminá-lo na proxima pagina
	obj.temp = 1;
	// Identifica novo botão
	obj.id = 'btn_' + p_nome;
	obj.name = 'btn_' + p_nome;
	if(p_barra.id == 'barra_botoes_bottom_sp') {
		obj.className = 'botao';
		obj.style.marginLeft = '4px';
	} else {
		obj.className = 'botao_cab';
	}
	// Gera o conteudo visual do objeto
	obj.innerHTML = '<img src="_imagens/botoes/16x16/' + p_nome + '.gif" id="img_'+p_nome+'" width="16" height="16" align="absmiddle"> ' + p_label;
	// Gera evento do click no objeto
	obj.onclick = function() {  eval(p_click); }

	// Adiciona o botão a barra determinada
               obj.temp = 1;
	p_barra.appendChild(obj);
}

/* 
Função: Image to Check
Inserida: 19/01/2006 16:36
Ultima alteração: 19/01/2006 16:36
Propósito: Transforma um img e um input type="hidden" em um checkbox, alternando as imagens conforme clicado.

*/
		
function f_img_check(obj, img_check, img_uncheck, v_field) {
	if(obj.src.indexOf(img_check) != -1) {
		v_field.value = 0;
		obj.src = img_uncheck;
	} else {
		v_field.value = 1;
		obj.src = img_check;
	}
}

/* 
Função: Testa CNPJ
Inserida: 19/01/2006 16:37
Ultima alteração: 19/01/2006 16:37
Propósito: Testa a validade de um nro de cnpj
*/
		
function testacnpj(cnpj)
{
  while (cnpj.indexOf('.') > 0)
  {
    cnpj= cnpj.replace('.', '');
  }
  while (cnpj.indexOf('-') > 0)
  {
    cnpj = cnpj.replace('-', '');
  }
  while (cnpj.indexOf('/') > 0)
  {
    cpnj = cnpj.replace('/', '');
  }
  res = false;
  digito = 0;
  if(cnpj.length == 14)
  {
    cnpjdv = cnpj.substring(12, 14);
        digito = 0;
        controle = "";
        for(i=0;i<2;i++)
        {
          soma = 0;
          for(j=0;j<12;j++)
          {
            soma += (cnpj.substring(j, j+1)*1)*((11+i-j)%8+2);
          }
          if(i == 1)
          {
            soma += digito * 2;
          }
          digito = 11 - soma%11;
          if (digito > 9)
          {
            digito = 0;
          }
          controle = controle+""+digito;
    }
        if(controle == cnpjdv)
        {
          res = true;
        }
  }
  return res;
}

/* 
Função: Testa CPF
Inserida: 19/01/2006 16:38
Ultima alteração: 19/01/2006 16:38
Propósito: Testa a validade de um nro de CPF
*/
		
function testacpf(cpf)
{
  while (cpf.indexOf('.') > 0)
  {
    cpf = cpf.replace('.', '');
  }
  while (cpf.indexOf('-') > 0)
  {
    cpf = cpf.replace('-', '');
  }
  while (cpf.indexOf('/') > 0)
  {
    cpf = cpf.replace('/', '');
  }
  if(cpf == '00000000000')
  {
    return true;
  }
  digito1 = 0;
  digito2 = 0;
  if(cpf.length == 11)
  {
    for(i=0;i<9;i++)
        {
          digito1 += (cpf.substring(i, i+1)*1)*(10-i);
        }
        if ((digito1%11==1)||(digito1%11==0))
        {
          digito1 = 0;
        }
        else
        {
          digito1 = 11-(digito1%11);
        }
        for (i=0;i<10;i++)
        {
          digito2 += (cpf.substring(i, i+1)*1)*(11-i);
        }
        if ((digito2%11==1)||(digito2%11==0))
        {
          digito2 = 0;
        }
        else
        {
          digito2 = 11 - (digito2%11);
        }
        return ((digito1+""+digito2)==cpf.substring(9, 11));
  }
  else
  {
    return false;
  }
}

/* 
Função: Testa CNPJ/CPF
Inserida: 19/01/2006 16:39
Ultima alteração: 19/01/2006 16:39
Propósito: Testa a validade de um CNPJ ou CPF, de acordo com o tamanho do nro passado
*/
		
function testacpfcnpj(cpfcnpj)
{
  if(cpfcnpj.length == 14)
  {
    return testacnpj(cpfcnpj);
  }
  else
  {
    return testacpf(cpfcnpj);
  }
}

/* 
Função: Carrega Imagem
Inserida: 19/01/2006 16:41
Ultima alteração: 19/01/2006 16:41
Propósito: Carrega uma imagem selecionada em um input:file em um img.
Obs: inserida em onChange do input:file
*/
		
function f_carrega_imagem(v_file_input, v_image_preview) {
	if(v_file_input.value != "") {
		v_image_preview.style.display = '';
		v_image_preview.src = v_file_input.value;
	} else {
		v_image_preview.style.display = 'none';
	}
}

/* 
Função: Erro Imagem
Inserida: 19/01/2006 16:42
Ultima alteração: 19/01/2006 16:42
Propósito: Trata um erro de carregamento da imagem em um img. 
display => Exibe mensagem de erro quando não for possível carregar
Evento: onError
*/
		
function f_erro_imagem(v_image_preview, display) {
	v_image_preview.style.display = 'none';
	if(display) {
		alert('Nao foi possivel carregar esta imagem!');
	}
}

/* 
Função: Limita Imagem
Inserida: 19/01/2006 16:44
Ultima alteração: 19/01/2006 16:44
Propósito: Limita as dimensões de uma imagem em um img, sem alterar a proporção
*/
		
function f_limita_imagem(v_image, v_width, v_height) {
	larga = ((v_image.width/v_image.height) > (v_width/v_height));
	if(v_image.height > v_height || v_image.width > v_width) {
		if (larga) {
			v_image.width = v_width;
		} else {
			v_image.height = v_height;
		}
	}
}

/* 
Função: Show Modal
Inserida: 19/01/2006 16:44
Ultima alteração: 19/01/2006 16:44
Propósito: Abre uma nova janela de forma Modal
*/
		
function showModal( p_pagina, p_target, p_resize, p_scroll, p_status, p_width, p_height )
{
 var path     = p_pagina.split('/');
 var pagina   = path[ path.length -1 ].split('?');
	 resize	  = ( p_resize != null || p_resize != 0 ) ? p_resize : false;
	 scrol 	  = ( p_scroll != null || p_scroll != 0 ) ? p_scroll : false;
	 status   = ( p_status != null || p_status != 0 ) ? p_status : '';
	 width	  = ( p_width  != null || p_width  != 0 ) ? p_width  : 0;
	 height	  = ( p_height != null || p_height != 0 ) ? p_height : 0; 
	 esquerda = ( screen.width  ) ? ( screen.width  - parseInt( width )  ) / 2 : 0;
	 topo	  = ( screen.height ) ? ( screen.height - parseInt( height ) ) / 2 : 0; 
	 win 	  = window.open( p_pagina, p_target ,'height='+ height +', width='+ width +', left='+ esquerda + ', top=' + topo + ', toolbar=0, location=0,directories=0,status='+ status +',menuBar=0,scrollBars='+ scrol +',resizable=' + resize + '');

	 win.focus(); 
}

/* 
Função: Currency
Inserida: 19/01/2006 16:46
Ultima alteração: 28/11/2006 11:16
Propósito: Converte um valor numerico para formatação monetaria
Ex: 1 = 1,00
*/
		
function toCurrency(v_valor) {
	v_valor = Math.round(Number(v_valor)*100)/100;
	var partes = String(v_valor).split('.');
	if (partes.length > 1) {
		partes[1] = String(partes[1]);
		if(partes[1].length == 0) {
			partes[1] = '00';
		}
		if(partes[1].length == 1) {
			partes[1] = partes[1]+'0';
		}
		if(partes[1].length > 2) {
			if (Number(partes[1].substr(0,2)) < 10 ) {
				partes[1] = '0'+Math.round(partes[1].substr(0,4)/100);
			} else {
			    partes[1] = String(partes[1]).substr(0,2);
			}
				
		}
		var dec = partes[1];
	} else {
		var dec = '00';
	}
	var result = 0;
	if ((v_valor >= 0 && Math.round(v_valor) > v_valor) || (v_valor <= 0 && Math.round(v_valor) < v_valor)) {
			result = (Math.round(v_valor)-1)+'.';
	} else {
			result = Math.round(v_valor)+'.';
	}
//	var dec = (((Math.round(v_valor*100) % 100)<10)?'0':'')+(Math.round(v_valor*100) % 100);
	return result+dec;
}

/*
function toCurrency(v_valor) {
                var result = 0;
                if (Math.round(v_valor) > v_valor) {
                        result = (Math.round(v_valor)-1)+'.';
                } else {
                        result = Math.round(v_valor)+'.';
                }
	var dec = (((Math.round(v_valor*100) % 100)<10)?'0':'')+(Math.round(v_valor*100) % 100);
	return result+dec;
}
*/

/* 
Função: Valor do Campo
Inserida: 19/01/2006 16:47
Ultima alteração: 27/09/2006 09:37
Propósito: Busca o valor de um campo em um formulário
*/
		
function f_valor_campo(p_campo, p_form) {
  var value = '';
  var j = 0;
  for(var i=0;i<p_form.elements.length;i++) {
    if(p_form.elements[i].name == p_campo && !p_form.elements[i].disabled) {
      switch(p_form.elements[i].type) {
        case 'radio':
          if(p_form.elements[i].checked) {
            return p_form.elements[i].value;
          }
          break;
        case 'checkbox':
          if (p_form.elements[i].checked) {
            if (j != 0) {
              value += ',';
            }
            value += p_form.elements[i].value;
            j++;
          }
          break;
		case 'select-multiple':
            if (j != 0) {
              value += ',';
            }
			z = 0;
			for(var k=0;k<p_form.elements[i].options.length;k++) {
				if(p_form.elements[i].options[k].selected) {
					if(z != 0)
						value += ',';
		            value += p_form.elements[i].options[k].value;
					z++;
				}
			}
			j++;
			break;
        default:
          if (j != 0) {
            value += ',';
          }
          value += p_form.elements[i].value;
          j++;
          break;				
        }
      }
    }
    return value;
}

/* 
Função: Lista - Cria Option Select
Inserida: 19/01/2006 16:47
Ultima alteração: 11/09/2006 17:20
Propósito: Insere um option em um select
*/
		
function f_cria_option(p_value, p_text, p_select) {
	var v_opt = document.createElement('option');
	v_opt.value = p_value;
	v_opt.text = p_text; 
	try {
		p_select.add(v_opt,null);
	} catch(e) {
		p_select.add(v_opt);
	}
	return v_opt;
}

/* 
Função: Lista - Limpa Select
Inserida: 19/01/2006 16:48
Ultima alteração: 13/09/2006 12:00
Propósito: Exclui todos os options do select
*/
		
function f_limpa_select(obj) {
   while (obj.options.length > 0)
        obj.options[0] = null;
   while (obj.childNodes.length > 0)
        obj.removeChild(obj.childNodes[0]);
}

/* 
Função: Prototype isCNPJ
Inserida: 19/01/2006 16:50
Ultima alteração: 20/01/2006 08:44
Propósito: Verifica se o valor da string é um CNPJ válido
*/
		
String.prototype.isCNPJ = function() {
	return testacnpj(this);
}

/* 
Função: Prototype isMail
Inserida: 19/01/2006 16:51
Ultima alteração: 19/01/2006 16:51
Propósito: Verifica se o valor da String é um e-mail
*/
		
String.prototype.isMail = function(){
		var test
		var emails = this.split( ';' );
		for (var em=0; em < emails.length; em++ ) {
			var pt1    = emails[em].split( '@' );
			var valid = '.-_@';
			if ( ( pt1.length != 2 ) || ( pt1[ 0 ].length == 0 ) || ( pt1[ 1 ].length == 0 ) ) return( false );
			else {
				for ( var i = 0 ; i < valid.length - 1 ; i++ ){
					if ( pt1[ 0 ].split( valid.charAt( i ) ).hasEmptyElements() ) return( false );
					if ( pt1[ 1 ].split( valid.charAt( i ) ).hasEmptyElements() ) return( false );
				}			
			}
			
			for ( var i = 0 ; i < emails[em].length ; i++ ){
				var v_char = emails[em].toUpperCase().charCodeAt( i );
				if ( valid.indexOf( String.fromCharCode( v_char ) ) == -1 )
					if ( !( ( ( v_char >= 65 ) && ( v_char <= 90 ) ) || ( ( v_char >= 48 ) && ( v_char <= 57 ) ) ) ) return( false );
			}	
		}
		return( true );
	}

/* 
Função: Prototype isCPF
Inserida: 19/01/2006 16:52
Ultima alteração: 20/01/2006 08:43
Propósito: Verifica se o valor da String é um CPF
*/
		
String.prototype.isCPF = function(){
    return testacpf(this);
}

/* 
Função: Prototype isDataHora
Inserida: 19/01/2006 16:54
Ultima alteração: 19/01/2006 16:54
Propósito: Verifica se o valor da String é uma data/Hora no formata dd/mm/yyyy HH:MM válida.
*/
		
String.prototype.isDataHora = function(){
		var pt = this.split( '/' );
		var dt = new Date();
		var dd = Number( pt[ 0 ] );
		var mm = Number( pt[ 1 ] );
		var yy = Number(this.substr(6,4));
		var hh = this.substr(11,2);
		var mi = this.substr(14,2);

		// Data sem HORA
		if ( this.length < 15 ) return false ;
		
		// Caso seja preenchida com segundos
		if (this.length > 15) 
			var ss = this.substr(17,2); 
		else 
			var ss = '00';

		if ( !( ( hh >= 00 ) && ( hh < 24 ) && ( mi >= 00 ) && ( mi < 60 ) && ( ss >= 00 ) && ( ss < 60 ) ) )
		   return( false );
			
		if ( pt.length < 3 ) return( false );
		
		if ((mm == 1 || mm == 3 || mm == 5 || mm == 7 || mm == 8 || mm == 10 || mm == 12) && (dd <= 0 || dd > 31)) return false;
			
		if ((mm == 4 || mm == 6 || mm == 9 || mm == 11 ) && (dd <= 0 || dd > 30)) return false;

		if ((mm == 2 ) && (dd <= 0 || (yy%4 == 0 && dd > 29 ) || (yy%4 != 0 && dd > 28 ))) return false;

		if (yy < 1900 || yy > 2100) return false;
		return true;
//		dt.setFullYear( yy , mm - 1 , dd );

//		return( [ yy , ( mm < 10 ? '0' : '' ) + mm , ( dd < 10 ? '0' : '' ) + dd ].join( '' ) == dt.Dtos() );
	}

/* 
Função: Prototype isDate
Inserida: 19/01/2006 16:55
Ultima alteração: 05/05/2006 08:57
Propósito: Verifica se o valor da string é uma data valida
*/
		
String.prototype.isDate = function(){
		var pt = this.split( '/' );
		var dt = new Date();
		var dd = Number( pt[ 0 ] );
		var mm = Number( pt[ 1 ] );
		var yy = Number( pt[ 2 ] );
		
		if ( pt.length != 3 ) return( false );
		
		if ((mm == 1 || mm == 3 || mm == 5 || mm == 7 || mm == 8 || mm == 10 || mm == 12) && (dd <= 0 || dd > 31)) return false;
			
		if ((mm == 4 || mm == 6 || mm == 9 || mm == 11 ) && (dd <= 0 || dd > 30)) return false;

		if ((mm == 2 ) && (dd <= 0 || (yy%4 == 0 && dd > 29 ) || (yy%4 != 0 && dd > 28 ))) return false;

		if (yy < 1900 || yy > 2100) return false;
		
		if (mm < 01 || mm > 12) return false;
		return true;
	}

/* 
Função: Prototype isPlaca
Inserida: 19/01/2006 16:56
Ultima alteração: 09/02/2006 10:44
Propósito: Verifica se o valor de uma string é uma placa valida no formato 'XXX0000'
*/
		
String.prototype.isPlaca = function(){
		if ( this.replace('-','').length != 7) return( false );
		v_num = this.replace('-','').substr(3,4);
		if ( isNaN( v_num ) ) return( false );
		return( true );
	}

/* 
Função: Prototype isNumber
Inserida: 19/01/2006 16:56
Ultima alteração: 20/01/2006 15:56
Propósito: Verifica se o valor da string é um numero
*/
		
String.prototype.isNumber = function(){
  return( !isNaN( this.split( '.' ).join( '' ).split( ',' ).join( '' ).split( '-' ).join( '' ) ) );
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

/* 
Função: Prototype hasEmptyElements
Inserida: 19/01/2006 16:58
Ultima alteração: 19/01/2006 16:58
Propósito: Verifica se um array possui elementos em branco, nulos ou indefinidos
*/
		
Array.prototype.hasEmptyElements = function(){
		for ( var i = 0 ; i < this.length ; i++ )
			if ( ( this[ i ] == '' ) || ( this[ i ] == null ) || ( this[ i ] == undefined ) )
				return( true );
		return( false );
	}

/* 
Função: Prototype Dtos
Inserida: 19/01/2006 16:58
Ultima alteração: 19/01/2006 16:58
Propósito: ???
*/
		
Date.prototype.Dtos = function(){
		var dd = this.getDate();
		var mm = this.getMonth() + 1;
		var yy = this.getFullYear();
		
		return( [ yy , ( mm < 10 ? '0' : '' ) + mm , ( dd < 10 ? '0' : '' ) + dd ].join( '' ) );
	}

/* 
Função: Minimo
Inserida: 30/01/2006 15:08
Ultima alteração: 30/01/2006 15:08
Propósito: Retorna o menor dos valores fornecidos como parametro
*/
		
function min() {
  if(arguments.length <= 0) {
    alert('Não foram fornecidos parâmetros para a função!');
  }
  var v_menor = arguments[0];
  for(var i=1;i<arguments.length;i++) {
    v_menor = ((v_menor <= arguments[i])?v_menor:arguments[i]);
  }
  return v_menor;
}

/* 
Função: Marcar/Desmarcar Todos os Check
Inserida: 31/01/2006 12:06
Ultima alteração: 31/01/2006 12:06
Propósito: Marca ou desmarca todos os checks com determinado nome no formulario
*/
		
function f_marcar_todos_check(v_form, v_name, v_marca) {
  for(var i=0;i<v_form.elements.length;i++) {
    if(v_form.elements[i].type == 'checkbox' && v_form.elements[i].name == v_name) {
      v_form.elements[i].checked = v_marca;
    }
  }
}

/* 
Função: Organizar Colunas
Inserida: 13/02/2006 16:38
Ultima alteração: 13/02/2006 16:38
Propósito: Abre a janela de ordenação de colunas do sistema
*/
		
function f_organizar_colunas (p_table_id, p_cookie) {
  NewWindow('/_consultas/organizar_colunas.cfm?TABELA_ID='+p_table_id+'&COOKIE='+p_cookie, 'org_colunas', 600, 500, 'yes');
}

/* 
Função: Inicializa Filtros
Inserida: 17/02/2006 11:38
Ultima alteração: 17/02/2006 11:42
Propósito: Inicializa a opção de Filtros nas tabelas
*/
		
function initFiltros(p_tbl_id) {
	var v_tbl = document.getElementById(p_tbl_id);
	for (var i=0;i<v_tbl.tHead.rows.length;i++) {
		for(var j=0;j<v_tbl.tHead.rows[i].cells.length;j++) {
			var celula = v_tbl.tHead.rows[i].cells[j];
			if (celula.filtro) {
				celula.index = j;
				index = j;
				var v_div = document.createElement('div');
				v_div.style.position = 'absolute';
				v_div.style.width = celula.width;
				v_div.className = 'titulo_3';
				v_div.style.display = 'none';
				var v_list = document.createElement("select");
				opcoes = celula.filtro.split(',');
				f_cria_option('', '-- Tudo --', v_list);
				for (k=0;k<opcoes.length;k++) {
					if(opcoes[k].replace(' /g', '') != '') {
						f_cria_option(opcoes[k], opcoes[k], v_list);
					}
				}
				v_list.size = 5;
				v_list.onclick = function () {
					this.parentNode.style.display = 'none';
					f_filtra_celula(v_tbl, this.parentNode.parentNode.index, this.value);
				}
				v_div.appendChild(v_list);
				celula.appendChild(v_div);
				var v_btn = document.createElement('button');
				v_btn.value = '<img src="/_imagens/botoes/16x16/seta_down.gif" width="8" height="4" align="absmiddle" />';
				v_btn.className = 'botao-16x16';
				v_btn.style.height = 16;
				v_btn.title = 'Filtrar...';
				v_btn.onclick = function () {
					var scrOfY;
					var scrOfX;
					if( typeof( window.pageYOffset ) == 'number' ) {
					//Netscape compliant
						scrOfY = window.pageYOffset;
						scrOfX = window.pageXOffset;
					} else {
						if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
						//DOM compliant
							scrOfY = document.body.scrollTop;
							scrOfX = document.body.scrollLeft;
						} else {
							if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop || document.documentElement.scrollTop == 0) ) {
							//IE6 standards compliant mode
								scrOfY = document.documentElement.scrollTop;
								scrOfX = document.documentElement.scrollLeft;
							}
						}	
					}
					this.parentNode.div_filtro.style.top = event.clientY+scrOfY;
					this.parentNode.div_filtro.style.left = event.clientX;
					this.parentNode.div_filtro.style.display = ((this.parentNode.div_filtro.style.display == 'none')?'':'none');
				}
				celula.insertBefore(v_btn, celula.childNodes[0]);
				celula.div_filtro = v_div;
			}
		}
	}
}

/* 
Função: Filtra Celula
Inserida: 17/02/2006 11:39
Ultima alteração: 17/02/2006 11:39
Propósito: Filtra as linhas da tabela de acordo com o conteudo da celula
*/
		
function f_filtra_celula(p_tbl, p_cell, p_filtro) {
	for(var i=0;i<p_tbl.tBodies.length;i++) {
		for(var j=0;j<p_tbl.tBodies[i].rows.length;j++) {
			if(p_tbl.tBodies[i].rows[j].cells[p_cell] != null) {
				if (p_filtro == '') {
					p_tbl.tBodies[i].rows[j].style.display = '';
				} else {
					if(p_tbl.tBodies[i].rows[j].cells[p_cell].innerHTML == p_filtro) {
						p_tbl.tBodies[i].rows[j].style.display = '';
					} else {
						p_tbl.tBodies[i].rows[j].style.display = 'none';
					}
				}
			}
		}
	}
}

/* 
Função: Gera Input de Atributo
Inserida: 08/03/2006 17:50
Ultima alteração: 10/07/2006 11:01
Propósito: Gera os inputs dinamicos de atributos, de acordo com seu tipo, aplicando mascaras e outras funcionalidades como calendario

p_tipo = Tipo do campo (NUMERO,INTEIRO,CARACTER,HORA,DATA,DATA_HORA,LISTA)
p_nome = Nome e ID do campo no formulario
p_valores = valores passados para o tipo LISTA, separados por ","

*/
		
function f_input_atributo(p_tipo, p_nome, p_valores, p_function) {
	switch(p_tipo.toUpperCase()) {
		case 'NUMERO':
			v_str = '<input type="text" name="'+p_nome+'" id="'+p_nome+'" tipo="numerico" onKeyPress="return f_formata_numero_decimal(this)">';
			if(p_function) {
				p_function(v_str);
			} else {
				document.write(v_str);
			}
			break;
		case 'INTEIRO':
			v_str = '<input type="text" name="'+p_nome+'" id="'+p_nome+'" onKeyPress="return f_formata(this, \'0000000000000000000000000\')">';
			if(p_function) {
				p_function(v_str);
			} else {
				document.write(v_str);
			}
			break;
		case 'COR(HEXA)':
			v_str = '<input type="text" name="'+p_nome+'" id="'+p_nome+'" onKeyPress="return f_formata(this, \'#AAAAAA\')">';
			if(p_function) {
				p_function(v_str);
			} else {
				document.write(v_str);
			}
			break;
		case 'CARACTER':
			v_str = '<input type="text" name="'+p_nome+'" id="'+p_nome+'">';
			if(p_function) {
				p_function(v_str);
			} else {
				document.write(v_str);
			}
			break;
		case 'TEXTO_LONGO':
			v_str = '<textarea name="'+p_nome+'" id="'+p_nome+'" style="width:100%; height: 60px"></textarea>';
			if(p_function) {
				p_function(v_str);
			} else {
				document.write(v_str);
			}
			break;
		case 'HORA':
			v_str = '<input type="text" name="'+p_nome+'" id="'+p_nome+'" onKeyPress="return f_formata(this, \'00:00\')">';
			if(p_function) {
				p_function(v_str);
			} else {
				document.write(v_str);
			}
			break;
		case 'DATA':
			v_str = '<input type="text" name="'+p_nome+'" id="'+p_nome+'" style="width: 80px" onKeyPress="return f_formata(this, \'00/00/0000\')"><button class="botao-16x16" id="btn_'+p_nome+'"><img src="/_imagens/botoes/16x16/calendario.gif" width="16" height="16" align="absmiddle" /></button>';
			if(p_function) {
				p_function(v_str);
			} else {
				document.write(v_str);
			}
			Calendar.setup(
				{
				  inputField  : p_nome,      // ID of the input field
				  ifFormat    : "%d/%m/%Y",    // the date format
				  button      : "btn_"+p_nome,    // ID of the button
				  range       : [2001,2050]
				}
			);
			break;
		case 'DATA_HORA':
			v_str = '<input type="text" name="'+p_nome+'" id="'+p_nome+'" style="width: 110px" onKeyPress="return f_formata(this, \'00/00/0000 00:00\')"><button class="botao-16x16" id="btn_'+p_nome+'"><img src="/_imagens/botoes/16x16/calendario.gif" width="16" height="16" align="absmiddle" /></button>';
			if(p_function) {
				p_function(v_str);
			} else {
				document.write(v_str);
			}
			Calendar.setup(
				{
				  inputField  : p_nome,      // ID of the input field
				  ifFormat    : "%d/%m/%Y %H:%M",    // the date format
				  button      : "btn_"+p_nome,    // ID of the button
				  range       : [2001,2050],
				  showsTime   : true
				}
			);
			break;
		case 'LISTA':
			if(p_valores == undefined) {
				alert('Não foram fornecidos os valores para o preechimento da lista "'+p_nome+'"!');
				return;
			}
			var v_str = '<select name="'+p_nome+'" id="'+p_nome+'">';
			v_str += '<option value="">-- Selecione --</option>';
			v_valores = p_valores.split(',');
			for(var i=0;i<v_valores.length;i++) {
				v_str += '<option value="'+v_valores[i]+'">'+v_valores[i]+'</option>';
			}
			v_str += '</select>';
			if(p_function) {
				p_function(v_str);
			} else {
				document.write(v_str);
			}
			break;
		case 'FLAG':
			var v_str = '<select name="'+p_nome+'" id="'+p_nome+'">';
			v_str += '<option value="">-- Selecione --</option>';
			v_str += '<option value="1">Sim</option>';
			v_str += '<option value="0">N'+String.fromCharCode(227)+'o</option>';
			v_str += '</select>';
			if(p_function) {
				p_function(v_str);
			} else {
				document.write(v_str);
			}
			break;
		default:
			alert('Tipo "'+p_tipo.toUpperCase()+'" não implementado para os atributos!');
			break;
	}
}

/* 
Função: Formata numero com decimal e milhar
Inserida: 09/03/2006 14:24
Ultima alteração: 10/03/2006 16:34
Propósito: Formatar numero com decimais e milhar (00.000,00)
*/
		
function f_formata_decimal_milhar(_v)
{
  var _dollars=parseInt(_v);
  var _cents=parseInt((_v-_dollars)*100);
  var _negative=_dollars<0;
  if(_negative){_dollars=-_dollars;_cents=-_cents;}
  while(_cents.toString().length<2)_cents="0"+_cents;
  var _dA=_dollars.toString().split("");
  var _d="";
  for(var i=_dA.length-1;i>=0;i--)
  {
    var _comma="";
	if((_dA.length-i)%3==0 && i!=0)_comma=".";
    _d=_comma+_dA[i]+_d;
  }
  var _neg_sign=_negative?"-":"";
  var _result=_neg_sign+_d+","+_cents;
  return _result;
}

/* 
Função: Open Ajax
Inserida: 29/03/2006 10:26
Ultima alteração: 29/03/2006 10:26
Propósito: Função para iniciarmos o Ajax no browser do cliente
*/
		
function f_open_ajax() {
var ajax;
try{
    ajax = new XMLHttpRequest(); // XMLHttpRequest para browsers decentes, como: Firefox, Safari, dentre outros.
}catch(ee){
    try{
        ajax = new ActiveXObject("Msxml2.XMLHTTP"); // Para o IE da MS
    }catch(e){
        try{
            ajax = new ActiveXObject("Microsoft.XMLHTTP"); // Para o IE da MS
        }catch(E){
            ajax = false;
        }
    }
}
return ajax;
}

/* 
Função: data Ajax
Inserida: 29/03/2006 14:27
Ultima alteração: 31/07/2006 17:53
Propósito: Efetua uma consulta por ajax
*/
		
function f_query_ajax(p_url, p_fnc_result, p_fnc_carregando, p_synchronous) {
	
		var ajax = f_open_ajax();
		if(p_url.indexOf('?') != -1) 
			p_url += '&rnddate='+(new Date());
		else
			p_url += '?rnddate='+(new Date());
		ajax.open( "GET", p_url, !p_synchronous); // Envia o termo da busca como uma querystring, nos possibilitando o filtro na busca.
		ajax.onreadystatechange = function() {
			if(ajax.readyState == 1) { // Quando estiver carregando, exibe: carregando...
				if(p_fnc_carregando) {
					p_fnc_carregando();
				} else {
					p_fnc_result({texto: '<img src="/_imagens/uteis/carregando.gif">', ajax:ajax, toString: function() { return this.texto; }});
				}
			}
			if(ajax.readyState == 4) { // Quando estiver tudo pronto.
				var resultado = ajax.responseText; // Coloca o resultado (da busca) retornado pelo Ajax nessa variável (var resultado).
//				resultado = resultado.replace(/\+/g," "); // Resolve o problema dos acentos (saiba mais aqui: http://www.plugsites.net/leandro/?p=4)
				resultado = unescape(resultado); // Resolve o problema dos acentos
//				if(ajax.status == 200) {
					p_fnc_result({texto: resultado, ajax:ajax, toString: function() { return this.texto; }});
//				} else {
//					p_fnc_result({texto: resultado, ajax:ajax, toString: function() { return this.texto; }});
//				}
			}	
		}
		ajax.send(null);		
}	


/* 
Função: get Query String
Inserida: 29/03/2006 14:29
Ultima alteração: 27/09/2006 09:32
Propósito: Gera uma "query string" baseada nos campos de um formulario
*/
		
function f_get_query_string(p_form) {
	var res = '';
	with (p_form) {
		for(var i=0;i<p_form.elements.length;i++) {
			if(!p_form.elements[i].disabled && p_form.elements[i].name) {
				if(p_form.elements[i].type == 'radio' || p_form.elements[i].type == 'checkbox') {
					if(p_form.elements[i].checked) {
						res += p_form.elements[i].name+'='+escape(p_form.elements[i].value)+'&';
					}
				} else {
					res += p_form.elements[i].name+'='+escape(f_valor_campo(p_form.elements[i].name, p_form))+'&';
				}
			}
		}
	}
	res = res.substr(0,res.length-1);
	return res;
}

/* 
Função: Query Ajax WDDX
Inserida: 31/03/2006 09:37
Ultima alteração: 18/10/2006 10:07
Propósito: Função que gera uma conexão com o componente CFC e retorna os dados em WDDX para consulta.
Exemplo da função de retorno:
function list_response(obj){ //callback functions always take one argument. This is the result passed back from the server.
	if( (obj.ajax.readyState == 1) || (obj.ajax.readyState == 2) || (obj.ajax.readyState == 3) ){ // Quando estiver carregando, exibe: carregando...
		f_cria_carregando_ajax();
	}
	else if(obj.ajax.readyState == 4) { // Quando estiver tudo pronto.
		v_texto = '';
		v_linhas = new Array();
		v_linhas = obj.struct.cargo.toString().split(',');
		for (var i=0;i<v_linhas.length;i++) {
			v_texto +=  v_linhas[i] + '<br>';
		}
		document.getElementById('teste').innerHTML =  v_texto;
		f_hide_carregando_ajax();
	}	
}
*/
		
function f_query_wddx(p_url, p_arguments, p_fnc_result, p_not_show_carregando, p_referencia, p_synchronous) {
	if(!p_not_show_carregando) 
		f_cria_carregando_ajax();
	v_meta = '<META NAME="ColdFusionMXEdition" CONTENT="ColdFusion DevNet Edition - Not for Production Use.">';
	var ajax = f_open_ajax();
	// Cria um parametro com a data atual para fugir do cache do ajax.
	if(p_url.indexOf('?') != -1) 
		p_url += '&rnddate='+(new Date());
	else
		p_url += '?rnddate='+(new Date());
	ajax.open("POST", p_url, !p_synchronous); // Envia o termo da busca como uma querystring, nos possibilitando o filtro na busca.
	ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
	ajax.send(p_arguments);
	ajaxRef = p_referencia;
	ajax.onreadystatechange = function() {
	rObj = null;
	resultado = '';
	if(ajax.readyState == 4) {
		v_status_error = false;		
		try {
			var v_status = ajax.status;
		} catch(e) {
			v_status_error = true;
		}		
		if(v_status_error || ajax.status == 200) {			 
			var resultado = ajax.responseText; // Coloca o resultado (da busca) retornado pelo Ajax nessa variável (var resultado).
			resultado = resultado.replace(/\+/g," "); // Resolve o problema dos acentos (saiba mais aqui: http://www.plugsites.net/leandro/?p=4)
			resultado = unescape(resultado); // Resolve o problema dos acentos
			if (resultado.toString().replace(v_meta,'').length > 0){		
				rObj = parseWDDX(resultado.toString().replace(v_meta,''));
			}
			if(!p_not_show_carregando){				
				f_hide_carregando_ajax();
			}
		} else { 
			f_cria_erro_ajax();
			document.getElementById("div_erro").style.display = '';
			document.getElementById("div_erro_interno").style.display = '';
			document.getElementById("td_erro").innerHTML = ajax.responseText;
			if(!p_not_show_carregando) 
				f_hide_carregando_ajax();
			}
		}   	
		p_fnc_result({
				 texto: resultado.toString().replace(v_meta,'')
				,struct:rObj
				,ajax:ajax
				,referencia: ajaxRef
				,toString: function() { 
					return this.texto;  
				}
			});
	}
}

/* 
Função: Posiona e mostra carregando AJAX
Inserida: 31/03/2006 11:26
Ultima alteração: 31/03/2006 11:48
Propósito: Cria o DIV de carregando que é utilizado no AJAX
*/
		
function f_carregando_ajax() {
	if (document.getElementById('div_carregando')) {
		ns=(document.layers)?1:0;
		if (ns){
			Ypos=window.pageYOffset;
			Xpos=window.pageXOffset+window.innerWidth-200;
		}
		else{
			Ypos=document.body.scrollTop;
			Xpos=document.body.scrollLeft+window.document.body.clientWidth-200;
		}	

		with(document.getElementById('div_carregando')) {
			style.top = Ypos;	
			style.left = Xpos;
			style.width = '182px'; 
			style.height = '35px';
			style.display = '';
		}
	}
}

/* 
Função: Oculta o Carregando AJAX
Inserida: 31/03/2006 11:27
Ultima alteração: 31/03/2006 11:27
Propósito: Oculta o DIV de carregando e mata o setInterval de posicionamento
*/
		
function f_hide_carregando_ajax() {
	v_ajax_running--;
	if (document.getElementById('div_carregando') && v_ajax_running == 0) {
		window.clearInterval(v_timeoutId);
		v_timeoutId = 0;		
		document.getElementById('div_carregando').style.display = 'none';
	}
}


/* 
Função: Cria carregando AJAX
Inserida: 31/03/2006 11:28
Ultima alteração: 31/03/2006 11:48
Propósito: Cria o objeto DIV e seta o intervalo para a rotina de posicionamento do carregando
*/
var v_timeoutId = 0;
var v_ajax_running = 0;
function f_cria_carregando_ajax() {
	if (!document.getElementById('div_carregando')) {
		var v_div = document.createElement('DIV');	    
		document.body.appendChild(v_div);
		v_div.id = "div_carregando";
		v_div.style.position = "absolute";
		v_div.innerHTML = '<img height="35" width="182" src="/_imagens/uteis/processando_1.gif">';
	}
	if (v_timeoutId == 0) {
		v_timeoutId = window.setInterval(f_carregando_ajax,50);
	}
	v_ajax_running++;
}

/* Indica se ainda está sendo executada alguma função AJAX */
function f_ajax_running() {
	return v_ajax_running;
}


/* 
Função: Cria erro AJAX
Inserida: 03/04/2006 18:13
Ultima alteração: 03/04/2006 18:13
Propósito: Cria uma janela de erro para funções rodadas pelo AJAX
*/
		
function f_cria_erro_ajax() {
		if (!document.getElementById('div_erro')) {
			var v_div_interno = document.createElement('DIV');	    
			v_div_interno.id = "div_erro_interno";
			v_div_interno.style.position = "absolute";
			v_div_interno.style.top = 15;
			v_div_interno.style.left = 10;
			v_div_interno.style.width = 600;
			v_div_interno.style.height = 265;
			v_div_interno.style.display = 'none';
			v_div_interno.style.zIndex = 1;
			v_div_interno.innerHTML =   '<iframe frameborder="0" style="width:600px; height:265px;"></iframe>';
	
			var v_div = document.createElement('DIV');	    
			v_div.id = "div_erro";
			v_div.style.position = "absolute";
			v_div.style.top = 15;
			v_div.style.left = 10;
			v_div.style.width = 600;
			v_div.style.height = 265;
			v_div.style.display = 'none';
			v_div.style.zIndex = 1000;
			v_div.innerHTML =   '<table width="600" height="265" border="0" cellpadding="3" cellspacing="2">' +
								'  <tr id="barra_botoes_top">' + 
								'      <td height="25">Erro!</td>'+ 
								'   </tr>'+
								'   <tr class="obrigatorio">'+
								'      <td height="215"><div id="td_erro" style="overflow:scroll;vertical-align:top; width:596; height:215"></div></td>'+
								'   </tr>'+
								'   <tr id="barra_botoes_bottom">'+
								'      <td height="25"><button type="button" onClick="document.getElementById(\'div_erro\').style.display=\'none\'; document.getElementById(\'div_erro_interno\').style.display=\'none\'" class="botao"><img src="/_imagens/botoes/16x16/fechar_tela.gif" alt="" width="16" height="16" align="absmiddle">&nbsp;Fechar</button>'+   
								'      </td>'+
								'   </tr>'+
								'</table>';
			

			document.body.appendChild(v_div_interno);
			document.body.appendChild(v_div);
		}
	}

/* 
Função: Formata Data ColdFusion
Inserida: 04/04/2006 08:25
Ultima alteração: 04/04/2006 08:25
Propósito: Formata uma data fornecida pelo coldfusion
*/
		
function f_cf_date_format(p_date, p_format) {
	var date = new Date(p_date);
	var MONTH_NAMES = new Array('January','February','March','April','May','June','July','August','September','October','November','December');
	var DAY_NAMES = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
	var ret = p_format.replace(/dd/g, ((date.getDate() < 10)?'0':'')+date.getDate());
	var ret = ret.replace(/mm/g, ((Number(date.getMonth())+1 < 10)?'0':'')+(Number(date.getMonth())+1));
	var ret = ret.replace(/yyyy/g, date.getFullYear());
	var ret = ret.replace(/hh/g, ((date.getHours() < 10)?'0':'')+date.getHours());
	var ret = ret.replace(/mi/g, ((date.getMinutes() < 10)?'0':'')+date.getMinutes());
	var ret = ret.replace(/ss/g, ((date.getSeconds() < 10)?'0':'')+date.getSeconds());
	return ret;
}

/* 
Função: Exportar Excel
Inserida: 04/04/2006 11:30
Ultima alteração: 04/04/2006 11:30
Propósito: Exporta uma tabela para o Excel
*/
		
function f_exportar_excel(p_table) {
	v_span = document.createElement('span');
	p_table.parentNode.insertBefore(v_span, p_table);
	v_span.appendChild(p_table);
	v_html = v_span.innerHTML;
	v_span.removeNode();
	v_form = document.createElement('form');
	v_form.action = '/_consultas/exportar_excel.cfm';
	v_form.method = 'post';
	v_form.target = 'consultas';
	v_input = document.createElement('input');
	v_input.name = 'CONTEUDO';
	v_input.value = v_html;
	v_form.appendChild(v_input);
	document.body.appendChild(v_form);
	v_form.submit();
	v_input.removeNode();
	v_form.removeNode();
}


/* 
Função: Gerar Scroll
Inserida: 05/04/2006 16:16
Ultima alteração: 05/04/2006 16:54
Propósito: Gera um componente scroll
*/
		
function f_gera_scroll(p_name, p_min, p_max, p_position, p_on_change, p_on_move) {
	var MIN_X = 3;
	var MAX_X = 103;
	document.write('<div class="barra_rolagem" id="'+p_name+'_div" style="float:left"></div><input type="hidden" name="'+p_name+'" id="'+p_name+'" value="'+p_position+'" />');
	v_div_scroll = document.getElementById(p_name+'_div');
	v_div_cursor = document.createElement('img');
	v_div_cursor.className = 'barra_rolagem_cursor';
	v_div_cursor.style.position = 'relative';
	v_left = Math.round(((p_position-p_min)/(p_max-p_min)*(MAX_X-MIN_X))+MIN_X);
	v_div_cursor.style.left = v_left+'px';
	v_div_cursor.style.top = '1px';
	v_div_scroll.appendChild(v_div_cursor);
	v_input = document.getElementById(p_name);
	v_div_cursor.onChangePosition = function () {
		v_atual = (Number(String(this.style.left).replace('px',''))-MIN_X)/(MAX_X-MIN_X);
		v_input.value = (p_max-p_min)*v_atual;
		if(p_on_move) {
			p_on_move(v_input.value);
		}
	}	
	v_div_scroll.onmousedown = function () {
		f_get_scroll();
		var v_posicao = window.event.clientX-5 - scrOfX - f_posicao_objeto(this, true);
		this.childNodes[0].style.left = (v_posicao<MIN_X)?MIN_X:((v_posicao>MAX_X)?MAX_X:v_posicao);
		this.dragging = true;
		this.childNodes[0].onChangePosition();
	}
	v_div_scroll.onmousemove = function () {
		if(this.dragging) {
			f_get_scroll();
			var v_posicao = window.event.clientX-5 - scrOfX - f_posicao_objeto(this, true);
			this.childNodes[0].style.left = (v_posicao<MIN_X)?MIN_X:((v_posicao>MAX_X)?MAX_X:v_posicao);
			this.childNodes[0].onChangePosition();
		}
		this.dragging = ((v_posicao>=MIN_X)&&(v_posicao<=MAX_X));
		
	}
	v_div_scroll.onmouseup = function () {
		this.dragging = false;
	}
	v_div_cursor.onmousedown = function () {
		f_get_scroll();
		var v_posicao = window.event.clientX-5 - scrOfX - f_posicao_objeto(this, true);
		this.style.left = (v_posicao<MIN_X)?MIN_X:((v_posicao>MAX_X)?MAX_X:v_posicao);
		this.dragging = ((v_posicao>=MIN_X)&&(v_posicao<=MAX_X));
		this.onChangePosition();
	}
	v_div_cursor.onmousemove = function () {
		if(this.dragging) {
			f_get_scroll();
			var v_posicao = window.event.clientX-5 - scrOfX - f_posicao_objeto(this, true);
			this.style.left = (v_posicao<MIN_X)?MIN_X:((v_posicao>MAX_X)?MAX_X:v_posicao);
			this.onChangePosition();
		}
		this.dragging = ((v_posicao>=MIN_X)&&(v_posicao<=MAX_X));
		
	}
	v_div_cursor.onmouseup = function () {
		this.dragging = false;
	}
}

/* 
Função: Get Scroll
Inserida: 05/04/2006 16:17
Ultima alteração: 05/04/2006 16:17
Propósito: Busca o scroll efetuado na tela
*/
var v_get_scroll_element = null;
function f_get_scroll() {
	if( typeof( window.pageYOffset ) == 'number' ) {
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
		scrOfHeight = document.body.offsetHeight;
		scrOfWidth = document.body.offsetWidth;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
		scrOfHeight = document.body.offsetHeight;
		scrOfWidth = document.body.offsetWidth;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop || document.documentElement.scrollTop == 0) ) {
		if(v_get_scroll_element == null) {
			scrOfY = document.documentElement.scrollTop;
			scrOfX = document.documentElement.scrollLeft;
			scrOfHeight = document.documentElement.offsetHeight;
			scrOfWidth = document.documentElement.offsetWidth;
		} else {
			scrOfY = v_get_scroll_element.scrollTop;
			scrOfX = v_get_scroll_element.scrollLeft;
			scrOfHeight = v_get_scroll_element.offsetHeight;
			scrOfWidth = v_get_scroll_element.offsetWidth;
		}
	}
}

/* 
Função: Posição absoluta
Inserida: 05/04/2006 16:18
Ultima alteração: 05/04/2006 16:18
Propósito: Retorna a posicao absoluta do objeto na tela
*/
		
function f_posicao_objeto(p_obj,p_left){
	var total=0;
	while(p_obj!=null){
		total+=p_obj["offset"+(p_left?"Left":"Top")];
		p_obj=p_obj.offsetParent;
	}
	return total;
}

/* 
Função: Posição absoluta
Inserida: 05/04/2006 16:18
Ultima alteração: 05/04/2006 16:18
Propósito: Retorna a posicao absoluta do objeto na tela
*/
		
function f_posicao_obj(p_obj){
	var totalLeft=0;
	var totalTop=0;
	while(p_obj!=null){
		totalLeft+=p_obj.offsetLeft;
		totalTop+=p_obj.offsetTop;
		p_obj=p_obj.offsetParent;
	}
	return { top:totalTop, left:totalLeft };
}

/* 
Função: Texto HTML para JS
Inserida: 29/04/2006 10:05
Ultima alteração: 29/04/2006 10:25
Propósito: Converte os caracteres especiais do HTML para Javascript
*/
		
function f_html_to_js(texto) {
	text = texto;
    text = text.replace(/&quot;/g,unescape('%22'));
    text = text.replace(/&amp;/g,unescape('%26'));
    text = text.replace(/&lt;/g,unescape('%3C'));
    text = text.replace(/&gt;/g,unescape('%3E'));
    text = text.replace(/&nbsp;/g,unescape('%A0'));
    text = text.replace(/&iexcl;/g,unescape('%A1'));
    text = text.replace(/&cent;/g,unescape('%A2'));
    text = text.replace(/&pound;/g,unescape('%A3'));
    text = text.replace(/&yen;/g,unescape('%A5'));
    text = text.replace(/&brvbar;/g,unescape('%A6'));
    text = text.replace(/&sect;/g,unescape('%A7'));
    text = text.replace(/&uml;/g,unescape('%A8'));
    text = text.replace(/&copy;/g,unescape('%A9'));
    text = text.replace(/&ordf;/g,unescape('%AA'));
    text = text.replace(/&laquo;/g,unescape('%AB'));
    text = text.replace(/&not;/g,unescape('%AC'));
    text = text.replace(/&shy;/g,unescape('%AD'));
    text = text.replace(/&reg;/g,unescape('%AE'));
    text = text.replace(/&macr;/g,unescape('%AF'));
    text = text.replace(/&deg;/g,unescape('%B0'));
    text = text.replace(/&plusmn;/g,unescape('%B1'));
    text = text.replace(/&sup2;/g,unescape('%B2'));
    text = text.replace(/&sup3;/g,unescape('%B3'));
    text = text.replace(/&acute;/g,unescape('%B4'));
    text = text.replace(/&micro;/g,unescape('%B5'));
    text = text.replace(/&para;/g,unescape('%B6'));
    text = text.replace(/&middot;/g,unescape('%B7'));
    text = text.replace(/&cedil;/g,unescape('%B8'));
    text = text.replace(/&sup1;/g,unescape('%B9'));
    text = text.replace(/&ordm;/g,unescape('%BA'));
    text = text.replace(/&raquo;/g,unescape('%BB'));
    text = text.replace(/&frac14;/g,unescape('%BC'));
    text = text.replace(/&frac12;/g,unescape('%BD'));
    text = text.replace(/&frac34;/g,unescape('%BE'));
    text = text.replace(/&iquest;/g,unescape('%BF'));
    text = text.replace(/&Agrave;/g,unescape('%C0'));
    text = text.replace(/&Aacute;/g,unescape('%C1'));
    text = text.replace(/&Acirc;/g,unescape('%C2'));
    text = text.replace(/&Atilde;/g,unescape('%C3'));
    text = text.replace(/&Auml;/g,unescape('%C4'));
    text = text.replace(/&Aring;/g,unescape('%C5'));
    text = text.replace(/&AElig;/g,unescape('%C6'));
    text = text.replace(/&Ccedil;/g,unescape('%C7'));
    text = text.replace(/&Egrave;/g,unescape('%C8'));
    text = text.replace(/&Eacute;/g,unescape('%C9'));
    text = text.replace(/&Ecirc;/g,unescape('%CA'));
    text = text.replace(/&Euml;/g,unescape('%CB'));
    text = text.replace(/&Igrave;/g,unescape('%CC'));
    text = text.replace(/&Iacute;/g,unescape('%CD'));
    text = text.replace(/&Icirc;/g,unescape('%CE'));
    text = text.replace(/&Iuml;/g,unescape('%CF'));
    text = text.replace(/&ETH;/g,unescape('%D0'));
    text = text.replace(/&Ntilde;/g,unescape('%D1'));
    text = text.replace(/&Ograve;/g,unescape('%D2'));
    text = text.replace(/&Oacute;/g,unescape('%D3'));
    text = text.replace(/&Ocirc;/g,unescape('%D4'));
    text = text.replace(/&Otilde;/g,unescape('%D5'));
    text = text.replace(/&Ouml;/g,unescape('%D6'));
    text = text.replace(/&times;/g,unescape('%D7'));
    text = text.replace(/&Oslash;/g,unescape('%D8'));
    text = text.replace(/&Ugrave;/g,unescape('%D9'));
    text = text.replace(/&Uacute;/g,unescape('%DA'));
    text = text.replace(/&Ucirc;/g,unescape('%DB'));
    text = text.replace(/&Uuml;/g,unescape('%DC'));
    text = text.replace(/&Yacute;/g,unescape('%DD'));
    text = text.replace(/&THORN;/g,unescape('%DE'));
    text = text.replace(/&szlig;/g,unescape('%DF'));
    text = text.replace(/&agrave;/g,unescape('%E0'));
    text = text.replace(/&aacute;/g,unescape('%E1'));
    text = text.replace(/&acirc;/g,unescape('%E2'));
    text = text.replace(/&atilde;/g,unescape('%E3'));
    text = text.replace(/&auml;/g,unescape('%E4'));
    text = text.replace(/&aring;/g,unescape('%E5'));
    text = text.replace(/&aelig;/g,unescape('%E6'));
    text = text.replace(/&ccedil;/g,unescape('%E7'));
    text = text.replace(/&egrave;/g,unescape('%E8'));
    text = text.replace(/&eacute;/g,unescape('%E9'));
    text = text.replace(/&ecirc;/g,unescape('%EA'));
    text = text.replace(/&euml;/g,unescape('%EB'));
    text = text.replace(/&igrave;/g,unescape('%EC'));
    text = text.replace(/&iacute;/g,unescape('%ED'));
    text = text.replace(/&icirc;/g,unescape('%EE'));
    text = text.replace(/&iuml;/g,unescape('%EF'));
    text = text.replace(/&eth;/g,unescape('%F0'));
    text = text.replace(/&ntilde;/g,unescape('%F1'));
    text = text.replace(/&ograve;/g,unescape('%F2'));
    text = text.replace(/&oacute;/g,unescape('%F3'));
    text = text.replace(/&ocirc;/g,unescape('%F4'));
    text = text.replace(/&otilde;/g,unescape('%F5'));
    text = text.replace(/&ouml;/g,unescape('%F6'));
    text = text.replace(/&divide;/g,unescape('%F7'));
    text = text.replace(/&oslash;/g,unescape('%F8'));
    text = text.replace(/&ugrave;/g,unescape('%F9'));
    text = text.replace(/&uacute;/g,unescape('%FA'));
    text = text.replace(/&ucirc;/g,unescape('%FB'));
    text = text.replace(/&uuml;/g,unescape('%FC'));
    text = text.replace(/&yacute;/g,unescape('%FD'));
    text = text.replace(/&thorn;/g,unescape('%FE'));
    text = text.replace(/&yuml;/g,unescape('%FF'));
	return text;
}

/* 
Função: Compara duas datas
Inserida: 06/05/2006 15:16
Ultima alteração: 06/05/2006 15:17
Propósito: Parâmetros
	- p_data1 : Campo data 1
	- p_data2 : Campo data 2
Chamada
	- Deve ser colocada no evento onBlur
Retorno
    - -1 se a data 1 for maior que a data 2
    - 1 se a data 2 for maior que a data 1
    - 0 se as datas forem iguais
	- -2 Data 1 inválida
	- -3 Data 2 inválida
*/
		
function f_compara_data(p_data1, p_data2)
{
	if (!p_data1.isDataHora() && !p_data1.isDate()) 
		return -2;

	if (!p_data2.isDataHora() && !p_data2.isDate()) 
		return -3;
    
	var v_data1 = new Date(p_data1.substr(6,4),p_data1.substr(3,2)-1,p_data1.substr(0,2),p_data1.substr(11,2),p_data1.substr(14,2),00);
	var v_data2 = new Date(p_data2.substr(6,4),p_data2.substr(3,2)-1,p_data2.substr(0,2),p_data2.substr(11,2),p_data2.substr(14,2),00);;	
	
	if (v_data1 > v_data2) 
		return -1;
    else if (v_data1 < v_data2)
	         return 1;
	     else
	         return 0;
}


/* 
Função: Abrir Janela
Inserida: 19/05/2006 11:31
Ultima alteração: 29/06/2006 10:42
Propósito: Abre um formulario em outra janela
*/
		
function f_abrir_janela(p_url, p_refresh,p_width,p_height) {
                if(!p_height) p_height = 600;
                if(!p_width) p_width = 800;
	if(p_refresh && p_refresh != '') {
		p_url = p_url+((p_url.indexOf('?') != -1)?'&':'?')+'atualiza_combo=top.opener.'+p_refresh+'&janela=1';
	}

	NewWindow('/janela.cfm?url='+escape(p_url),'_blank',p_width,p_height,'yes');
}

/* 
Função: Lista - Seleciona todos elementos do Select Box
Inserida: 03/07/2006 14:46
Ultima alteração: 03/07/2006 14:55
Propósito: Seleciona todos elementos do Select Box
*/
		
function f_seleciona_todos( p_select )
{
 for(var i = 0; i < p_select.options.length;i++ )
     if( p_select.options[ i ].value.length > 0 )
	     p_select.options[ i ].selected = true;
     else 
	     p_select.options[ i ] = null;
}


/* 
Função: Lista - Seleciona elemento do Grupo
Inserida: 03/07/2006 14:46
Ultima alteração: 03/07/2006 14:55
Propósito: Seleciona elemento do Grupo
*/
		
function f_seleciona_grupo( p_select )
{
 for( i = 0; i < p_select.options.length; i++ )
  {
	v_grupo = p_select.options[ i ].value.split('||');

	if( v_grupo.length == 2 )
	{
	 if( p_select.value == parseInt( v_grupo[ 0 ] ) )
		 p_select.options[ i ].selected = true;
    }
  }  
}

/* 
Função: Lista - Remove componente de um Combo para outro
Inserida: 03/07/2006 14:47
Ultima alteração: 03/07/2006 14:55
Propósito: Remove componente de um Combo para outro
*/
		
function f_deleta_componente( p_obj_origem , j )
{
   p_obj_origem.options[ j ] = null;
}


/* 
Função: Lista - Adiciona componente
Inserida: 03/07/2006 14:48
Ultima alteração: 03/07/2006 14:51
Propósito: Adiciona componente 
*/
		
function f_adiciona_componente( p_obj_origem, p_texto, p_valor )
{
  var componente  = new Option( p_texto, p_valor, true, false );
	
  p_obj_origem.options[ p_obj_origem.length ] = componente;
}


/* 
Função: Lista - Copia componente de um Combo para outro
Inserida: 03/07/2006 14:48
Ultima alteração: 03/07/2006 14:51
Propósito: Copia componente de um Combo para outro
*/
		
function f_copia_todos( p_obj_origem , p_obj_destino )
{
   for(var i = 0, l = p_obj_origem.options.length;i<l;i++)
	 f_adiciona_componente( p_obj_destino , p_obj_origem.options[ i ].text , p_obj_origem.options[ i ].value );
	  
   for(var i = p_obj_origem.options.length-1; i >-1; i-- )
	 f_deleta_componente( p_obj_origem , i );
}					
//sinc

/* 
Função: Lista - Move componente de um Combo para outro
Inserida: 03/07/2006 14:49
Ultima alteração: 03/07/2006 14:53
Propósito: Move componente de um Combo para outro
*/
		
function f_adiciona_selecionado( p_obj_origem , p_obj_destino )
{
  for( var i = 0, l = p_obj_origem.options.length;i<l ; i++ )
	 if( p_obj_origem.options[ i ].selected )
		 f_adiciona_componente( p_obj_destino , p_obj_origem.options[ i ].text , p_obj_origem.options[ i ].value );

  for(var i = p_obj_origem.options.length-1;i>-1;i--)
	  if( p_obj_origem.options[ i ].selected  )
		   f_deleta_componente( p_obj_origem , i );
}

/* 
Função: Lista - Move componente de um mesmo combo para cima 
Inserida: 03/07/2006 14:49
Ultima alteração: 03/07/2006 14:54
Propósito: Move componente de um mesmo combo para cima 
*/
		
function f_mover_cima( p_combo )
{
 for( i = 0; i < p_combo.options.length; i++ )
 {
   if( p_combo.options[ i ].selected ) 
   {
	 if( i != 0 && ! p_combo.options[ i-1 ].selected )
	 { 
		f_mudar_posicao( p_combo, i , i-1 );
		p_combo.options[ i-1 ].selected = true;
	 }
   }
  }
}

/* 
Função: Lista - Move componente de um mesmo combo para baixo 
Inserida: 03/07/2006 14:50
Ultima alteração: 03/07/2006 14:54
Propósito: Move componente de um mesmo combo para baixo 
*/
		
function f_mover_baixo( p_combo )
{
 for( i = p_combo.options.length -1; i >= 0; i-- )
 {
   if( p_combo.options[ i ].selected )
   { 
    if( i != ( p_combo.options.length - 1 ) && ! p_combo.options[ i+1 ].selected )
	 {
	  f_mudar_posicao( p_combo,  i , i+1 ); 
	  p_combo.options[ i + 1 ].selected = true;
	 }
   }
  }
}

/* 
Função: Lista - Realiza a Reordenação dos Elementos dos Combos
Inserida: 03/07/2006 14:50
Ultima alteração: 03/07/2006 14:55
Propósito: Realiza a Reordenação dos Elementos dos Combos
*/
		
function f_mudar_posicao( p_combo , i , j )
{ 
  var o 		      = p_combo.options;
  var i_selected 	  = o[ i ].selected;
  var j_selected 	  = o[ j ].selected;
  var temp 	   		  = new Option( o[ i ].text, o[ i ].value, o[ i ].defaultSelected, o[ i ].selected );
  var temp2	   		  = new Option( o[ j ].text, o[ j ].value, o[ j ].defaultSelected, o[ j ].selected );
	  o[ i ]     	  = temp2;
	  o[ j ] 	   	  = temp;
	  o[ i ].selected = j_selected;
	  o[ j ].selected = i_selected;
}

/* 
Função: Texto do Campo
Inserida: 10/07/2006 11:00
Ultima alteração: 10/07/2006 11:00
Propósito: Retorna o texto do campo
*/
		
function f_get_texto_campo(p_campo) {
	switch(p_campo.type) {
		case 'select-one':
			return p_campo.options[p_campo.selectedIndex].text;
		case 'checkbox':
			return ((p_campo.checked)?'Sim':'Nao');
		default:
			return p_campo.value;
	}
}

/* 
Função: Habilitar/Desabilitar Frame
Inserida: 11/07/2006 09:16
Ultima alteração: 03/08/2006 10:50
Propósito: Desabilita um frame inteiro
Campos:
value = Indica se o frame será habilitado ou desabilitado
frame = Indica o frame a ser tratado (default: window);
*/
		
function f_desabilita_tela(value, frame) {
	if(!frame) {
		frame = window;
	}
		
	if(frame.vDivDisable && value) {
		f_desabilita_tela(false,frame);
	}
	if(value) {
		frame.vDivDisable = frame.document.createElement("div");
		frame.vDivDisable.vShield = frame.document.createElement("iframe");
		frame.document.body.appendChild(frame.vDivDisable);
		frame.document.body.appendChild(frame.vDivDisable.vShield);
		frame.oldOverflowX = frame.document.body.style.overflowX;
		frame.oldOverflowY = frame.document.body.style.overflowY;
		frame.document.body.style.overflowX = 'hidden';
		frame.document.body.style.overflowY = 'hidden';
		with(frame.vDivDisable) {
			zIndex = 100000;
			innerHTML = '';
			style.position = 'absolute';
			v_get_scroll_element_old = v_get_scroll_element;
			v_get_scroll_element = null;
			f_get_scroll();
			v_get_scroll_element = v_get_scroll_element_old;
			style.top  = scrOfY+'px';
			style.left = scrOfX+'px';
			style.height = frame.document.body.offsetHeight;
			style.width  = frame.document.body.offsetWidth;
			style.backgroundColor = '#000000';
			style.opacity 		= 0.40;
			style.filter	 	= "alpha(opacity=40)";
		}
		with(frame.vDivDisable.vShield) {
			zIndex = 99999;
			style.position = 'absolute';
			style.top  = scrOfY+'px';
			style.left = scrOfX+'px';
			style.height = frame.document.body.offsetHeight;
			style.width  = frame.document.body.offsetWidth;
			style.backgroundColor = '#000000';
			style.opacity 		= 0.40;
			style.filter	 	= "alpha(opacity=40)";
		}
		frame.vDivDisable.innerHTML = '<iframe width="100%" height="100%" style=" opacity = 0.05;filter: alpha(opacity=05) "></iframe>';
		frame.vDivDisable.interval = setInterval(function() {
														  	with(frame.vDivDisable) {
																zIndex = 100000;
																innerHTML = '';
																style.position = 'absolute';
																v_get_scroll_element_old = v_get_scroll_element;
																v_get_scroll_element = null;
																f_get_scroll();
																v_get_scroll_element = v_get_scroll_element_old;
																style.top  = scrOfY+'px';
																style.left = scrOfX+'px';
																style.height = frame.document.body.offsetHeight;
																style.width  = frame.document.body.offsetWidth;
															}
															with(frame.vDivDisable.vShield) {
																zIndex = 99999;
																style.position = 'absolute';
																style.top  = scrOfY+'px';
																style.left = scrOfX+'px';
																style.height = frame.document.body.offsetHeight;
																style.width  = frame.document.body.offsetWidth;
															}
														  },200);
	} else {
		if(frame.vDivDisable) {
			clearInterval(frame.vDivDisable.interval);
			frame.vDivDisable.innerHTML = '';
			if(frame.vDivDisable.vShield.parentNode)
				frame.vDivDisable.vShield.parentNode.removeChild(frame.vDivDisable.vShield);
			frame.vDivDisable.parentNode.removeChild(frame.vDivDisable);
			frame.document.body.style.overflowX = frame.oldOverflowX;
			frame.document.body.style.overflowY = frame.oldOverflowY;
		}
	}
}

/* 
Função: Janela Modal
Inserida: 03/08/2006 10:51
Ultima alteração: 03/08/2006 10:51
Propósito: Gera uma janela modal com desabilitacao do frame
*/
		
function f_janela_modal(enabled, frame, div) {
	if(!frame)
		frame = window;
	f_desabilita_tela(enabled, frame);
	if(enabled) {
		frame.vDivWindowModal = frame.document.createElement('div');
		div.style.display = 'block';
		div.style.visibility = 'visible';
		frame.vDivWindowModal.appendChild(div);
		with(frame.vDivWindowModal.style) {
			position	= 'absolute'; 
			height		= 200; 
			width		= 400; 
			v_get_scroll_element_old = v_get_scroll_element;
			v_get_scroll_element = null;
			f_get_scroll();
			v_get_scroll_element = v_get_scroll_element_old;
			top			= (((frame.document.body.offsetHeight-div.style.height.replace('px',''))/2)-50)+scrOfY; 
			left 		= (((frame.document.body.offsetWidth-div.style.width.replace('px',''))/2)-50)+scrOfX;
			zIndex 		=  1001; 
		}
		frame.document.body.appendChild(frame.vDivWindowModal);
	} else {
		frame.document.body.appendChild(div);
		frame.vDivWindowModal.parentNode.removeChild(frame.vDivWindowModal);
		div.style.display = 'none';
		div.style.visibility = 'hidden';
	}
}

/* 
Função: Campo de Consulta
Inserida: 10/08/2006 11:26
Ultima alteração: 10/08/2006 11:26
Propósito: Cria um campo de consulta
*/
		
function f_campo_query(p_obj, p_event, p_descricao, p_url, p_arguments, p_fnc_retorno, p_min_chars) {
	if(!p_min_chars) {
		p_min_chars = 0;
	}
	try {
		if(!v_div_cons) {
		}
	} catch(e) { v_div_cons = null; }
	//cria o div de consulta
	if(!v_div_cons) {
		v_div_cons = document.createElement('div');
		v_div_cons.style.position = 'absolute';
		v_div_cons.style.width = p_obj.offsetWidth;
		v_div_cons.style.display = 'none';
		v_div_cons.changeRecord = function (key) {
			if(key == 38 || key == 40) {
				if(this.currentRow == -1) {
					row = 0;
				} else {
					row = this.currentRow;
					if((key == 38 && row > 0) || (key == 40 && row < this.childNodes[0].tBodies[0].rows.length -1))
						row += (key == 38)?-1:1;
					else
						return;
				}
				for(var i=0;i<this.childNodes[0].tBodies[0].rows.length;i++) {
					this.childNodes[0].tBodies[0].rows[i].className = 'linha_2';
				}
				this.childNodes[0].tBodies[0].rows[row].className = 'linha_over';
				this.currentRow = row;
				this.childNodes[0].tBodies[0].rows[row].cells[0].onclick();
			}	
		}
		document.body.appendChild(v_div_cons);
	}
	//trata a saida do campo
	if(!p_obj.onblurfnc) {
		if(p_obj.onblur) {
			old_blur_fnc = p_obj.onblur;
		} else {
			old_blur_fnc = function () {};
		}
		p_obj.onblur = function () {
			setTimeout("v_div_cons.style.display = 'none'", 200);
			old_blur_fnc();
		}
		p_obj.onblurfnc = true;
	}
	//posiciona o objeto
	p_left = f_posicao_objeto(p_obj, true);
	p_top = f_posicao_objeto(p_obj, false)+p_obj.offsetHeight;
	v_div_cons.style.top = p_top;
	v_div_cons.style.left = p_left+1;
	v_div_cons.obj_ctrl = p_obj;
	var CHARSCONSULTA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ,./;[]1234567890-=+_ ';
	//busca o char pressionado
	if(window.event && window.event.keyCode) {
		key = window.event.keyCode;
	} else {
		key = p_event.charCode;
	} 
	v_div_cons.changeRecord(key);
	if(CHARSCONSULTA.indexOf(String.fromCharCode(key).toUpperCase()) == -1 && p_obj.value.length >= p_min_chars && key != 13 && key != 10 && key != 9) {
		return;
	}
	//38 - up 40 - down
	if(p_obj.value.length >= p_min_chars && key != 13 && key != 10) {
		v_div_cons.innerHTML = '';
		f_query_wddx(p_url, p_arguments, function(obj) {
												if (obj.ajax.readyState == 4) { 
													var v_tbl = document.createElement('table');
													v_tbl.className = 'borda';
													v_tbl.cellPadding = '3';
													v_tbl.cellSpacing = '1';
													v_tbl.width = '100%';
													var v_tb = document.createElement('tbody');
													for(var i=0;i<obj.struct[p_descricao].length;i++) {
														var v_tr = document.createElement('tr');
														var v_td = document.createElement('td');
														v_td.innerHTML = '<nobr>'+obj.struct[p_descricao][i]+'</nobr>';
														v_td.index = i;
														v_td.struct = obj.struct;
														v_tr.className = 'linha_2';
														v_td.onclick = function () { 
															v_div_cons.obj_ctrl.value = this.struct[p_descricao][this.index];
															p_fnc_retorno(this.struct,this.index);
														}

														v_tr.appendChild(v_td);
														v_tb.appendChild(v_tr);
													}
													v_tbl.appendChild(v_tb);
													v_div_cons.currentRow = -1;
													v_div_cons.innerHTML = '';
													v_div_cons.appendChild(v_tbl);

												}
											});	
		v_div_cons.style.display = '';		
		v_div_cons.changeRecord(key);
	} else {
		v_div_cons.style.display = 'none';
	}
}	


/* 
Função: Marca Checkbox
Inserida: 15/08/2006 15:39
Ultima alteração: 15/08/2006 15:39
Propósito: Marca ou desmarca todos os checkbox
*/
		
function f_marca_check(p_form, p_name, p_checked) {
  for(var i=0;i<p_form.elements.length;i++) {
    if(p_form.elements[i].name == p_name && p_form.elements[i].type == 'checkbox') {
      p_form.elements[i].checked = p_checked;
    }
  }
}

/* 
Função: Formata Date
Inserida: 11/09/2006 17:21
Ultima alteração: 02/11/2006 13:55
Propósito: Formata objeto Date para data
*/
		
function f_format_date(str) {
	var data = new Date(str);
	var v_result = ((String(data.getDate()).length == 1)?'0':'')+data.getDate();
	v_result += '/'+((String(data.getMonth()+1).length == 1)?'0':'')+(data.getMonth()+1);
	v_result += '/'+data.getYear();
	return v_result;
}

/* 
Função: Lista - Cria Option Group
Inserida: 13/09/2006 13:54
Ultima alteração: 13/09/2006 13:54
Propósito: Cria option group
*/
		
function f_cria_optgroup(p_label, p_select) {
   var v_opt = document.createElement('optgroup');
   v_opt.label = p_label;
   p_select.appendChild(v_opt);
   return v_opt;
}

/* 
Função: Altera para a proxima aba
Inserida: 20/09/2006 15:46
Ultima alteração: 20/09/2006 15:46
Propósito: Alterar as abas selecionadas
*/
		
	function mudaAbaSequencia(v_id) {
		var tbl = document.getElementById(v_id);
		var abas = tbl.rows[0].cells
		var nro_abas = abas.length;
		var corpos = new Array();
		var v_marcar_aba = 0;
		for(var i=0;i<tbl.rows.length;i++) {
			if(i!=0) {
				corpos[corpos.length] = tbl.rows[i];
				tbl.rows[i].cells[0].className = 'td_aba_corpo';
			}
		}
		var nro_corpos = corpos.length;

		for(var i=0;i<abas.length;i++) {
			if (i < nro_corpos) {
				if (abas[i].className == 'td_aba_up') {
				   abas[i].className = 'td_aba_down';
				   if (i+1 == abas.length || abas[i+1].className == 'td_aba_none') 
				      v_marcar_aba = 0;
				   else v_marcar_aba = i+1;
				}
			} else {
				abas[i].className = 'td_aba_none';
			}
		}
		
		abas[v_marcar_aba].className = 'td_aba_up';
		
		for(var i=0;i<corpos.length;i++) {
			if(v_marcar_aba == i) {
				corpos[i].style.display = '';
			} else {
				corpos[i].style.display = 'none';
			}
		}	
	}

/* 
Função: Tamanho do texto
Inserida: 26/09/2006 10:14
Ultima alteração: 26/09/2006 11:01
Propósito: Aumenta ou diminui tamanho do texto de um elemento
*/
		
var startSz = 2;
function f_textsize( trgt,inc,value ) {
	try {
		if(!value)
			value = false;
	} catch(e) {}
	var tgs = new Array( 'div','td','tr','table','span','p');
	var szs = new Array( '8','10','11','14','18','22','24' );
	if (!document.getElementById) return
	var d = document,cEl = null,sz,i,j,cTags;
		
	cEl = trgt;
//	if ( !( cEl = d.getElementById( trgt ) ) ) 
//		cEl = d.getElementsByTagName( trgt )[ 0 ];

//	startSz = 2;
	
		sz = startSz;
/*	for(var i=0;i<szs.length;i++) {
		if(cEl.style.fontSize == szs[i]+'px') {
			startSz = i;
			sz = startSz;
		}
	}*/
	if(!value) {
		sz += inc;
		
	}

	if ( sz < 0 ) sz = 0;
	if ( sz > 6 ) sz = 6;
	startSz = sz;

	cEl.style.fontSize = szs[ sz ];

	for ( i = 0 ; i < tgs.length ; i++ ) {
		cTags = cEl.getElementsByTagName( tgs[ i ] );
		for ( j = 0 ; j < cTags.length ; j++ ) {
//			cTags[ j ].style.fontSize = szs[ sz ];
			f_textsize(cTags[ j ],inc, true);
		}
	}
}

/* 
Função: Prototype cnpjcpf
Inserida: 30/10/2006 14:35
Ultima alteração: 30/10/2006 14:35
Propósito: Valida CNPJ e CPF
*/
		
String.prototype.isCNPJCPF = function() {
	if (this.length == 14)
		return testacnpj(this);
	else 
		return testacpf(this);
}

/* 
Função: Query String List
Inserida: 06/11/2006 18:51
Ultima alteração: 06/11/2006 18:51
Propósito: Monta o query string baseado no parametro passado
*/
		
function f_get_query_string_list(p_form,p_lista_campos) {
	var res = '';
	with (p_form) {
		var arraylist = p_lista_campos.split(",");
		for(var i=0;i<arraylist.length;i++) {
			if(!eval(arraylist[i]).disabled && eval(arraylist[i]).name) {
				if(eval(arraylist[i]).type == 'radio' || eval(arraylist[i]).type == 'checkbox') {
					if(eval(arraylist[i]).checked) {
						res += eval(arraylist[i]).name+'='+escape(eval(arraylist[i]).value)+'&';
					}
				} else {
					res += eval(arraylist[i]).name+'='+escape(f_valor_campo(eval(arraylist[i]).name, p_form))+'&';
				}
			}
		}
	}
	res = res.substr(0,res.length-1);
	return res;
}


/* 
Função: Limpa Acentuação
Inserida: 08/01/2007 12:01
Ultima alteração: 08/01/2007 15:35
Propósito: //===========================================================================
// Retorna a string sem os acentos
*/
		
function f_limpa_acentos(text) {
  var i, ac, nc;
  ac = 'áäâàãéëêèíïîìóöôòõúüûùçñýÿÁÄÂÀÃÉËÊÈÍÏÎÌÓÖÔÒÕÚÜÛÙÇÑÝ';
  nc = 'aaaaaeeeeiiiiooooouuuucnyyAAAAAEEEEIIIIOOOOOUUUUCNY';

  for (i = 0; i < ac.length; i++) {
       text = text.replace(ac.charAt(i), nc.charAt(i));
  }
  return text;
}


function f_exibir_mensagem(text,totalDelay,position) {
	if(!document.dvMensagem) {
		document.dvMensagem = document.createElement("div");
		with(document.dvMensagem) {
			style.position = 'absolute';
			style.padding = '3px 3px 3px 3px'
			style.backgroundColor = '#FF0000';
			style.color = '#ffffff';
			style.display = 'none';
		}
		document.body.appendChild(document.dvMensagem);
	}
	document.dvMensagem.innerHTML = text;
	document.dvMensagem.countDelay = 0;
	document.dvMensagem.delay = 50;
	document.dvMensagem.totalDelay = totalDelay;
	if(position) {
		with(document.dvMensagem) {
			style.top = position.top;	
			style.left = position.left;
			style.display = '';
		}
	}
	document.dvMensagem.interval = setInterval(
		function() {
			if(!position) {
				if (document.layers){
					Ypos=window.pageYOffset;
					Xpos=window.pageXOffset+window.innerWidth-200;
				}
				else{
					Ypos=document.body.scrollTop;
					Xpos=document.body.scrollLeft+window.document.body.clientWidth-200;
				}
				with(document.dvMensagem) {
					style.top = Ypos;	
					style.left = Xpos;
					style.display = '';
				}
			}
			document.dvMensagem.countDelay += Number(document.dvMensagem.delay);
			if(Number(document.dvMensagem.totalDelay) <= Number(document.dvMensagem.countDelay)) {
				clearInterval(document.dvMensagem.interval);
				document.dvMensagem.style.display = 'none';
			}
		}
		,50);
}
/*

Object.prototype.dump = function (nivel) {
	var v_nivel;
	if(!nivel) {
		v_nivel = 0;
	} else {
		v_nivel = nivel;
	}
	v_result = '';
	for(x in this) {
		v_ident = '';
		for(var i=0;i<v_nivel;i++) {
			v_ident += '  ';
		}
		try {
			if(x == 'dump') {
				// Elimina o dump desta funcao
			} else if (typeof(this[x]) == 'function') {
			} else 
			if(typeof(this[x]) == 'object') {
				v_result += v_ident+x+": \n"+this[x].dump(v_nivel+1);
			} else {
				v_result += v_ident+x+": "+this[x]+" tipo: "+typeof(this[x])+'\n';
			}
		} catch(e) {}
	}
	return v_result;
}*/
/*
Object.prototype.dumpToHTML = function () {
	v_result = '<table border="1" cellpadding="3"><tr><td colspan="2">Javascript Dump</td></tr>';
	for(x in this) {
		try {
			v_result += '<tr><td>'+x+': '+typeof(this[x])+'</td><td>';
			if(typeof(this[x]) == 'object') {
				v_result += this[x].dumpToHTML();
			} else if(typeof(this[x]) == 'function') {
				v_result += String(this[x]).split('{')[0];
			} else {
				v_result += (String(this[x]).toHTML() != '')?String(this[x]).toHTML():'[Empty String]';
			}
			v_result += '</td></tr>';
		} catch(e) {}
	}
	v_result += '</table>';
	return v_result;
}

String.prototype.toHTML = function() {
	return this.replace(/&/g,'&amp;').replace(/>/g,'&gt;').replace(/</g,'&lt;').replace(/\n/g,'<br>').replace(/ /g,'&nbsp;').replace(/\t/g,'&nbsp;&nbsp;&nbsp;&nbsp;');
}



/*Date.prototype.parseFromWDDX = function(str) {
	var v_date = str.split("T")[0].split("-");
	var v_time = str.split("T")[1].split('-')[0];
	this = new Date(v_date[0],v_date[1],v_date[2],v_time[0],v_time[1],v_time[2]);
}

Date.prototype.format = function(mask) {
	var v_result = String(mask);
	v_result = String(v_result).replace(/dd/g,Number(this.getDate()).format('00'));
	v_result = String(v_result).replace(/mm/g,Number(this.getMonth()+1).format('00'));
	v_result = String(v_result).replace(/yyyy/g,Number(this.getYear()).format('0000'));
	v_result = String(v_result).replace(/hh24/g,Number(this.getHours()).format('00'));
	v_result = String(v_result).replace(/mi/g,Number(this.getMinutes()).format('00'));
	v_result = String(v_result).replace(/ss/g,Number(this.getSeconds()).format('00'));
	return v_result;
}

Number.prototype.lsformat = function(mask) {
	var v_result = this.format(mask);
	return v_result.replace(/,/g,'@').replace('.',',').replace(/@/g,'.');
}

*/

/* Seleciona um conjunto de valores em um input multi-select */
function f_seleciona_select(input,list) {
	var v_list = ','+String(list)+',';
	for(var i=0;i<input.options.length;i++) {
		input.options[i].selected = (v_list.indexOf(','+input.options[i].value+',') != -1);
	}
}

Number.prototype.format = function(mask) {
	var normal = String(mask).split('.')[0];
	var decimal = (String(mask).split('.').length > 1)?String(mask).split('.')[1]:'';
	var v_valor;
	if(decimal.length > 0 && decimal.replace(/0/g,'') != '') {
		alert('Formato inválido para a maskara: "'+mask);
		return null;
	}
	if(decimal.length == 0 && String(mask).indexOf('.') != -1) {
		// Considera todas as casas decimais do Número
		v_valor = this;
	} else if (decimal.length == 0 && String(mask).indexOf('.') == -1) {
		// Arredonda o valor, considerando as casas decimais
		v_valor = Math.round(this);
	} else if (decimal.length > 0) {
		// Arredonda o valor de acordo com as casas decimais fornecidas
		v_multiplicador = 1;
		for(var i=0;i<decimal.length;i++) {
			v_multiplicador *= 10;
		}
		v_valor = Math.round(this*v_multiplicador)/v_multiplicador;
		// Ajusta as casas decimais
		if(String(v_valor).indexOf('.') == -1) {
			v_valor = String(v_valor)+'.'+String('').rpad(decimal.length,'0');
		} else if(String(v_valor).split('.')[1].length < decimal.length) {
			v_valor = String(v_valor).rpad(String(v_valor).length + (decimal.length - String(v_valor).split('.')[1].length) ,'0');
		}
	} else {
		alert('Não foi possível determinar a formatação decimal!');
		return null;
	}
	if(String(normal).replace(/,/g,'').replace(/0/g,'') != '') {
		alert('Formato inválido para a maskara: "'+mask);
		return null;
	}
	if(String(normal).replace(/,/g,'').length > String(v_valor).split('.')[0].length) {
		var v_diferenca = String(normal).replace(/,/g,'').length - String(v_valor).split('.')[0].length;
		v_valor = String(v_valor).lpad(String(v_valor).length+v_diferenca,'0');
	}
	v_valor = String(v_valor);
	// Insere os separadores de milhar
	if(String(normal).indexOf(',') != -1) {
		v_resultados = [];
		while(v_valor.length > 0) {
			if(v_valor.indexOf('.') != -1) {
				if(v_valor.indexOf('.') >= 2) {
					v_resultados.push(v_valor.substring(v_valor.indexOf('.')-3,v_valor.length));
					v_valor = v_valor.substr(0,v_valor.split('.')[0].length-3);
				} else {
					v_resultados = v_valor;
					v_valor = '';
				}
			} else {
				v_resultados.splice(0,0,v_valor.substring((v_valor.length >= 3)?v_valor.length-3:0, v_valor.length));
				v_valor = v_valor.substr(0,(v_valor.length >= 3)?v_valor.length-3:0);
			}
		}
		v_valor = v_resultados.join(',');
	}
	return v_valor;
}

String.prototype.lpad = function(length,str) {
	var v_result = this;
	while (v_result.length < length) {
		v_result = str + v_result;
	}
	return v_result;
	return String(v_result).substr(v_result.length-length,length);
}

String.prototype.rpad = function(length,str) {
	var v_result = this;
	while (v_result.length < length) {
		v_result = v_result + str;
	}
	return String(v_result).substr(v_result.length-length,length);
}

Number.prototype.lsformat = function(mask) {
	var v_result = this.format(mask);
	return v_result.replace(/,/g,'@').replace('.',',').replace(/@/g,'.');
}

String.prototype.getDate = function() {
	if(!this.isDate()) {
		return null;
	}
	return new Date(this.split('/')[2],this.split('/')[1],this.split('/')[0]);
};

Date.prototype.format = function(mask) {
	if(!mask)
		return String(this.getDate()).lpad(2,'0')+'/'+String(this.getMonth()).lpad(2,'0')+'/'+String(this.getYear()).lpad(4,'0');
	else {
		var result = String(mask);
		result = result.replace(/dd/g,String(this.getDate()).lpad(2,'0'));
		result = result.replace(/mm/g,String(this.getMonth()+1).lpad(2,'0'));
		result = result.replace(/yyyy/g,String(this.getYear()).lpad(4,'0'));
		result = result.replace(/hh24/g,String(this.getHours()).lpad(2,'0'));
		result = result.replace(/mi/g,String(this.getMinutes()).lpad(2,'0'));
		result = result.replace(/ss/g,String(this.getSeconds()).lpad(2,'0'));
		return result;
	}
}

String.prototype.getDateTime = function() {
	v_parts = this.split(' ');
	if(this == '') {
		return null;
	}
	if(v_parts.length > 2) {
		return null;
	}
	if(v_parts.length > 1) {
		return new Date(v_parts[0].split('/')[2],v_parts[0].split('/')[1]-1,v_parts[0].split('/')[0],nvl(v_parts[1].split(':')[0],0),nvl(v_parts[1].split(':')[1],0),nvl(v_parts[1].split(':')[2],0),0);
	} else {
		return new Date(v_parts[0].split('/')[2],v_parts[0].split('/')[1]-1,v_parts[0].split('/')[0],0,0,0,0);
	}
}

function f_dump(obj,nivel) {
	var v_nivel;
	if(!nivel) {
		v_nivel = 0;
	} else {
		v_nivel = nivel;
	}
	v_result = '';
	for(x in obj) {
		v_ident = '';
		for(var i=0;i<v_nivel;i++) {
			v_ident += '  ';
		}
		try {
			if(x == 'dump') {
				// Elimina o dump desta funcao
			} else if (typeof(obj[x]) == 'function') {
			} else if(typeof(obj[x]) == 'object') {
				v_result += v_ident+x+": \n"+obj[x].dump(v_nivel+1);
			} else {
				v_result += v_ident+x+": "+obj[x]+" tipo: "+typeof(obj[x])+'\n';
			}
		} catch(e) {}
	}
	return v_result;
}

function f_seta_botao_atalho(botao,accessKey) {
	botao.accessKey = accessKey;
	try {
		var v_texto = botao.childNodes[1].nodeValue.replace('&nbsp;',' ');
		if(v_texto.indexOf(accessKey.toUpperCase()) != -1) {
			if(v_texto.indexOf(accessKey.toLowerCase()) != -1 && v_texto.indexOf(accessKey.toUpperCase()) < v_texto.indexOf(accessKey.toLowerCase())) {
				v_texto = v_texto.replace(accessKey.toUpperCase(),'<u>'+accessKey.toUpperCase()+'</u>');
			} else if (v_texto.indexOf(accessKey.toLowerCase()) == -1) {
				v_texto = v_texto.replace(accessKey.toUpperCase(),'<u>'+accessKey.toUpperCase()+'</u>');
			}
			
		}
		if(v_texto.indexOf(accessKey.toLowerCase()) != -1) {
			if(v_texto.indexOf(accessKey.toUpperCase()) != -1 && v_texto.indexOf(accessKey.toLowerCase()) < v_texto.indexOf(accessKey.toUpperCase())) {
				v_texto = v_texto.replace(accessKey.toLowerCase(),'<u>'+accessKey.toLowerCase()+'</u>');
			} else if (v_texto.indexOf(accessKey.toUpperCase()) == -1) {
				v_texto = v_texto.replace(accessKey.toLowerCase(),'<u>'+accessKey.toLowerCase()+'</u>');
			}
		}
		botao.childNodes[1].removeNode();
		botao.innerHTML = botao.innerHTML+v_texto;
	} catch(e) {
	}
}

function f_get_style_rule(v_selector) {
	for(var i=document.styleSheets.length-1;i>=0;i--) {
		v_rules = (document.styleSheets[i].rules)?(document.styleSheets[i].rules):(document.styleSheets[i].cssRules);
		for(var j=v_rules.length-1;j>=0;j--) {
			if(v_rules[j].selectorText == v_selector)
				return v_rules[j];
		}
	}
	return null;
}

function f_query_ajax_inner(url, obj) {
	f_query_ajax(url 
				,function (obj2) {
					obj.innerHTML = String(obj2).replace('<NOSCRIPT>','').replace('</NOSCRIPT>','');
				});
}

function f_atualizar() {
	window.location.reload();
}

function f_form_read_only(p_form,value) {
	with(p_form) {
		for(var i=0;i<p_form.elements.length;i++) {
			switch(p_form.elements[i].type) {
				case 'select-one':
				case 'select-multiple':
				case 'radio':
				case 'checkbox':
					p_form.elements[i].disabled = value;
					break;
				default:
					p_form.elements[i].readOnly = value;
					break;
			}
		}
	}
}
	
function f_controle_preenchimento(p_obj) {
				if (p_obj.getAttribute('texto_interno')) {
								p_obj.value = p_obj.getAttribute('texto_interno');
				} 
				p_obj.onkeypress = function() {
						if (p_obj.value == p_obj.getAttribute('texto_interno'))
						    p_obj.value = '';
				}
				p_obj.onfocus = function() {
						 p_obj.style.backgroundColor = '#FFFFBF';
				}
				
				p_obj.onblur = function() {
					 p_obj.style.backgroundColor = '#FFFFFF';
						if (!p_obj.value) {
								p_obj.value = p_obj.getAttribute('texto_interno');
						}
				}
}	

function window_open(url) {
	window.open(url);
}

function f_run_defer_scripts_text(text) {
	var v_div = document.createElement('div');
	v_div.innerHTML = text;
	f_run_defer_scripts(v_div);
}

function f_run_defer_scripts (element) {
	for(var i=0;i<element.childNodes.length;i++) {
		if(element.childNodes[i].tagName && element.childNodes[i].tagName.toUpperCase() == 'SCRIPT') {
			if(element.childNodes[i].getAttribute('defer')) {
				eval(element.childNodes[i].innerHTML);
				continue;
			}
		}
		if(element.childNodes[i].childNodes && element.childNodes[i].childNodes.length > 0) {
			f_run_defer_scripts (element.childNodes[i]);
		}
	}
}

function currencyFormat(fld, milSep, decSep, TamMax, e) 
{
   valor_campo = eval(fld);
   valor_campo = valor_campo.value.length;
   max_campo = eval(TamMax);

   if (valor_campo < max_campo)
   {
      var sep = 0;
      var key = '';
      var i = j = 0;
      var len = len2 = 0;
      var strCheck = '0123456789';
      var aux = aux2 = '';
      var whichCode = (window.Event) ? e.which : e.keyCode;
      if (whichCode == 13) 
         return true;  // Enter
      key = String.fromCharCode(whichCode);  // Get key value from key code
      if (strCheck.indexOf(key) == -1) 
         return false;  // Not a valid key
      len = fld.value.length;
      for(i = 0; i < len; i++)
         if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) 
            break;
      aux = '';
      for(; i < len; i++)
         if (strCheck.indexOf(fld.value.charAt(i))!=-1) 
            aux += fld.value.charAt(i);
      aux += key;
      len = aux.length;
      if (len == 0) 
         fld.value = '';
      if (len == 1) 
         fld.value = '0'+ decSep + '0' + aux;
      if (len == 2) 
         fld.value = '0'+ decSep + aux;
      if (len > 2)
      {
         aux2 = '';
         for (j = 0, i = len - 3; i >= 0; i--)
         {
            if (j == 3)
            {
               aux2 += milSep;
               j = 0;
            }
            aux2 += aux.charAt(i);
            j++;
         }
         fld.value = '';
         len2 = aux2.length;
         for (i = len2 - 1; i >= 0; i--)
            fld.value += aux2.charAt(i);
         fld.value += decSep + aux.substr(len - 2, len);
      }
      return false;
   }
   else
   {
      return false;
   }
}

function f_inner_flash(object,inner) {
	object.innerHTML = inner;
}


//Semelhante ao number_format do PHP
function number_format( number, decimals, dec_point, thousands_sep ) {
    // %     note 1: For 1000.55 result with precision 1 in FF/Opera is 1,000.5, but in IE is 1,000.6
    // *     examplo 1: number_format(1234.56);
    // *     retorno 1: '1,235'
    // *     examplo 2: number_format(1234.56, 2, ',', ' ');
    // *     retorno 2: '1 234,56'
    // *     examplo 3: number_format(1234.5678, 2, '.', '');
    // *     retorno 3: '1234.57'
    // *     examplo 4: number_format(67, 2, ',', '.');
    // *     retorno 4: '67,00'
    // *     examplo 5: number_format(1000);
    // *     retorno 5: '1,000'
    // *     examplo 6: number_format(67.311, 2);
    // *     retorno 6: '67.31'
 
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}

function f_obrigatorio(v_campo,v_obrigatorio,v_default_class) {
	if(v_obrigatorio) {
		v_campo.setAttribute('obrigatorio','1');
		v_campo.className = 'requerido_form';
	} else {
		v_campo.setAttribute('obrigatorio','1');
		v_campo.className = v_default_class;
	}
}
