// format valores no formulario cpf


function FormataCPF(pForm,pCampo,pTamMax,pPos1,pPos2,pPosTraco,pTeclaPres)
{
	var wTecla, wVr, wTam;	
	var nerros=true;
	
    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;
		pForm[pCampo].value = toInteger(pForm[pCampo].value);
		nerros=true;
	}
	else
	{
		
		pForm[pCampo].value = toInteger(pForm[pCampo].value);
		nerros = false;
		
		
	}

	if (wTecla == 9) nerros = true;
	return nerros;
}

// format valores no formulario

function FormataValorDisplay(pForm, pCampo, pTamMax, pVirgula) 
{
	wVr = pForm[pCampo].value;
	wVr = wVr.toString().replace( "/", "" );
	wVr = wVr.toString().replace( "/", "" );
	wVr = wVr.toString().replace( ",", "" );
	wVr = wVr.toString().replace( ".", "" );
	wVr = wVr.toString().replace( ".", "" );
	wVr = wVr.toString().replace( ".", "" );
	wVr = wVr.toString().replace( ".", "" );
	wTam = wVr.length;

      if (pVirgula == 1) {
		if ( wTam <= 2 ){ 
	 		pForm[pCampo].value = wVr ; }
	 	if ( (wTam > 2) && (wTam <= 5) ){
		   pForm[pCampo].value = wVr.substr( 0, wTam - 2 ) + ',' + wVr.substr( wTam - 2, wTam ) ; }
	 	if ( (wTam >= 6) && (wTam <= 8) ){
    	   pForm[pCampo].value = wVr.substr( 0, wTam - 5 ) + '.' + wVr.substr( wTam - 5, 3 ) + ',' + wVr.substr( wTam - 2, wTam ) ; }
	 	if ( (wTam >= 9) && (wTam <= 11) ) {
	 		pForm[pCampo].value = wVr.substr( 0, wTam - 8 ) + '.' + wVr.substr( wTam - 8, 3 ) + '.' + wVr.substr( wTam - 5, 3 ) + ',' + wVr.substr( wTam - 2, wTam ) ; }
	 	if ( (wTam >= 12) && (wTam <= 14) ){
	 		pForm[pCampo].value = wVr.substr( 0, wTam - 11 ) + '.' + wVr.substr( wTam - 11, 3 ) + '.' + wVr.substr( wTam - 8, 3 ) + '.' + wVr.substr( wTam - 5, 3 ) + ',' + wVr.substr( wTam - 2, wTam ) ; }
	 	if ( (wTam >= 15) && (wTam <= 17) ){
	 		pForm[pCampo].value = wVr.substr( 0, wTam - 14 ) + '.' + wVr.substr( wTam - 14, 3 ) + '.' + wVr.substr( wTam - 11, 3 ) + '.' + wVr.substr( wTam - 8, 3 ) + '.' + wVr.substr( wTam - 5, 3 ) + ',' + wVr.substr( wTam - 2, wTam ) ;}
     } else { 
		if ( wTam <= 3 ){ 
	 		pForm[pCampo].value = wVr ; }
	 	if ( (wTam > 3) && (wTam <= 6) ){
		   pForm[pCampo].value = wVr.substr( 0, wTam - 3 ) + '.' + wVr.substr( wTam - 3, wTam ) ; }
	 	if ( (wTam >= 7) && (wTam <= 9) ) {
    	   pForm[pCampo].value = wVr.substr( 0, wTam - 6 ) + '.' + wVr.substr( wTam - 6, 3 ) + '.' + wVr.substr( wTam - 3, wTam ) ; }
	 	if ( (wTam >= 10) && (wTam <= 12) ) {
	 		pForm[pCampo].value = wVr.substr( 0, wTam - 9 ) + '.' + wVr.substr( wTam - 9, 3 ) + '.' + wVr.substr( wTam - 6, 3 ) + '.' + wVr.substr( wTam - 3, wTam ) ; }
	 	if ( (wTam >= 13) && (wTam <= 15) ){
	 		pForm[pCampo].value = wVr.substr( 0, wTam - 12 ) + '.' + wVr.substr( wTam - 12, 3 ) + '.' + wVr.substr( wTam - 9, 3 ) + '.' + wVr.substr( wTam - 6, 3 ) + '.' + wVr.substr( wTam - 3, wTam ) ; }
	 	if ( (wTam >= 16) && (wTam <= 18) ){
	 		pForm[pCampo].value = wVr.substr( 0, wTam - 15 ) + '.' + wVr.substr( wTam - 15, 3 ) + '.' + wVr.substr( wTam - 12, 3 ) + '.' + wVr.substr( wTam - 9, 3 ) + '.' + wVr.substr( wTam - 6, 3 ) + '.' + wVr.substr( wTam - 3, wTam ) ;}
	 }
}

//verifica cpf
function VCPF(pForm, pCampo)
 {
	var wVr, wVrCPF, wVrSEQ, wTam, wSoma, wSoma2, i, j, wDig1, wDig2,aux,
	    wVETOR_CC = new Array(11),
	    wVETOR_PESO = new Array(11);
 	var Erro = false;
	wVrCPF = pForm[pCampo].value;
	aux = pForm[pCampo].value;
	
  
	wVr= aux.toString().substring(0,3) + aux.toString().substring(4,7) + aux.toString().substring(8,11) + aux.toString().substring(12,14) ;     
//	wVr = wVr.toString().replace(".","");
//	wVr = wVr.toString().replace(".","");
//	wVr = wVr.toString().replace(".","");
//	wVr = wVr.toString().replace("-","");
	wTam = wVr.length + 1;

    if (wTam < 11) {
	  alert("Nº de dígitos do CPF menor que o normal. Redigite !!!");
	  pForm[pCampo].value = "";
	  pForm[pCampo].focus();
	  return false;
	}
    
	for (i = 0; i < wVr.length; i++) {
	   if (isNaN(parseInt(wVr.charAt(i))) ) {
  	     alert("O CPF contém dígitos inválidos. Corrija-o !!!");
	     pForm[pCampo].value = "";
	     pForm[pCampo].focus();
	     return false;
	   }
	}
	
	//comentado abaixo por claudio para testes
	//if (wVr == '11111111111' || wVr == '22222222222' || wVr == '33333333333' || wVr == '44444444444' || wVr == '55555555555' || 
	//    wVr == '66666666666' || wVr == '77777777777' || wVr == '88888888888' || wVr == '99999999999') {
  	//     alert("CPF Inválido. Redigite-o !!!");
	//     pForm[pCampo].value = "";
	//     pForm[pCampo].focus();
	//     return false;
    //	}
    
    wSoma = 0;
	wSoma2 = 0;
    j = 2;
    for (i = 0; i < 11; i++) {
	   wVETOR_CC[i] = wVr.charAt(i);
	   wVETOR_PESO[i] = j;
	   j++; 
	} 
    i = 0;	  
    while (i < 9)  {
	   i++;
	   if (i < 10) {
          wSoma += wVETOR_CC[9 - i] * wVETOR_PESO[i - 1]; }
	   wSoma2 += wVETOR_CC[10 - i] * wVETOR_PESO[i - 1];
	}
	wDig1 = (wSoma * 10) % 11;
	wDig2 = (wSoma2 * 10) % 11;
	if (wDig1 == 10) { 
	    wDig1 = 0;
	}	
	if (wDig2 == 10) { 
	    wDig2 = 0;
	}		
    if (parseInt(wVr.charAt(9)) != wDig1 || parseInt(wVr.charAt(10)) != wDig2) {
  	     alert("CPF com Dígito Verificador inválido. Redigite-o !!!");
//	     pForm[pCampo].value = "";
	     pForm[pCampo].focus();

	     return false;
    }	
    pForm[pCampo].value = wVrCPF;
//    pForm[pCampo + 1].value = wVrSEQ;

	return true;  // VerificaChaveAcesso(pForm, 1, 2, 3);
}



NUM_DIGITOS_CPF  = 11;
NUM_DIGITOS_CNPJ = 14;
NUM_DGT_CNPJ_BASE = 8;


String.prototype.lpad = function(pSize, pCharPad)
{
	var str = this;
	var dif = pSize - str.length;
	var ch = String(pCharPad).charAt(0);
	for (; dif>0; dif--) str = ch + str;
	return (str);
} //String.lpad


String.prototype.trim = function()
{
	return this.replace(/^\s*/, "").replace(/\s*$/, "");
} //String.trim


function unformatNumber(pNum)
{
	return String(pNum).replace(/\D/g, "").replace(/^0+/, "");
} //unformatNumber


function formatCpfCnpj(pCpfCnpj, pUseSepar, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	if (pUseSepar==null) pUseSepar = true;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var numero = unformatNumber(pCpfCnpj);

	numero = numero.lpad(maxDigitos, '0');
	if (!pUseSepar) return numero;

	if (pIsCnpj)
	{
		reCnpj = /(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})$/;
		numero = numero.replace(reCnpj, "$1.$2.$3/$4-$5");
	}
	else
	{
		reCpf  = /(\d{3})(\d{3})(\d{3})(\d{2})$/;
		numero = numero.replace(reCpf, "$1.$2.$3-$4");
	}
	return numero;
} //formatCpfCnpj


function dvCpfCnpj(pEfetivo, pIsCnpj)
{
	if (pIsCnpj==null) pIsCnpj = false;
	var i, j, k, soma, dv;
	var cicloPeso = pIsCnpj? NUM_DGT_CNPJ_BASE: NUM_DIGITOS_CPF;
	var maxDigitos = pIsCnpj? NUM_DIGITOS_CNPJ: NUM_DIGITOS_CPF;
	var calculado = formatCpfCnpj(pEfetivo, false, pIsCnpj);
	calculado = calculado.substring(2, maxDigitos);
	var result = "";

	for (j = 1; j <= 2; j++)
	{
		k = 2;
		soma = 0;
		for (i = calculado.length-1; i >= 0; i--)
		{
			soma += (calculado.charAt(i) - '0') * k;
			k = (k-1) % cicloPeso + 2;
		}
		dv = 11 - soma % 11;
		if (dv > 9) dv = 0;
		calculado += dv;
		result += dv
	}

	return result;
} //dvCpfCnpj


function isCpf(pCpf)
{
	var numero = formatCpfCnpj(pCpf, false, false);
	var base = numero.substring(0, numero.length - 2);
	var digitos = dvCpfCnpj(base, false);
	var algUnico, i;

	// Valida dígitos verificadores
	if (numero != base + digitos) return false;

	/* Não serão considerados válidos os seguintes CPF:
	 * 000.000.000-00, 111.111.111-11, 222.222.222-22, 333.333.333-33, 444.444.444-44,
	 * 555.555.555-55, 666.666.666-66, 777.777.777-77, 888.888.888-88, 999.999.999-99.
	 */
	algUnico = true;
	for (i=1; i<NUM_DIGITOS_CPF; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	return (!algUnico);
} //isCpf


function isCnpj(pCnpj)
{
	var numero = formatCpfCnpj(pCnpj, false, true);
	var base = numero.substring(0, NUM_DGT_CNPJ_BASE);
	var ordem = numero.substring(NUM_DGT_CNPJ_BASE, 12);
	var digitos = dvCpfCnpj(base + ordem, true);
	var algUnico;

	// Valida dígitos verificadores
	if (numero != base + ordem + digitos) return false;

	/* Não serão considerados válidos os CNPJ com os seguintes números BÁSICOS:
	 * 11.111.111, 22.222.222, 33.333.333, 44.444.444, 55.555.555,
	 * 66.666.666, 77.777.777, 88.888.888, 99.999.999.
	 */
	algUnico = numero.charAt(0) != '0';
	for (i=1; i<NUM_DGT_CNPJ_BASE; i++)
	{
		algUnico = algUnico && (numero.charAt(i-1) == numero.charAt(i));
	}
	if (algUnico) return false;

	if (ordem == "0000") return false;
	return (base == "00000000"
		|| parseInt(ordem, 10) <= 300 || base.substring(0, 3) != "000");
} //isCnpj


function isCpfCnpj(pCpfCnpj)
{
	var numero = pCpfCnpj.replace(/\D/g, "");
	if (numero.length > NUM_DIGITOS_CPF)
		return isCnpj(pCpfCnpj)
	else
		return isCpf(pCpfCnpj);
} //isCpfCnpj



function FormataCGC(pForm,pCampo,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 < 14 && 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 > 2 && wTam <= 14) {
		   wVr = wVr.substr(0, wTam - 2) + '-' + wVr.substr(wTam - 2, wTam);
		}
		if ( wTam == 14){
	       wVr = wVr.substr( 0, wTam - 12 ) + '.' + wVr.substr(wTam - 12, 3) + '.' + wVr.substr(wTam - 9, 3) + "/" + wVr.substr(wTam - 6, wTam);
		}
		pForm[pCampo].value = wVr;
	
	}

}


function VCGC(pForm, pCampo)
{ 
//= pForm[pCampo].value.toString().substring(0,15)
// pForm[pCampo].value.toString().substring(16, 2);
	var Numero; 
	var Digito; 
	var CNPJ ,aux = pForm[pCampo].value

	//Numero = Numero.replace(".","");
	//Numero = Numero.replace(".","");
	//Numero = Numero.replace("/","");
	//Numero = Numero.replace("-","");

	Numero = aux.toString().substring(0,2) + aux.toString().substring(3,6) + aux.toString().substring(7,10) + aux.toString().substring(11,15);
	CNPJ= aux.toString().substring(0,2) + aux.toString().substring(3,6) + aux.toString().substring(7,10) + aux.toString().substring(11,15) + aux.toString().substring(16,18);
	Digito=aux.toString().substring(16,18);

//	CNPJ = CNPJ.replace(".","");
//	CNPJ = CNPJ.replace(".","");
//	CNPJ = CNPJ.replace("/","");
//	CNPJ = CNPJ.replace("-","");

	var CGC = Numero;
	var peso1 = '543298765432';
	var peso2 = '654329876543';
	var soma1 = 0;
	var soma2 = 0;
	var digito1 = 0;
	var digito2 = 0;
          
	 if (CNPJ == '00000000000000'){
	 	alert("CNPJ Inválido. Redigite!");
		pForm[pCampo].value = "";
	  	pForm[pCampo].focus();
	  	return false;
	 } 
	 
	 if ((Numero.length + Digito.length + 1 > 1) && (Numero.length + Digito.length + 1 < 15)) 
	 {
	  alert("Nº de dígitos do CNPJ menor que o normal. Redigite !!!");
	  pForm[pCampo].value = "";
	  pForm[pCampo].focus();
	  return false;
	 }	
 
 	if (Numero.length + Digito.length + 1 > 1){
 		 
		 for (i = 1; i < 12 - Numero.length + 1; i++) 
		 {
		  CGC = eval("'" + 0 + CGC + "'")
		 }
		    
		 for (i = 1; i < CGC.length+1; i++) 
		 {
		  soma1 += CGC.substring(i, i-1) * peso1.substring(i, i-1);
		 } 
		
		 soma1 %= 11;
		
		 if (soma1  < 2) 
		 {
		  digito1 = 0;
		 }
		 else 
		 {
		  digito1 = 11 - soma1; 
		 }
		
		 for (i = 1; i < CGC.length+1; i++) 
		 {
		  soma2 += CGC.substring(i, i-1) * peso2.substring(i, i-1);
		 } 
		 
		 soma2 += digito1 * 2 
		 soma2 %= 11;
		
		 if (soma2  < 2) 
		 {
		  digito2 = 0;
		 }
		 else 
		 {
		  digito2 = 11 - soma2; 
		 }
		
		 if (eval("'" + digito1 + digito2 + "'") != Digito)
		 {
		 // alert("CNPJ inválido. Redigite !!!");
//		  pForm[pCampo].value = "";
//		  pForm[pCampo].focus();
		  return false;
		 }
		 else 
		 {
		  return true;
		 }
	}
}

// Formata Data
function FormataData(pForm, pCampo,pTeclaPres) {
	var wTecla = pTeclaPres.keyCode;
	wVr = pForm[pCampo].value;
	wVr = wVr.replace( ".", "" );
	wVr = wVr.replace( "/", "" );
	wVr = wVr.replace( "/", "" );
	wTam = wVr.length + 1;

	if ( wTecla != 9 && wTecla != 8 ){
		if ( wTam > 2 && wTam < 5 )
			pForm[pCampo].value = wVr.substr( 0, wTam - 2  ) + '/' + wVr.substr( wTam - 2, wTam );
		if ( wTam >= 5 && wTam <= 10 )
			pForm[pCampo].value = wVr.substr( 0, 2 ) + '/' + wVr.substr( 2, 2 ) + '/' + wVr.substr( 4, 4 ); 
	}			
}


//Formatar Telefone
function FormataTEL(pForm, pCampo, pTeclaPres) {
	var wTecla = pTeclaPres.keyCode;
	var wTam;
	wVr = pForm[pCampo].value;
	wVr = wVr.replace( ".", "" );
//	wVr = wVr.replace( "(", "" );
//	wVr = wVr.replace( ")", "" );
	wVr = wVr.replace( "-", "" );
	wVr = wVr.replace( "/", "" );
	wTam = wVr.length + 1;

	if ( wTecla != 9 && wTecla != 8 ){
		if ( wTam > 0 && wTam < 2 ) 
			pForm[pCampo].value = '(' ;
		if ( wTam > 3 && wTam < 5 ) 
			pForm[pCampo].value = wVr.substr( 0, 8 ) + ')' + wVr.substr( 8, 4 );
		if ( wTam > 7 && wTam < 9 ) 
			pForm[pCampo].value = wVr.substr( 0, 8 ) + '-' + wVr.substr( 8, 4 );
		if ( wTam > 11)
			pForm[pCampo].value = wVr.substr( 0, 8 ) + '-' + wVr.substr( 8, 4 ); 
	}			
}

// 
function CampoUpcase (pForm, pCampo, pOperacao) {
   if (pOperacao == "+") {
     pForm[pCampo].value = pForm[pCampo].value.toUpperCase();
   } else {
     pForm[pCampo].value = pForm[pCampo].value.toLowerCase();
   }
}

//
function FormataCEP(pForm, pCampo, pTeclaPres) {
	var wTecla = pTeclaPres.keyCode;
	var wTam;
	wVr = pForm[pCampo].value;
	wVr = wVr.replace( ".", "" );
	wVr = wVr.replace( "-", "" );
	wVr = wVr.replace( "/", "" );
	wTam = wVr.length + 1;

	if ( wTecla != 9 && wTecla != 8 ){
		if ( wTam > 2 && wTam < 6 )
			pForm[pCampo].value = wVr.substr( 0, wTam - 2  ) + '.' + wVr.substr( wTam - 2, wTam );
		if ( wTam >= 6 && wTam <= 9 )
			pForm[pCampo].value = wVr.substr( 0, 2 ) + '.' + wVr.substr( 2, 3 ) + '-' + wVr.substr( 5, 3 ); 
	}			
}



//email
function VerificaEmail(pcampo)  { 

	  pcampo.value = pcampo.value.toLowerCase();					
      parametro = pcampo.value;								
	  teste_parametro = "false"; 
	  tamanho_parametro = parametro.length;
	  aposicao = 0; //posicao @
	  pposicao = 0; //poiscao ponto
	  narrobas = 0; // numero de @
	  for (i = 0; i < tamanho_parametro; i++) { /*verifica se existe espaco em branco */
		   if (parametro.charAt(i) == "@") {
		  	     narrobas = narrobas + 1
				 aposicao = i;
		   }
		   if (parametro.charAt(i) == ".") {
		  	     
				 pposicao = i;
		   }
		   
	   }
	   if (aposicao > 0 && aposicao+1 < pposicao && narrobas<2){
     	   teste_parametro = "true"; 
	   }	   
      	  
	  for (i = 0; i < tamanho_parametro; i++) { /*verifica se existe espaco em branco */
		   if (parametro.charAt(i) == " ") {
		  	     teste_parametro = "false"; 
		   }
	   }
		
	   if (tamanho_parametro < 5) {
	   	  teste_parametro = "false"; /*tamanho minimo*/
	   }
	  
			
	   if (parametro.charAt(0) == " " || parametro.charAt(1) == " ") { /*Primeiros chars em branco */
			  teste_parametro = "false"; 
	   }
				
		
		if (teste_parametro == "false" && tamanho_parametro != 0 ) { /*Existe algum problema no preenchiento do nome */
			alert("E-mail inválido!");
			pcampo.focus();
			return false;
		} else {
			return true;
		}
}



function LTrim(str)
/***
        PURPOSE: Remove leading blanks from our string.
        IN: str - the string we want to LTrim

        RETVAL: An LTrimmed string!
***/
{
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(0)) != -1) {
            // We have a string with leading blank(s)...

            var j=0, i = s.length;

            // Iterate from the far left of string until we
            // don't have any more whitespace...
            while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
                j++;


            // Get the substring from the first non-whitespace
            // character to the end of the string...
            s = s.substring(j, i);
        }

        return s;
}


//RTrim(string) : Returns a copy of a string without trailing spaces.
//==================================================================
function RTrim(str)
/***
        PURPOSE: Remove trailing blanks from our string.
        IN: str - the string we want to RTrim

        RETVAL: An RTrimmed string!
***/
{
        // We don't want to trip JUST spaces, but also tabs,
        // line feeds, etc.  Add anything else you want to
        // "trim" here in Whitespace
        var whitespace = new String(" \t\n\r");

        var s = new String(str);

        if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
            // We have a string with trailing blank(s)...

            var i = s.length - 1;       // Get length of string

            // Iterate from the far right of string until we
            // don't have any more whitespace...
            while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
                i--;


            // Get the substring from the front of the string to
            // where the last non-whitespace character is...
            s = s.substring(0, i+1);
        }

        return s;
}




//Trim(string) : Returns a copy of a string without leading or
//               trailing spaces
//=============================================================
function Trim(str)
/***
        PURPOSE: Remove trailing and leading blanks from our string.
        IN: str - the string we want to Trim

        RETVAL: A Trimmed string!
***/
{
        return RTrim(LTrim(str));
}


function toInteger(checkString)
{
 var newString = "";    
 var count = 0;         
    for (i = 0; i < checkString.length; i++) {
        ch = checkString.substring(i, i+1);
        if (ch >= "0" && ch <= "9") 
        {
            newString += ch;
        }
        else
        {
         if (ch == "-") newString += ch;
         if (ch == ".") newString += ch;
         if (ch == "/") newString += ch;
        }
    }
    
    return newString; //checkString;
}


//function so_numero(pForm,pCampo,pTeclaPres)
//{
// var wTecla 
//  var nerro = true;
//    wTecla =  pTeclaPres.keyCode;
//	if ( wTecla == 8 || wTecla == 88 || wTecla >= 48 && wTecla <= 57 || wTecla >= 96 && wTecla <= 105)
//	{
//		pForm[pCampo].value = toInteger(pForm[pCampo].value);
//		nerro = true;
//	}
//	else
//	{
//		pForm[pCampo].value = toInteger(pForm[pCampo].value);
//		nerro = false;
//	}
// return nerro;	
//}


var keyCodigo = 0;

function soNumeroPress(evento){

	if (keyCodigo == 0){
	
		keyCodigo = evento.keyCode;
	
	}
	
	if ((keyCodigo == 8 || keyCodigo == 13 || keyCodigo == 9 || keyCodigo == 71 || keyCodigo == 46 || keyCodigo  == 37  || keyCodigo  == 39) || (keyCodigo >= 48 && keyCodigo <= 57) || (keyCodigo >= 96 && keyCodigo <= 105)) 
	{
		VerifiqueTAB=true; 

		return true;

	} else {

		return false;

	}


}


function soNumeroDown(evento){


	keyCodigo = evento.keyCode;

	if ((keyCodigo == 8 || keyCodigo == 13 || keyCodigo == 9 || keyCodigo == 46) || (keyCodigo >= 48 && keyCodigo <= 57) || (keyCodigo >= 96 && keyCodigo <= 105)){
		VerifiqueTAB=true; 

		return true;

	} else {

		return false;

	}

}




VerifiqueTAB=true;
function Mostra(quem, tammax) {
	if ( (quem.value.length == tammax) && (VerifiqueTAB) ) {
		var i=0,j=0, indice=-1;
		for (i=0; i<document.forms.length; i++) {
			for (j=0; j<document.forms[i].elements.length; j++) {
				if (document.forms[i].elements[j].name == quem.name) {
					indice=i;
					break;
				}
			}
			if (indice != -1)
		         break;
		}
		for (i=0; i<=document.forms[indice].elements.length; i++) {
			if (document.forms[indice].elements[i].name == quem.name) {
				while ( (document.forms[indice].elements[(i+1)].type == "hidden") &&
						(i < document.forms[indice].elements.length) ) {
							i++;
				}
				document.forms[indice].elements[(i+1)].focus();
				VerifiqueTAB=false;
				break;
			}
		}
	}
}

//<!-- -->

function PararTAB() 
{ 
   VerifiqueTAB=false; 
} 

//<!-- -->

function ChecarTAB(evento) 
{ 

   VerifiqueTAB=true; 
   		
   keyCodigo = evento.keyCode;

   if ((keyCodigo == 8 || keyCodigo == 13 || keyCodigo == 9 || keyCodigo == 71) || (keyCodigo >= 48 && keyCodigo <= 57) || (keyCodigo >= 96 && keyCodigo <= 105))
   {
	return true;
    } else 
	
    {
	return false;
	}

} 

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}


function limpacampo(campo,frase) {
		campo.value = frase;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function verifica_email_esqueci() {
  a = document.form1;
  err = '';
   texto = a.email.value;
	if (texto.length < 1) 
	 { 
		err+='\n- Entre com o seu e-mail.';
		erro=true;
 	 }
	else
	 { 
		//Validando o e-mail
		var str = texto; // email string
		var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
		if (!reg1.test(str) && reg2.test(str)) // if syntax is valid
		 {  texto=''  }
		else
		 { 
	 		err+='\n- O seu endereço de e-mail é inválido.';
			erro=true; 
		 }
	 }
	 
  if (err.length > 0) {
      alert('Por Favor, verifique os seguintes erros: '+err);
  } else {
      a.submit();
  } 
}

function submitenter(myfield,e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;

if (keycode == 13)
   {
   myfield.form.submit();
   return false;
   }
else
   return true;
}



function muda_frame ( nid ) {
	var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1];
	var FFextraHeight=getFFVersion>=0.1? 16 : 0; //extra height in px to add to iframe in FireFox 1.0+ browsers
	var currentfr=document.getElementById(nid);
	if (currentfr && !window.opera) {
		currentfr.style.display="block";
	}
	if (currentfr.contentDocument && currentfr.contentDocument.body.offsetHeight) { //ns6 syntax
		currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight; 
	} else if (currentfr.Document && currentfr.Document.body.scrollHeight) { //ie5+ syntax
		currentfr.height = currentfr.Document.body.scrollHeight;
	}
}

function makeCep() {
	  a = document.formCep;
	  err = '';
	  if (a.cep1.value.length == 0 || a.cep2.value.length == 0 ){ 
		err+='\n- Digite seu CEP corretamente.';
		erro=true;
	  }
	  if (err.length > 0) {
		  alert('Por Favor, verifique o(s) seguinte(s) erro(s): '+err);
	  } else {
		  a.submit();
	  }
}

function Contato() {
  a = document.formContato;
  err = '';
	if (a.nome.value == ''){ 
		err+='\n- Digite seu nome.';
		erro=true;
	}
    texto = a.email.value;
	if (texto.length < 1) 
	 { 
		err+='\n- Digite seu e-mail.';
		erro=true;
 	 }
	else
	 { 
		//Validando o e-mail
		var str = texto; // email string
		var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
		if (!reg1.test(str) && reg2.test(str)) // if syntax is valid
		 {  texto=''  }
		else
		 { 
	 		err+='\n- O seu endereço de e-mail é inválido.';
			erro=true; 
		 }
	 }
	if (a.ddd.value.length < 1 || a.telefone.value.length < 1){ 
		err+='\n- Digite seu telefone.';
		erro=true;
	}
	if (a.cidade.value.length < 1){ 
		err+='\n- Digite sua cidade.';
		erro=true;
	}
	if (a.mensagem.value.length < 1){ 
		err+='\n- Digite sua mensagem.';
		erro=true;
	}

	  if (err.length > 0) {
		  alert('Por Favor, verifique os seguintes erros: '+err);
	  } else {
		  a.submit();
	  } 
}

function limpar_contato() {
	var a = document.formContato;
	
	a.nome.value = '';
	a.email.value = '';
	a.ddd.value = '';
	a.telefone.value = '';
	a.cidade.value = '';
	a.mensagem.value = '';
	
}


function cadastro() {
  a = document.formCad;
  err = '';
	var temSelec;
	if(a.pessoa[0].checked)
	{
		if (a.nome.value.length < 1){ 
			err+='\n- Digite seu nome.';
			erro=true;
		}
		if (a.cpf.value.length < 1){ 
			err+='\n- Digite seu CPF.';
			erro=true;
		} else {
			if (isCpf(a.cpf.value)==false){ 
				err+='\n- CPF Inválido.';
				erro=true;
			}
		}
		var temSelec;
		for(i=0; i<a.sexo.length; i++) {
			if(a.sexo[i].checked) {
				temSelec=true;
			}
		}
		if(!temSelec) {
			err+='\n- Selecione o sexo.';
			erro=true;
		}
		
		if (a.dia.value.length < 1 || a.mes.value.length < 1 || a.ano.value.length < 1){ 
			err+='\n- Digite sua data de nascimento.';
			erro=true;
		}
	}
	else{
		if (a.razaoSocial.value.length < 1){ 
			err+='\n- Digite sua Razão Social.';
			erro=true;
		}
		if (a.cnpj.value.length < 1){ 
			err+='\n- Digite seu CNPJ.';
			erro=true;
		} else {
			if (isCnpj(a.cnpj.value)==false){ 
				err+='\n- CNPJ Inválido.';
				erro=true;
			}
		}
	}
	

	if (a.ddd_res.value.length < 1 || a.tel_res.value.length < 1){ 
		err+='\n- Digite seu telefone residencial.';
		erro=true;
	}
	if (a.ddd_cel.value.length < 1 || a.cel.value.length < 1){ 
		err+='\n- Digite seu celular.';
		erro=true;
	}
	
	texto = a.email.value;
	if (texto.length < 1) 
	 { 
		err+='\n- Digite seu e-mail.';
		erro=true;
	 }
	else
	 { 
		//Validando o e-mail
		var str = texto; // email string
		var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
		if (!reg1.test(str) && reg2.test(str)) // if syntax is valid
		 {  texto=''  
		 	if(a.email.value != a.email2.value)
			{
				err+='\n- Confirmação de e-mail inválido.';
				erro=true; 
			}
		 }
		else
		 { 
			err+='\n- O seu endereço de e-mail é inválido.';
			erro=true; 
		 }
	 }
	if (a.senha.value.length < 1){ 
		err+='\n- Digite sua senha.';
		erro=true;
	}
	if (a.confirma.value.length < 1){ 
		err+='\n- Digite a confirmação da senha.';
		erro=true;
	}
	if (a.confirma.value != a.senha.value){ 
		err+='\n- A confirmação de senha não está correta.';
		erro=true;
	}

	if (a.endereco.value.length < 1){ 
		err+='\n- Digite seu endereço.';
		erro=true;
	}
	if (a.numero.value.length < 1){ 
		err+='\n- Digite seu número.';
		erro=true;
	}
	if (a.bairro.value.length < 1){ 
		err+='\n- Digite seu número.';
		erro=true;
	}
	if (a.cep1.value.length < 1 || a.cep2.value.length < 1){ 
		err+='\n- Digite seu CEP.';
		erro=true;
	}
	if (a.cidade.value.length < 1){ 
		err+='\n- Digite sua cidade.';
		erro=true;
	}
	if (a.estado.value.length < 1){ 
		err+='\n- Selecione seu estado.';
		erro=true;
	}
	if (a.pais.value.length < 1){ 
		err+='\n- Digite seu pais.';
		erro=true;
	}
	if (a.camera.value.length < 1){ 
		err+='\n- Selecione como Conheceu a Revelaweb.';
		erro=true;
	}
	if (!a.aceito.checked){ 
		err+='\n- É preciso aceitar o contrato para continuar.';
		erro=true;
	}

	  if (err.length > 0) {
		  alert('Por Favor, verifique os seguintes erros: '+err);
	  } else {
		  var sexoS = "masculino";
		  if(a.sexo[1].checked)
		  	sexoS = "feminino";
			
		  var pessoa = "fisica";
		  if(a.pessoa[1].checked)
		  	pessoa = "juridica";
		
		ajax('inc/cadastro.php','erroCadastro','POST','nome='+encodeURI(a.nome.value)+'&cpf='+encodeURI(a.cpf.value)+'&sexo='+encodeURI(sexoS)+'&dia='+encodeURI(a.dia.value)+'&mes='+encodeURI(a.mes.value)+'&ano='+encodeURI(a.ano.value)+'&ddd_res='+encodeURI(a.ddd_res.value)+'&tel_res='+encodeURI(a.tel_res.value)+'&ddd_cel='+encodeURI(a.ddd_cel.value)+'&cel='+encodeURI(a.cel.value)+'&email='+encodeURI(a.email.value)+'&senha='+encodeURI(a.senha.value)+'&endereco='+encodeURI(a.endereco.value)+'&numero='+encodeURI(a.numero.value)+'&bairro='+encodeURI(a.bairro.value)+'&cep1='+encodeURI(a.cep1.value)+'&cep2='+encodeURI(a.cep2.value)+'&cidade='+encodeURI(a.cidade.value)+'&estado='+encodeURI(a.estado.value)+'&pais='+encodeURI(a.pais.value)+'&camera='+encodeURI(a.camera.value)+'&pessoa='+encodeURI(pessoa)+"&complemento="+encodeURI(a.complemento.value)+"&cnpj="+encodeURI(a.cnpj.value)+'&razaoSocial='+encodeURI(a.razaoSocial.value));
	  } 
}



function alterar() {
   a = document.formCad;
  err = '';
	var temSelec;
	
	if(a.razaoSocial.value == '')
	{
		var temSelec;
		for(i=0; i<a.sexo.length; i++) {
			if(a.sexo[i].checked) {
				temSelec=true;
			}
		}
		if(!temSelec) {
			err+='\n- Selecione o sexo.';
			erro=true;
		}
		if (a.dia.value.length < 1 || a.mes.value.length < 1 || a.ano.value.length < 1){ 
			err+='\n- Digite sua data de nascimento.';
			erro=true;
		}
	}
	if (a.ddd_res.value.length < 1 || a.tel_res.value.length < 1){ 
		err+='\n- Digite seu telefone residencial.';
		erro=true;
	}
	if (a.ddd_cel.value.length < 1 || a.cel.value.length < 1){ 
		err+='\n- Digite seu celular.';
		erro=true;
	}
	
	texto = a.email.value;
	if (texto.length < 1) 
	 { 
		err+='\n- Digite seu e-mail.';
		erro=true;
	 }
	else
	 { 
		//Validando o e-mail
		var str = texto; // email string
		var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
		if (!reg1.test(str) && reg2.test(str)) // if syntax is valid
		 {  texto=''  
		 	if(a.email.value != a.email2.value)
			{
				err+='\n- Confirmação de e-mail inválido.';
				erro=true; 
			}
		 }
		else
		 { 
			err+='\n- O seu endereço de e-mail é inválido.';
			erro=true; 
		 }
	 }
	if (a.senha.value.length < 1){ 
		err+='\n- Digite sua senha.';
		erro=true;
	}
	if (a.confirma.value.length < 1){ 
		err+='\n- Digite a confirmação da senha.';
		erro=true;
	}
	if (a.confirma.value != a.senha.value){ 
		err+='\n- A confirmação de senha não está correta.';
		erro=true;
	}

	if (a.endereco.value.length < 1){ 
		err+='\n- Digite seu endereço.';
		erro=true;
	}
	if (a.numero.value.length < 1){ 
		err+='\n- Digite seu número.';
		erro=true;
	}
	if (a.bairro.value.length < 1){ 
		err+='\n- Digite seu número.';
		erro=true;
	}
	if (a.cep1.value.length < 1 || a.cep2.value.length < 1){ 
		err+='\n- Digite seu CEP.';
		erro=true;
	}
	if (a.cidade.value.length < 1){ 
		err+='\n- Digite sua cidade.';
		erro=true;
	}
	if (a.estado.value.length < 1){ 
		err+='\n- Selecione seu estado.';
		erro=true;
	}
	if (a.pais.value.length < 1){ 
		err+='\n- Digite seu pais.';
		erro=true;
	}

	  if (err.length > 0) {
		  alert('Por Favor, verifique os seguintes erros: '+err);
	  } else {
		  var sexoS = "masculino";
		  if(a.sexo[1].checked)
		  	sexoS = "feminino";
			
		  ajax('inc/alterar.php','erroCadastro','POST','nome='+encodeURI(a.nome.value)+'&cpf='+encodeURI(a.cpf.value)+'&sexo='+encodeURI(sexoS)+'&dia='+encodeURI(a.dia.value)+'&mes='+encodeURI(a.mes.value)+'&ano='+encodeURI(a.ano.value)+'&ddd_res='+encodeURI(a.ddd_res.value)+'&tel_res='+encodeURI(a.tel_res.value)+'&ddd_cel='+encodeURI(a.ddd_cel.value)+'&cel='+encodeURI(a.cel.value)+'&email='+encodeURI(a.email.value)+'&senha='+encodeURI(a.senha.value)+'&endereco='+encodeURI(a.endereco.value)+'&numero='+encodeURI(a.numero.value)+'&bairro='+encodeURI(a.bairro.value)+'&cep1='+encodeURI(a.cep1.value)+'&cep2='+encodeURI(a.cep2.value)+'&cidade='+encodeURI(a.cidade.value)+'&estado='+encodeURI(a.estado.value)+'&pais='+encodeURI(a.pais.value)+"&complemento="+encodeURI(a.complemento.value));
	  } 
}


function historico_por_pedido() {

		a = document.formHistorico;
		err = '';
		if (a.num_ped.value == ''){ 
		  err+='\n- Digite o número do pedido.';
		  erro=true;
		}
		if (err.length > 0) {
		  alert('Por Favor, verifique os seguintes erros: '+err);
		  a.num_ped.focus();
		} else {
		  a.submit();
		} 

}

function historico_por_data() {

		a = document.formHistorico;
		err = '';
		if (a.data.value == ''){ 
		  err+='\n- Selecione a data da pesquisa.';
		  erro=true;
		}
		if (err.length > 0) {
		  alert('Por Favor, verifique os seguintes erros: '+err);
		} else {
		  a.submit();
		} 

}

function trocar_email() {  
  a = document.form1;
  err = '';
  texto = a.email_antigo.value;
	if (texto.length < 1) 
	 { 
		err+='\n- Entre com o seu antigo e-mail.';
		erro=true;
 	 }
	else
	 { 
		//Validando o e-mail
		var str = texto; // email string
		var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
		if (!reg1.test(str) && reg2.test(str)) // if syntax is valid
		 {  texto=''  }
		else
		 { 
	 		err+='\n- O seu antigo endereço de e-mail é inválido.';
			erro=true; 
		 }
	 }
	 
	   texto = a.email_novo.value;
	if (texto.length < 1) 
	 { 
		err+='\n- Entre com o seu novo e-mail.';
		erro=true;
 	 }
	else
	 { 
		//Validando o e-mail
		var str = texto; // email string
		var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
		if (!reg1.test(str) && reg2.test(str)) // if syntax is valid
		 {  texto=''  }
		else
		 { 
	 		err+='\n- O seu novo endereço de e-mail é inválido.';
			erro=true; 
		 }
	 }
	 if (a.senhax.value.length < 1) 
	 { 
		err+='\n- Entre com a sua senha.';
		erro=true;
 	 }
	 
  if (err.length > 0) {
      alert('Por Favor, verifique os seguintes erros: '+err);
  } else {
      a.submit();
  } 
}

function trocar_senha() {  
  a = document.formTrocarSenha;
  err = '';
	 if (a.senha_atual.value.length < 1) 
	 { 
		err+='\n- Digite sua senha atual.';
		erro=true;
 	 }
	 if (a.senha_nova.value.length < 1) 
	 { 
		err+='\n- Digite sua nova senha.';
		erro=true;
 	 }
	 if (a.confirma.value.length < 1){ 
		err+='\n- Digite a confirmação da senha.';
		erro=true;
	}
	if (a.confirma.value != a.senha_nova.value){ 
		err+='\n- A confirmação de senha não está correta.';
		erro=true;
	}
	 
  if (err.length > 0) {
      alert('Por Favor, verifique os seguintes erros: '+err);
  } else {
      a.submit();
  } 
}


function alterar_entrega() {
	  a = document.formEditEntrega;
	  err = true;
	  msg = "";
	  if(a.contato_nome.value.length == 0){
		  err = false;
		  msg += "\n- Nome do Contato.";
	  }
	  if((a.ddd_res.value.length == 0)||(a.tel_res.value.length == 0)){
		  err = false;
		  msg += "\n- Telefone residencial.";
	  }
	  if(a.endereco.value.length == 0){
		  err = false;
		  msg += "\n- Endereco.";
	  }
	  if(a.numero.value.length == 0){
		  err = false;
		  msg += "\n- Número.";
	  }
	  if(a.bairro.value.length == 0){
		  err = false;
		  msg += "\n- Bairro.";
	  }
	  if(a.cidade.value.length == 0){
		  err = false;
		  msg += "\n- Cidade.";
	  }
	  if(a.estado.value.length == 0){
		  err = false;
		  msg += "\n- Estado.";
	  }
	  if(a.pais.value.length == 0){
		  err = false;
		  msg += "\n- País.";
	  }
	  if((a.cep1.value.length == 0) || (a.cep2.value.length == 0)){
		  err = false;
		  msg += "\n- Digite corretamente seu cep.";
	  }
	  if(err == false){
		  alert("Por Favor, verifique as seguintes informações: \n" + msg);
	  } else {
		  a.submit();
	  }
}

function vaiesp()  {
	document.formEspecial.action = 'especial.php';
	document.formEspecial.target = 'especial';
	document.formEspecial.submit();
}

function atualiza_papel() {
	document.form4.submit();
}

function xofera_font(font,size) {

	parent.document.formEspecial.size.value = size;
	parent.document.formEspecial.font.value = font;

}

function xofera_carta(id,preco,media,descricao) {

	parent.document.formEspecial.quantidade.value = 1;
	parent.document.formEspecial.descricao.value = descricao;
	parent.document.formEspecial.cartao.value = id;
	parent.document.formEspecial.preco.value = preco;
	parent.document.formEspecial.media.value = media;

}

function ver_cartao() {

	  a = document.formEspecial;  
	  err = true;
	  msg = "";
	  if(a.font.value.length == 0 || a.size.value.length == 0){
		  err = false;
		  msg += "\n- Selecione uma font.";
	  }
	  if(a.cartao.value.length == 0 || a.media.value.length == 0){
		  err = false;
		  msg += "\n- Selecione um cartão.";
	  }
	  if(a.mensagem.value.length == 0){
		  err = false;
		  msg += "\n- Digite a mensagem do cartão.";
	  }
	  		
	  campo = removeChar(a.mensagem.value);
	  
	  if(err == false) {
		  alert("Por Favor, verifique os seguintes problemas: \n" + msg);
	  } else {
		  MM_openBrWindow('bt/cartao.php?mensagem='+campo+'&media='+a.media.value+'&font='+a.font.value+'&size='+a.size.value,'','scrollbars=no,width=620,height=423');
	  }
}

function comprar_cartao() {

	  a = document.formEspecial;  
	  err = true;
	  msg = "";
	  if(a.font.value.length == 0 || a.size.value.length == 0){
		  err = false;
		  msg += "\n- Selecione uma font.";
	  }
	  if(a.cartao.value.length == 0 || a.media.value.length == 0){
		  err = false;
		  msg += "\n- Selecione um cartão.";
	  }
	  if(a.mensagem.value.length == 0){
		  err = false;
		  msg += "\n- Digite a mensagem do cartão.";
	  }
	  		
	  campo = removeChar(a.mensagem.value);
	  
	  if(err == false){
		  alert("Por Favor, verifique os seguintes problemas: \n" + msg);
	  } else {
		 a.submit();
	  }

}

function removeChar(input) {
	var output = "";
	for (var i = 0; i < input.length; i++) {
		if ((input.charCodeAt(i) == 13) && (input.charCodeAt(i + 1) == 10)) {
			i++;
			output += "<br>";
		} else {
			output += input.charAt(i);
	   }
	}
		return output;
}
	
	String.prototype.fullTrim = function()
	{
	   return this.replace(/\s+/g," ").replace(/^\s*([\s\S]*\S+)\s*$|^\s*$/,"$1");
	}


function mensagemlen() {
	  if (document.formEspecial.mensagem.value.length > 500) {
		 document.formEspecial.mensagem.value = document.formEspecial.mensagem.value.substring(0, 500)
		 return false;
	  } else {
		 document.formEspecial.tamanho.value=document.formEspecial.mensagem.value.length
		 return true;
	  }
}

function verificador_anti_popup() {
	
	if (!window.open('pop.php','popimaginary','height=1,width=1,top=9000,left=9000,scrollbars=no')) {
		document.all('errPopup').style.display = 'inline';
	} else {
		window.close('popimaginary');
		document.all('errPopup').style.display = 'none';
	}	
	
}


function finalizar_pedido(frete,acao){	
		a = document.finaliza;
		a.action = acao;
			
		if(frete.length == 0){
			alert('Por favor, Para finalizar o pedido, Selecione um serviço de entrega!');
		} else {
			a.submit();
		}
	
}

function login_celebration() {
	
	a = document.celebration;
	
	if(a.pwd.value == "" || a.pwd.value == "sua senha") {
		alert('REVELAWEB CELEBRATION\n\n\nPor favor, preencha sua senha para entrar.\n\n');
		a.pwd.focus();
	} else {
		a.submit();
	}
}


function Recover() {
  a = document.formContato;
  err = '';
	if (a.nome.value == ''){ 
		err+='\n- Digite seu nome.';
		erro=true;
	}
    texto = a.email.value;
	if (texto.length < 1) 
	 { 
		err+='\n- Digite seu e-mail.';
		erro=true;
 	 }
	else
	 { 
		//Validando o e-mail
		var str = texto; // email string
		var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
		var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid
		if (!reg1.test(str) && reg2.test(str)) // if syntax is valid
		 {  texto=''  }
		else
		 { 
	 		err+='\n- O seu endereço de e-mail é inválido.';
			erro=true; 
		 }
	 }
	if (a.ddd.value.length < 1 || a.telefone.value.length < 1){ 
		err+='\n- Digite seu telefone.';
		erro=true;
	}
	if (a.cidade.value.length < 1){ 
		err+='\n- Digite sua cidade.';
		erro=true;
	}
	if (a.mensagem.value.length < 1){ 
		err+='\n- Digite sua mensagem.';
		erro=true;
	}

	  if (err.length > 0) {
		  alert('Por Favor, verifique os seguintes erros: '+err);
	  } else {
		  a.submit();
	  } 
}



function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function P7_Snap() { //v2.67 by PVII
 var g,x,y,ox,bx,oy,p,tx,a,b,k,d,da,e,el,tw,q0,xx,yy,w1,pa='px',args=P7_Snap.arguments;a=parseInt(a);
 if(document.layers||window.opera){pa='';}for(k=0;k<(args.length);k+=4){
 if((g=MM_findObj(args[k]))!=null){if((el=MM_findObj(args[k+1]))!=null){
 a=parseInt(args[k+2]);b=parseInt(args[k+3]);x=0;y=0;ox=0;oy=0;p="";tx=1;
 da="document.all['"+args[k]+"']";if(document.getElementById){
 d="document.getElementsByName('"+args[k]+"')[0]";if(!eval(d)){
 d="document.getElementById('"+args[k]+"')";if(!eval(d)){d=da;}}
 }else if(document.all){d=da;}if(document.all||document.getElementById){while(tx==1){
 p+=".offsetParent";if(eval(d+p)){x+=parseInt(eval(d+p+".offsetLeft"));y+=parseInt(eval(d+p+".offsetTop"));
 }else{tx=0;}}ox=parseInt(g.offsetLeft);oy=parseInt(g.offsetTop);tw=x+ox+y+oy;
 if(tw==0||(navigator.appVersion.indexOf("MSIE 4")>-1&&navigator.appVersion.indexOf("Mac")>-1)){
  ox=0;oy=0;if(g.style.left){x=parseInt(g.style.left);y=parseInt(g.style.top);}else{
  w1=parseInt(el.style.width);bx=(a<0)?-5-w1:-10;a=(Math.abs(a)<1000)?0:a;b=(Math.abs(b)<1000)?0:b;
  x=document.body.scrollLeft+event.clientX+bx;y=document.body.scrollTop+event.clientY;}}
 }else if(document.layers){x=g.x;y=g.y;q0=document.layers,dd="";for(var s=0;s<q0.length;s++){
  dd='document.'+q0[s].name;if(eval(dd+'.document.'+args[k])){x+=eval(dd+'.left');y+=eval(dd+'.top');
  break;}}}e=(document.layers)?el:el.style;xx=parseInt(x+ox+a),yy=parseInt(y+oy+b);
 if(navigator.appVersion.indexOf("MSIE 5")>-1 && navigator.appVersion.indexOf("Mac")>-1){
  xx+=parseInt(document.body.leftMargin);yy+=parseInt(document.body.topMargin);}
 e.left=xx+pa;e.top=yy+pa;}}}
}

function checkCapsLock( e ) {
    var myKeyCode=0;
    var myShiftKey=false;
    var myMsg='Caps Lock is On.\n\nTo prevent entering your password incorrectly,\nyou should press Caps Lock to turn it off.';

    // Internet Explorer 4+
    if ( document.all ) {
        myKeyCode=e.keyCode;
        myShiftKey=e.shiftKey;

    // Netscape 4
    } else if ( document.layers ) {
        myKeyCode=e.which;
        myShiftKey=( myKeyCode == 16 ) ? true : false;

    // Netscape 6
    } else if ( document.getElementById ) {
        myKeyCode=e.which;
        myShiftKey=( myKeyCode == 16 ) ? true : false;

    }

    // Upper case letters are seen without depressing the Shift key, therefore Caps Lock is on
    if ( ( myKeyCode >= 65 && myKeyCode <= 90 ) && !myShiftKey ) {
		P7_Snap('capspos','Layer1',0,0);
		document.getElementById('Layer1').style.display='inline';
		//alert( myMsg );
    // Lower case letters are seen while depressing the Shift key, therefore Caps Lock is on
    } else if ( ( myKeyCode >= 97 && myKeyCode <= 122 ) && myShiftKey ) {
       	P7_Snap('capspos','Layer1',0,0);
		document.getElementById('Layer2').style.display='inline';
		//alert( myMsg );
    } else {
		document.getElementById('Layer1').style.display='none';
	}	
		
}




function verHora(Hora) {
	var val = new String(Hora);
	valStr = val.split(':');

	if(valStr.length != 2) return false
	else 
	{
		if (eval(valStr[0]) > 23)
			{return false}
		else if(eval(valStr[0].length) < 2)
			{return false}
		else if(eval(valStr[1].length) < 2)
			{return false}
		else if (eval(valStr[1]) > 59)
			{return false}
		else
			{return true};
	}
}

function VerificaNumero(valor) {
    valor = valor.replace(",", ".");
	if (isNaN(valor)){
		valor.value = '';
		return false;
	}
	else {return true;}
}

function VerificaNumeroNeg(valor){
	if (isNaN(UtlRoundOff(valor.value,'en'))){
		alert('Este campo só pode ter valor numérico.');
		valor.value = '';
		valor.focus();
		return 0;
	}
	if(UtlRoundOff(valor.value,'en') < 0){
		alert('Este campo só pode ter valor positivo.');
		valor.value = '0';
		valor.focus();
		return 0;
	}
}

function deselect(obj){
//tira seleção de objeto radiobox
	for(i=0;i<=document.all(obj).length-1;i++){
		//alert(document.all(obj)[i].estavaCheck + " - " + document.all(obj)[i].checked);
		if(document.all(obj)[i].checked){
			if(document.all(obj)[i].estavaCheck == ''){
				document.all(obj)[i].estavaCheck = 'S';
			}
			else{// if(document.all(obj)[i].estavaCheck == i){
				document.all(obj)[i].estavaCheck = '';
				document.all(obj)[i].checked = false;
			}
		}
		else{
			document.all(obj)[i].estavaCheck = '';
		}
	}
}


function FormataValor(campo, tammax, teclapres){
	var dec = 02;
	var tecla = teclapres.keyCode;
	var vr = document.all[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 (tam < tammax && tecla != 8){ tam = vr.length + 1 ; }
	//if (tecla == 8 ){	tam = tam - 1 ; } //backspace
	//if ( /*tecla == 8 ||*/ (tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105)){// || tecla == 46){
	if ((tecla >= 48 && tecla <= 57) || (tecla >= 96 && tecla <= 105)){// || tecla == 46){
		//if ( tam <= 4 ){ document.all[campo].value = vr; }
		if(tam >= 1 && tam < 4) { document.all[campo].value = vr; }
		else if ( tam <= dec ){
			document.all[campo].value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam );
		}
		else if ( (tam > 4) && (tam <= 17) ){
			document.all[campo].value = vr.substr( 0, tam - dec ) + ',' + vr.substr( tam - dec, tam );
		}
	}
}

function SaltaCampo (campo,prox,tammax,teclapres){
	var tecla = teclapres.keyCode;
	var vr = document.all[campo].value;
	//alert(tecla);
	if( tecla == 109 || tecla == 188 || /*tecla == 110 ||*/ tecla == 111 || tecla == 223 || tecla == 108 ){
		document.all[campo].value = vr.substr( 0, vr.length - 1 ); }
	else{
		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 (tecla != 0 && tecla != 9 && tecla != 16 ){
		
			if ( tam == tammax ){
				if ( document.all[prox] )
					document.all[prox].focus();
			}
		}
	}
}

function UtlRoundOff(fNum,langID) {
	var dec = 02;
    fNum = new String(fNum); 
	//var val = new String(Math.round(fNum.replace(',','.')*100)/100); 
	var val = new String(fNum.replace(',','.')); 
	var retVal, newVal;
	var i, j = 0;
	valStr = val.split('.');
	retVal = '';
	
	if(valStr.length < 2){
		if(val != ''){
			retVal = valStr[0]+'.';
			for(i=1;i<=dec;i++)
				retVal+='0';
		}
	}
	else if(valStr[1].length < 4 && val != ''){
		for(i=1;i<=dec-1;i++){
			if(valStr[1].length == i){
				for(j=1;j<=dec-valStr[1].length;j++)
					valStr[1]+='0';
			}
		}
		retVal = valStr[0]+'.'+valStr[1];
	}
	else if(val != ''){
		retVal=valStr[0]+'.'+valStr[1].substr(0,dec);
	}

	if (langID == "en")
		return retVal;
		
	newVal=retVal;
	for(i=0;i<retVal.length;i++)
	{
		if (retVal.substring(i,i+1) == ".")
			{
			newVal =retVal.substring(0,i) + "," + retVal.substring(i+1,retVal.length)
			retVal = newVal
			}
		else if (retVal.substring(i,i+1) == ",")
			{
			newVal =retVal.substring(0,i) + "." + retVal.substring(i+1,retVal.length)
			retVal = newVal
			}
	}
	return newVal;
}

function incrementa(campo,acao,descr) {
 		  
		  if (acao == 'up') {
			 document.getElementById(campo).value = eval(parseInt(document.getElementById(campo).value) + 1);
		  } else if (acao == 'down') {
			 document.getElementById(campo).value = eval(parseInt(document.getElementById(campo).value) - 1);
		  }
		  
		  if(document.getElementById(campo).value == 0) {
			  if(confirm('Você deseja apagar "'+descr+'" da cesta de compras ?')) {
		  		document.cesta.submit();
			  } else {
			    document.getElementById(campo).value = 1;
			  }
		  } else {
			  document.cesta.submit();
		  }
}


function mudar_preco(acao){
		
	if(acao == 'royal') {
	   document.getElementById('botao1').style.background.image = "img/papel_royal01.gif";
	   document.getElementById('botao2').style.background.image = "img/papel_econo01.gif";
	   window.precos.location.href="precos.php?papel=2";
	} else {	
	   document.getElementById('botao1').style.background.image  = "img/papel_royal02.gif";
	   document.getElementById('botao2').style.background.image  = "img/papel_econo02.gif";
	   window.precos.location.href="precos.php?papel=1";
	}
}

function replaceHtml(str)
{
		str = str.replace("&", "#amp;");
		str = str.replace("Æ", "#Aelig;");
		str = str.replace("æ", "#aelig;");
		str = str.replace("Ç", "#Ccedil;");
		str = str.replace("ç", "#ccedil;");
		str = str.replace("ç", "#ccedil;");
		str = str.replace("Ð", "#ETH;");
		str = str.replace("Ø", "#Oslash;");
		str = str.replace("ø", "#oslash;");
		str = str.replace("Å", "#Aring;");
		str = str.replace("å", "#aring;");
		str = str.replace("Ä", "#Auml;");
		str = str.replace("ä", "#auml;");
		str = str.replace("Ë", "#Euml;");
		str = str.replace("ë", "#euml;");
		str = str.replace("ë", "#euml;");
		str = str.replace("Ï", "#Iuml;");
		str = str.replace("ï", "#iuml;");
		str = str.replace("ß", "#szlig;");
		str = str.replace("Þ", "#thorn;");
		str = str.replace("®", "##174;");
		str = str.replace("©", "##169;");
		str = str.replace("§", "##167;");
		str = str.replace("¢", "##162;");
		str = str.replace("ª", "##170;");
		str = str.replace("«", "##171;");
		str = str.replace("»", "##187;");
		str = str.replace("°", "##186;");
		str = str.replace("¹", "##185;");
		str = str.replace("²", "##178;");
		str = str.replace("³", "##179;");
		str = str.replace("°", "##186;");
		str = str.replace("µ", "##181;");
		str = str.replace("¶", "##182;");
		str = str.replace("½", "##189;");
		str = str.replace("¼", "##188;");
		str = str.replace("¾", "##190;");
		str = str.replace("¿", "##191;");
		str = str.replace("£", "##163;");
		str = str.replace("¥", "##165;");
		str = str.replace("‘", "''");
		str = str.replace("’", "''");

		str = str.replace("Á", "#Aacute;");
		str = str.replace("á", "#aacute;");
		str = str.replace("É", "#Eacute;");
		str = str.replace("é", "#eacute;");
		str = str.replace("Í", "#Iacute;");
		str = str.replace("í", "#iacute;");
		str = str.replace("Ó", "#Oacute;");
		str = str.replace("ó", "#oacute;");
		str = str.replace("Ú", "#Uacute;");
		str = str.replace("ú", "#uacute;");
		str = str.replace("Ý", "#Yacute;");
		str = str.replace("ý", "#yacute;");

		str = str.replace("Â", "#Acirc;");
		str = str.replace("â", "#acirc;");
		str = str.replace("Ê", "#Ecirc;");
		str = str.replace("ê", "#ecirc;");
		str = str.replace("Î", "#Icirc;");
		str = str.replace("î", "#icirc;");
		str = str.replace("Ô", "#Ocirc;");
		str = str.replace("ô", "#ocirc;");
		str = str.replace("Û", "#Ucirc;");
		str = str.replace("û", "#ucirc;");

		str = str.replace("Ã", "#Atilde;");
		str = str.replace("ã", "#atilde;");
		str = str.replace("Õ", "#Otilde;");
		str = str.replace("õ", "#otilde;");
		str = str.replace("Ñ", "#Ntilde;");
		str = str.replace("ñ", "#ntilde;");

		str = str.replace("À", "#Agrave;");
		str = str.replace("à", "#agrave;");
		str = str.replace("È", "#Egrave;");
		str = str.replace("è", "#egrave;");
		str = str.replace("Ì", "#Igrave;");
		str = str.replace("ì", "#igrave;");
		str = str.replace("Ò", "#Ograve;");
		str = str.replace("ò", "#ograve;");
		str = str.replace("Ù", "#Ugrave;");
		str = str.replace("ù", "#ugrave;");
		
		return str
}

// JavaScript Document
