/* ------------------------------------------------------------------ */
/*     NÚCLEO do Preenchimento de SELECTS                             */
/* ------------------------------------------------------------------ */

function create_opcao(id,opcao) {
   var new_opcao = document.createElement("option");
   var texto = document.createTextNode(opcao);
   new_opcao.setAttribute("value",id);
   new_opcao.appendChild(texto); //Adiciona o texto a OPTION.
   return new_opcao; // Retorna a nova OPTION.
}

/* ------------------------------------------------------------------ */
/*     FIM DO NÚCLEO                                                  */
/* ------------------------------------------------------------------ */

function ValidaContato() {
 if(document.formulario.nome.value.length == 0) {
    alert("Preencha seu nome.");
    document.formulario.nome.focus();
    return false;
 }
 if(document.formulario.email.value.length == 0) {
    alert("Preencha seu e-mail.");
    document.formulario.email.focus();
    return false;
 } else {
     var email = document.formulario.email.value;
     if(email.indexOf('@') == "-1" ||
		email.lastIndexOf('.') < email.indexOf('@') ||
		email.indexOf('@') == "0" ||
		email.indexOf('.') == (email.indexOf('@'))+1 ||
		email.lastIndexOf('.') == (email.length)-1 ||
		email.length < 5)
		{
			alert("Verifique seu e-mail.")
            document.formulario.email.focus();
			return false
		}
 }
 if(document.formulario.mensagem.value.length == 0) {
    alert("Digite sua mensagem.");
    document.formulario.mensagem.focus();
    return false;
 }
}

function AtivarAba(valor) {
    document.getElementById('passo1').className = 'inativo';
    document.getElementById('passo2').className = 'inativo';
    document.getElementById('passo3').className = 'inativo';
    document.getElementById('passo4').className = 'inativo';

    document.getElementById('passo1_conteudo').style.display='none';
    document.getElementById('passo2_conteudo').style.display='none';
    document.getElementById('passo3_conteudo').style.display='none';
    document.getElementById('passo4_conteudo').style.display='none';

    document.getElementById('passo'+valor).className = 'ativo';
    document.getElementById('passo'+valor+'_conteudo').style.display='block';
}

function VerificaRegistro() {
 if(document.formulario.dominio.value.length == 0) {
    AtivarAba(1);
    alert("Digite o domínio que deseja hospedar.");
    document.formulario.dominio.focus();
    return false;
 }

 if(document.formulario.registrar[0].checked == false && document.formulario.registrar[1].checked == false) {
    AtivarAba(1);
    alert("O que deseja fazer com seu dominio.");
    document.formulario.dominio.focus();
    return false;
 }

 if(document.formulario.pessoa[0].checked) {
  if(document.formulario.nome.value.length == 0) {
    AtivarAba(2);
    alert('Preencha seu nome.');
    document.formulario.nome.focus();
    return false;
  }
  if(document.formulario.cpf.value.length == 0) {
    AtivarAba(2);
    alert('Preencha seu CPF.');
    document.formulario.cpf.focus();
    return false;
  } else {
   if(validarCPF(document.formulario.cpf.value) == false) {
    AtivarAba(2);
    alert('CPF inválido. Verifique!');
    document.formulario.cpf.focus();
    return false;
   }
  }
 }

 if(document.formulario.pessoa[1].checked) {
  if(document.formulario.razao.value.length == 0) {
    AtivarAba(2);
    alert('Preencha a razão social da empresa.');
    document.formulario.razao.focus();
    return false;
  }
  if(document.formulario.fantasia.value.length == 0) {
    AtivarAba(2);
    alert('Preencha o nome fantasia da empresa.');
    document.formulario.fantasia.focus();
    return false;
  }
  if(document.formulario.cnpj.value.length == 0) {
    AtivarAba(2);
    alert('Preencha o CNPJ da empresa.');
    document.formulario.cnpj.focus();
    return false;
  }
  if(document.formulario.responsavel.value.length == 0) {
    AtivarAba(2);
    alert('Preencha o nome do responsável pela empresa.');
    document.formulario.responsavel.focus();
    return false;
  }
 }

 if(document.formulario.email.value.length == 0) {
    AtivarAba(2);
    alert("Preencha o e-mail.");
    document.formulario.email.focus();
    return false;
 } else {
     var email = document.formulario.email.value;
     if(email.indexOf('@') == "-1" ||
		email.lastIndexOf('.') < email.indexOf('@') ||
		email.indexOf('@') == "0" ||
		email.indexOf('.') == (email.indexOf('@'))+1 ||
		email.lastIndexOf('.') == (email.length)-1 ||
		email.length < 5)
		{
            AtivarAba(2);
			alert("E-mail inválido. Verifique!!!.")
            document.formulario.email.focus();
			return false
		}
 }

 if(document.formulario.telefone.value.length == 0) {
    AtivarAba(2);
    alert('Preencha o CEP.');
    document.formulario.telefone.focus();
    return false;
 }
 if(document.formulario.cep.value.length == 0) {
    AtivarAba(2);
    alert('Preencha o CEP.');
    document.formulario.cep.focus();
    return false;
 }
 if(document.formulario.endereco.value.length == 0) {
    AtivarAba(2);
    alert('Preencha o endereço.');
    document.formulario.endereco.focus();
    return false;
 }
 if(document.formulario.numero.value.length == 0) {
    AtivarAba(2);
    alert('Preencha o número.');
    document.formulario.numero.focus();
    return false;
  }
  if(document.formulario.bairro.value.length == 0) {
    AtivarAba(2);
    alert('Preencha o bairro.');
    document.formulario.bairro.focus();
    return false;
  }
  if(document.formulario.cidade.value == "") {
    AtivarAba(2);
    alert('Qual a cidade?');
    document.formulario.cidade.focus();
    return false;
  }
  if(document.formulario.estado.value == "") {
    AtivarAba(2);
    alert('Qual o Estado?');
    document.formulario.estado.focus();
    return false;
  }
  if(document.formulario.aceito.checked == false) {
    AtivarAba(4);
    alert('Leia atentamente o contrato e, se concorda, selecione a caixa para continuar o registro.');
    document.formulario.aceito.focus();
    return false;
  }

 document.formulario.submit();
}

function Avancar() {
 if(document.getElementById('passo4').className == 'ativo') {
  VerificaRegistro();
 } else {

 if(document.getElementById('passo3').className == 'ativo') {
  AtivarAba(4);
 }

 if(document.getElementById('passo2').className == 'ativo') {
  AtivarAba(3);
 }

 if(document.getElementById('passo1').className == 'ativo') {
  AtivarAba(2);
 }
 }
}

function Voltar() {
 if(document.getElementById('passo2').className == 'ativo') {
  AtivarAba(1);
 }

 if(document.getElementById('passo3').className == 'ativo') {
  AtivarAba(2);
 }

 if(document.getElementById('passo4').className == 'ativo') {
  AtivarAba(3);
 }

}

function PessoaFisica() {
 document.formulario.razao.value = "";
 document.formulario.fantasia.value = "";
 document.formulario.cnpj.value = "";

 document.getElementById('pessoa_fisica').style.display = "block";
 document.getElementById('pessoa_juridica').style.display = "none";
}

function PessoaJuridica() {
 document.formulario.nome.value = "";
 document.formulario.cpf.value = "";

 document.getElementById('pessoa_fisica').style.display = "none";
 document.getElementById('pessoa_juridica').style.display = "block";
}


function PegaCidade(cid) {
    document.formulario.cidade.innerHTML= "";
    new_opcao = create_opcao(""," Carregando, aguarde! ");
    document.formulario.cidade.appendChild(new_opcao);
 jphp("POST","jphp/pega_cidade.php","cid="+cid,"mostra_cidades");
}

function mostra_cidades(html) {
  var ped1 = html.split(";");
  var tam = ped1.length;
 // var novo = "";
 document.formulario.cidade.innerHTML= "";

    new_opcao = create_opcao("","Selecione sua Cidade");
    document.formulario.cidade.appendChild(new_opcao);

  for(i=0; i<tam -1; i++) {
    var vem = ped1[i].split("|");
    new_opcao = create_opcao(vem[0],vem[1]);
    document.formulario.cidade.appendChild(new_opcao);

  }

}



/* formatacao e validacao de campos */

function Info(campo,texto) {
 var local = document.getElementById('info'+campo);
 local.innerHTML = texto;
}

function Numeros()
{
	if(event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 8)
		event.returnValue = true;
	else
		event.returnValue = false;
}

function FormataCNPJ(x,tecla){
        // Por Tiago Araujo Silva (tiago@tiagoaraujo.com)

        separador="-";
        tecla=tecla.keyCode;
        valor=x.value.split('');
        formatado="";
        i=0;

        while(i<valor.length){
            caractere=valor[i];
            numeros=/^\d+$/;
            if(numeros.test(caractere) || caractere==separador){ formatado+=String(caractere);}
            if((formatado.length==2) && tecla!=8){formatado+="."; i++;}
            if((formatado.length==6) && tecla!=8){formatado+="."; i++;}
            if((formatado.length==10) && tecla!=8){formatado+="/"; i++;}
            if((formatado.length==15) && tecla!=8){formatado+="-"; i++;}
            i++;
        }
        x.value=formatado;
    }

function formataTELEFONE(x,tecla){
        // Por Tiago Araujo Silva (tiago@tiagoaraujo.com)

        separador="-";
        tecla=tecla.keyCode;
        valor=x.value.split('');
        formatado="";
        i=0;

        while(i<valor.length){
            caractere=valor[i];
            numeros=/^\d+$/;
            if(numeros.test(caractere) || caractere==separador){ formatado+=String(caractere);}
            if((formatado.length==2) && tecla!=8){formatado+=" "; i++;}
            if((formatado.length==7) && tecla!=8){formatado+=separador; i++;}
            i++;
        }
        x.value=formatado;
}

function validarCPF(cpf)
{
	cpf = cpf.replace("-", "")
	cpf = cpf.replace(".", "")
	cpf = cpf.replace(".", "")

	if(cpf.length < 11)
		return false

	var cpfCount = ""

	for(i=0;i<10;i++)
	{
		cpfCount = ""

		for(j=0;j<11;j++)
			cpfCount += i

		if(cpfCount == cpf)
		{
			return false
			break
		}
	}

	var a = []
	var b = new Number
	var c = 11

	for(i=0; i<11; i++)
	{
		a[i] = cpf.charAt(i)
		if(i < 9) b += (a[i] * --c)
	}

	if((x = b % 11) < 2)
		a[9] = 0
	else
		a[9] = 11-x

	b = 0
	c = 11
	for(y=0; y<10; y++) b += (a[y] * c--)

	if((x = b % 11) < 2)
		a[10] = 0
	else
		a[10] = 11-x

	if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]))
		return false

	return true
}

function formataCEP(x,tecla){
        // Por Tiago Araujo Silva (tiago@tiagoaraujo.com)

        separador="-";
        tecla=tecla.keyCode;
        valor=x.value.split('');
        formatado="";
        i=0;

        while(i<valor.length){
            caractere=valor[i];
            numeros=/^\d+$/;
            if(numeros.test(caractere) || caractere==separador){ formatado+=String(caractere);}
            if((formatado.length==5) && tecla!=8){formatado+=separador; i++;}
            i++;
        }
        x.value=formatado;
}

function FormataCPF(x,tecla){
        // Por Tiago Araujo Silva (tiago@tiagoaraujo.com)

        separador="-";
        tecla=tecla.keyCode;
        valor=x.value.split('');
        formatado="";
        i=0;

        while(i<valor.length){
            caractere=valor[i];
            numeros=/^\d+$/;
            if(numeros.test(caractere) || caractere==separador){ formatado+=String(caractere);}
            if((formatado.length==3) && tecla!=8){formatado+="."; i++;}
            if((formatado.length==7) && tecla!=8){formatado+="."; i++;}
            if((formatado.length==11) && tecla!=8){formatado+="-"; i++;}
            i++;
        }
        x.value=formatado;
}

function FormataData(campo,teclapres)
{
	var tecla = document.getElementById(campo).value;
	tecla = tecla.length;
	tecla = document.getElementById(campo).value.substring(tecla-1,tecla);
	if(tecla>-1 && tecla<10)
	{
		vr = document.getElementById(campo).value;
		var erro=0;
		vr = vr.replace( ".", "" );
		vr = vr.replace( "/", "" );
		vr = vr.replace( "/", "" );
		tam = vr.length+1;
		if(tam>2)
			{
			dia = (document.getElementById(campo).value.substring(0,2));
			if(dia<01 || dia>31)
				{
				Info(campo,"Data inv&aacute;lida. <b>DIA</b>");
				erro=1;
				} else { Info(campo,""); }
			}
		if(tam>4)
			{
			mes = (document.getElementById(campo).value.substring(3,5));
			if(mes<01 || mes>12)
				{
                Info(campo,"Data inv&aacute;lida. <b>M&Ecirc;S</b>");
				erro=2;
				}
			else
				{
				if(mes == 4 || mes == 6 || mes == 9 || mes == 11)
					{
						if(dia > 30)
						{
					Info(campo,"Para o m&ecirc;s em quest&atilde;o n&atilde;o existe este dia.");
					erro=1;
						}
					}
				else if(mes==02 && dia>29)
				{
					Info(campo,"O m&ecirc;s de fevereiro tem no m&aacute;ximo 29 dias.");
					erro=1;
				}
				}
			}
		if(tam==9)
			{
			ano = (document.getElementById(campo).value.substring(6,10));
			if(mes==02 && (ano%4!=0) && dia>28)
			{
				Info(campo,"Este ano n&atilde;o &eacute; bissexto.");
				erro=3;
			}
			}
		if(erro==0)
			{
			if ( teclapres.keyCode != 9 && teclapres.keyCode != 8 )
				{
				if(tam==3)
					{
					document.getElementById(campo).value = vr.substr( 0, tam - 1  ) + '/';
					}
				else if ( tam >3 && tam < 5 )
					document.getElementById(campo).value = vr.substr( 0, tam - 2  ) + '/' + vr.substr( tam - 2, tam );
				else if ( tam >= 5 && tam <= 10 )
					document.getElementById(campo).value = vr.substr( 0, 2 ) + '/' + vr.substr( 2, 2 ) + '/' + vr.substr( 4, 4 );
				}
			}
		else if(erro==1)
			{
			document.getElementById(campo).value="";
			var teste1=document.getElementById(campo).value;
			}
		else if(erro==2)
			{
			document.getElementById(campo).value="";
			document.getElementById(campo).value=dia+'/';
			}
		else if(erro=3)
			{
			document.getElementById(campo).value="";
			document.getElementById(campo).value=dia+'/'+mes+'/';
			}
		}
		else
		{
	if(teclapres.keyCode!=8 && tecla!='/')
		{
		Info(campo,'Caracteres inv&aacute;lidos');
		tecla=document.getElementById(campo).value.length;
		document.getElementById(campo).value=document.getElementById(campo).value.substring(0,tecla-1);
		}
	}
	temletra = /^[0-9]{1,}$/;
	tecla=document.getElementById(campo).value;
	tecla=tecla.replace(document.getElementById(campo).value.substring(2,3),"");
	tecla=tecla.replace(document.getElementById(campo).value.substring(5,6),"");
	if(tecla.search(temletra)==-1)
	document.getElementById(campo).value="";
}