// JavaScript Document
function f_fechar_div_resposta(p_f_eval){
	html_responta  = '<table width="100%">';
	html_responta += '<tbody>';
	html_responta += '<tr>';
	html_responta += '<td align="left" style=" font-weight:bold;color:#0033CC; font-size:14px;">';
	html_responta += 'Executando....';
	html_responta += '</td>';
	html_responta += '</tr>';
	html_responta += '</tbody>';
	html_responta += '</table width="100%">';

	document.getElementById('div_resposta').style.display='none';
	document.getElementById('div_resposta').innerHTML=html_responta;
	
	if(p_f_eval != '')
		eval(p_f_eval)
	
}

/***********************************************************************************************************************/

function trim(string)
{
	//caso tenha espaços no fim
	while(string.charAt(string.length - 1) == ' ')
	{
		string = string.substring(0, string.length - 1);
	}
	//caso tenha espaços no início
	while(string.charAt(0) == ' ')
	{
		string = string.substring(1, string.length);
	}
	
	return string;
}

function f_marca_select(p_elemento,p_valor){
	var i=0;

	while(eval('document.getElementById("'+p_elemento+'").options['+i+']')){
	 	  
		  if(eval('document.getElementById("'+p_elemento+'").options['+i+'].value') == p_valor){
		  	
			 eval('document.getElementById("'+p_elemento+'").selectedIndex = '+i);
		  }
			
		  i++;
	}
}

/***********************************************************************************************************/
function f_erro(id){
	
	alert('ERRO: Exintem informações que não estão presentes. Preencha todos os campos obrigatórios antes de continuar!')
	
	if(document.getElementById(id) && document.getElementById(id).type != 'hidden')
		document.getElementById(id).focus();
		
	return false;
}

/********************************************************************************************************************/

function f_formt_data(data){
	
	
	if(data.indexOf("/") >0){
		data = data.split("/");
		data = data[2]+'/'+data[1]+'/'+data[0];
		
	}
	else if(data.indexOf("-") >0){
		data = data.split("-");
		data = data[2]+'/'+data[1]+'/'+data[0];
	}
	
	return data;
}

/**************************************************************************************************************/

function f_compara_data(datai_str, dataf_str)
{
	
	//datas obrigatoriamente no formato DD/MM/AAAA
	dti = new String(datai_str);
	dtf = new String(dataf_str);
	anof = parseInt(dtf.substr(6));
	anoi = parseInt(dti.substr(6));
	mesf = dtf.substr(3, 2);
	mesi = dti.substr(3, 2);
	diaf = dtf.substr(0, 2);
	diai = dti.substr(0, 2);
	
	
	if(anof < anoi)
	{
		
		return false;
	}
	else
	{
		if(anof == anoi && mesf < mesi)
		{
				
			return false;

		}
		else
		{
			if(anof == anoi && mesf == mesi && diaf < diai)
			{
					
				return false;
			}
			else
			{
				return true;
			}
		}
	}
}

/***********************************************************************************************************************/

function limit_keys(selectObj, type, evt, limite)
{
	
	/*origem descnhecida!
	modificada por MAU (MAURICIO BARROS)
	MAU>limit_keys(selectObj, type, evt, limite): 
	Permite que o usuario digite somente caracteres com o tipo selecionado em type.
	selectObj: Id do campo a ser validado.
	type: tipo de dado do campo: alphanum;
								 numeric;
								 float;
								 date;
	limite: Maxlength do campo;
	*chamada:onKeyUp="return limit_keys(this, 'numeric', event, 4);" onKeyPress="return limit_keys(this, 'numeric', event, 4);" onKeyDown="return limit_keys(this, 'numeric', event, 4);"
	*/
	
	nr_carecteres = selectObj.value.length;
	var keyCode = 0;
	var ret_val = true;
	//alert('ok');
	
	if (evt) 
	{
		keyCode = evt.keyCode || evt.which;
	}
	else 
	{
		// The old version of this file did not use the evt parameter
		// and would only work under IE.
		keyCode = window.event.keyCode;
	}
	
	//alert(keyCode)
	
	if(nr_carecteres >= limite)
	{
		ok = 'false';
		
		if(!( keyCode == 8 || keyCode == 39 || keyCode == 37 || keyCode == 46))
		{
			return false;
			
		}
	}
	
	// Allow special characters: BACKSPACE, TAB, RETURN, LEFT ARROW,RIGHT ARROW to go through
	if(keyCode == 8)// ((keyCode == 8) || (keyCode == 9) || (keyCode == 13) || (keyCode == 37) || (keyCode == 39)) 
	{
		return (ret_val);
	}
	
	if (type == 'phone') 
	{
		// Numeric values and punctuation are OK
		ret_val = test_keycode( '0123456789()-.', keyCode);
	}
	else if (type == 'alphanum') 
	{
		//alert(keyCode);
		ret_val = ((keyCode >= 48) && (keyCode <= 57)) || ((keyCode >= 65) && (keyCode <= 90)) 
			   || ((keyCode >= 97) && (keyCode <= 122)) ||  keyCode == 32 || (keyCode == 8) 
			   || (keyCode == 37) || (keyCode == 45) || (keyCode == 46)
			   || (keyCode == 47)|| (keyCode == 118)|| ((keyCode >= 192)&&(keyCode <= 255));
	}
	else if (type == 'numeric') 
	{
		// Simply test for a numeric value
		ret_val = ((keyCode >= 48) && (keyCode <= 57)  || keyCode == 46);
	}
	else if (type == 'float') 
	{
		// Simply test for a numeric value
		ret_val = ((keyCode >= 48) && (keyCode <= 57)) || keyCode <= 44 ;
	}
	else if (type == 'date') 
	{	
		var strtmp = '';
		var rExpr = new RegExp("[0-9/]");
		var inicio = selectObj.value.length - 1;
		var text = selectObj.value;

		if(keyCode != 8)
		{
			if(rExpr.test(text.substr(inicio, 1)) != true)
				strtmp = text.substr(0, inicio);
				
			if(text.length == 3 && text.substr(2, 1) != '/')
				strtmp = text.substr(0, 2) + '/' + text.substr(2, 1);
				
			if(text.length == 6 && text.substr(5, 1) != '/')
				strtmp = text.substr(0, 5) + '/' + text.substr(5, 1);
				
			if(strtmp != '')
				selectObj.value = strtmp;
		}
	}
	return (ret_val);
}


/*************************************************************************************************************************/

function VerificaData(src)
{
	//validar data de nascimento
         erro=0;
         hoje = new Date();
         anoAtual = hoje.getFullYear();
         barras = src.value.split("/");
         
		 if (barras.length == 3){
                   dia = barras[0];
                   mes = barras[1];
                   ano = barras[2];
				   // resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano <= anoAtual && ano >= 1900));
                   //alterado por Robeiro dia 19/01/2007
				   resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano >= 1900));
                   if (!resultado) {
                             alert("Formato de data invalido!");
                             src.value = '';
							 src.focus();                            
                   }
         } else {
                   alert("Formato de data invalido!");                   
                   src.value = '';
				   src.focus();
         }
} // doDate

/**************************************************************************************************************************/

function f_mask_date(p_obj, evt)
{
	var strtmp = '';
	var rExpr = new RegExp("[0-9]");
	var inicio = p_obj.value.length - 1;
	var text = p_obj.value;
	
	if (evt) 
		key = evt.keyCode || evt.which;
	else 
		key = window.event.keyCode;
			
	if(key != 8)
	{
		if(rExpr.test(text.substr(inicio, 1)) != true)
			strtmp = text.substr(0, inicio);
			
		if(text.length == 3 && text.substr(2, 1) != '/')
			strtmp = text.substr(0, 2) + '/' + text.substr(2, 1);
			
		if(text.length == 6 && text.substr(5, 1) != '/')
			strtmp = text.substr(0, 5) + '/' + text.substr(5, 1);
			
		if(strtmp != '')
			p_obj.value = strtmp;
	}
	
}

/***************************************************************************************************************************/

function valida_data(data)
{
	//validar data 
         erro=0;
         hoje = new Date();
         anoAtual = hoje.getFullYear();
         barras = data.split("/");
         
		 if (barras.length == 3){
			   
			   dia = barras[0];
			   mes = barras[1];
			   ano = barras[2];
			   
			   // resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano <= anoAtual && ano >= 1900));
			   //alterado por Robeiro dia 19/01/2007
			   resultado = (!isNaN(dia) && (dia > 0) && (dia < 32)) && (!isNaN(mes) && (mes > 0) && (mes < 13)) && (!isNaN(ano) && (ano.length == 4) && (ano >= 1900));
			   
			   if (!resultado) {
						return false;                          
			   }
				   
         } else {
              
			  return false;
         }
	
	return true;
} // doDate

/**************************************************************************************************************************/

function f_apagar_dados_tabela(p_id, p_vet_execao)
{
	if(p_vet_execao && p_vet_execao != '')
		vet_execao = p_vet_execao.split('**');
	else
		vet_execao = '';

	if(document.getElementById(p_id))
	{
		trs = document.getElementById(p_id).childNodes;
		
		for(i = 0; i < trs.length;i++)
		{
			//alert(trs[i].tagName)
			tds = trs[i].childNodes;
			//alert(1)
			for(j = 0; j < tds.length; j++)
			{
				filhos_tds = tds[j].childNodes;
				//alert(filhos_tds.length)
				for(k = 0; k < filhos_tds.length; k ++)
				{
					//alert(2)
					if(filhos_tds[k])
					{
						if(filhos_tds[k].type)
						{	
							//alert(3)
							if(filhos_tds[k].type == "text" || filhos_tds[k].type == 'hidden' || filhos_tds[k].type == 'textarea')
							{
								execao = false;
								
								if(p_vet_execao && p_vet_execao != ''){
									 for(s = 0; s < vet_execao.length; s++){
									 
									 	if(filhos_tds[k].id.indexOf(vet_execao[s]) >= 0){
											execao = true;
											break;
										}
									 
									 }//for(s = 0; s < $vet_execao.length; s++){
								
								}
								
								//alert(filhos_tds[k].value)
								if(!execao)
								{
									filhos_tds[k].value = '';
								}
								//alert(filhos_tds[k].value);
								
							}
						}
					}
				}
			}
		}
	}
	else
	{
		alert("O elementeo de id "+p_id+" nao existe!");
	}

}

/******************************************************************************************************************************/


function f_formatar_moeda_ponto_virgula(vr)
{
	/*MAU>
	Origem UFG 13/09/2006- autor MAU(Mauricio barros)
	Com base em outras funceos
	
	f_formatar_moeda_ponto_virgula: retrona o vr em formato de moeda acrecentenado . e , s******/
	
	vr = new String(vr);
	
		//recolocar zero a direita.
		str_total = new String(vr);
		pos_ponto = str_total.indexOf(".");
		if(pos_ponto > -1) 
		{
			
			pri_casa = str_total.substring(pos_ponto + 1, pos_ponto + 2);
			sec_casa = str_total.substring(pos_ponto + 2, pos_ponto + 3);
			
			if(!pri_casa)
				str_total = str_total+".00";
			else  if(!sec_casa)
					str_total = str_total+"0";
					   
			vr = str_total;
		}
		else
			vr = vr+".00";

	
	
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;
	
	if(vr == '')
		vr = 0;
		
	
	if ( tam <= 2 )
	{
		vr = vr; 
	}

	if ( (tam > 2) && (tam <= 5) )
	{
		vr = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ); 
	}

	if ( (tam >= 6) && (tam <= 8) )
	{
		vr = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); 
	}

	if ( (tam >= 9) && (tam <= 11) )
	{
		vr = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); 
	}

	if ( (tam >= 12) && (tam <= 14) )
	{
		vr = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); 
	}

	if ( (tam >= 15) && (tam <= 17) )
	{
		vr = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
	}

	return vr;
}



function FormataValor(campo,tammax,teclapres,form) 
{
	/*MAU>
	 origem desconhecida
	 modificada por MAU (MAURICIO BARROS)
	 function FormataValor(campo,tammax,teclapres,form): trasforma o conteudo de um campo em formato de moeda 
	 separao com "." e "," (1.222.222,01).OBS. chamada: onKeyDown = "return FormataValor(this.id, 13, event);"
	 */
	
	var tecla = teclapres.keyCode;
	vr = document.getElementById(campo).value;
	vr = vr.replace( "/", "" );
	vr = vr.replace( "/", "" );
	vr = vr.replace( ",", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	vr = vr.replace( ".", "" );
	tam = vr.length;
	
	if(vr == '')
		vr = 0;
	
	if(tam >= tammax)
	{
		ok = 'false';
		
		if(!( tecla == 8 || tecla == 39 || tecla == 37 || tecla == 46))
		{
			return false;
			
		}
	}
	
	
	if (tam < tammax && tecla != 8)
	{ 
		tam = vr.length + 1; 
	}
	if (tecla == 8 )
	{ 
	tam = tam - 1; 
	}
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
	{
		if ( tam <= 2 )
		{
			document.getElementById(campo).value = vr; 
		}

		if ( (tam > 2) && (tam <= 5) )
		{
			document.getElementById(campo).value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ); 
		}

		if ( (tam >= 6) && (tam <= 8) )
		{
			document.getElementById(campo).value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); 
		}

		if ( (tam >= 9) && (tam <= 11) )
		{
			document.getElementById(campo).value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); 
		}

		if ( (tam >= 12) && (tam <= 14) )
		{
			document.getElementById(campo).value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ); 
		}

		if ( (tam >= 15) && (tam <= 17) )
		{
			document.getElementById(campo).value = vr.substr( 0, tam - 14 ) + '.' + vr.substr( tam - 14, 3 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam );
		}
	} 
	else 
	{
		return false;
	}
}


function f_formatar_moeda_ponto(valor)
{
	/*MAU> 
	Origem UFG 13/09/2006 - autor MAU(mauricio Barros)
	
	function f_formatar_moeda_ponto(valor): formata valor para tipo ponto flutuante em formato 
	que pode ser interpretado de forma correta em operacoes aritmeticas em javascript, muito util 
	quando se trabalha com moedas.
	*/
	
	if(valor == '')
	{
		valor = 0;
	}
	else
	{
		vet_valor = valor.split(".");
		
		for(i = 0; i < vet_valor.length -1; i++)
		{
			
			valor = valor.replace( ".", "" );
		}
		
		valor       = valor.replace( ",", "." );
		vet_valor   = valor.split(".");
		vet_valor_0 = vet_valor[0];
		

		vet_valor_0_retorno = vet_valor_0;
		
		for( i =0 ; i < vet_valor_0.length -1; i++)
		{
			if(vet_valor_0[i] != 0 || i ==  vet_valor_0.length -2 )
			{
				vet_valor_0_retorno = vet_valor_0.substr(i);
				break;
			}
		}
		
		if(vet_valor[1])
			valor = vet_valor_0_retorno+"."+vet_valor[1];
		else
			valor = vet_valor_0_retorno+".00";

		
	}
	
	return valor; 
}




/*************************** dtable  ********************************************************************/

function f_remove_row(p_tbody, p_quant_final, id_row, p_func)
{
	//alert(id_row);
	var count_row = nr_linhas;
	
	if(p_quant_final == 0)
		p_quant_final = count_row - 1;
	else
		p_quant_final -= 1;
	
	while(p_quant_final < count_row)
	{
	    var tbody = document.getElementById(p_tbody);
	    var row   = document.getElementById('row_'+p_tbody+'_'+id_row);
		
		tbody.removeChild(row);
		count_row -= 1;
		
		//nr_linhas = count_row;
		//document.getElementById('count_'+p_tbody+'_row').value = count_row.toString();
		
		if(count_row < 1)
		{
			eval(p_func);
		}
	}
	
}

function create_button_lov(p_name, p_onclick)
{
	//var newa = document.createElement('a');
	//newa.setAttribute('href', '#');
	
	var newimg = document.createElement('img');
	newimg.setAttribute('src', 'imagens/btn_alterar.gif');
	newimg.setAttribute('alt', 'Alterar');
	newimg.setAttribute('name', p_name);
	newimg.setAttribute('id', p_name);
	newimg.setAttribute('width', '20');
	newimg.setAttribute('heigth', '20');
	newimg.setAttribute('border', '0');
	newimg.setAttribute('align', 'absmiddle');
	newimg.style.cursor = 'pointer';
	newimg.onclick = function (evt) {eval(p_onclick)};
	//newimg.onmouseout =  function (evt) {MM_swapImgRestore();}
	//newimg.onmouseover = function (evt) {MM_swapImage(p_name,'','imagens/btn_alterar_hover.gif',1);}
	
	//newa.appendChild(newimg);
	return newimg;
}

function create_textarea(p_name, p_class, p_rows, p_cols)
{
	var newtextarea = document.createElement('textarea');
	newtextarea.setAttribute('name', p_name);
	newtextarea.setAttribute('id', p_name);
	newtextarea.setAttribute('cols', p_cols);
	newtextarea.setAttribute('rows', p_rows);
	newtextarea.className = p_class;
	return newtextarea;
}

function create_input(p_name, p_type, p_class, p_size, p_value)
{
	var newinput = document.createElement('input');
	newinput.setAttribute('type', p_type);
	newinput.setAttribute('name', p_name);
	newinput.setAttribute('id', p_name);
	newinput.setAttribute('value', p_value);
	
	if(p_type != 'hidden' && p_type != 'radio')
	{
		newinput.setAttribute('size', p_size);
		newinput.className = p_class;
	}		
	return newinput;
}

function create_select()		   //p_name, p_class, p_size, p_selected, p_args)
{
	var newselect = document.createElement('select');
	newselect.setAttribute('name', create_select.arguments[0]);
	newselect.setAttribute('id', create_select.arguments[0]);
	newselect.setAttribute('size', create_select.arguments[2]);
	newselect.className = create_select.arguments[1];
	
	var newoption;
	var j = 0;
	
	for(i = 4; i < create_select.arguments.length; i += 2)
	{
		newoption = document.createElement('option');
		newoption.text = create_select.arguments[i + 1];
		newoption.setAttribute('value', create_select.arguments[i]);
		newselect.options.add(newoption, j++);
		
		if(create_select.arguments[3] == create_select.arguments[i])
			newselect.options[j - 1].selected = true;
	}
	
	return newselect;
}


function create_remove(p_name,p_onclick)
{
	var newimg = document.createElement('img');
	newimg.width = '25';
	newimg.heigth = '25';
	//newimg.setAttribute('width', '25');
	//newimg.setAttribute('heigth', '25');
	newimg.setAttribute('border', '0');
	newimg.setAttribute('src', 'imagens/excluir1.jpg');
	newimg.setAttribute('alt', 'Remover campo');
	newimg.setAttribute('name', p_name);
	newimg.setAttribute('id', p_name);
	newimg.setAttribute('align', 'absmiddle');
	newimg.onclick = function (evt) {eval(p_onclick)};

	newimg.style.cursor = 'pointer';
	
	return newimg;

}

function f_criar_in_out(p_value,p_id_in, p_id_out,p_in_out)
{
	if(p_in_out == 'in')
	{
		in_in 	= p_id_in;
		out_out = p_id_out
	}
	else
	{
		in_in 	= p_id_out;
		out_out = p_id_in;
	}
	
	vet_out    = document.getElementById(out_out).value.split(',');
	vet_in     = document.getElementById(in_in).value.split(',');
	
	string_out = '';
	
	
	if(document.getElementById(in_in).value != '')
		document.getElementById(in_in).value += ','+p_value;
	else 
		document.getElementById(in_in).value  =  p_value;
	
	//retirar de vet_out
	for(i = 0; i < vet_out.length; i++)
	{
		if(vet_out[i] !=  p_value)
		{	
			string_out += vet_out[i];
			
			if(i < vet_out.length - 1)
			{
				//verifiar ultmo elemento
				if( i == vet_out.length - 2 && vet_out[i + 1] ==  p_value )
				 string_out += '';
				else
					string_out += ',';
			}
		}
	}
	
	document.getElementById(out_out).value = string_out;

}

/********************************************************************************************************************************/