/*
********************************************************************************
'* Desenvolvido por Ricardo Fernandes
'* Responsável: Ricardo Fernandes
'* Funcionalidade: Rotinas JAVASCRIPT de uso comum do site
'* Desenvolvido em: 26/11/2005
'********************************************************************************
*/
//Função que só Permite Digitar Números
function soNumeros()  
{
	if (event.keyCode < '48' || event.keyCode > '58') 
	{
		event.keyCode = '127';
		alert('Digite apenas números!');
		return false;
	}
}

function cpf(pcpf)
 {

 if (pcpf.length != 11) {sim=false}
 else {sim=true}

  if (sim )  // valida o primeiro digito
  {
  for (i=0;((i<=(pcpf.length-1))&& sim); i++)
  {
   val = pcpf.charAt(i)
   if

 ((val!="9")&&(val!="0")&&(val!="1")&&(val!="2")&&(val!="3")&&(val!="4")

 &&    (val!="5")&&(val!="6")&&(val!="7")&&(val!="8")) {sim=false}
   }

   if (sim)
  {
    soma = 0
    for (i=0;i<=8;i++)
    {
     val = eval(pcpf.charAt(i))
     soma = soma + (val*(i+1))
    }

    resto = soma % 11
    if (resto>9) dig = resto -10
    else  dig = resto
    if (dig != eval(pcpf.charAt(9))) { sim=false }
   else   // valida o segundo digito
    {

     soma = 0
    for (i=0;i<=7;i++)
     {
     val = eval(pcpf.charAt(i+1))
      soma = soma + (val*(i+1))
    }

     soma = soma + (dig * 9)
    resto = soma % 11
     if (resto>9) dig = resto -10
     else  dig = resto
   if (dig != eval(pcpf.charAt(10))) { sim = false }
    else sim = true
   }
   }
  }

  if (!sim) 
	{ 
    alert("Valor invalido de CPF")
		formulario.txtCPF.value='';
	}
}


function cnpj(campo){
	var i;
	erro=true;
	s = campo.value;
	var c = s.substr(0,12);
	var dv = s.substr(12,2);
	var d1 = 0;

	for (i = 0; i < 12; i++){
		d1 += c.charAt(11-i)*(2+(i % 8));
	}

	if (d1 == 0) erro= false;
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;

	if (dv.charAt(0) != d1) erro= false;

	d1 *= 2;
	for (i = 0; i < 12; i++){
		d1 += c.charAt(11-i)*(2+((i+1) % 8));
	}
	
	d1 = 11 - (d1 % 11);
	if (d1 > 9) d1 = 0;
	if (dv.charAt(1) != d1) erro= false;

	if(s !='')
	{
		if (!erro){
			alert("Preencha corretamente o campo CNPJ!");
			campo.focus();
			return false;
		} else {
			return true;
		}
	}
}

function validaEmail(email,campo)
{ 
var exclude=/[^@\-\.\w]|^[_@\.\-]|[\._\-]{2}|[@\.]{2}|(@)[^@]*\1/; 
var check=/@[\w\-]+\./; 
var checkend=/\.[a-zA-Z]{2,3}$/; 
	if(campo.value.length!=0)
	{
		if(((email.search(exclude) != -1)||(email.search(check)) == -1)||(email.search(checkend) == -1))
		{ 
			alert('O e-mail está incorreto!'); 
			campo.focus();
			return false; 
		}else{ 
			return true; 
		} 
	}
} 

// Funções para utilização de datas
function verificaData(objData)
{
	var data = objData.value;
	if (data.length == 0)
		return true;
//testa se o tamanho da string é válida
	if (data.length != 10)
	{
		alert('Data inválida ! Digite a data no formato DD/MM/AAAA!');
		objData.value = '';
		objData.focus();
		return false;
	}
//separa a data que foi entrada em 3 partes: dia, mes e ano
	var dia = parseFloat(data.substring(0, data.indexOf('/')));
	var mes = parseFloat(data.substring((data.indexOf('/') + 1), data.lastIndexOf('/')));
	var ano = parseFloat(data.substring((data.lastIndexOf('/') + 1), data.length));
// verifica o ano
	if (ano < 1900 || ano > 2100)
	{
		alert('Data inválida ! Ano incorreto!');
		objData.value = '';
		objData.focus();
		return false;
	}
// verifica o mês
	if (mes < 1 || mes > 12)
	{
		alert('Data inválida ! Mês incorreto!');
		objData.value = '';
		objData.focus();
		return false;
	}
//verifica o dia
	var diaOk = true
	if (dia < 1)
		diaOk = false;
	if (mes == 1 || mes == 3 || mes == 5 || mes == 7 || mes == 8 || mes == 10 || mes == 12)
	{
		if (dia > 31)
			diaOk = false;
	}
	else
	{
		if (mes == 4 || mes == 6 || mes == 9 || mes == 11)
		{
			if (dia > 30)
				diaOk = false;
		}
		else
		{
			if ((ano % 400) == 0 || ((ano % 100) != 0 && (ano % 4) == 0))
			{
				if (dia > 29) 
					diaOk = false;
			}
			else
			{
				if (dia > 28) 
					diaOk = false;
			}
		}
	}
	if (! diaOk)				
	{
		alert('Data inválida ! Dia incorreto!');
		objData.value = '';
		objData.focus();
		return false;
	}
	return true;
}

function formataData(objData,teclaPres)
{
	var vr = objData.value;
	var tecla = teclaPres.keyCode;
	if ((tecla > 47 && tecla < 58) || tecla == 9 || tecla == 8)
	{	
		vr = vr.replace( '.', '' );
		vr = vr.replace( '/', '' );
		vr = vr.replace( '/', '' );
		tam = vr.length + 1;
		if ( tecla != 9 && tecla != 8 )
		{
			if ( tam > 2 && tam < 5 )
				objData.value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
			if ( tam >= 5 && tam <= 10 )
				objData.value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
		}
	}
	else
		event.keyCode = '127';
}

function verificaHora(objHora)
{
	var hora = objHora.value;
	
	if (hora.length == 0)
		return true;

//testa se o tamanho da string é válida
	if (hora.length != 5)
	{
		alert('Hora inválida ! Digite a hora no formato HH:MM!');
		objHora.value = '';
		objHora.focus();
		return false;
	}
	
//separa a hora que foi entrada em 2 partes: hora e minuto
	var hh = parseFloat(hora.substring(0, hora.indexOf(':')));
	var mm = parseFloat(hora.substring((hora.lastIndexOf(':') + 1), hora.length));
	
// verifica a hora
	if (hh < 0 || hh > 23)
	{
		alert('Hora inválida ! A hora deve estar entre 0 e 23!');
		objHora.value = '';
		objHora.focus();
		return false;
	}

// verifica o minuto
	if (mm < 0 || mm > 59)
	{
		alert('Hora inválida ! Minuto incorreto!');
		objHora.value = '';
		objHora.focus();
		return false;
	}
	return true;
}

function formataHora(objHora,teclaPres)
{
	var vr = objHora.value;
	var tecla = teclaPres.keyCode;
	if ((tecla > 47 && tecla < 58) || tecla == 9 || tecla == 8)
	{	
		vr = vr.replace( ':', '' );
		tam = vr.length + 1;
		if ( tecla != 9 && tecla != 8 )
		{
			if ( tam > 2 && tam < 5 )
				objHora.value = vr.substr( 0, tam - 2  ) + ':' + vr.substr( tam - 2, tam );
		}
	}
	else
		event.keyCode = '127';
}

function formataHoraSegundo(objHora,teclaPres) 
{
	var tecla = teclaPres.keyCode;
	var vr = objHora.value;
	if ((tecla > 47 && tecla < 58) || tecla == 9 || tecla == 8)
	{	
		vr = vr.replace( ".", "" );
		vr = vr.replace( ":", "" );
		vr = vr.replace( ":", "" );
		tam = vr.length + 1;
		if ( tecla != 9 && tecla != 8 )
		{
			if ( tam > 2 && tam < 5 )
				objHora.value = vr.substr( 0, tam - 2  ) + ':' + vr.substr( tam - 2, tam );
			if ( tam >= 5 && tam <= 10 )
				objHora.value = vr.substr( 0, 2 ) + ':' + vr.substr( 2, 2 ) + ':' + vr.substr( 4, 2 );


		}
	}
	else
		event.keyCode = "127";
}

function verificaHoraSegundo(objHora) 
{
	var err = 0;
	var hora = objHora.value;
	var re = /:/
//testa se o tamanho da string é válida
	if (hora.length == 0)
		return true;
	if ( (hora.length >= 7) && (hora.length <= 8) ) 
	{
//checa se a string possui caracteres inválidos
		if (isNaN(hora.replace(re,'').replace(re,'')))
			err = 1;
		else
		{
			pri_barra=hora.indexOf(':');
			hr=hora.substring(0,pri_barra);
			inicio_min=pri_barra+1;
			seg_barra=hora.lastIndexOf(':');
			mm=hora.substring(inicio_min, seg_barra);
			seg=hora.substring(seg_barra+1, hora.length);
			if (hr < 0 || hr > 23)
				err = 2;
			if (mm < 0 || mm > 59)
				err = 3;
			if (seg < 0 || seg > 59)
				err = 4;
		}
//mensagens de erro
		if (err == 1)
		{
			alert('Hora inválida ! Utilize somente números e ":"...');
			objHora.focus();
			return false;
		}
		if (err == 2) 
		{
			alert('Hora inválida ! A hora está incorreta...');
			objHora.focus();
			return false;
		}
		if (err == 3)
		{ 
			alert('Hora inválida! O minuto está incorreto...');
			objHora.focus();
			return false;
		}
		if (err == 4)
		{ 
			alert('Hora inválida! O segundo está incorreto...');
			objHora.focus();
			return false;
		}
	}
	else 
	{
		alert( 'Hora inválida! Preencha-a no formato HH:MM:SS.' );
		objHora.focus();
		return false;
	}
}

function conta(campo,comprimento,campo_mostrar){
//	var campo=document.formulario.txtMensagem;
//	var comprimento=500;
//	var campo_mostrar=document.formulario.txtConta;
	if (campo.value.length > comprimento)
	{
		campo.value = campo.value.substr(campo.value,comprimento);
	}
	campo_mostrar.value = comprimento - campo.value.length;
}

function onFormataValor(campo,tammax,teclapres,i) 
{ 
	if(campo.readOnly || campo.disabled) 
		return false; 
	
	var tecla = teclapres.keyCode; 
	var vr = campo.value; 
	if (i == 0) 
	{ 
		if ((vr.indexOf(',')) == -1) 
		{ 
			vr = vr+'00' 
		} 
		else 
		{ 
			n = vr.substr( vr.length - 2, vr.length ) 
			if ((n.indexOf(',')) == 0) 
			{ 
				vr = vr+'0' 
			} 
		} 
	} 
	vr = vr.replace( ",", "" ); 
	vr = vr.replace( ".", "" ); 
	vr = vr.replace( ".", "" ); 
	vr = vr.replace( ".", "" ); 
	tam = vr.length; 
	if (i == 1) 
	{ 
		if (tam < tammax && tecla != 8) 
		{ 
			tam = vr.length + 1 ; 
		} 
		if (tecla == 8 ) 
		{       
			tam = tam - 1 ; 
		} 
	} 
	if (tam <= 11) 
	{ 
		if ( tam <= 2 ) 
		{ 
			campo.value = vr ; 
		} 
		if ( (tam > 2) && (tam <= 5) ) 
		{ 
			campo.value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; 
		} 
		if ( (tam >= 6) && (tam <= 8) ) 
		{ 
			campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; 
		} 
		if ( (tam >= 9) && (tam <= 11) ) 
		{ 
			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) ) 
		{ 
			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) ) 
		{ 
			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 ) ;
		} 
	}               
} 

function mascara(objForm, strField, sMask, evtKeyPress) 
{
	/*** 
	* Descrição.: formata um campo do formulário de 
	* acordo com a máscara informada... 
	* Parâmetros: - objForm (o Objeto Form) 
	* - strField (string contendo o nome 
	* do textbox) 
	* - sMask (mascara que define o 
	* formato que o dado será apresentado, 
	* usando o algarismo "9" para 
	* definir números e o símbolo "!" para 
	* qualquer caracter... 
	* - evtKeyPress (evento) 
	* Uso.......: <input type="textbox" 
	* name="xxx"..... 
	* onkeypress="return mascara(document.rcfDownload, 'str_cep', '99999-999', event);"> 
	* Observação: As máscaras podem ser representadas como os exemplos abaixo: 
	* CEP -> 99.999-999 
	* CPF -> 999.999.999-99 
	* CNPJ -> 99.999.999/9999-99 
	* Data -> 99/99/9999 
	* Tel Resid -> (99) 999-9999 
	* Tel Cel -> (99) 9999-9999 
	* Processo -> 99.999999999/999-99 
	* C/C -> 999999-! 
	* E por aí vai... 
	***/

	var i, nCount, sValue, fldLen, mskLen,bolMask, sCod, nTecla;

	if(document.all) 
	{ // Internet Explorer
		nTecla = evtKeyPress.keyCode; }
	else if(document.layers) { // Nestcape
		nTecla = evtKeyPress.which;
	}

	sValue = objForm[strField].value;

	// Limpa todos os caracteres de formatação que
	// já estiverem no campo.
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( "-", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( ".", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "/", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( "(", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( ")", "" );
	sValue = sValue.toString().replace( " ", "" );
	sValue = sValue.toString().replace( " ", "" );
	fldLen = sValue.length;
	mskLen = sMask.length;

	i = 0;
	nCount = 0;
	sCod = "";
	mskLen = fldLen;

	while (i <= mskLen) {
		bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
		bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

		if (bolMask) {
			sCod += sMask.charAt(i);
			mskLen++; }
		else {
			sCod += sValue.charAt(nCount);
			nCount++;
		}

		i++;
	}

	objForm[strField].value = sCod;

	if (nTecla != 8) { // backspace
		if (sMask.charAt(i-1) == "9") { // apenas números...
			return ((nTecla > 47) && (nTecla < 58)); } // números de 0 a 9
		else { // qualquer caracter...
			return true;
		} }
	else {
		return true;
	}
}

function minusculo(campo)
{
	eval('document.formulario.'+campo+'.value = document.formulario.'+campo+'.value.toLowerCase();');
}

function maiusculo(campo)
{
	eval('document.formulario.'+campo+'.value = document.formulario.'+campo+'.value.toLowerCase();');
}


function validaCNPJ() 
{
	CNPJ = document.formulario.txtCNPJ.value;
	erro = new String;

	if(CNPJ.length !=0)
	{
		if (CNPJ.length < 18) 
		{
			erro += "É necessario preencher corretamente o número do CNPJ! \n\n"; 
			if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-"))
			{
				if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
			}
		}
		
		//substituir os caracteres que não são números
		if(document.layers && parseInt(navigator.appVersion) == 4)
		{
			x = CNPJ.substring(0,2);
			x += CNPJ. substring (3,6);
			x += CNPJ. substring (7,10);
			x += CNPJ. substring (11,15);
			x += CNPJ. substring (16,18);
			CNPJ = x; 
		} else {
			CNPJ = CNPJ. replace (".","");
			CNPJ = CNPJ. replace (".","");
			CNPJ = CNPJ. replace ("-","");
			CNPJ = CNPJ. replace ("/","");
		}
		var nonNumbers = /\D/;
		if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n"; 
	
		var a = [];
		var b = new Number;
		var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
	
		for (i=0; i<12; i++)
		{
			a[i] = CNPJ.charAt(i);
			b += a[i] * c[i+1];
		}
		if ((x = b % 11) < 2) 
		{ 
			a[12] = 0 
		} 
		else 
		{ 
			a[12] = 11-x 
		}
		b = 0;
	
		for (y=0; y<13; y++) 
		{
			b += (a[y] * c[y]); 
		}
	
		if ((x = b % 11) < 2) 
		{ 
			a[13] = 0; 
		}else{ 
			a[13] = 11-x; 
		}
	
		if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13]))
		{
			erro +="Dígito verificador com problema!";
		}
	
		if (erro.length > 0)
		{
			alert(erro);
			document.formulario.txtCNPJ.focus();
			return false;
		} 
		return true;
	}
}

function validaCPF(){	

	CPF = document.txtCPF;
	var CPFarray = new Array(11);
	var soma;
	var resto;	
	var ok = false;
	
	// Formata o CPF e verifica se o formato é permitido
	CPF = CPF.replace('.', '');
	CPF = CPF.replace('-', '');

	alert(CPF);

	if(CPF.length != 11 || isNaN(CPF.valueOf())) 
		ok = false;

	if(	CPF == "00000000000" || CPF == "11111111111" ||
		CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
		CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
		CPF == "88888888888" || CPF == "99999999999") 
			ok = false;
	
	// Gera um Array com os digitos do CPF recebido
	for(soma = 0, i = 0 ; i < 11 ; i++)
		CPFarray[i] = CPF.charAt(i).valueOf();
	
	// Confere o 1º digito verificador	
	for(soma = 0, i = 0 ; i < 9 ; i++)
		soma +=  CPFarray[i]* (10-i)
		resto = soma % 11;
	if(resto == 0 || resto == 1)
	{ 
		if(CPFarray[9] != 0)
			ok = false; 
	}
	else if(CPFarray[9] != 11 - resto )	
		return false;
	
	// Confere o 2º digito verificador
	for(soma = 0, i = 0 ; i < 10 ; i++)
		soma +=  CPFarray[i]* (11-i)
	resto = soma % 11;	

	if(resto == 0 || resto == 1)
	{ 
		if(CPFarray[10] != 0)
			ok = false; 
	}
	else if(CPFarray[10] != 11 - resto )	
		ok = false;
	
	if(ok)
		alert('correto')
	else
		alert('parou parou!')	
	// Os 2 digitos verificadores estão
	// corretos, por isso, retorna true	
	//return true;	
}  


function isNUMB(c) 
 { 
 if((cx=c.indexOf(","))!=-1) 
  { 
  c = c.substring(0,cx)+"."+c.substring(cx+1); 
  } 
 if((parseFloat(c) / c != 1)) 
  { 
  if(parseFloat(c) * c == 0) 
   { 
   return(1); 
   } 
  else 
   { 
   return(0); 
   } 
  } 
 else 
  { 
  return(1); 
  } 
 } 

function LIMP(c) 
 { 
 while((cx=c.indexOf("-"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("/"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(","))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("."))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf("("))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(")"))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 while((cx=c.indexOf(" "))!=-1) 
  { 
  c = c.substring(0,cx)+c.substring(cx+1); 
  } 
 return(c); 
 } 

function VerifyCNPJ(CNPJ) 
 { 
 CNPJ = LIMP(CNPJ); 
 if(isNUMB(CNPJ) != 1) 
  { 
  return(0); 
  } 
 else 
  { 
  if(CNPJ == 0) 
   { 
   return(0); 
   } 
  else 
   { 
   g=CNPJ.length-2; 
   if(RealTestaCNPJ(CNPJ,g) == 1) 
    { 
    g=CNPJ.length-1; 
    if(RealTestaCNPJ(CNPJ,g) == 1) 
     { 
     return(1); 
     } 
    else 
     { 
     return(0); 
     } 
    } 
   else 
    { 
    return(0); 
    } 
   } 
  } 
 } 
function RealTestaCNPJ(CNPJ,g) 
 { 
 var VerCNPJ=0; 
 var ind=2; 
 var tam; 
 for(f=g;f>0;f--) 
  { 
  VerCNPJ+=parseInt(CNPJ.charAt(f-1))*ind; 
  if(ind>8) 
   { 
   ind=2; 
   } 
  else 
   { 
   ind++; 
   } 
  } 
  VerCNPJ%=11; 
  if(VerCNPJ==0 || VerCNPJ==1) 
   { 
   VerCNPJ=0; 
   } 
  else 
   { 
   VerCNPJ=11-VerCNPJ; 
   } 
 if(VerCNPJ!=parseInt(CNPJ.charAt(g))) 
  { 
  return(0); 
  } 
 else 
  { 
  return(1); 
  } 
 } 
  

  function FormataCGC(Formulario, Campo, TeclaPres) 
  { 
    var tecla = TeclaPres.keyCode; 
    var strCampo; 
    var vr; 
    var tam; 
    var TamanhoMaximo = 14; 
  
    eval("strCampo = document." + Formulario + "." + Campo); 
  
    vr = strCampo.value; 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace(",", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    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 (tam < TamanhoMaximo && 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) 
      { 
        strCampo.value = vr; 
      } 
       if ((tam > 2) && (tam <= 6)) 
       { 
         strCampo.value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam); 
       } 
       if ((tam >= 7) && (tam <= 9)) 
       { 
         strCampo.value = vr.substr(0, tam - 6) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam); 
      } 
       if ((tam >= 10) && (tam <= 12)) 
       { 
         strCampo.value = vr.substr(0, tam - 9) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam); 
      } 
       if ((tam >= 13) && (tam <= 14)) 
       { 
         strCampo.value = vr.substr(0, tam - 12) + '.' + vr.substr(tam - 12, 3) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam); 
      } 
       if ((tam >= 15) && (tam <= 17)) 
       { 
         strCampo.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); 
      } 
    } 
  } 


function TESTA() 
{ 
	if(document.formulario.txtCNPJ.value != '')
	{
		if(VerifyCNPJ(document.formulario.txtCNPJ.value) == 1) 
		{ 
			var x = 0;
		} 
		else 
		{ 
			alert("CNPJ não é válido!"); 
			document.formulario.txtCNPJ.focus(); 
		} 
		return; 
	}
} 

function enviaPaginacao(vAbsolutePage,vURL)
{
	formulario.action=vURL;
	formulario.vAbsolutePage.value = vAbsolutePage;
	formulario.submit();
}

function validaCombos()
{
	if(document.formulario.cmbCampeonato.value==0)
	{
		alert('Informe o campeonato!');
		document.formulario.cmbCampeonato.focus();
		return false;
	}

	if(document.formulario.cmbDivisao.value==0)
	{
		alert('Informe a divisão!');
		document.formulario.cmbDivisao.focus();
		return false;
	}

	if(document.formulario.cmbCategoria.value==0)
	{
		alert('Informe a categoria!');
		document.formulario.cmbCategoria.focus();
		return false;
	}

	return true;
}

function atribuiCombos()
{
	cdCampeonato = formulario.cmbCampeonato;
	cdDivisao = formulario.cmbDivisao;
	cdCategoria = formulario.cmbCategoria;
	cdTemporada = formulario.cmbTemporada;
}

//AJAX
// A função abaixo pega a versão mais nova do xmlhttp do IE e verifica se é Firefox. Funciona nos dois.
function createXMLHTTP() 
{
	try 
	{
        	ajax = new ActiveXObject("Microsoft.XMLHTTP");
	} 
	catch(e) 
	{
		try 
		{
			ajax = new ActiveXObject("Msxml2.XMLHTTP");
			//alert(ajax);
		}
        catch(ex) 
        {
            try 
            {
                ajax = new XMLHttpRequest();
            }
            catch(exc) 
            {
                alert("Esse browser não tem recursos para uso do Ajax");
                ajax = null;
            }
        }
        return ajax;
        }
        
        var arrSignatures = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP","Microsoft.XMLHTTP"];

        for (var i=0; i < arrSignatures.length; i++) 
        {
            try 
            {
                var oRequest = new ActiveXObject(arrSignatures[i]);
                return oRequest;
            }catch(oError){
        }
    }

    throw new Error("MSXML is not installed on your system.");
}

function ajaxFase(cdCampeonato,cdDivisao,cdCategoria,cdTemporada)
{
    // Criação do objeto XMLHTTP
    var oHTTPRequest = createXMLHTTP(); 
    // Abrindo a solicitação HTTP. O primeiro parâmetro informa o método post/get
    // O segundo parâmetro informa o arquivo solicitado que pode ser asp, php, txt, xml, etc.
    // O terceiro parametro informa que a solicitacao nao assincrona,
    // Para solicitação síncrona, o parâmetro deve ser false
	var vURL = "ajaxFase.asp?cmbCampeonato=" + cdCampeonato + "&cmbDivisao=" + cdDivisao + "&cmbCategoria=" + cdCategoria + "&cmbTemporada=" + cdTemporada
    oHTTPRequest.open("post", vURL , true);
    // Para solicitações utilizando o método post, deve ser acrescentado este cabecalho HTTP
    oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    // A função abaixo é executada sempre que o estado do objeto muda (onreadystatechange)
    oHTTPRequest.onreadystatechange=function() 
    {
        // O valor 4 significa que o objeto já completou a solicitação
        if (oHTTPRequest.readyState==4)
        {
            // Abaixo o texto é gerado no arquivo executa.asp e colocado no div
            document.all.divTitFase.innerHTML = '<font class="textoPequenoPreto"><b>Fase</b></font>';
            document.all.divFase.innerHTML = oHTTPRequest.responseText;
        }
    }
    // Abaixo é enviada a solicitação. Note que a configuração
    // do evento onreadystatechange deve ser feita antes do send.
    oHTTPRequest.send("cmbCampeonato=" + cdCampeonato + "&cmbDivisao=" + cdDivisao + "&cmbCategoria=" + cdCategoria + "&cmbTemporada=" + cdTemporada);
}

function ajaxNewUser(nmUsuario)
{
    var oHTTPRequest = createXMLHTTP(); 
    var vURL = "checkNewUser.asp?nmUsuario=" + nmUsuario
    oHTTPRequest.open("post", vURL , true);
    oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    // A função abaixo é executada sempre que o estado do objeto muda (onreadystatechange)
    oHTTPRequest.onreadystatechange=function() 
    {
        // O valor 4 significa que o objeto já completou a solicitação
        if (oHTTPRequest.readyState==4)
        {
            // Abaixo o texto é gerado no arquivo executa.asp e colocado no div
            if(oHTTPRequest.responseText!='')
            {
                document.all.divUser.innerHTML = oHTTPRequest.responseText;
                document.all.txtUsuario.value='';
                document.all.txtUsuario.focus();
            }else
            {
                document.all.divUser.innerHTML='';
            }
        }
    }
    // Abaixo é enviada a solicitação. Note que a configuração
    // do evento onreadystatechange deve ser feita antes do send.
    oHTTPRequest.send("nmUsuario=" + nmUsuario);
}

function carregaAjax()
{
	atribuiCombos();

	if (cdCampeonato.value!=0 && cdDivisao.value!=0 && cdCampeonato.value!=0 && cdCategoria.value!=0 && cdTemporada.value!=0)
	{
		ajaxFase(cdCampeonato.value,cdDivisao.value,cdCategoria.value,cdTemporada.value);
	}
}

function FormataReais(fld, milSep, decSep, e) 
{
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) 
		return true;

	key = String.fromCharCode(whichCode);  // Valor para o código da Chave
	if (strCheck.indexOf(key) == -1) 
		return false;  // Chave inválida

	len = fld.value.length;
	for(i = 0; i < len; i++)
		if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) 
			break;

		aux = '';
		for(; i < len; i++)
			if (strCheck.indexOf(fld.value.charAt(i))!=-1) 
				aux += fld.value.charAt(i);
				aux += key;
				len = aux.length;
			if (len == 0) fld.value = '';
			if (len == 1) fld.value = '0'+ decSep + '0' + aux;
			if (len == 2) fld.value = '0'+ decSep + aux;
			if (len > 2) 
			{
				aux2 = '';
				for (j = 0, i = len - 3; i >= 0; i--) 
				{
					if (j == 3) 
					{
						aux2 += milSep;
						j = 0;
					}
					aux2 += aux.charAt(i);
					j++;
				}
				fld.value = '';
				len2 = aux2.length;
				for (i = len2 - 1; i >= 0; i--)
					fld.value += aux2.charAt(i);
					fld.value += decSep + aux.substr(len - 2, len);
			}
			return false;
}

function alimentaGrid(indice,totCategoria)
{
	var nomeArbitro = eval('formulario.cmbArbitro_'+indice+'[formulario.cmbArbitro_'+indice+'.selectedIndex].label;')
	var cdArbitro = eval('formulario.cmbArbitro_'+indice+'.value;')
	myArray = new Array();	
    //alert(totCategoria);
    //return false;
	if(totCategoria==5)
	{
		if(indice==1)
		{
			myArray[0] = "10000";
			myArray[1] = "01000";
			myArray[2] = "00000";
			myArray[3] = "10000";
			myArray[4] = "01000";
		}
	
		if(indice==2)
		{
			myArray[0] = "00000";
			myArray[1] = "10000";
			myArray[2] = "01000";
			myArray[3] = "00000";
			myArray[4] = "10000";
		}
		
		if(indice==3)
		{
			myArray[0] = "01000";
			myArray[1] = "00000";
			myArray[2] = "10000";
			myArray[3] = "01000";
			myArray[4] = "00000";
		}
	
		if(indice==4)
		{
			myArray[0] = "00100";
			myArray[1] = "00010";
			myArray[2] = "00100";
			myArray[3] = "00010";
			myArray[4] = "00100";
		}
	
		if(indice==5)
		{
			myArray[0] = "00010";
			myArray[1] = "00100";
			myArray[2] = "00010";
			myArray[3] = "00100";
			myArray[4] = "00010";
		}
	}
	
	if(totCategoria==4)
	{
		if(indice==1)
		{
			myArray[0] = "00000";
			myArray[1] = "10000";
			myArray[2] = "10000";
			myArray[3] = "01000";
			myArray[4] = "00000";
		}
		
		if(indice==2)
		{
			myArray[0] = "01000";
			myArray[1] = "01000";
			myArray[2] = "00000";
			myArray[3] = "10000";
			myArray[4] = "00000";
		}

		if(indice==3)
		{
			myArray[0] = "10000";
			myArray[1] = "00000";
			myArray[2] = "01000";
			myArray[3] = "00000";
			myArray[4] = "00000";
		}
		
		if(indice==4)
		{
			myArray[0] = "00100";
			myArray[1] = "00010";
			myArray[2] = "00100";
			myArray[3] = "00010";
			myArray[4] = "00100";
		}
	
		if(indice==5)
		{
			myArray[0] = "00010";
			myArray[1] = "00100";
			myArray[2] = "00010";
			myArray[3] = "00100";
			myArray[4] = "00010";
		}		
	}

	if(totCategoria==3)
	{
		if(indice==1)
		{
			myArray[0] = "00000";
			myArray[1] = "01000";
			myArray[2] = "10000";
			myArray[3] = "00000";
			myArray[4] = "00000";
		}

		if(indice==2)
		{
			myArray[0] = "10000";
			myArray[1] = "00000";
			myArray[2] = "01000";
			myArray[3] = "00000";
			myArray[4] = "00000";
		}

		if(indice==3)
		{
			myArray[0] = "01000";
			myArray[1] = "10000";
			myArray[2] = "00000";
			myArray[3] = "00000";
			myArray[4] = "00000";
		}

		if(indice==4)
		{
			myArray[0] = "00100";
			myArray[1] = "00010";
			myArray[2] = "00100";
			myArray[3] = "00010";
			myArray[4] = "00100";
		}
	
		if(indice==5)
		{
			myArray[0] = "00010";
			myArray[1] = "00100";
			myArray[2] = "00010";
			myArray[3] = "00100";
			myArray[4] = "00010";
		}		
	}

	if(totCategoria==2)
	{
		if(indice==1)
		{
			myArray[0] = "10000";
			myArray[1] = "01000";			
		}
	}
	
	if(totCategoria==1)
	{
		if(indice==1)
		{
			myArray[0] = "10000";
		}

		if(indice==2)
		{
			myArray[0] = "01000";
		}

		if(indice==3)
		{
			myArray[0] = "00100";
		}

		if(indice==4)
		{
			myArray[0] = "00010";
		}

		if(indice==5)
		{
			myArray[0] = "00001";
		}
	}
		
	for(i=0;i<totCategoria;i++)
	{
		arrayTecnico = eval('myArray['+i+']');
		for(j=0;j<=4;j++)
		{
			var flagTecnico = eval('arrayTecnico.substr('+j+',1)');
			if(flagTecnico=="1")
			{
				eval('document.getElementById("layer_'+j+'_'+i+'").innerHTML=nomeArbitro.trim();');
				eval('document.getElementById("hdnOficial_'+j+'_'+i+'").value='+cdArbitro+'');
			}
		}
	}
}

function carregaFantasia(idCategoria)
{
	//Exemplo de uso:  onChange="carregaFantasia(this.value);"
	formulario.cmbFantasia.disabled = false;
	while(formulario.cmbFantasia.length > 0)
	{
		formulario.cmbFantasia.options.remove(0);
	}

	for (i = 1 ; i <= MaxTam ; i++) 
	{
		{
		    //alert(idCategoria +' == '+ array_cdCategoria[i]);
			if (parseInt(idCategoria) == parseInt(array_cdCategoria[i]) )
			{
				var newElem = document.createElement("OPTION");
				newElem.value = array_cdFantasia[i];
				newElem.text  = array_nmFantasia[i];
				formulario.cmbFantasia.options.add(newElem);
			}
		}
	}
}

function pictureInfo()
{
	var vURL = 'pictureInfo.asp';
	window.open(vURL,'winPopUp','width=350,height=200,toolbar=no,scrollbar=no,resizable=no,maximized=no,left=200,top=100');
}

function ajaxEscalaArbitro(cdOficial)
{
    /*

    var oHTTPRequest = createXMLHTTP(); 
    var vURL = "ajaxEscalaArbitro.asp?cdArbitro=" + nmUsuario;
    oHTTPRequest.open("post", vURL , true);
    oHTTPRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    // A função abaixo é executada sempre que o estado do objeto muda (onreadystatechange)
    oHTTPRequest.onreadystatechange=function() 
    {
        // O valor 4 significa que o objeto já completou a solicitação
        if (oHTTPRequest.readyState==4)
        {
            // Abaixo o texto é gerado no arquivo executa.asp e colocado no div
            if(oHTTPRequest.responseText!='')
            {
                document.all.divUser.innerHTML = oHTTPRequest.responseText;
                document.all.txtUsuario.value='';
                document.all.txtUsuario.focus();
            }else
            {
                document.all.divUser.innerHTML='';
            }
        }
    }
    // Abaixo é enviada a solicitação. Note que a configuração
    // do evento onreadystatechange deve ser feita antes do send.
    oHTTPRequest.send("nmUsuario=" + nmUsuario);
    */
}
