<!--

// ------------------------------------------------------------------------------------------ //
// Acrescenta algumas propriedades aos controles:
// .Indice			: indica o índice na tela para o controle
// .IndiceAnterior	: indica o índice do controle anterior
// .IndicePosterior	: indica o índice para o controle posterior
// .Tam				: tamanho máximo para digitação
// .AutoSkip		: indica se pula para o próximo campo após completar o tamanho do campo
// .Tipo			: indica o tipo de dado
//						'D' -> só dígitos de 0(zero) a 9(nove)
//						'N' -> dígitos de 0(zero) a 9(nove), "."(ponto) e ","(vírgula)
//						'C' -> caracteres de 'a' até 'z' e de 'A' até 'Z'
//						'CPFCNPJ' -> permite formatação especial para CPF ou CNPJ
//						'CPF'     -> permite formatação especial para CPF
//						'CNPJ'    -> permite formatação especial para CNPJ
//						outro -> qualquer caracter entre ascii 32 e ascii 127
// .Saltar			: (reservado) indica o momento de saltar de campo
// ------------------------------------------------------------------------------------------ //

// Carrega índices para o próximo controle e controle anterior
function InicializarIndices()
{
	if (document.CargaInicial==null)
	{
		document.CargaInicial=false;		// Seta para só fazer uma vez por documento
		var ctrlAnterior=null;

		for ( var iForm=0; iForm < document.forms.length; iForm++ )
		{
			var IndAnt=0;
			for ( var i=0; i<document.forms[iForm].elements.length;i++)
			{
				var e=document.forms[iForm].elements[i];
				if ( e.type!="hidden" && e.type!="image" )		
				{
					if ( ctrlAnterior != null )
					{
						ctrlAnterior.IndicePosterior=i;
						ctrlAnterior.FormPosterior=iForm;
					}
					ctrlAnterior=e;
					e.Indice=i;
					e.Form=iForm;
					e.IndiceAnterior=IndAnt;
					if ( iForm==0 )
						e.FormAnterior=0;
					else
						e.FormAnterior=iForm-1;
				}
			}
		}
		//if ( ctrlAnterior!=null )
		//{
		//	ctrlAnterior.IndicePosterior=i-1;
		//}
	}
}

// Colocar o foco em determinado campo
function SetarFoco ( ind, QualF )
	{
	QualF=CalcQualF(QualF);
	
	if ( QualF==-2 )
		return;
	if ( QualF==-1 )
		QualF=0;
	InicializarIndices();
	if ( isNaN(ind) && document.forms[QualF].elements[ind].type!="hidden" )
		document.forms[QualF].elements[ind].focus();
	else
		for (;ind<document.forms[QualF].elements.length;ind++)
			if ( document.forms[QualF].elements[ind].type!="hidden" )
				break;
		if ( ind<=document.forms[QualF].elements.length )
			document.forms[QualF].elements[ind].focus();
	}

// Limpar o conteúdo do(s) campo(s)
function LimparCampo ( ind, QualF )
	// Para -1, limpa todos os elementos
{

	QualF=CalcQualF(QualF);
	if ( QualF==-2 )
		return;
	if ( QualF==-1 )
		QualF=0;
	if (isNaN(ind))			// Limpa pelo nome
	{
		document.forms[QualF].elements[ind].value="";
	}
	else
	{
		var TForm;
		if ( QualF==-1 )
		{
			QualF=0;
			TForm=document.forms.length;
		}
		else
			TForm=QualF+1;
		var count=-1;
		var bFim=false;
		for ( var iForm = QualF; (!bFim && iForm < TForm); iForm++ )
		{
			for ( var i=0; (!bFim && i < document.forms[iForm].elements.length); i++ )
			{
				if ( document.forms[iForm].elements[i].type=="text" || document.forms[iForm].elements[i].type=="password" )
				{
					count++;
					if ((ind==-1) || (ind==count))
						document.forms[iForm].elements[i].value="";
					if ( ind==count )
						bFim=true;
				}
			}
		}
	}
}

// Verificar qual navegador
function QualNavegador() 
{
	var s = navigator.appName;
	if ( s == "Microsoft Internet Explorer" )
		return "IE";
	else if ( s == "Netscape" )
		return "NE";
	else
		return "";
}

// Verificar qual a versão do navegador
function QualVersao()
{
	var s = navigator.appVersion;
	if ( QualNavegador() == "IE" )
	{
		var i = s.search("MSIE");
		s=s.substring(i+5);
		i=s.search(".");
		return parseInt(s.substring(0,i+1));
	}
	else if ( QualNavegador() == "NE" )
		return parseInt(s.substring(0,1));
	else
		return 0;
}

// Verificar se é Macintosh
function SeMac()
{
	var s = navigator.appVersion;
	var v = s.search("Mac");  

	if (v!=-1)
	{
		return "MAC";
	}

	return 0;
}


// Setar o evento
// ------------------------------------------------------------------------------------------ //
// Função   : SetarEvento
// Descrição: Seta eventos para permitir verificação de digitação e salto de campo
// Entradas:  - ctrl: referência ao controle (this)
//            - Tam:  tamanho máximo do input
//            - Tipo: indica o tipo de campo para digitação
//            - AutoSkip: Indica se faz o "autoskip" ou não: default: true
//            - CasasDec: Somente para o tipo 'N'. Limita o número de casas decimais ( após a vírgula )
// ------------------------------------------------------------------------------------------ //
function SetarEvento(ctrl, Tam, Tipo, AutoSkip, CasasDec )
{
	// Filtra navegadores conhecidos
	var s = QualNavegador();
	if ( s.length==0 )
		return;
	if ( s=="IE" && QualVersao()>6 )
		return;
	if ( s=="NE" && QualVersao()>4 )
		return;

		
	if (ctrl.onkeypressSet==null)
	{
		ctrl.onkeypressSet=true;
		
		if (AutoSkip==null)
			AutoSkip=true;
		if (Tipo!=null)
			Tipo.toUpperCase();
		else
			Tipo="";
		if ( CasasDec==null )
			CasasDec=-1;
		ctrl.Tam=Tam;
		ctrl.Tipo=Tipo;
		ctrl.AutoSkip=AutoSkip;
		ctrl.Saltar=false;
		ctrl.CasasDec=CasasDec;
		InicializarIndices();
		//alert(InicializarIndices());
		var txtFun="";
		if ( ctrl.onkeypress!= null )
			txtFun=ExtrairCodigo(ctrl.onkeypress);
		txtFun += ExtrairCodigo(ValidarTecla);
		var myFun = new Function("evnt", txtFun);
		ctrl.onkeypress=myFun;
		if (QualNavegador()=="IE" && QualVersao()>=5)
		{
			txtFun="";
			if ( ctrl.onkeyup != null )
				txtFun=ExtrairCodigo(ctrl.onkeyup);
			txtFun += ExtrairCodigo(SaltarCampo);
			myFun=new Function("ctrl", txtFun);
			ctrl.onkeyup=myFun;
		}
	}
}

function SetarEvento_Backsa(ctrl, Tam, Tipo, AutoSkip, CasasDec )
{
	// Filtra navegadores conhecidos
	var s = QualNavegador();
	if ( s.length==0 )
		return;
	if ( s=="IE" && QualVersao()>5 )
		return;
	if ( s=="NE" && QualVersao()>4 )
		return;

	if (ctrl.onkeypressSet==null)
	{
		ctrl.onkeypressSet=true;
		if (AutoSkip==null)
			AutoSkip=true;
		if (Tipo!=null)
			Tipo.toUpperCase();
		else
			Tipo="";
		if ( CasasDec==null )
			CasasDec=-1;
		ctrl.Tam=Tam;
		ctrl.Tipo=Tipo;
		ctrl.AutoSkip=AutoSkip;
		ctrl.Saltar=false;
		ctrl.CasasDec=CasasDec;
		InicializarIndices();
		var txtFun="";
		if ( ctrl.onkeypress!= null )
			txtFun=ExtrairCodigo(ctrl.onkeypress);
		txtFun += ExtrairCodigo(ValidarTecla);
		var myFun = new Function("evnt", txtFun);
		ctrl.onkeypress=myFun;
		if (QualNavegador()=="IE" && QualVersao()==5)
		{
			txtFun="";
			if ( ctrl.onkeyup != null )
				txtFun=ExtrairCodigo(ctrl.onkeyup);
			txtFun += ExtrairCodigo(SaltarCampo);
			myFun=new Function("ctrl", txtFun);
			ctrl.onkeyup=myFun;
		}
	}
}



function SaltarCampo(ctrl)
{
	if (ctrl==null)
		ctrl=this;
	if ( ctrl.AutoSkip && ctrl.Saltar)
		if (ctrl.Saltar)
		{
			ctrl.Saltar=false;
			if ( ctrl.IndicePosterior != null )
				SetarFoco(ctrl.IndicePosterior, ctrl.FormPosterior);
		}
}

// Fazer o salto de campo
function ValidarTecla (evnt)
{

	var tk;
    var c;
	// Recebe a tela pressionada
	tk = ( (QualNavegador()=="IE") ? event.keyCode : evnt.which);
    c=String.fromCharCode(tk);
	c=c.toUpperCase();
	
	// -- Este trecho faz com que o <Enter> tenha a função de <Tab>, mas acho inviável, pois não é possível
	//       colocar o foco em campos do Tipo "image", e, neste caso, nunca seria possível fazer a submissão
	//       do formulário
	// if ( tk == 13 )
	// {
	//	this.Saltar=true;
	//	SaltarCampo(this);
	//	return false;
	// }
	
	// Só aceita teclas alfanuméricas. Não aceita teclas de controle
    if ( tk < 32 )
		return true;
	if ( tk > 127 )
		return false;
	//if (this.value.length==this.Tam)
	//	return false;

	switch ( this.Tipo )
	{
	case "D":
		if ( c<"0" || c>"9" )
			return false;
		break;
	case "N":
		if ( (this.CasasDec==0) && (c==',') )
			return false;
		if ( (c<"0" || c>"9") && (c!="." && c!=",") )
			return false;
		if ( (c==",") && ((this.value.search(",")>-1) || (this.value.length==0)) )
			return false;
		if ( (c==".") && ( (this.value.length==0) || (this.value.search(",")!=-1) || (Conta(this.value,'.')==0 && this.value.length>3) ) )
			return false;
		if ( (c==",") && ( this.value.indexOf('.')!=-1 && this.value.length-this.value.lastIndexOf('.') != 4 ) )
				return false;
		if ( (c==".") && (this.value.length-this.value.lastIndexOf('.') != 4) )
		{
			if  (!((this.value.length < 3) && (this.value.indexOf('.')==-1)))
				return false;
		}
		if ( this.value.indexOf(',')==-1 )
		{
			j=this.value.lastIndexOf(".");
			if ( (j!=-1) && this.value.length>j+3 )
			{
				if ( (c!=',') && (c!='.') )
					return false;
			}
		}
		if ( (this.CasasDec > 0) && (this.value.indexOf(',')>-1) && (this.value.length==this.value.indexOf(',')+1+this.CasasDec) )
			return false;
		break;
	case "C":
		if ( c<"A" || c>"Z" )
			return false;
		break;
	case "CNPJ":
	case "CPF":
	case "CPFCNPJ":
		var bComFormato=true;
		var sTipo=this.Tipo;
		if ( this.value.indexOf(".")==-1 && this.value.indexOf("-")==-1 && this.value.indexOf("/")==-1 && this.value.length==3 && c!="." && c!="-" && c!="/")
			bComFormato=false;
		else if ( this.value.indexOf(".")==-1 && this.value.indexOf("-")==-1 && this.value.indexOf("/")==-1 && this.value.length>3 )
			bComFormato=false;
		if ( (c<"0" || c>"9") && (!bComFormato) )
			return false;
		if ( bComFormato )
		{
			if  ( (c<"0" || c>"9") && (c!="." && c!="-") )
			{
				if ( this.Tipo.indexOf("CNPJ")==-1 )
					return false;
				else if ( c!= "/" )
					return false;
			}
			
			if ( (c=="-") && (this.value.indexOf("-")!=-1) )
				return false;
			if ( (c=="/") && (this.value.indexOf("/")!=-1) )
				return false;
		}
		if ( this.value.indexOf(".")==-1 && this.value.indexOf("-")==-1 && this.value.indexOf("/")==-1 && this.value.length==3 && c!="." && c!="-" && c!="/")
			bComFormato=false;
		if ( bComFormato )
		{
			sTipo="";
			if ( c=='.' )
			{
				if ( this.value.length < 2 )
					return false;
				else if ( (i=this.value.indexOf('.')) != -1 )
					if ( this.value.length-i != 4 )
						return false;
			}
			if ( (this.value.length == 2) && (c=='.') )
				if ( this.Tipo.indexOf("CNPJ")==-1 )
					return false;
				else
					sTipo="CNPJ";
			if (sTipo=="" )
			{
				if ( this.Tipo=="CNPJ" )
					sTipo="CNPJ";
				else if ( this.Tipo=="CPF" )
					sTipo="CPF";
				if ( (this.value.indexOf("/")!=-1) || (this.value.indexOf('.')==2) )
					sTipo="CNPJ";
				else if ( this.value.indexOf("-")!=-1 )
					sTipo="CPF";
			}
			if ( sTipo=="CPF" && c=="/" )
				return false;
			// Limita os dígitos após o "-"
			
			if ( this.value.indexOf("-")!=-1 && ( (this.value.indexOf("-")+3==this.value.length) || c=='.') )
				return false;
			var qtdpto=Conta(this.value,".");
			if ( qtdpto==2 && c=="." )
				return false;
			//if ( qtdpto<2 && (c=="-" || c=="/") )
			//	return false;
			if ( c!="." )
			{
				// Limita máximo de dígitos após a barra "/"
				if ( sTipo=="CNPJ" && c=="-" && this.value.lastIndexOf("/")+5 != this.value.length )
					return false;
				var interpto=0;
				if ( this.value.indexOf("/")==-1 && this.value.indexOf("-")==-1 )
					interpto=3;
				// Tem que ter 3 números entre cada ponto
				var j=this.value.lastIndexOf(".");
				var i=this.value.length;
				var qtdcar=this.value.length-this.value.lastIndexOf(".");
				if ( (j!=-1) && ((qtdcar-1)<=interpto) )
				{
					if ( qtdcar==4 && c!="-" && c!="/")
						return false;
					else if ( qtdcar<4 && (c<"0" || c>"9") )
						return false;
				}
				if ( this.value.indexOf("/") != -1 )
				{
					// Tem que ter 4 dígitos após o "/"
					if ( this.value.lastIndexOf("/")+5 == this.value.length && c!="-")
						return false;
				}
			}
		}
		break;
		
	case "DEC":
		if ( (this.CasasDec==0) && (c==',') )
			return false;
		if ( (c<"0" || c>"9") && (c!=",") )
			return false;
		if ( (c==",") && ((this.value.search(",")>-1) || (this.value.length==0)) )
			return false;
		if ( (this.CasasDec > 0) && (this.value.indexOf(',')>-1) && (this.value.length==this.value.indexOf(',')+1+this.CasasDec) )
			return false;
		break;
	
	case "ALERT":
		if ( c<"A" || c>"Z" )
		{
			alert("A senha de efetivação passou a ser codificada. \nPara mais detalhes, clique sobre o link \"Saiba mais\", ao lado do campo de senha.");  
			return false;
		}
		break;

	case "ALERTLOGIN":
		if ((c<"0" || c>"9") || (c<"A" || c>"Z"))
		{
			alert("A senha de login deverá ser preenchida com a utilização do Teclado Virtual. \nPara mais detalhes, clique sobre o link \"Saiba mais\".");  
			return false;
		}
		break;
		
	default:
		break;
	}
	
	this.Saltar=(this.value.length==this.Tam-1);
	if ( !this.Saltar )
	{
		if ( this.Tipo.indexOf("CPF")!=-1 || this.Tipo.indexOf("CNPJ")!=-1 )
		{
			if ( bComFormato )
			{
				 // Com formatação: para salto, verifica preenchimento de 2 dígitos de controle
				if ( this.value.indexOf("-") != -1 )
				{
					if ( !this.Saltar && this.value.indexOf("-")+2 == this.value.length )
						this.Saltar=true;
				}
			}
			else
			{
				// Sem formatação: para salto, verifica tamanho máximo de digitação (CPF:11 / CNPJ: 15)
				if ( this.Tipo=="CPF" && this.value.length==10 )
					this.Saltar=true;
				else if ( this.value.length==14 )
					this.Saltar=true;
			}
		}
		else if ( this.Tipo=='N' && this.CasasDec>0 && (this.value.indexOf(',')!=-1) && (this.value.indexOf(',')+this.CasasDec==this.value.length) )
			this.Saltar=true;
	}
	
	if ( ((QualNavegador()=="IE") && QualVersao()<5) || (QualNavegador()!="IE") )
		SaltarCampo(this);

	return true;
}


function CheckUnCheck(QualCtrl, QualInd, QualF, Checked)
{
	QualF=CalcQualF(QualF);
	var ctrl;
	
	if ( QualF==-2 )
		return;
	if ( QualF==-1 )
		QualF=0;
	if ( document.forms[0].elements[QualCtrl].length>0 )
	{
		if ( !(isNaN(QualInd)) )
			ctrl=document.forms[QualF].elements[QualCtrl][QualInd];
	}
	else
		ctrl=document.forms[QualF].elements[QualCtrl];
	if ( (ctrl!=null) && (ctrl.type=="radio" || ctrl.type=="checkbox") )
		ctrl.checked=Checked;
}


function Check(QualCtrl, QualInd, QualF)
{
	CheckUnCheck(QualCtrl, QualInd, QualF, true);
}

function UnCheck(QualCtrl, QualInd, QualF)
{
	CheckUnCheck(QualCtrl, QualInd, QualF, false);
}


// Funções de uso comum


// ------------------------------------------------------------------------------------------ //
// Função:    CalcQualF()
// Descrição: Utilização interna
// Entrada:   QualF
// ------------------------------------------------------------------------------------------ //
function CalcQualF(QualF)
{
	if ( QualF==null )
	{

		if ( document.forms.length==0 )
			QualF=-2;
			
		else
			QualF=-1;
	}
	else if ( isNaN(QualF) )
	{
		for ( var i=0; i < document.forms.length; i++ )
		{
			if ( document.forms[i].name==QualF )
			{
				QualF=i;
				break;
			}
		}
		if ( i == document.forms.length )
			QualF=-2;
	}

	return QualF;
}

// ------------------------------------------------------------------------------------------ //
// Função:    Conta()
// Descrição: Calcular a quantidade de ocorrências de um caracter em uma string
// Entrada:   texto, car
// ------------------------------------------------------------------------------------------ //
function Conta(texto, car)
{
	var count = 0;
	var pos = texto.indexOf(car);
	while ( pos != -1 ) 
	{ 
		count++;
		pos = texto.indexOf(car,pos+1);
	}
	return count;
}

function ExtrairCodigo(funct)
{
	var sfunct=funct.toString();
	var s = sfunct.substr(sfunct.indexOf('{')+1);
	s = s.substring(1,s.lastIndexOf('}')-1);
	return s;
}

// ------------------------------------------------------------------------------------------ //
// Função:    Tecla()
// Descrição: Permite somente a entrada de números
// Entrara:   e  - Tecla digitada
// ------------------------------------------------------------------------------------------ //

function Tecla(e)
{
	if(document.all) // Internet Explorer
	var tecla = event.keyCode;

	else if(document.layers) // Nestcape
	var tecla = e.which;

	if(tecla > 47 && tecla < 58) // numeros de 0 a 9
	return true;
	else
{
	if (tecla != 8) // backspace
	return false;
	else
	return true;
}

}

// ------------------------------------------------------------------------------------------ //
// Função:    MandaFoco()
// Descrição: Manda o foco para o campo especificado na chamada da função
// Entrara:   ctrl - referência ao controle corrente: (this)
//			  Tam  - Tamanho do campo 
//            QualC- Qual campo será enviado o foco
// ------------------------------------------------------------------------------------------ //

function MandaFoco(ctrl, Tam, QualC)
{	
	if (ctrl.value.length >= Tam)
	{
	eval('document.forms[0].' + QualC + '.focus()');
	}
}

// ------------------------------------------------------------------------------------------ //
// Função:	FormataCPF()
// Descrição:	Criar mascara no input do campo CPF
// ------------------------------------------------------------------------------------------ //

function FormataCPF(pForm,pCampo,pTamMax,pPos1,pPos2,pPosTraco,pTeclaPres)
{
 var wTecla, wVr, wTam;
 wTecla = pTeclaPres.keyCode;
 wVr = pForm[pCampo].value;
 wVr = wVr.toString().replace( "-", "" );
 wVr = wVr.toString().replace( ".", "" );
 wVr = wVr.toString().replace( ".", "" );
 wVr = wVr.toString().replace( "/", "" );
 wTam = wVr.length ;

 if (wTam < pTamMax && wTecla != 8) { 
    wTam = wVr.length + 1 ; 
 }

 if (wTecla == 8 ) { 
    wTam = wTam - 1 ; 
 }
   
 if ( wTecla == 8 || wTecla == 88 || wTecla >= 48 && wTecla <= 57 || wTecla >= 96 && wTecla <= 105 ){
  if ( wTam <= 2 ){
    pForm[pCampo].value = wVr ;
  }
  if (wTam > pPosTraco && wTam <= pTamMax) {
        wVr = wVr.substr(0, wTam - pPosTraco) + '-' + wVr.substr(wTam - pPosTraco, wTam);
  }
  if ( wTam == pTamMax){
        wVr = wVr.substr( 0, wTam - pPos1 ) + '.' + wVr.substr(wTam - pPos1, 3) + '.' + wVr.substr(wTam - pPos2, wTam);
  }
  pForm[pCampo].value = wVr;
 
 }

}

function Limpa(valor)
{
	campo = valor;
	full = campo.value;

	if (full == "Nº DO DOCUMENTO")
	{
		campo.value = '';
		campo.focus();
	}

}

//-->