var objBrow;
var ERRO= false;
var LAST_FIELD;
var CURRENT_FIELD=null;
var LAST_ERROR_FIELD=null;
var LAST_ERROR_VALUE= "";
var REPETITION_ERROR= false;

//CONSTANTES UTILIZADAS
SIZE_DATE = 8;
SIZE_CEP = 8
SIZE_ACCOUNT = 7;
SIZE_AG_ACCOUNT = 11;
MAX_NUMERIC = Number.MAX_VALUE; 
SIZE_MONEY = 10; 
SIZE_FLOAT = 10; 
SIZE_CPF =11;
SIZE_CNPJ=14;
SIZE_PERCENT =6;
SIZE_BRANCH =4;
SIZE_MONTH_YEAR= 6;
SIZE_TIME= 4;
SIZE_PLACA= 7;
MAX_VALUE= 999999999.99

function validaConteudo(event, el, tipo )
{
	var key;
	if (getObjBrow().isNetscape())
		key = String.fromCharCode( event.which );
	else
		key = String.fromCharCode( event.keyCode );
	if ( getObjBrow().isNetscape() && event.which == 8 )
		return true;
	if( isNNType(tipo,"money") || tipo == "percent"|| isNNType(tipo,"float"))
	{
		if( isNumeric(key) )	
		{
			return true;
		}else{ 
			if( key == ",")
				return (el.value.indexOf(",") == -1);
			else
				return false;
		}		
	//Tipos livres de consistencia na digitacao
	}else if( tipo == "email" || tipo == "uppercase" ){
		return true;
	}else if( tipo == "text"){
		return( isAlfa(key) || key == " " || key == "'");
	}else if( tipo == "alfanumeric"){
		return( isAlfaNumeric(key));
	}else{  // todos os outros tipos só aceitam números
		return isNumeric(key);
	}
}

function isUpper(key)
{
	var ret= (key >= "A" && key <= "Z");
	return ret;
}

function unformatField(valor, tipo)
{
	var type= ""; 
	var vr= String(valor);
	var ret= "";
	if( arguments.length < 1)
		type= new String("default");
	else
		type= new String(tipo);
	//-- Tipos que nao precisam de desformatacao --//
	if( type == "email" || type == "uppercase" || type == "alfanumeric" || type == "default") 
		return valor;

	//--- Retira quaisquer formatacoes existentes no campo ---//
	var caracter= "", ok= false;
	for ( i=0; i < vr.length; i++ )
	{
		caracter = vr.substring(i,i+1);
		if( type != "text")
			ok= ( caracter != '.' && caracter != '/' && caracter != '-' && caracter != ' ' && caracter != '%' && caracter != '(' && caracter != ')' && caracter != ':' );
		else
			ok= isAlfa( caracter) || caracter == " " || caracter == "'";
		if( ok)
			ret += caracter;
	}
	return ret;
}

function removeCaracs(field, type)
{
	var value= unformatField(field.value,type);
	if( field.value != value)
		field.value= unformatField(field.value,type);
	focusNetscape(field);
}

function focusNetscape( campo)
{
	CURRENT_FIELD= campo;
	if( navigator.appName.indexOf("Netscape") != -1)
	{
		if( ERRO )
		{
			LAST_FIELD.focus(); 
			ERRO= false; 
		}
	}
}

function formatDate( field, mensErro )
{
	var valor= justNumbersStr(field.value);
	LAST_FIELD= field;
	var errMsg= "Data inválida. Digite novamente.";
	var dtObj= new DateValidation(field.value);
	
	if( !isNumeric(valor) || !dtObj.isDate() )
	{
		showError(errMsg,mensErro);
		focusCamp(field);
		return false;
	}else{
		field.value= dtObj.getDateValue();
	}
	ERRO= false;
	return true;
}

function formatTime(field, mensErro )
{
	var valor= justNumbersStr(field.value);
	LAST_FIELD= field;
	var errMsg= "Hora inválida. Digite novamente.";
	switch( valor.length )
	{
		case 1: valor= "0" + valor + "00"; break;
		case 2: valor+= "00"; break;
		case 3: valor= "0" + valor + "0"; break;
	}

	valor= repeatStr(valor,"0",4,"right");
	if( !isNumeric(valor) || !isTime(valor))
	{
		showError(errMsg,mensErro);
		focusCamp(field);
		return false;
	}
	field.value= valor.substring(0,2) + ":" + valor.substring(2,4);
	ERRO= false;
	return true;
}

function isTime(time)
{
	var re= /^([0-1]\d[0-5]\d)|(2[0-3][0-5]\d)$/;
	return re.test(time);
}

function formatAg_Account(campo,mensErro)
{
	var valor= justNumbersStr(campo.value);
	var msgError= "Agência/Conta corrente incorretos. Digite novamente.";
	LAST_FIELD= campo;
	if( valor == "" || valor == null)
		return false;

	valor= justNumbersStr(valor);
	if( !isNumeric(valor) || (valor.length < SIZE_AG_ACCOUNT))
	{
		showError(msgError, mensErro);
		focusCamp(campo);
		return false;
	}
	var temp= valor.substring(0,4) + "-" + valor.substring(4,9) + "-" + valor.substring(9,11);
	campo.value= temp;
	ERRO= false;
	return true; 
}

function formatAg_Savings(campo,mensErro)
{
	var valor= campo.value;
	var msgError= "Agência/Conta poupança incorretos. Digite novamente.";
	LAST_FIELD= campo;
	if( valor == "" || valor == null)
		return false;
	valor= justNumbersStr(valor);
	if( !isNumeric(valor) || (valor.length < SIZE_AG_ACCOUNT))
	{
		showError(msgError, mensErro);
		focusCamp(campo);
		return false;
	}
	var temp= valor.substring(0,4) + "-" + valor.substring(4,10) + "-" + valor.substring(10,11);
	campo.value= temp;
	ERRO= false;
	return true; 
}

function formatBranch(campo,mensErro)
{
	var errMsg= "Agência inválida. Digite novamente.";
	var valor= campo.value;
	if( valor == "" || valor == null)
		return false;
	valor= justNumbersStr(valor);
	LAST_FIELD= campo;
	if( !isNumeric(valor) || (valor.length < SIZE_BRANCH) )
	{
		showError(errMsg,mensErro); 
		focusCamp(campo);
		return false;
	}
	ERRO= false;
	return true; 
}

function formatAccount(campo, mensErro)
{
	var errMsg= "Conta corrente inválida. Digite novamente.";
	var valor= campo.value;
	if( valor == "" || valor == null)
		return false;
	valor= justNumbersStr(valor);
	LAST_FIELD= campo;
	if( !isNumeric(valor) || (valor.length < SIZE_ACCOUNT) )
	{
		showError(errMsg,mensErro);
		focusCamp(campo);
		return false;
	}
	var temp= valor.substring(0,5) + "-" + valor.substring(5,7);
	campo.value= temp;
	ERRO= false;
	return true; 
}

function formatCEP(campo,mensErro)
{
	var valor= campo.value;
	if( valor == "" || valor == null)
		return false;
	valor= justNumbersStr(valor);
	var errMsg= "CEP inválido. Digite novamente.";
	LAST_FIELD= campo;
	if( !isNumeric(valor) || (valor.length != SIZE_CEP) )
	{
		showError(errMsg,mensErro);
		focusCamp(campo);
		return false;
	}else{
		var temp= valor.substring(0,5) + "-" + valor.substring(5,8);
		campo.value= temp;
	}
	ERRO= false;
	return true; 
}

function formatPlaca(campo,mensErro)
{
	var valor= campo.value;
	if( valor == "" || valor == null)
		return false;
	var valornumerico= justNumbersStr(valor);
	var valoralfa = campo.value.substring(0,3);
	valor = valoralfa + valornumerico  	
	var errMsg= "Placa inválida. Digite novamente.";
	LAST_FIELD= campo;
	if( !isNumeric(valornumerico) || (valor.length != SIZE_PLACA) || !isAlfa(valoralfa)  )
	{
		showError(errMsg,mensErro);
		focusCamp(campo);
		return false;
	}else{
		var temp= valoralfa + "-" + valornumerico
		campo.value= temp;
	}
	ERRO= false;
	
	return true; 
}

function formatavalidaPlaca(campo,mensErro){

//Não permitir digitar a placa com tres letras iguais e 4 numeros iguais

	var valor= campo.value;
	if( valor == "" || valor == null)
		return false;
	var valornumerico= justNumbersStr(valor);
	var valoralfa = campo.value.substring(0,3);
	valor = valoralfa + valornumerico  	
	var errMsg= "Placa inválida. Digite novamente.";
	LAST_FIELD= campo;
	if( !isNumeric(valornumerico) || (valor.length != SIZE_PLACA) || !isAlfa(valoralfa)  )
	{
		showError(errMsg,mensErro);
		focusCamp(campo);
		return false;
	}else{
		var temp= valoralfa + "-" + valornumerico
		campo.value= temp;
	}
	ERRO= false;
	
	if ((temp.substring(0,1) == temp.substring(1,2)) && (temp.substring(1,2) == temp.substring(2,3))){
		//letra iguais
		if ((temp.substring(4,5) == temp.substring(5,6)) && (temp.substring(5,6) == temp.substring(6,7)) && (temp.substring(6,7) == temp.substring(7,8)) ){	
			showError(errMsg,mensErro);
			focusCamp(campo);
			return false;
		}
	}
	
	return true; 
	
}


function formatNumeric(campo,mensErro)
{
	var msgError= "Valor inválido. Digite novamente.";
	var valor= campo.value;
	if( valor == "" || valor == null)
		return false;
	valor= justNumbersStr(valor);
	LAST_FIELD= campo;
	if( !isNumeric(valor))
	{
		showError(msgError,mensErro);
		focusCamp(campo);
		return false;
	}
	ERRO= false;
	return true; 
}

function formatPercent(campo,mensErro)
{
	return formatFloat(campo,mensErro,2); 
}

function formatEmail(campo, msgErro)
{
	var errMsg= "E-mail incorreto. Digite novamente.";
	var email= trim(campo.value);
	LAST_FIELD= campo;

	if( email == "" || email == null)
		return false;
	if( !isEmail(email))
	{
		showError(errMsg, msgErro);
		focusCamp(campo);
		return false;
	}
	ERRO= false;
	return true;
}

function formatText(campo,msgErro)
{
	var texto= new String(campo.value);
	LAST_FIELD= campo;
	if( texto == "" || texto == null)
		return false;
	if( !isAlfa(removeStr(texto,new Array(" ","'"))) )
	{
		showError("Valor inválido.\nPor favor, digite apenas letras neste campo.",msgErro);
		focusCamp(campo);
		return false;
	}	
	ERRO=false;
	return true;
}

function formatUpperCase(campo,msgErro)
{
	var texto= String(campo.value);
	LAST_FIELD= campo;
	if( texto == "" || texto == null)
		return false;
	campo.value= texto.toUpperCase();
	ERRO=false;
	return true;
}

function formatFloat(field, mensErro, numdec)
{
	var errMsg= "Valor inválido. Digite novamente.";
	var numDecimais= (numdec?numdec:2);
	var vr= toFloat(trim(field.value),numDecimais);
	LAST_FIELD= field;

	if( !isFloatNumber(vr))
	{
		showError(errMsg,mensErro); 
		focusCamp(field);
		return false;
	}
	field.value= vr;
	ERRO= false;
	return true;
}

function formatMoney(field, mensErro, numdec)
{
	var errMsg= "Valor inválido. Digite novamente.";
	var numDecimais= (numdec?numdec:2);
	var vr= toFloat(trim(field.value),numDecimais);
	LAST_FIELD= field;

	if( !isFloatNumber(vr))
	{
		showError(errMsg,mensErro); 
		focusCamp(field);
		return false;
	}else{
		if( verifyMaxValue(vr))
		{
			field.value= "0,00";
			ERRO=true;
			return false;
		}
	}

	// -- Codigo para formatacao do campo --
	var vraux = "", caracter= "";
	var posDec= vr.indexOf(",");
	var valorDec= vr.substring( posDec+1);
	// Da dir. p/ esq. vai formatando o numero com separadores de milhar.
	for ( i= posDec; i > 0; i--)
	{
		pos= i - posDec;
		if( i != posDec && (pos % 3 == 0))
			vraux += ".";
		vraux += vr.substring(i, i-1 );
	}
	vrfinal= invertStr(vraux);
	field.value = vrfinal + ","+ valorDec;

	ERRO=false;
	return true;
}

function setMaxValue(value)
{
	MAX_VALUE= value;
}

function verifyMaxValue(v)
{
	var vr= String(v);
	if(vr.length > 0)
	{
      if (parseFloat(vr) > MAX_VALUE)
			return true;
	}
	return false;
}

function repeatNStr(value, num)
{
	var ret= "";
	for( var i=0; i< num; i++) ret+= value;
	return ret;
}

function toFloat(src, numdec)
{
	var source= trim(src);
	var tam= source.length;
	var posDec= source.indexOf(",");

	if( source.length == 0) source= "0"; // previne erro em valores vazios.

	/* Se nao tiver ponto decimal inclui zeros */
	if( posDec == -1)
	   return removeStr(source,".") + "," + repeatNStr("0",numdec);
	else{
		source= removeStr(source,".");
		if( posDec == 0)                        // ponto decimal eh o primeiro?
			return "0"+ source+ repeatNStr("0",numdec+1-source.length);
		else{
			if( (posDec > tam-numdec-1))         // Nao tem decimais suficientes?
				source+= repeatNStr("0",posDec - (tam-numdec-1));
			posDec= source.indexOf(",");
			return parseInt(source.substring(0,posDec),10)+ source.substring(posDec,posDec+numdec+1);
		}
	}
}


function formatCPF(campo,mensErro) 
{
	var valor= repeatStr(justNumbersStr(campo.value), "0", SIZE_CPF);
	var msgError= "CPF inválido. Digite novamente.";
	LAST_FIELD= campo;
	if( valor == "" ||  valor == null)
		return false;
	if(  !isCPF(valor) )
	{
		showError(msgError,mensErro);
		focusCamp(campo);
		return false;
	}else{
		var temp= new String("");
		temp= valor.substring(0,3) + "." + valor.substring(3,6) + "." + valor.substring(6,9) + "-" + valor.substring(9,11)
		campo.value= temp;
	}
	ERRO=false;
	return true;
}

function formatCNPJ(campo,mensErro) 
{
	var valor= repeatStr(justNumbersStr(campo.value), "0", SIZE_CNPJ);
	var msgError= "CNPJ inválido! Digite novamente.";
	LAST_FIELD= campo;

	if( valor == "" ||  valor == null)
		return false;

	if(  !isCNPJ(valor) )
	{
		showError(msgError,mensErro);
		focusCamp(campo);
		return false;
	}else{
		var temp= new String("");
		temp= valor.substring(0,2) + "." + valor.substring(2,5) + "." + valor.substring(5,8) + "/" + valor.substring(8,12) + "-" + valor.substring(12,14);
		campo.value= temp;
	}
	ERRO=false;
	return true;
}

function formatCPF_CNPJ(campo,mensErro) 
{
	var valor= justNumbersStr(campo.value);
	var msgErro;
	msgErro= mensErro?mensErro:'CPF/CNPJ inválido. Digite novamente.';
	if( valor.length <= SIZE_CPF)
	{
		return formatCPF(campo,msgErro);
	}
	else
	{
		return formatCNPJ(campo,msgErro);
	}
}

function formatInterval(campo, minimo, maximo, mensErro)
{
	var valor= justNumbersStr(campo.value);
	var msgError= "Valor inválido. Digite novamente.";
	LAST_FIELD= campo;
	if( valor == "" || valor == null)
		return false;
	if( !isNumeric(campo.value))
	{
		showMessage(msgError,mensErro);
		focusCamp(campo);     	 
		return false;
	}else if( (parseInt(valor,10) < minimo) || (parseInt(valor,10) > maximo)) {
		showError( "Valor inválido. Digite um valor entre " + minimo + " e " + maximo + ".", mensErro);
		focusCamp(campo);
		return false;
	}
	ERRO=false;
	return true;
} 

function formatMonthYear(campo, msgError)
{
	valor= justNumbersStr(campo.value);
	LAST_FIELD= campo;

	var errMsg= "Mês e ano inválidos. Digite novamente.";
	if( valor == "" || valor == null)
		return false;
	if( !isNumeric(valor))
	{
		showError(errMsg, msgError);
		focusCamp(campo);
		return false;
	}else{
		var vr= vr= "01"+ valor;
		var dtObj= new DateValidation(vr);
		if( !dtObj.isDate())
		{
			showError(errMsg, msgError);
			focusCamp(campo);
			return false;
		}else{
			campo.value= dtObj.getMonthDateValue();
		}
	}
	ERRO= false;
	return true; 
}

function formatAlfaNumeric(campo,msgErro)
{
	var texto= new String(campo.value);
	LAST_FIELD= campo;

	if( texto == "" || texto == null)
		return false;
	if( !isAlfaNumeric(texto))
	{
		showError("Valor inválido.\nPor favor, digite apenas letras ou números neste campo.",msgErro);
		focusCamp(campo);
		return false;
	}	
	ERRO=false;
	return true;
}

function formatCamp(campo, tipo, par1, par2, par3) 
{
	var numArgs= formatCamp.arguments.length;
	var ret= false;
	ERRO= false;
	var b= getObjBrow();
	//-- IE 4 apresenta problema de loop no onblur --// 
	if( b.isIE() && parseInt(b.getMajorver(),10) < 5)  
	{
		if( LAST_ERROR_FIELD == campo && LAST_ERROR_VALUE == campo.value)
		{
			REPETITION_ERROR= true;
		}else{
			LAST_ERROR_FIELD= campo;
			LAST_ERROR_VALUE= campo.value;
			REPETITION_ERROR= false;
		}
	}
	if( isFieldEmpty(campo,tipo))
		return false;
	if( numArgs == 2)
		par1= "";
	if( tipo == "account")
		ret= formatAccount(campo,par1);
	else if( tipo == "branch")
		ret= formatBranch(campo,par1);
	else if( tipo == "ag_account")
		ret= formatAg_Account(campo,par1);
	else if( tipo == "ag_savings")
		ret= formatAg_Savings(campo,par1);
	else if( tipo == "cpf")
		ret= formatCPF(campo,par1);
	else if( tipo == "cnpj")
		ret= formatCNPJ(campo,par1);
	else if( tipo == "cpf_cnpj")
		ret= formatCPF_CNPJ(campo,par1);
	else if( tipo == "date")	
		ret= formatDate( campo,par1);
	else if( tipo == "time")	
		ret= formatTime( campo,par1);
	else if( isNNType(tipo,"money"))
		ret= formatMoney(campo,par1, parseInt(tipo.substring(5),10));
	else if( isNNType(tipo,"float"))
		ret= formatFloat(campo,par1, parseInt(tipo.substring(5),10));
	else if( tipo == "numeric")
		ret= formatNumeric(campo,par1);
	else if( tipo == "cep")
		ret= formatCEP(campo,par1);
	else if( tipo == "placa")
		ret= formatPlaca(campo,par1);
	else if( tipo == "email")
		ret= formatEmail(campo,par1);
	else if( tipo == "percent")
		ret= formatPercent(campo,par1);
	else if( tipo == "month_year")
		ret= formatMonthYear(campo);
	else if( tipo == "interval")
	{
		if( numArgs <= 4)
			par3= "";
		ret= formatInterval(campo, par1, par2, par3);
	}
	else if( tipo == "text")
		ret= formatText(campo,par1);
	else if( tipo == "uppercase")
		ret= formatUpperCase(campo,par1);
	else if( tipo == "alfanumeric")
		ret= formatAlfaNumeric(campo,par1);
	else
		alert( "Tipo passado para formatação é inválido: " + tipo);
	//-- Controlando problema com onblur no IE 4 --// 
	if( b.isIE() && parseInt(b.getMajorver(),10) < 5)  
	{
		if(	REPETITION_ERROR)
		{
			campo.value= "";
			REPETITION_ERROR= false;
			ret= false;
		}
		if( !ERRO)
		{
			LAST_ERROR_FIELD= null;
			LAST_ERROR_VALUE= "";
		}
	}
	return ret;
}

function isFieldEmpty( field, type)
{
	var empty= false;
	var value= trim(field.value);
	if( !field || value.length == 0)
		empty= true;
	if( isNNType(type,"money"))
	{
		if( empty )
		{
			field.value= "0,00";
			empty= true;
		}
	}
	return empty;
}

function saltaCampo( evento,field,tipo,tamanho)
{
	var tecla;
	var maxSize;
	var fieldSize;
	if( isNNType(tipo,"float")) tipo= "float";
	if( isNNType(tipo,"money")) tipo= "money";

	switch(tipo)
	{
		case "date":		maxSize=SIZE_DATE;	break;
		case "time":		maxSize=SIZE_TIME;	break;
		case "cpf": 		maxSize=SIZE_CPF;		break;
		case "cnpj": 		maxSize=SIZE_CNPJ;	break;
		case "cpf_cnpj": 	maxSize=SIZE_CNPJ; 	break;
		case "cep": 		maxSize=SIZE_CEP; 	break;
		case "account": 	maxSize=SIZE_ACCOUNT; break;
		case "branch": 	maxSize=SIZE_BRANCH; break;
		case "percent": 	maxSize=SIZE_PERCENT; break;
		case "ag_account": 
		case "ag_savings": 
			maxSize=SIZE_AG_ACCOUNT; break;
		case "month_year":	maxSize=SIZE_MONTH_YEAR; break;
		case "float":
			if( saltaCampo.arguments.length > 3)  // Tamanho foi informado?
				maxSize= tamanho;
			else
				maxSize= SIZE_FLOAT;
			break;
		case "money":
			if( !verifyMaxValue(field.value))
			{ 
				if( saltaCampo.arguments.length > 3)  // Tamanho foi informado?
					maxSize= tamanho;
				else
					maxSize= SIZE_MONEY;
			}else{
				field.value= "0,00";
			}
			break;
		case "text":
		case "uppercase":
		case "interval":
		case "alfanumeric":
		case "default":
		case "numeric":
		case "email":
			maxSize= tamanho;
	}
	(getObjBrow().isNetscape())?tecla = evento.which:tecla = evento.keyCode;
	fieldSize=String(field.value).length;
	if ( fieldSize >= maxSize && tecla >= 48 )
	{
		autoSkip(field);
		return true;
	}else return false;
}

function showError(msgInfra, msgUsuario)
{
	ERRO= true;
	if(typeof msgUsuario != "undefined" && msgUsuario != "" && msgUsuario!= null)
		alert(msgUsuario);
	else
		alert(msgInfra);
}

function focusCamp(campo)
{
	if( getObjBrow().isNetscape())
		campo.value= "";
	else
		campo.focus();
		campo.value= "";
	ERRO= true;
}

function getObjBrow() 
{
	if( typeof objBrow != "object")
		objBrow= new Browser();
	return objBrow;
}

function unformatFields()
{
	var field= null;
	var form = null;
	for( var c=0; c< arguments.length; c++)
	{
		var form= arguments[c];
		if( !form || (typeof form != "object"))
		{
			alert("Argument "+ (c+1) + " is not a form object!");
			return;
		}
		for( var i=0; i< form.length; i++)
		{
			field= form.elements[i];
			var type= "";
			if(field.type == "text")
			{
				type= getValidationType(field);
				if( type)
				{
					valor= unformatField(field.value,type);	 
					field.value= (!valor?"":valor);
				}
			}
		}
	}
}

function getValidationType(field)
{
	if( !field.onblur) return null;
	var blurCode= changeStr(removeStr(field.onblur.toString()," "),"\'","\"");
	blurCode= removeStr(removeStr(blurCode,"\n"),"\t").toLowerCase();
	var re= /^.*formatcamp\((.*)\).*$/;
	var result= (re.exec(blurCode))[1];
	return (result.split("\"")[1]);
}

function isNNType(fieldType,type)
{
	return (fieldType.indexOf(type) == 0);
}

