// JavaScript Document

/*# CPF */
 function validarCPF(obj){
   var cpf = document.getElementById(obj).value;
   var filtro = /^\d{3}.\d{3}.\d{3}-\d{2}$/i;
   if(!filtro.test(cpf)){
     window.alert("CPF inválido. Tente novamente.");
	 document.getElementById(obj).value="";
	 return false;
   }
   
   cpf = remove(cpf, ".");
   cpf = remove(cpf, "-");
    
   if(cpf.length != 11 || cpf == "00000000000" || cpf == "11111111111" ||
	  cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" ||
	  cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" ||
	  cpf == "88888888888" || cpf == "99999999999"){
	  window.alert("CPF inválido. Tente novamente.");
	 document.getElementById(obj).value="";
	  return false;
   }

   soma = 0;
   for(i = 0; i < 9; i++)
   	 soma += parseInt(cpf.charAt(i)) * (10 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(9))){
	 window.alert("CPF inválido. Tente novamente.");
	 document.getElementById(obj).value="";
	 return false;
   }
   soma = 0;
   for(i = 0; i < 10; i ++)
	 soma += parseInt(cpf.charAt(i)) * (11 - i);
   resto = 11 - (soma % 11);
   if(resto == 10 || resto == 11)
	 resto = 0;
   if(resto != parseInt(cpf.charAt(10))){
     window.alert("CPF inválido. Tente novamente.");
	 document.getElementById(obj).value="";
	 return false;
   }
 	//window.alert("CPF valido.");
  //return false;
 }
 
 function remove(str, sub) {
   i = str.indexOf(sub);
   r = "";
   if (i == -1) return str;
   r += str.substring(0,i) + remove(str.substring(i + sub.length), sub);
   return r;
 }

/*# */
function pergunta(pagina,texto){
var name = confirm(texto)
	if (name == true){
		window.location=pagina;
	}
}

 /*# MUDA PARA O PROXIMO CAMPO # */
function proximoCampo(valor, campo1, campo2){
	var v = document.getElementById(campo1).value;
	if(v.length==valor){
		document.getElementById(campo2).focus();
	}
}

/*#SO NUMERO#*/
var reDigits = /^\d+$/;
function doDigits(pStr, path){
	if (reDigits.test(pStr)) {
		//alert(pStr + " contÃ©m apenas dÃ­gitos.");
	} else if (pStr != null && pStr != "") {
		//alert(pStr + " NÃƒO contÃ©m apenas dÃ­gitos.");
		document.getElementById(path).value = pStr.substring(0,(pStr.length-1));
	}
}

/*# MOEDA */
var reMoeda = /^\d{1,3}(\.\d{3})*\,\d{2}$/;
function doMoeda(pStr, path)
{
	if (reMoeda.test(pStr)) {
		//alert(pStr + " Ã© um valor financeiro vÃ¡lido.");
	} else if (pStr != null && pStr != "") {
		alert(pStr + " NÃƒO Ã© um valor financeiro vÃ¡lido.");
		document.getElementById(path).focus();
	}
}

/*# TELEFONE */
padraoFone = /\d{4}-\d{4}/;
//padraoFone = /\(?\d{2}\)?\d{4}-\d{4}/;
function testFone(x) {
   a = x.Phone.value;
   OK = padraoFone.exec(a);
   if ( !OK ){
       window.alert ("Este numero de telefone esta incorreto!");
       x.Phone.focus();
   }
   else {
       window.alert ("Obrigado, seu numero de telefone Ã© Â» " + OK[0]);
   }
}

/*# MASCARA */
function txtBoxFormat(objeto, sMask, evtKeyPress) {
    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;
} else {
    nTecla = evtKeyPress.which;
    if (nTecla == 8) {
        return true;
    }
}

    sValue = objeto.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( ")", "" );
    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) == "/") || (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++;
    }

    objeto.value = sCod;

    if (nTecla != 8) { // backspace
      if (sMask.charAt(i-1) == "9") { // apenas nÃºmeros...
        return ((nTecla > 47) && (nTecla < 58)); } 
      else { // qualquer caracter...
        return true;
      } 
    }
    else {
      return true;
    }
  }
//<input type="text" size="20" onkeypress="return txtBoxFormat(this, '999.999.999-99', event);" maxlength="14"> XXX.XXX.XXX-XX

//////////

/*
 Padawan's JavaScript-Mega-Validator 3000+
 Todos os direitos reservados para Diego Pires Plentz
 VocÃª pode usar esse cÃ³digo nas suas pÃ¡ginas desde que mantenha os crÃ©ditos ;-)
 */
 
 //Verifica qual o browser do visitante e armazena na variÃ¡vel pÃºbica clientNavigator,
 //Caso Internet Explorer(IE) outros (Other)
 if (navigator.appName.indexOf('Microsoft') != -1){
 	clientNavigator = "IE";
 }else{
 	clientNavigator = "Other";
 }
 function Verifica_Data(data, obrigatorio){
 //Se o parÃ¢metro obrigatÃ³rio for igual Ã  zero, significa que elepode estar vazio, caso contrÃ¡rio, nÃ£o
  var data = document.getElementById(data);
 	var strdata = data.value;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strdata != "")){
 		//Verifica a quantidade de digitos informada esta correta.
 		if (strdata.length != 10){
 			alert("Formato da data nÃ£o Ã© vÃ¡lido. Formato correto: - dd/mm/aaaa.");
 			data.focus();
 			return false
 		}
 		//Verifica mÃ¡scara da data
 		if ("/" != strdata.substr(2,1) || "/" != strdata.substr(5,1)){
 			alert("Formato da data nÃ£o Ã© vÃ¡lido. Formato correto: - dd/mm/aaaa.");
 			data.focus();
 			return false
 		}
 		dia = strdata.substr(0,2)
 		mes = strdata.substr(3,2);
 		ano = strdata.substr(6,4);
 		//Verifica o dia
 		if (isNaN(dia) || dia > 31 || dia < 1){
 			alert("Formato do dia nÃ£o Ã© vÃ¡lido.");
 			data.focus();
 			return false
 		}
 		if (mes == 4 || mes == 6 || mes == 9 || mes == 11){
 			if (dia == "31"){
 				alert("O mÃªs informado nÃ£o possui 31 dias.");
 				data.focus();
 				return false
 			}
 		}
 		if (mes == "02"){
 			bissexto = ano % 4;
 			if (bissexto == 0){
 				if (dia > 29){
 					alert("O mÃªs informado possui somente 29 dias.");
 					data.focus();
 					return false
 				}
 			}else{
 				if (dia > 28){
 					alert("O mÃªs informado possui somente 28 dias.");
 					data.focus();
 					return false
 				}
 			}
 		}
 	//Verifica o mÃªs
 		if (isNaN(mes) || mes > 12 || mes < 1){
 			alert("Formato do mÃªs nÃ£o Ã© vÃ¡lido.");
 			data.focus();
 			return false
 		}
 		//Verifica o ano
 		if (isNaN(ano)){
 			alert("Formato do ano nÃ£o Ã© vÃ¡lido.");
 			data.focus();
 			return false
 		}
 	}
 }
 
 /*# COMPARA DUAS DATAS */
 function Compara_Datas(data_inicial, data_final){
 	//Verifica se a data inicial Ã© maior que a data final
 	var data_inicial = document.getElementById(data_inicial);
 	var data_final   = document.getElementById(data_final);
 	str_data_inicial = data_inicial.value;
 	str_data_final   = data_final.value;
 	dia_inicial      = data_inicial.value.substr(0,2);
 	dia_final        = data_final.value.substr(0,2);
 	mes_inicial      = data_inicial.value.substr(3,2);
 	mes_final        = data_final.value.substr(3,2);
 	ano_inicial      = data_inicial.value.substr(6,4);
 	ano_final        = data_final.value.substr(6,4);
 	if(ano_inicial > ano_final){
 		alert("A data inicial deve ser menor que a data final."); 
 		data_inicial.focus();
 		return false
 	}else{
  	if(ano_inicial == ano_final){
   	if(mes_inicial > mes_final){
    	alert("A data inicial deve ser menor que a data final.");
 				data_final.focus();
 				return false
 			}else{
 				if(mes_inicial == mes_final){
 					if(dia_inicial > dia_final){
 						alert("A data inicial deve ser menor que a data final.");
 						data_final.focus();
 						return false
 					}
 				}
 			}
 		}
 	}
 }
 
 function Verifica_Hora(hora, obrigatorio){
 //Se o parÃ¢metro obrigatÃ³rio for igual Ã  zero, significa que elepode estar vazio, caso contrÃ¡rio, nÃ£o
 	var hora = document.getElementById(hora);
 	if((obrigatorio == 1) || (obrigatorio == 0 && hora.value != "")){
 		if(hora.value.length < 5){
 			alert("Formato da hora invválido. Por favor, informe a hora no formato correto: hh:mm");
 			hora.focus();
 			return false
 		}
 		if(hora.value.substr(0,2) > 23 || isNaN(hora.value.substr(0,2))){
 			alert("Formato da hora invÃ¡lido.");
 			hora.focus();
 			return false
 		}
 		if(hora.value.substr(3,2) > 59 || isNaN(hora.value.substr(3,2))){
 			alert("Formato do minuto inválido.");
 			hora.focus();
 			return false
 		}
 	}
 }
 
  /*# VERIFICA E-MAIL */
var reEmail1 = /^[\w!#$%&'*+\/=?^`{|}~-]+(\.[\w!#$%&'*+\/=?^`{|}~-]+)*@(([\w-]+\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail2 = /^[\w-]+(\.[\w-]+)*@(([\w-]{2,63}\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail3 = /^[\w-]+(\.[\w-]+)*@(([A-Za-z\d][A-Za-z\d-]{0,61}[A-Za-z\d]\.)+[A-Za-z]{2,6}|\[\d{1,3}(\.\d{1,3}){3}\])$/;
var reEmail = reEmail3;
 function doEmail(obj){
 eval("reEmail = reEmail" + 3);
 pStr = document.getElementById(obj).value;
	if (reEmail.test(pStr)) {
		//alert(pStr + " é um endereço de e-mail válido.");
	} else if (pStr != null && pStr != "") {
		alert(pStr + " não é um endereço de e-mail válido.");
		document.getElementById(obj).value="";
		document.getElementById(obj).focus();
		return false;
	}
} // doEmai
 
 
 /*# TAMANHO DO CAMPO */
 function Verifica_Tamanho(campo, tamanho){
 //usado para campos textarea onde nÃ£o se tem o atributo maxlenght
 	var campo = document.getElementById(campo);
 	if(campo.value.length > tamanho){
 		alert("O campo suporta no máximo " + tamanho + " caracteres.");
 		campo.focus();
 		return false
 	}
 }
 
 function Verifica_Cep(cep, obrigatorio){
 //Se o parÃ¢metro obrigatÃ³rio for igual Ã  zero, significa que elepode estar vazio, caso contrÃ¡rio, nÃ£o
 	var cep    = document.getElementById(cep);
 	var strcep = cep.value;
 	if((obrigatorio == 1) || (obrigatorio == 0 && strcep != "")){
 		if (strcep.length != 9){
 			alert("CEP informado inválido.");
 			cep.focus();
 			return false
 		}else{
 			if (strcep.indexOf("-") != 5){
 				alert("Formato de CEP informado inválido.");
 				cep.focus();
 				return false
 			}else{
 				if (isNaN(strcep.replace("-","0"))){
 					alert("CEP informado inválido.");
 					cep.focus();
 					return false
 				}
 			}
 		}
 	}	  
 }
 
 function Bloqueia_Caracteres(evnt){
 //FunÃ§Ã£o permite digitaÃ§Ã£o de nÃºmeros
 	if (clientNavigator == "IE"){
 		if (evnt.keyCode < 48 || evnt.keyCode > 57){
 			return false
 		}
 	}else{
 		if ((evnt.charCode < 48 || evnt.charCode > 57) && evnt.keyCode == 0){
 			return false
 		}
 	}
 }
 
 function Ajusta_Data(input, evnt){
 //Ajusta mÃ¡scara de Data e sÃ³ permite digitaÃ§Ã£o de nÃºmeros
 	if (input.value.length == 2 || input.value.length == 5){
 		if(clientNavigator == "IE"){
 			input.value += "/";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += "/";
 			}
 		}
 	}
 //Chama a funÃ§Ã£o Bloqueia_Caracteres para sÃ³ permitir a digitaÃ§Ã£o de nÃºmeros
 	return Bloqueia_Caracteres(evnt);
 }
 
 function Ajusta_Hora(input, evnt){
 //Ajusta mÃ¡scara de Hora e sÃ³ permite digitaÃ§Ã£o de nÃºmeros
 	if (input.value.length == 2){
 		if(clientNavigator == "IE"){
 			input.value += ":";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += ":";
 			}
 		}
 	}
 //Chama a funÃ§Ã£o Bloqueia_Caracteres para sÃ³ permitir a digitaÃ§Ã£o de nÃºmeros
 	return Bloqueia_Caracteres(evnt);
 }
 
 function Ajusta_Cep(input, evnt){
 //Ajusta mÃ¡scara de CEP e sÃ³ permite digitaÃ§Ã£o de nÃºmeros
 	if (input.value.length == 5){
 		if(clientNavigator == "IE"){
 			input.value += "-";
 		}else{
 			if(evnt.keyCode == 0){
 				input.value += "-";
 			}
 		}
 	}
 //Chama a funÃ§Ã£o Bloqueia_Caracteres para sÃ³ permitir a digitaÃ§Ã£o de nÃºmeros
 	return Bloqueia_Caracteres(evnt);
 }
 
 function Atualiza_Opener(){
 //Atualiza a pÃ¡gina opener da popup que chamar a funÃ§Ã£o
 	window.opener.location.reload();
 }
/*
 <input name="data" type="text" id="data" maxlength="10" onKeypress="return Ajusta_Data(this, event);"> 
 <input name="hora" type="text" id="hora" maxlength="5" onKeypress="return Ajusta_Hora(this, event);"> 
 <input name="cep" type="text" id="cep" maxlength="9" onKeypress="return Ajusta_Cep(this, event);">
 <input name="numero" type="text" id="numero" maxlength="20" onKeypress="return Bloqueia_Caracteres(event);""> 
*/
