//Alteracao de Senha

function voltar()
{
	try
	{
		if (document.referrer != window.location.href)
			window.location.assign(document.referrer); 
	}
	catch (e)
	{
	}
	
	return false;
}

function DeixaNumeros(campo)
{
	var i;
	var soNumeros = "";
	var modificado = false;

	for (i = 0; i < campo.value.length; i++)
	{
		if (campo.value.charAt(i) >= '0' && campo.value.charAt(i) <= '9')
		{
			soNumeros += campo.value.charAt(i);
		}
		else
		{
			modificado = true;
		}
	}

	if (modificado == true)
	{
		 campo.value = soNumeros;
	}
}

function ValidaAlteracaoSenha()
{
	// todos menos o cpf

	if ((document.getElementById("senha").value == "")
		|| (document.getElementById("novasenha").value == "")
		|| (document.getElementById("confirmanovasenha").value == ""))
	{
		window.alert("Todos os campos devem estar preenchidos!");
		return false;
	}

	if (document.getElementById("novasenha").value != document.getElementById("confirmanovasenha").value)
	{
		window.alert("A confirmaçãoo da senha é diferente da nova senha informada");
		return false;
	}

	if (document.getElementById("novasenha").value.length != 4)
	{
		window.alert("Senha inválida. Sua senha deve ter 4 dígitos numéricos.");
		return false;
	}
	
	return true;
}


//Validacao de Login de Cliente

function ValidaLoginCliente()
{
	var campoSenha = false;
	
	if (document.logintorpedocliente.senha) {
		campoSenha = true;
	}
	
	if ((document.logintorpedocliente.ddd.value == "")
		|| (document.logintorpedocliente.meuoi.value == "")
		|| (campoSenha && document.logintorpedocliente.senha.value == ""))
	{
		window.alert("Todos os campos devem estar preenchidos!");
		return false;
	}

	return true;
}

//Valida Login Nao cliente

function ValidaLoginNaoCliente()
{

	if ((document.logintorpedonaocliente.email.value == "")
		|| (document.logintorpedonaocliente.senha.value == ""))
	{
		window.alert("Todos os campos devem estar preenchidos!");
		return false;
	}

	return true;
}

//Torpedo
//Reinicializacao de senhas Cliente
function ValidaEnvioDeTorpedo()
{

	if ((document.torpedo.para_ddd.value == "")
		|| (document.torpedo.para_numero.value == "")
		|| (document.torpedo.mensagem.value == "")
		){
		window.alert("Os campos referentes ao Número Oi do destinatário e o corpo da mensagem devem estar preenchidos");
		return false;
	}
	return true;
}

// Validacao de CPF

function ValidaCPF(CPF){

   var i;
   cpf_value = LIMP(CPF);
   s = cpf_value;
   document.getElementById("cpf").value = s;

   var c = s.substr(0,9);
   var dv = s.substr(9,2);
   var d1 = 0;

   for (i = 0; i < 9; i++)
   {
      d1 += c.charAt(i)*(10-i);
   }

   if (d1 == 0){
      return (0);
   }

   d1 = 11 - (d1 % 11);

   if (d1 > 9) d1 = 0;
   if (dv.charAt(0) != d1)
   {
      return (0);
   }

   d1 *= 2;

   for (i = 0; i < 9; i++)
   {
      d1 += c.charAt(i)*(11-i);
   }

   d1 = 11 - (d1 % 11);

   if (d1 > 9) d1 = 0;
   if (dv.charAt(1) != d1)
   {
      return (0);
   }

   return (1);

} 

//Validacoes de CNPJ
function ValidaCNPJ(CNPJ)
{
   CNPJ = LIMP(CNPJ);
   if(isNUMB(CNPJ) != 1)
   {
      return(0);
   }
   else
   {
      if (CNPJ == '12345678901234'){
         return(1);
      }
      if(CNPJ == 0){
         return(0);
      }
      else{
         g=CNPJ.length-2;
         if(RealTestCNPJ(CNPJ,g) == 1)
         {
            g=CNPJ.length-1;
            if(RealTestCNPJ(CNPJ,g) == 1)
            {
               return(1);
            }
            else
            {
               return(0);
            }
         }
         else
         {
            return(0);
         }
      }
   }
}

function isNUMBER(what){
	if(isNUMB(what.value) != 1){
	  window.alert("Neste campo só são permitidos números!");
	  what.value="";
	  return false;
	}
	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 RealTestCNPJ(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);
   }
}


//Critica Cadastro
function ValidaCadastroCliente(){

	if ((document.cadastrotorpedocliente.ddd.value == "")
	|| (document.cadastrotorpedocliente.meuoi.value == "")
	|| (document.cadastrotorpedocliente.dia.value == "")
	|| (document.cadastrotorpedocliente.mes.value == "")
	|| (document.cadastrotorpedocliente.cpf.value == "")
	|| (document.cadastrotorpedocliente.ano.value == "")
	)
	{
		window.alert("Todos os campos devem estar preenchidos!");
		return false;
	}
	
	if ((ValidaCPF(document.cadastrotorpedocliente.cpf.value) == 0) && (ValidaCNPJ(document.cadastrotorpedocliente.cpf.value) == 0))
	{
		window.alert("O número do CPF/CNPJ informado não é válido. Informe o seu CPF/CNPJ utilizando somente dígitos.");
		return false;
	}

	return true;
}

function ValidaCadastroNaoCliente()
{

	// valida quanto a nulidade
	if ((document.getElementById("estado").value == "")
	 	|| (document.getElementById("cepi").value == "")
	 	|| (document.getElementById("cepf").value == "")
	 	|| (document.getElementById("cidade").value == "")
	 	|| (document.getElementById("bairro").value == "")
	 	|| (document.getElementById("complemento").value == "")
	 	|| (document.getElementById("numero").value == "")
	 	|| (document.getElementById("endereco").value == "")
	 	|| (document.getElementById("email").value == "")
	 	|| (document.getElementById("dia").value == "")
	 	|| (document.getElementById("mes").value == "")
	 	|| (document.getElementById("ano").value == "")
		|| (document.getElementById("nome").value == ""))
	{
		window.alert("Com exceção do CPF, todos os campos são obrigatórios!");
		return false;
	}

	if (!document.getElementById("email").value.match(/^[.\w-]+@([\w-]+\.)+[a-zA-Z]{2,6}$/))
	{
		window.alert("E-mail inválido, verifique");
		return false;
	}

	if (document.getElementById("cpf").value != ""){
		if (ValidaCPF(document.getElementById("cpf").value) == 0)
		{
			window.alert("O número do CPF/CNPJ informado não é válido. Informe o seu CPF/CNPJ utilizando somente dígitos.");
			return false;
		}
	}

	document.getElementById("cep").value = document.getElementById("cepi").value + document.getElementById("cepf").value;


	document.getElementById("datanascimento").value 
				= document.getElementById("dia").value 
				+ "/" + document.getElementById("mes").value 
				+ "/" + document.getElementById("ano").value;

	return true;


}


//Reinicializacao de senhas Cliente
function ValidaResetSenhaCliente()
{

	if ((document.reinicializarsenhacliente.dados.dddOi.value == "")
		|| (document.reinicializarsenhacliente.dados.numeroOi.value == "")
		|| (document.reinicializarsenhacliente.dia.value == "")
		|| (document.reinicializarsenhacliente.mes.value == "")
		|| (document.reinicializarsenhacliente.ano.value == "")
		|| (document.reinicializarsenhacliente.dados.cpf.value == "")){
		window.alert("Todos os campos devem estar preenchidos!");
		
		return false;
	}

	if ((ValidaCPF(document.reinicializarsenhacliente.dados.cpf.value) == 0) && (ValidaCNPJ(document.reinicializarsenhacliente.dados.cpf.value) == 0))
	{
		window.alert("O número do CPF/CNPJ informado não é válido. Informe o seu CPF/CNPJ utilizando somente dígitos.");
		return false;
	}

	return true;
}

function ValidaResetSenhaNaoCliente()
{

	if ((document.getElementById("email").value == "")
		|| (document.getElementById("dia").value == "")
		|| (document.getElementById("mes").value == "")
		|| (document.getElementById("ano").value == ""))
	{
		window.alert("Todos os campos devem estar preenchidos!");
		return false;
	}

	if (!document.getElementById("email").value.match(/^[.\w-]+@([\w-]+\.)+[a-zA-Z]{2,6}$/))
	{
		window.alert("E-mail inválido, verifique");
		return false;
	}

	if (document.getElementById("cpf").value != "")
	{
		if (ValidaCPF(document.getElementById("cpf").value) == 0)
		{
			window.alert("O número do CPF/CNPJ informado não é válido. Informe o seu CPF/CNPJ utilizando somente dígitos.");
			return false;
		}
	}

	return true;
}


// Acerta o target do form
function acertaSite(form)
{
	if (form.SITE.value == "") return false;
	
	form.action=form.SITE.value;
	return true;
	
}



function pulaCampo(item,tipo,campo)
{

	if (item == null)
		return false;

	if (campo == null)
		return false;

	if (item.value.length == item.maxLength)
		campo.focus();

	return true;

}

function ValidaLoginClienteTopo()
{

	if ((document.frm.ddd.value == "")
		|| (document.frm.numero.value == "")) {
		window.alert("Todos os campos devem estar preenchidos!");
		return false;
	}

	return true;
}


function validaGenerico(item,tipo,form)
{

	if (item == null)
		return false;


	switch (tipo)
	{
		// caso seja numérico
		case 'n':	if (isNaN(parseInt(item.value)) && item.length > 0)
					{
						window.alert("o campo possui caracteres não numéricos");
						return false;
					}
					break;

	}

	try {
		if (item.value.length == item.maxLength && form != null && form.elements[item.tabIndex]) {
			form.elements[item.tabIndex].focus();
		}
	} catch(e){}
	
	return true;

}

// Marca/desmarca checkboxes com id de prefixo prefix e numerados sequencialmente
function selecionaOpcoes(prefix, obj)
{
	var check = (obj.checked) ? true : false;

	var c = 1;

	while (o = document.getElementById(prefix + c++))
	{
		if (o.type=='checkbox') o.checked=check;
	}
}


// Valida formulário de Seja um Parceiro
function validaFormParceiro(frm)
{
	var mail = document.sejaParceiro.email.value;

	var campos = new Array('razao_social', 'cnpj', 'endereco_empresa', 'numero', 'bairro', 'cidade', 'estado', 'cep', 'telefone', 'fax', 'email');
	var msgs = new Array('Razão social inválida!', 'O número do CPF/CNPJ informado não é válido. Informe o seu CPF/CNPJ utilizando somente dígitos.', 'Endereço inválido!',
				 'Número inválido!', 'Bairro inválido!', 'Cidade inválida!', 'Estado inválido!',
				 'CEP inválido.', 'Telefone inválido', 'FAX inválido!', 'Email inválido!');

	for (i = 0; i < campos.length; i++)
	{
		eval ("var obj=frm." + campos[i]);

		if (obj.value == "" || (campos[i]=='cnpj' && !ValidaCNPJ(obj.value)))
		{
			alert(msgs[i]);
			//obj.focus();
			return false;
		}
	}

	if (!mail.match(/^[.\w-]+@([\w-]+\.)+[a-zA-Z]{2,6}$/))
	{
		window.alert("E-mail inválido, verifique");
		return false;
	}

	return true;
}

function ValidaSugestoes()
{
	var mail = document.sugestoes.email.value;
	var data = document.sugestoes.dataNascimento.value;
	var dataInvalida = "Data de nascimento inválida, o formato é dd/mm/aaaa";

	if ((document.sugestoes.nome.value == "")
		|| (mail == "")
		|| (document.sugestoes.ddd.value == "")
		|| (document.sugestoes.telefone.value == "")
		|| (document.sugestoes.dataNascimento.value == "")
		|| (document.sugestoes.mensagem.value == ""))
	{
		window.alert("Todos os campos precisam estar preenchidos");
		return false;
	}

	if (!mail.match(/^[.\w-]+@([\w-]+\.)+[a-zA-Z]{2,6}$/))
	{
		window.alert("E-mail inválido, verifique");
		return false;
	}


	if (data.length != 10)
	{
		window.alert(dataInvalida);
		return false;
	}
	
	var dia = data.substr(0,2);
	var mes = data.substr(3,2);
	var ano = data.substr(6,4);

	if (isNaN(parseInt(dia)) || isNaN(parseInt(mes)) || isNaN(parseInt(ano)))
	{
		window.alert(dataInvalida);
		return false;
	}


	if (mes > 12 || mes < 1)
	{
		window.alert(" Mes inválido ");
		return false;
	}
	if (ano > 2005 || ano < 1900)
	{
		window.alert(" Ano inválido ");
		return false;
	}
	// fazer o limite por mes
	if (dia > 31 || dia < 1)
	{
		window.alert(" Dia inválido");
	}


	return true;
}

function callHotSite(url2go, width, height){

	hotsite = window.open(url2go, "hotsite", 'width=' + width + ', height=' + height + ', toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes,left=0');
	return false;
}

// Form pré - fale com a oi
function trataFormPreFale(frm)
{
	if (document.getElementById('rdduvidas').checked)
	{
		if (frm.assunto.value == '')
		{
			alert("Por favor, selecione o assunto.");
			return false;
		}
		else
		{
			document.location.href = frm.assunto.value;
			return false;
		}
	}
	else
	{
		document.location.href = ("/wb/POi/POi_sugestoes_e_criticas?categoria_faq=" + ((frm.assunto.value).split("categoria="))[1] + "&assunto="+frm.assunto.selectedIndex);
		return false;
	}
	
	return false;
}


// Calcula o Dígito Verificador de um aparelho
function calculaDV(ddd, tel)
{
	somat=0;
	digito=0;
	peso = new Array("5", "4", "3", "2", "7", "6", "5", "4", "3", "2");

	valor = new String(ddd) + new String(tel);
	tam = 10;

	for (i = 0; i < tam ; i++)
	{
		somat += valor.charAt(i) * peso[i]
	}

	digito = (11 - (somat % 11));
	if ((digito == 10) || (digito == 11))
		digito = 0

	return(digito);
}

function mostraDV(ddd, tel)
{
	if (!ddd.match(/^[0-9]{2}$/))
	{
		alert('DDD inválido!');
		return;
	}

	if (!tel.match(/^[0-9]{8}$/))
	{
		alert('Telefone inválido!');
		return;
	}

	document.getElementById('spandv').innerHTML='<b>O número do DV que você deve informar ao seu banco é: ' + calculaDV(ddd, tel) + '</b>';
}


