
/*checar navegador do usuario*/
var sAgent = navigator.userAgent;
var bIsIE = sAgent.indexOf("MSIE") > -1;
var bIsNav = sAgent.indexOf("Mozilla") > -1 && !bIsIE;

/*************************************************************************************************************************************/
// Validacao de Campos
//desbitlitar clique direito

function bloquearBotaoDireito(e) 
{
	var rightclick;
	if (!e) 
		var e = window.event;
		
	if (e.which) 
		rightclick = (e.which == 3);
	else if (e.button) 
			rightclick = (e.button == 2);
			
	//alert('Rightclick: ' + rightclick); // true or false]
	if (rightclick==2||rightclick==3) 
	{
		oncontextmenu = 'return false';
 	}
}

//document.onmousedown = bloquearBotaoDireito
//document.oncontextmenu = new Function("return false;")


function f_retira_strigs(selectObj, evt)
{
	
	var keyCode = 0;
	var ret_val = true;
	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(keyCode == 44 || keyCode == 39)
		return false;
	else
		return true;

}

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 validarTabela(p_id)
{
	
	if(document.getElementById(p_id))
	{
		trs = document.getElementById(p_id).childNodes;
		//trs = tbody[0].childNodes;//document.getElementById(p_id).childNodes;
		
		for(i = 0; i < trs.length;i++)
		{
			
			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(3)
					if(filhos_tds[k])
					{
						
						//alert(filhos_tds[k].id);
						if(filhos_tds[k].type)
						{	
							if(filhos_tds[k].type == "text")
							{
								
								text = trim(filhos_tds[k].value)
								if( text == '')
								{
									return false;
								}
							}
							else if(filhos_tds[k].type == "textarea")
							{
								
								tam = trim(filhos_tds[k].value).length;
								//alert(tam);
								if( tam == 0)
								{
									return false;
								}
							}
						}
					}
				}
			}
		}
	}
	else
	{
		alert("O elementeo de id "+p_id+" nao existe!");
		return false;
	}
	
	return true;
}
function apagarDadosTabela(p_id)
{
	
	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)
						{	
							tipo = filhos_tds[k].type;
							if(tipo == "text" || tipo == 'hidden' || tipo == 'password' )
							{
								
								//alert(filhos_tds[k].value);
								filhos_tds[k].value = '';
							}
							else if(tipo == 'textarea'){
								filhos_tds[k].value = '';	
							}
								
							
						}
					}
				}
			}
		}
	}
	else
	{
		alert("O elemento de id "+p_id+" não existe!");
	}

}
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;
	}
	
	
	if(nr_carecteres >= limite)
	{
		ok = 'false';
		
		if(!( keyCode == 8 || keyCode == 39 || keyCode == 37 || keyCode == 46))
		{
			return false;
			
		}
	}
	
	//alert(keyCode);
	// 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') 
	{
		ret_val = ((keyCode >= 48) && (keyCode <= 57)) || ((keyCode >= 65) && (keyCode <= 90)) 
			   || ((keyCode >= 97) && (keyCode <= 122)) ||  keyCode == 32 || (keyCode == 8) || (keyCode == 37) || (keyCode == 46) ;
	}
	else if (type == 'numeric') 
	{
		// Simply test for a numeric value
		ret_val = ((keyCode >= 48) && (keyCode <= 57));
	}
	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 validaEmail(p_email) 
{
	
	if (p_email.value != "")
	{
		prim = p_email.value.indexOf("@")
		if(prim < 2) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf("@",prim + 1) != -1) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf(".") < 1) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf(" ") != -1) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}		
		if(p_email.value.indexOf(".@") > 0) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf("@.") > 0) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf(".com.br.") > 0) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf("/") > 0) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf("[") > 0) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf("]") > 0) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf("(") > 0) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf(")") > 0)
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		if(p_email.value.indexOf("..") > 0) 
		{
			//alert("O e-mail informado parece não estar correto.");
			p_email.focus();
			p_email.select();
			return false;
		}
		
		return true;
	}
}


function comparaData(datai_str, dataf_str)
{
	//datas obrigatoriamente no formato DD/MM/AAAA
	dti = new String(datai_str);
	dtf = new String(dataf_str);
	anof = dtf.substr(6);
	anoi = 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 'ERRO';
	}
	else
	{
		if(anof == anoi && mesf < mesi)
		{
			return 'ERRO';
		}
		else
		{
			if(anof == anoi && mesf == mesi && diaf < diai)
			{
				return 'ERRO';
			}
			else
			{
				return 'SIGA';
			}
		}
	}
}


/**********************************************************************************************************************************/
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 formataMoedaPontoVirgula(vr)
{
	/*MAU>
	Origem UFG 13/09/2006- autor MAU(Mauricio barros)
	Com base em outras funceos
	
	formataMoedaPontoVirgula: 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 formataMoedaPonto(valor)
{
	/*MAU> 
	Origem UFG 13/09/2006 - autor MAU(mauricio Barros)
	
	function formataMoedaPonto(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; 
}

/*************************************************************************************************/
function arredonda(valor , casas )
{
   /*MAU> 
  	Origem  http://lib.seven.com.br/ampliar.asp?codcat=18&codartigo=423
	Colaborador..: João Batista Neto
	Categoria(s).: Javascript;
	Versão.......: 0.01b
	Data.........: 31/12/2002 02:08:24
	Visualizado..: 3705 vezes
	Fonte........: Internet
	
   function arredonda(valor , casas ) :areendodar numero em ponto flutuante com precisao definido pelo parametro casas, retorna valor com tioo float****************/

   valor = parseFloat(valor);
   var novo = Math.round( valor * Math.pow( 10 , casas ) ) / Math.pow( 10 , casas );

   return novo;

}
/*******************************************************************************************************************/
/* Formatação para qualquer mascara */

function formatar(src, evento, mask) 
{
  /*MAU>
  fonte:http://lib.seven.com.br/ampliar.asp?codcat=18&codartigo=733
  Colaborador..: Rafael S. Matos
	Exemplos:
	CEP
	OnKeyPress="formatar(this, event, '#####-###')"
	CPF
	OnKeyPress="formatar(this, event, '###.###.###-##')"
	DATA
	OnKeyPress="formatar(this, event, '##/##/####')"
  */
  	if(!permiteNumeros(evento))
  		return false;
  
	var i = src.value.length;
	var saida = mask.substring(0,1);
	var texto = mask.substring(i)
	
	alert(texto.substring(0,1)+'-'+saida);
	
	
	
	if (texto.substring(0,1) != saida){
		src.value += texto.substring(0,1);
	}
}
//*******************************************************************************************************************/
/* Validação de data */

function verificaData(src)
{
	if(src.value != ''){
		
         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 + 10 && ano >= 1900));
			if (!resultado){
		         return false;
			}
			
			return true;
         }
		 else{
		 	return true;
         }
	}
} // 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 calculaTamanho(pTamanho,pPeenchido)
{
	//Utilizar no envento onKeyUp
	var valRetorno = '';
	valRetorno = pTamanho - pPeenchido.value.length;
	return valRetorno;
}

function tamanhoTxtArea(pTxtArea,pTamanho)
{ 
	//Utilizar no envento onKeyUp
	if (pTxtArea.value.length >= pTamanho)
	{
		 return pTxtArea.value.substr(0,pTamanho);
	}
	else
	{
	 	return pTxtArea.value;
	}
}

/*************************************

ALTERAÇÕES: AURÉLIO LUIZ
DATA: 26/11/2007
FUNCIONALIDADES: IMPLEMENTADO MÉTODOS PARA VALIDAÇÃO E FORMATAÇÃO DE HORAS

*************************************/

// valida uma hora digitada no formato hh:mm
// hora: id do input a ser validado
// obrigatorio: valida se o input pode estar vazio (0) ou nao (!=0)
function validaHora(hora, obrigatorio){ 

	var hora = document.getElementById(hora);  
	if((obrigatorio == 1) || (obrigatorio == 0 && hora.value != "")){  
         if(hora.value.length < 5){
			alert("Formato da hora inválido. Por favor, informe a hora no formato correto: hh:mm");  
			hora.focus();
			return false
         }
         if(hora.value.substr(0,2) > 23 || isNaN(hora.value.substr(0,2))){  
             alert("Formato da hora inválido.");  
             hora.focus();
             return false
         }  
         if(hora.value.substr(3,2) > 59 || isNaN(hora.value.substr(3,2))){
             alert("Formato do minuto inválido.");
             hora.focus();  
             return false
		}  
		return true;
	}
}

// formata máscara de hora e só permite digitação de números
// input: elemento input a ser formatado
// evnt: evento associado ao input
function formataHora(input, evnt){

	if (input.value.length == 2){  
    	if(bIsIE){
        	input.value += ":";
        }else{  
        	if(evnt.keyCode == 0){
            	input.value += ":";
			}
		}
	}
}

/*************************************

ALTERAÇÕES: AURÉLIO LUIZ
DATA: 09/01/2008
FUNCIONALIDADES: IMPLEMENTADO MÉTODO PARA CHECAR USUÁRIO EXISTENTE

*************************************/


// usada no cadastro, mostra um alerta caso o usuario já exista
// url: arquivo responsavel pela consulta sql
// metodo: metodo da requisição
// modo:
// form: nome do formulario onde se encontra o input
// input: id do input a ser validado
function envia(url, metodo, modo, input){

	var username = document.getElementById(input).value;	
	remoto  = new ajax();
	xmlhttp = remoto.enviar(url + "?username=" + username, metodo, modo );
	
	if(xmlhttp) {
		document.getElementById('alerta').className = 'alerta';
		document.getElementById('alerta').innerHTML = 'Este usuário já está cadastrado!';
	} else {
		document.getElementById('alerta').className = '';
		document.getElementById("alerta").innerHTML = '';
	}
}


/*************************************

ALTERAÇÕES: AURÉLIO LUIZ
DATA: 09/01/2008
FUNCIONALIDADES: IMPLEMENTADO MÉTODO QUE PERMITE APENAS A DIGITAÇÃO DE NÚMEROS

*************************************/


// evento: evento associado ao input
// input: elemento ao qual se vai associar a função
// chamada: onkeypress="return permiteNumeros(event);"
function permiteNumeros(evento){
	
	if(bIsIE){
		if((evento.keyCode >= 48 && evento.keyCode <= 57) || evento.keyCode == 13){
			return true;
		}
		else
			return false;
	}
	else{
		if((evento.which >= 48 && evento.which <= 57) || evento.which == 8 || evento.which == 0 || evento.keyCode == 13){
			return true;
		}
		else
			return false;
	}
}



/*************************************

ALTERAÇÕES: AURÉLIO LUIZ
DATA: 12/04/2008
FUNCIONALIDADES: IMPLEMENTADO MÉTODO QUE FORMATA UM NUMERO EM VALOR MONETÁRIO AO DIGITAR

*************************************/

// chamada: formataMoeda(document.forms.id_formulario.id_input, casas_decimais);

addEvent = function(o, e, f, s){
	var r = o[r = "_" + (e = "on" + e)] = o[r] || (o[e] ? [[o[e], o]] : []), a, c, d;
	r[r.length] = [f, s || o], o[e] = function(e){
		try{
			(e = e || event).preventDefault || (e.preventDefault = function(){e.returnValue = false;});
			e.stopPropagation || (e.stopPropagation = function(){e.cancelBubble = true;});
			e.target || (e.target = e.srcElement || null);
			e.key = (e.which + 1 || e.keyCode + 1) - 1 || 0;
		}catch(f){}
		for(d = 1, f = r.length; f; r[--f] && (a = r[f][0], o = r[f][1], a.call ? c = a.call(o, e) : (o._ = a, c = o._(e), o._ = null), d &= c !== false));
		return e = null, !!d;
    }
};

removeEvent = function(o, e, f, s){
	for(var i = (e = o["_on" + e] || []).length; i;)
		if(e[--i] && e[i][0] == f && (s || o) == e[i][1])
			return delete e[i];
	return false;
};

function formataMoeda(o, n, dig, dec){
	o.c = !isNaN(n) ? Math.abs(n) : 2;
	o.dec = typeof dec != "string" ? "," : dec, o.dig = typeof dig != "string" ? "." : dig;
	addEvent(o, "keypress", function(e){
		if(e.key > 47 && e.key < 58){
			var o, s, l = (s = ((o = this).value.replace(/^0+/g, "") + String.fromCharCode(e.key)).replace(/\D/g, "")).length, n;
			if(o.maxLength + 1 && l >= o.maxLength) return false;
			l <= (n = o.c) && (s = new Array(n - l + 2).join("0") + s);
			for(var i = (l = (s = s.split("")).length) - n; (i -= 3) > 0; s[i - 1] += o.dig);
			n && n < l && (s[l - ++n] += o.dec);
			o.value = s.join("");
		}
		e.key > 30 && e.preventDefault();
	});
}



/*************************************

ALTERAÇÕES: AURÉLIO LUIZ
DATA: 28/04/2008
FUNCIONALIDADES: IMPLEMENTADO MÉTODO QUE RETORNA UMA STRING ALEATORIA COM 32 CARACTERES

*************************************/

function textoAleatorio(){
	
	var data = new Date();
	
	var letras = 'abcdefghiklmnopqrstuvwxyz'+data.getTime();
	var aleatorio = '';
	
	for (var i = 0; i<32; i++){
		var rnum = Math.floor(Math.random() * letras.length);
		aleatorio += letras.substring(rnum, rnum + 1);
	}
	
	return aleatorio;
}



function extensaoArquivo(file){
	
	var tipo = "";
	
	if (file.value != ""){
	
		arquivo = (file.value);
		tipo    = arquivo.substring(arquivo.length-4,arquivo.length);
		tipo    = tipo.toLowerCase()
	}
	
	return tipo;
}

/*************************************

ALTERAÇÕES: AURÉLIO LUIZ
DATA: 20/06/2008
FUNCIONALIDADES: IMPLEMENTADO MÉTODO QUE PERMITE LIMITAR O TAMANHO MÁXIMO DE UM TEXTAREA

*************************************/

// obj: objeto html textarea
function maxLength(obj){
	
	var mlength = obj.getAttribute ? parseInt(obj.getAttribute("maxlength")) : "";
	if (obj.getAttribute && obj.value.length>mlength)
		obj.value = obj.value.substring(0,mlength)
}

/**
 * Copyright (c) 2009, Nathan Bubna
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * This plugin exists to make it trivial to notify your users that
 * things are in progress.  The typical case is waiting for an
 * AJAX call to finish loading.  Just call:
 * 
 *   $.loading();
 *
 * to toggle a page-wide message on and off, or you can call:
 *
 *   $('#foo').loading()
 *
 * to do the same, but locate the message within a specific element(s).
 *
 * If you want to ensure that a call doesn't errantly toggle on when
 * you meant to toggle off (or vice versa), then put a boolean value
 * as your first argument.  true is on, false is off.
 *
 *   $.loading(false); // will only ever toggle off
 *   $.loading(true, {align: 'bottom-right'});  // will only ever toggle on
 *
 * If you want a loading message to automatically go on while your
 * AJAX stuff is happening (and off when done), there's a convenient option
 * to set that up properly for you. Just do:
 *
 *   $.loading({onAjax:true, text: 'Waiting...'});
 *
 * If you want to avoid a too-quick-to-see flash of the loading message
 * in situations where the "loading" happens in a flash, then you can set
 * a delay value (in milliseconds) to block the display of the loading
 * message on all but "long" loads:
 *
 *   $.loading({onAjax:true, delay: 100});
 *
 * You can change any of the default options by altering the $.loading
 * properties (or sub-properties), like this:
 *
 *  $.loading.classname = 'loadMsg';
 *  $.loading.css.border = '1px solid #000';
 *  $.loading.working.time = 5000;
 *
 * All options can also be overridden per-call by passing in
 * an options object with the overriding properties, like so:
 *
 *  $.loading({ element:'#cancelButton', mask:true });
 *  $('#foo').loading(true, { img:'loading.gif', align:'center'});
 *
 * And if that isn't enough, this plugin supports the metadata plugin as a
 * way to specify options directly in your markup.
 *
 * Be sure to check out the provided demo for an easy overview of the most
 * commonly used options!! Of course, everything in this plugin is easy to
 * configure and/or override with those same techniques.
 *
 * To employ multiple pulse effects at once, just separate with spaces:
 *
 *  $.loading({ pulse: 'working fade', mask:true });
 *
 * Of particular note here is that it is easy to plug in additional
 * "pulse" effects.  Just add an object with a 'run' function to $.loading
 * under the desired effects name, like this:
 *
 *  $.loading.moveLeft = {
 *      time: 500,
 *      run: function(opts) {
 *          var self = this, box = opts.box;
 *          // save interval like this and it will be cleared for you
 *          // when this loading call is toggled off
 *          opts.moveLeft.interval = setInterval(function() {
 *              box.left += 1;
 *              self.animate(box);
 *          }, opts.moveLeft.time);
 *      }
 *  }
 *
 * then use it by doing something like:
 * 
 *  $.loading({ pulse: 'moveLeft', align:{top:0,left:0} });
 *
 * If you add an 'end' function to that same object, then the end function
 * will be called when the loading message is turned off.
 *
 * Speaking of turning things on and off, this plugin will trigger 'loadingStart'
 * and 'loadingEnd' events when loading is turned on and off, respectively.
 * The options will, of course, be available as a second argument to functions
 * that are bound to these events.  See the demo source for an example. In
 * future versions, this plugin itself may use those events, but for now they
 * are merely notifications.
 *
 * If you are certain you only want the loading message displayed for a limited
 * period of time, you may set the 'max' option to have it automatically end
 * after the specified number of milliseconds:
 *
 *  $.loading({ text: 'Wait!', pulse: false, mask: true, max: 30000 });
 *
 * Contributions, bug reports and general feedback on this is welcome.
 *
 * @version 1.6.4
 * @name loading
 * @author Nathan Bubna

;(function($) {

    // the main interface...
    var L = $.loading = function(show, opts) {
        return $('body').loading(show, opts, true);
    };
    $.fn.loading = function(show, opts, page) {
        opts = toOpts(show, opts);
        var base = page ? $.extend(true, {}, L, L.pageOptions) : L;
        return this.each(function() {
            var $el = $(this),               // support metadata
                l = $.extend(true, {}, base, $.metadata ? $el.metadata() : null, opts);
            if (typeof l.onAjax == "boolean") {
                L.setAjax.call($el, l);
            } else {
                L.toggle.call($el, l);
            }
        });
    };

    // position CSS for page opts //TODO: better support test...
    var fixed = { position: $.browser.msie ? 'absolute' : 'fixed' };

    // all that's extensible and configurable...
    $.extend(L, {
        version: "1.6.4",
        // commonly-used options
        align: 'top-left',
        pulse: 'working error',
        mask: false,
        img: null,
        element: null,
        text: 'Loading...',
        onAjax: undefined,
        delay: 0,
        max: 0,
        // less commonly-used options
        classname: 'loading',
        imgClass: 'loading-img',
        elementClass: 'loading-element',
        maskClass: 'loading-mask',
        css: { position:'absolute', whiteSpace:'nowrap', zIndex:1001 },
        maskCss: { position:'absolute', opacity:.15, background:'#333',
                   zIndex:101, display:'block', cursor:'wait' },
        cloneEvents: true,
        pageOptions: { page:true, align:'top-center', css:fixed, maskCss:fixed },
        // rarely-used options
        html: '<div></div>',
        maskHtml: '<div></div>',
        maskedClass: 'loading-masked',
        maskEvents: 'mousedown mouseup keydown keypress',
        resizeEvents: 'resize',

        // pulse plugin properties
        working: {
            time: 10000,
            text: 'Still working...',
            run: function(l) {
                var w = l.working, self = this;
                w.timeout = setTimeout(function() {
                    self.height('auto').width('auto').text(l.text = w.text);
                    l.place.call(self, l);
                }, w.time);
            }
        },
        error: {
            time: 100000,
            text: 'Task may have failed...',
            classname: 'loading-error',
            run: function(l) {
                var e = l.error, self = this;
                e.timeout = setTimeout(function() {
                    self.height('auto').width('auto').text(l.text = e.text).addClass(e.classname);
                    l.place.call(self, l);
                }, e.time);
            }
        },
        fade: {
            time: 800,
            speed: 'slow',
            run: function(l) {
                var f = l.fade, s = f.speed, self = this;
                f.interval = setInterval(function() {
                    self.fadeOut(s).fadeIn(s);
                }, f.time);
            }
        },
        ellipsis: {
            time: 300,
            run: function(l) {
                var e = l.ellipsis, self = this;
                e.interval = setInterval(function() {
                    var et = self.text(), t = l.text, i = dotIndex(t);
                    self.text((et.length - i) < 3 ? et + '.' : t.substring(0,i));
                }, e.time);
                function dotIndex(t) {
                    var x = t.indexOf('.');
                    return x < 0 ? t.length : x;
                }
            }
        },
        type: {
            time: 100,
            run: function(l) {
                var t = l.type, self = this;
                t.interval = setInterval(function() {
                    var e = self.text(), el = e.length, txt = l.text;
                    self.text(el == txt.length ? txt.charAt(0) : txt.substring(0, el+1));
                }, t.time);
            }
        },

        // functions
        toggle: function(l) {
            var old = this.data('loading');
            if (old) {
                if (l.show !== true) old.off.call(this, old, l);
            } else {
                if (l.show !== false) l.on.call(this, l);
            }
        },
        setAjax: function(l) {
            if (l.onAjax) {
                var self = this, count = 0, A = l.ajax = {
                    start: function() { if (!count++) l.on.call(self, l); },
                    stop: function() { if (!--count) l.off.call(self, l, l); }
                };
                this.bind('ajaxStart.loading', A.start).bind('ajaxStop.loading', A.stop);
            } else {
                this.unbind('ajaxStart.loading ajaxStop.loading');
            }
        },
        on: function(l, force) {
            var p = l.parent = this.data('loading', l);
            if (l.max) l.maxout = setTimeout(function() { l.off.call(p, l, l); }, l.max);
            if (l.delay && !force) {
                return l.timeout = setTimeout(function() {// break
                    delete l.timeout;
                    l.on.call(p, l, true);
                }, l.delay);
            }
            if (l.mask) l.mask = l.createMask.call(p, l);
            l.display = l.create.call(p, l);
            if (l.img) {
                l.initImg.call(p, l);
            } else if (l.element) {
                l.initElement.call(p, l);
            } else {
                l.init.call(p, l);
            }
            p.trigger('loadingStart', [l]);
        },
        initImg: function(l) {
            var self = this;
            l.imgElement = $('<img src="'+l.img+'"/>').bind('load', function() {
                l.init.call(self, l);
            });
            l.display.addClass(l.imgClass).append(l.imgElement);
        },
        initElement: function(l) {
            l.element = $(l.element).clone(l.cloneEvents).show();
            l.display.addClass(l.elementClass).append(l.element);
            l.init.call(this, l);
        },
        init: function(l) {
            l.place.call(l.display, l);
            if (l.pulse) l.initPulse.call(this, l);
        },
        initPulse: function(l) {
            $.each(l.pulse.split(' '), function() {
                l[this].run.call(l.display, l);
            });
        },
        create: function(l) {
            var el = $(l.html).addClass(l.classname).css(l.css).appendTo(this);
            if (l.text && !l.img && !l.element) el.text(l.originalText = l.text);
            $(window).bind(l.resizeEvents, l.resizer = function() { l.resize(l); });
            return el;
        },
        resize: function(l) {
            l.parent.box = null;
            if (l.mask) l.mask.hide();
            l.place.call(l.display.hide(), l);
            if (l.mask) l.mask.show().css(l.parent.box);
        },
        createMask: function(l) {
            var box = l.measure.call(this.addClass(l.maskedClass), l);
            l.handler = function(e) { return l.maskHandler(e, l); };
            $(document).bind(l.maskEvents, l.handler);
            return $(l.maskHtml).addClass(l.maskClass).css(box).css(l.maskCss).appendTo(this);
        },
        maskHandler: function(e, l) {
            var $els = $(e.target).parents().andSelf();
            if ($els.filter('.'+l.classname).length != 0) return true;
            return !l.page && $els.filter('.'+l.maskedClass).length == 0;
        },
        place: function(l) {
            var box = l.align, v = 'top', h = 'left';
            if (typeof box == "object") {
                box = $.extend(l.calc.call(this, v, h, l), box);
            } else {
                if (box != 'top-left') {
                    var s = box.split('-');
                    if (s.length == 1) {
                        v = h = s[0];
                    } else {
                        v = s[0]; h = s[1];
                    }
                }
                if (!this.hasClass(v)) this.addClass(v);
                if (!this.hasClass(h)) this.addClass(h);
                box = l.calc.call(this, v, h, l);
            }
            this.show().css(l.box = box);
        },
        calc: function(v, h, l) {
            var box = $.extend({}, l.measure.call(l.parent, l)),
                H = $.boxModel ? this.height() : this.innerHeight(),
                W = $.boxModel ? this.width() : this.innerWidth();
            if (v != 'top') {
                var d = box.height - H;
                if (v == 'center') {
                    d /= 2;
                } else if (v != 'bottom') {
                    d = 0;
                } else if ($.boxModel) {
                    d -= css(this, 'paddingTop') + css(this, 'paddingBottom');
                }
                box.top += d;
            }
            if (h != 'left') {
                var d = box.width - W;
                if (h == 'center') {
                    d /= 2;
                } else if (h != 'right') {
                    d = 0;
                } else if ($.boxModel) {
                    d -= css(this, 'paddingLeft') + css(this, 'paddingRight');
                }
                box.left += d;
            }
            box.height = H;
            box.width = W;
            return box;
        },
        measure: function(l) {
            return this.box || (this.box = l.page ? l.pageBox(l) : l.elementBox(this, l));
        },
        elementBox: function(e, l) {
            if (e.css('position') == 'absolute') {
                var box = { top: 0, left: 0 };
            } else {
                var box = e.position();
                box.top += css(e, 'marginTop');
                box.left += css(e, 'marginLeft');
            }
            box.height = e.outerHeight();
            box.width = e.outerWidth();
            return box;
        },
        pageBox: function(l) {
            var full = $.boxModel && l.css.position != 'fixed';
            return { top:0, left: 0,
                     height: get(full, 'Height'), width: get(full, 'Width') };
            function get(full, side) {
                var doc = document;
                if (full) {
                    var s = side.toLowerCase(), d = $(doc)[s](), w = $(window)[s]();
                    return d - css($(doc.body), 'marginTop') > w ? d : w;
                }
                var c = 'client'+side;
                return Math.max(doc.documentElement[c], doc.body[c]);
            }
        },
        off: function(old, l) {
            this.data('loading', null);
            if (old.maxout) clearTimeout(old.maxout);
            if (old.timeout) return clearTimeout(old.timeout);// break
            if (old.pulse) old.stopPulse.call(this, old, l);
            if (old.originalText) old.text = old.originalText;
            if (old.mask) old.stopMask.call(this, old, l);
            $(window).unbind(old.resizeEvents, old.resizer);
            if (old.display) old.display.remove();
            if (old.parent) old.parent.trigger('loadingEnd', [old]);
        },
        stopPulse: function(old, l) {
            $.each(old.pulse.split(' '), function() {
                var p = old[this];
                if (p.end) p.end.call(l.display, old, l);
                if (p.interval) clearInterval(p.interval);
                if (p.timeout) clearTimeout(p.timeout);
            });
        },
        stopMask: function(old, l) {
            this.removeClass(l.maskedClass);
            $(document).unbind(old.maskEvents, old.handler);
            old.mask.remove();
        }
    });

    // a few private functions...
    function toOpts(s, l) {
        if (l === undefined) {
            l = (typeof s == "boolean") ? { show: s } : s;
        } else {
            l.show = s;
        }
        // default pulse to off if doing an img
        if (l && (l.img || l.element) && !l.pulse) l.pulse = false;
        // if onAjax and they didn't specify show, default to false
        if (l && l.onAjax !== undefined && l.show === undefined) l.show = false;
        return l;
    }
    function css(el, prop) {
        var val = el.css(prop);
        return val == 'auto' ? 0 : parseFloat(val, 10);
    }
})(jQuery);

$(function(){
	
	$.loading({onAjax:true, text: 'Carregando...', img:'imagens/loading.gif', align:'center', pulse: 'working fade', mask:true });
});
 */
