// JavaScript Document
oldObj   = "";
oldValor = "";
inteiro  = new RegExp("[0-9]");


function validateMessageVol(oForm)
{
	if(oForm.codigoArea.value == '')
	{
		alert('Por favor, informe o DDD de destino do torpedo SMS.');
		oForm.codigoArea.focus();
		return false;
	}
	
	if(oForm.numTelefone.value == '')
	{
		alert('Por favor, informe o número do celular de destino do torpedo SMS.');
		oForm.numTelefone.focus();
		return false;
	}
 
	if(!isNumberCelular(oForm.numTelefone))
	{
		return false;
	}
	
	//Retira as quebras de linha da mensagem digitada pelo usuario.
	oForm.mensagem.value = oForm.mensagem.value.replace(/\r?\n/g," ");
	//Retira os espaços duplos, que podem acontecer na retirada das quebras de linha.
	while ( oForm.mensagem.value.indexOf("  ") > -1 ){
		oForm.mensagem.value = oForm.mensagem.value.replace(/  /g," ");
	}
	
	if(oForm.mensagem.value == '')
	{
		alert('Digite a sua mensagem.');
		oForm.mensagem.focus();
		return false;
	}
 
	var iTotal = 0;
 
	iTotal += document.SendMessageVOLForm.nomeContato.value.length;
	//iTotal += document.SendMessageVOLForm.telefoneContato.value.length;
	iTotal += document.SendMessageVOLForm.mensagem.value.length;
		
	if(iTotal > 71)
	{
		alert('Seu torpedo excedeu a quantidade máxima de caracteres.\nPor favor, reescreva a sua mensagem.');
		oForm.mensagem.focus();
		return false;
	}
	return true;
}
 
function validateInsert(objForm)
{
	if (isEmpty(objForm.nome.value))
	{
		alert("Por favor informe seu Nome");
		objForm.nome.focus();
		objForm.nome.select();
		return false;
	}
	else if (isEmpty(objForm.dataNascimento.value))
	{
		alert("Por favor informe a Data Nascimento");
		objForm.dataNascimento.focus();
		objForm.dataNascimento.select();
		return false;
	}
	else if (!validaDataNascimento(objForm.dataNascimento))
	{
		return false;
	}
	else if (!validaCPF(objForm.cpf))
	{
		return false;
	}
	else if (!validaTelefone(objForm.telefone))
	{
		return false;
	}
	else if (objForm.login.value!=objForm.confirmacao.value)
	{
		alert("Confirmação de e-mail não coincide com o login.");
		return false;
	}
	/*
	else if (!objForm.auth.checked)
	{
		alert("Para continuar com seu cadastro no serviço Vivo Torpedo Web Gratuito, é necessário autorizar a utilização de seus dados, conforme política exposta no site.");
		return false;
	}
	*/
	else if (isEmpty(objForm.pwdcaptcha.value))
	{
		alert("Por favor, digite as letras indicadas abaixo para confirmação de seu cadastro.");
		objForm.pwdcaptcha.focus();
		objForm.pwdcaptcha.select();
		return false;
	}
	return true;
}
 
function validateNewPasswd(objForm)
{
	if (!validaCPF(objForm.cpf))
	{
		return false;
	}
	else if (isEmpty(objForm.pwdcaptcha.value))
	{
		alert("Digite a palavra abaixo no campo indicado para confirmar o envio");
		objForm.pwdcaptcha.focus();
		objForm.pwdcaptcha.select();
		return false;
	}
	return true;
}
 
function validateUpdate(objForm)
{
	if (isEmpty(objForm.nome.value))
	{
		alert("Por favor informe seu Nome");
		objForm.nome.focus();
		objForm.nome.select();
		return false;
	}
	else if (isEmpty(objForm.dataNascimento.value))
	{
		alert("Por favor informe a Data Nascimento");
		objForm.dataNascimento.focus();
		objForm.dataNascimento.select();
		return false;
	}
	else if (!validaDataNascimento(objForm.dataNascimento))
	{
		return false;
	}
	else if (!validaTelefone(objForm.numTelefone))
	{
		return false;
	}
	else if (!isEmpty(objForm.newPasswd.value))
    {
   		if (objForm.newPasswd.value.length < 4)
    	{
    		alert("Por favor, informe nova senha com 4 dígitos");
        	objForm.newPasswd.focus();
			objForm.newPasswd.select();
        	return false;
    	}
    	else if (isEmpty(objForm.confPasswd.value))
    	{
    		alert("A senha deve ser confirmada");
    		objForm.confPasswd.focus();
			objForm.confPasswd.select();
        	return false;
    	}
    	else if (objForm.newPasswd.value != objForm.confPasswd.value)
    	{
        	alert("Por favor, verifique a senha e a confirmação de senha digitada, pois os dados não conferem.");
        	objForm.newPasswd.focus();
			objForm.newPasswd.select();
        	return false;
    	}
    }
	return true;
}
 
function loadUpdate()
{
	//formatando o campo telefone
	checaTelefone(document.UpdateNoClientForm.numTelefone);
	
	//formatando o CPF
	checaCPF(document.UpdateNoClientForm.cpf);
	document.getElementById("text_cpf").innerHTML = "<b>CPF:</b>&nbsp;&nbsp; " + document.UpdateNoClientForm.cpf.value;
}
 
function validaDataNascimento(obj)
{
	var dia  = new Date();
    var mes  = dia.getMonth() + 1;
    var hoje = dia.getDate().toString() + "/" + mes.toString() + "/" + dia.getYear().toString();
	
	dtNascimento = obj;
	
	if (dtNascimento.value != "")
    {
		if(!(isValidDate(dtNascimento.value)))
		{
			alert("Preencha o campo Data de Nascimento corretamente.");
			dtNascimento.value = "";
			dtNascimento.focus();
			return false;
		}
	}
	return true;
}
 
function isValidDate(date)
{
	var dia, mes, ano;
   	var isBissexto = false;
	
	var r = /^[0-9]{2,2}\/[0-9]{2,2}\/[0-9]{4,4}$/ 
	
	if(! r.test(date))
		return false;
	
	var strDate = new String(date)
	
	var data = strDate.split('/');
			
	if (data.length != 3)
		return false;
			
	dia = data[0];
	mes = data[1];
	ano = data[2];
 
	//if ((ano < 1950) || (ano > 2050))
	//	return false;
 
	if (((ano % 4) == 0) && (((ano % 100) != 0) || ((ano % 400) == 0)))
		isBissexto = true;
 
	if ((mes < 1) ||(mes > 12))
		return false;
 
	if(dia < 1)
		return false;
 
	var meses = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
 
	if (isBissexto)
		meses[1] = 29;
 
	if (dia > meses[mes - 1])
		return false;
 
	return true;  
}
 
function formatarData(campo, teclapres)
{
    var tecla = 0;
    
    if (window.event)
	{
		tecla = window.event.keyCode;
	}
	else if (teclapres)
	{
		tecla = teclapres.which;
	}
    
	if (tecla == 8 || tecla == 46)
	{
        return; /* Quando BackSpace ou Delete for pressionado, deixa o usuario fazer o que quiser */
	}
    valorSemFormato = campo.value;
	valorSemFormato = valorSemFormato.replace("/", "");
    valorSemFormato = valorSemFormato.replace("/", "");
    
	tamanho = valorSemFormato.length;
	
	if (tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )
	{
 
        if ((tamanho >= 2) && (tamanho <= 3))
		{
            campo.value = valorSemFormato.substr(0, 2) + "/" + valorSemFormato.substr(2, tamanho);
        }
		else if ((tamanho >= 4) && (tamanho <= 9))
        {
            campo.value = valorSemFormato.substr(0, 2) + "/" + valorSemFormato.substr(2, 2) + "/" + valorSemFormato.substr(4, 4);
        }
		else
        {
            campo.value = valorSemFormato;
        }
 
    }
    if(!isDataEnter(valorSemFormato)){
        campo.value = campo.value.substr(0,(campo.value.length -1));
    }
}
 
function isDataEnter(s)
{
    if (s.length == 0) return false;
 
    var caracteresValidos = "0123456789/";
    var c;
 
    for (i = 0; i <= s.length; i++)
    {
        c = s.charAt(i);
        if (caracteresValidos.indexOf(c) == -1)
        {
            return false;
        }
    }
    return true;
}
 
function checaCPF(obj)
{
  valor = obj.value;
  if(valor != oldValor || oldObj != obj){
	for(i=0;i<valor.length;i++){

	  if(!inteiro.test(valor.charAt(i))){

		valor = valor.substring(0,i) + valor.substring(i+1,valor.length);

		i = -1;

	  }

	}

	if(valor.length < 1){
	  valor = "";
	}else if(valor.length > 3 && valor.length < 7){
	  valor = valor.substring(0,3) + "." + valor.substring(3,valor.length);
	}else if(valor.length > 6 && valor.length < 10){
	  valor = valor.substring(0,3) + "." + valor.substring(3,6) + "." + valor.substring(6,valor.length);
	}else if(valor.length > 9 && valor.length < 12){
	  valor = valor.substring(0,3) + "." + valor.substring(3,6) + "." + valor.substring(6,9) + "-" + valor.substring(9,valor.length);
	}else if(valor.length > 11){
	  valor = valor.substring(0,3) + "." + valor.substring(3,6) + "." + valor.substring(6,9) + "-" + valor.substring(9,11);
	}
	obj.value = valor;
	oldValor = valor;
	oldObj = obj;
  }
}
 
function validaCPF(obj)
{
	if (isEmpty(obj.value))
	{
		alert("Por favor informe seu número de CPF.");
		obj.focus();
		obj.select();
		return false;
	}
	else if (!isCPF(obj.value))
	{
		alert("O CPF informado é inválido.");
		obj.focus();
		obj.select();
		return false;
	}
	return true;
}
 
function validaCPFOnBlur(obj)
{
	if (isEmpty(obj.value))
	{
		return false;
	}
	else if (!isCPF(obj.value))
	{
		alert("O CPF informado é inválido.");
		return false;
	}
	return true;
}
 
//-----------------------------------------------------------------------------
//-- Valida se o valor informado é vazio                                     --
//-----------------------------------------------------------------------------
function isEmpty(value)
{
	var str = trim(value);
	if (str != "")
	{
		return false;
	}
	return true;
}
 
function checaTelefone(obj)
{
	  valor = obj.value;
	  if(valor != oldValor || oldObj != obj){
		for(i=0;i<valor.length;i++){

		  if(!inteiro.test(valor.charAt(i))){

			valor = valor.substring(0,i) + valor.substring(i+1,valor.length);

			i = -1;

		  }

		}

		if(valor.length < 1){
		  valor = "";
		}else if(valor.length < 3){
		  valor = "(" + valor.substring(0,2);
		}else if(valor.length < 7){
		  valor = "(" + valor.substring(0,2) + ")" + valor.substring(2,6);
		}else{
		  valor = "(" + valor.substring(0,2) + ")" + valor.substring(2,6) + "-" + valor.substring(6,10);
		}
		obj.value = valor;
		oldValor = valor;
		oldObj = obj;
  }
}
 
function formataTelefone(obj)
{
	  valor = obj.value;
	  var valorNovo = "";;
	  if(valor.length < 13){
		for(i=0;i<valor.length;i++){

		  if(inteiro.test(valor.charAt(i))){

			valorNovo = valorNovo + valor.charAt(i);

		  }

		}

		valorNovo = "(" + valorNovo.substring(0,2) + ")" + valorNovo.substring(2,5) + "-" + valorNovo.substring(5,9);

		obj.value = valorNovo;

	 }

} 



function validaTelefone(obj)

{

	var telefone = obj.value;

	

	telefone = ClearStr(telefone, '-');

	telefone = ClearStr(telefone, '(');

	telefone = ClearStr(telefone, ')');

	telefone = ClearStr(telefone, ' ');

	

	if (isEmpty(telefone))

	{

		alert("Por favor informe o Telefone");

		obj.focus();

		obj.select();

		return false;

	}

	else if (telefone.length < 10)
	{
		alert("Telefone incompleto");
		obj.focus();
		obj.select();
		return false;
	}
	return true;
}
 
 
function trim(str) 
{
	str = str.toString().replace(/\$|\ /g,'');
	return str;
}
 
function checaNome(obj)
{
	var caracteresValidos = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789???????_ ";
    var c;
 
	valor = obj.value;
	
	if(valor != oldValor || oldObj != obj)
	{
		for(i=0; i < valor.length; i++)
		{
			c = valor.charAt(i);
	        if (caracteresValidos.indexOf(c) == -1)
	        {
	            valor = valor.substring(0,i) + valor.substring(i+1,valor.length);
				i = -1;
	        }
		}
		obj.value = valor;
		oldValor = valor;
		oldObj = obj;
	}
}
 
function onlyNumber(field, evt, begin, end)
{
	var keycode = 0;
	
	if (window.event)
	{
		keycode = window.event.keyCode;
	}
	else if (evt)
	{
		keycode = evt.which;
	}
	
	if (keycode < (48 + begin) || keycode > (48 + end))
	{
		if (keycode == 8 || keycode == 0 || keycode == 9)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	else
	{
		return true;
	}
}
 
function countChars(field, evt)
{
	var keycode = 0;
	var iTotal  = 0;
	var iAux    = 0;
	
	//alert(field.value.length);
	//iTotal += document.SendMessageVOLForm.nomeContato.value.length;
	//iTotal += document.SendMessageVOLForm.telefoneContato.value.length;
	//iTotal += document.SendMessageVOLForm.mensagem.value.length;
	
	iTotal += field.value.length;
	
	if (window.event)
	{
		keycode = window.event.keyCode;
	}
	else if (evt)
	{
		keycode = evt.which;
	}
	
	if (keycode == 8)
		iAux = iTotal - 1;
	else
		iAux = iTotal + 1;
	

	//alert(keycode + " - " + iTotal + " - " + iAux);
	
	if(iTotal > 399 && keycode != 8 && keycode != 46)
	{
		field.value = field.value.substring(0,400);
		return false;
	}
	
	if (iAux >= 0){
		document.getElementById("totalChar").innerHTML = 400 - iAux;
		return true;
	}	
}
 
function isNumberCelular(celular)
{
	// Verifica o comprimento do n?mero do celular
	if (celular.value.length < 8)
	{
		alert('O número digitado está incompleto. Verifique.');
		celular.focus();
		return false;
	}
	return true;
}
 
//######################################//
//## BEGIN: FUNÇÕES VALIDAÇÃO DE CPF  ##//
//######################################//
function isCPF(CNUMB)
{
  if(Verify(CNUMB))
  {
    return true;
  }
  else
  {
    return false;
  }
  return;
}
 
function ClearStr(str, c)
{
  while((cx=str.indexOf(c))!=-1)
  {
    str = str.substring(0,cx)+str.substring(cx+1);
  }
  return(str);
}
 
function ParseNumb(c)
{
  c=ClearStr(c,'-');
  c=ClearStr(c,'/');
  c=ClearStr(c,',');
  c=ClearStr(c,'.');
  c=ClearStr(c,'(');
  c=ClearStr(c,')');
  c=ClearStr(c,' ');
  if((parseFloat(c) / c != 1))
  {
    if(parseFloat(c) * c == 0)
    {
      return(c);
    }
    else
    {
      return(0);
    }
  }
  else
  {
    return(c);
  }
}
 
function Verify(CNUMB)
{
  CNUMB = ParseNumb(CNUMB);
  
	if ((CNUMB == '00000000000') || (CNUMB == '11111111111') || 
       	(CNUMB == '22222222222') || (CNUMB == '33333333333') || 
	   	(CNUMB == '44444444444') || (CNUMB == '55555555555') || 
	   	(CNUMB == '66666666666') || (CNUMB == '77777777777') || 
	   	(CNUMB == '88888888888') || (CNUMB == '99999999999') || 
	   	(CNUMB == '01234567890') || (CNUMB == '12345678909'))
	{
		return false;
	}
 
  
  
  if(CNUMB == 0)
  {
    return(false);
  }
  else
  {
    g=CNUMB.length-2;
    if(TestDigit(CNUMB,g))
    {
      g=CNUMB.length-1;
      if(TestDigit(CNUMB,g))
      {	
        return(true);
      }
      else
      {
        return(false);
      }
    }
    else
    {
      return(false);
    }
  }
}
 
function TestDigit(CNUMB, g)
{
  var dig=0;
  var ind=2;
  for(f=g;f>0;f--)
  {
    dig += parseInt(CNUMB.charAt(f-1))*ind;
    ind++;
  }
  dig%=11;
  if(dig<2)
  {
    dig=0;
  }
  else
  {
    dig=11-dig;
  }
  if(dig!=parseInt(CNUMB.charAt(g)))
  {
    return(false);
  }
  else
  {
    return(true);
  }
}
//####################################//
//## END: FUNÇÕES VALIDAÇÃO DE CPF  ##//
//####################################//
 
function upper(obj)
{
	obj.value = obj.value.toUpperCase();
}
 
function showMessage(str)
{
	alert(str);
}