
var error =1;
$(document).ready(function(){

	 
	 $("#sufixo").change( function() {
 			
			if($('#sufixo').val() == 'org.br'){
			   alert("Para registrar domínio ORG.BR é exigido a documentaçao que comprove a natureza da instituiçao nao governamental sem fins lucrativos e o CNPJ.\n\r Nos casos em que a instituiçao é um consulado ou uma embaixada, a exigencia do CNPJ para esse DPN é dispensada");
		    }
			
			if($('#sufixo').val() == 'coop.br'){
			   alert("Exige-se o CNPJ e comprovante de registro junto a Organizaçao das Cooperativas Brasileiras");
		    }
			
			
			
      });

     
	 
	
	/*$('#sparceiro').click(function(){
		if(this.checked == true)
			document.getElementById('trParceria').style.display = '';
		else
			document.getElementById('trParceria').style.display = 'none';
	});*/
	
	
	$('#nparceiro').click(function(){
		if(this.checked == true)
			document.getElementById('trParceria').style.display = 'none';
		else
			document.getElementById('trParceria').style.display = '';
	});


	var j = '';
	$('.check').click(function(){

		if(this.checked == true)			   
			j += this.value + '|';
		else
			j = j.split(this.value + '|');
   });
	
	
	
	$("form").submit( function () {
		  
document.getElementById('dominio').value = $('#strdominio').val() + '|' + j + $('#extdominio').val();
		
		$('#carregamento').html("<img src='imagens/ajax.gif'>");
		
		if($('#strdominio').val() == ''){
			alert('Campo domínio nao pode ser vazio');
			$('#carregamento').html("");
			return false;
		}
		
		if($('#tipodominiosel').val() == ''){
			alert('Por favor selecione uma das 3 opção de registro de domínio');
			$('#carregamento').html("");
			return false;
		}
		
		
		
		if($('#tipopessoasel').val() == ''){
			alert('Por favor informe o típo de cliente');
			$('#carregamento').html("");
			return false;
		}
		
		if($('#documento').val() == ''){
			alert('Por favor informe o CNPJ / CPF');
			$('#carregamento').html("");
			return false;
		}
		
		if($('#tipopessoasel').val() == 'F'){
			if(VerificaCPF($('#documento').val())==false){
			  	//alert('Vai retornar falso');
				$('#carregamento').html("");
				return false;
			}
		}else{
			
			if(valida_cnpj(document.getElementById('documento'))==false){
				$('#carregamento').html("");
			   return false;
			}
			
		}
		
		var dominio = $('#strdominio').val()+'.'+$('#sufixo').val();
		
		
		
		if($('#sufixo').val()!='com' || $('#sufixo').val()!='net' || $('#sufixo').val()!='cc' || $('#sufixo').val()!='info' || $('#sufixo').val()!='biz' || $('#sufixo').val()!='tv' || $('#sufixo').val()!='name' || $('#sufixo').val()!='ws'){
			
			var perg = parseInt($('#tipodominiosel').val());
			
			$.getJSON("ajaxEppDominioInfo.php?dominio="+dominio+"&doc="+$('#documento').val(), function(data){
				 if(data.status == 1){
				    	
			    	   if(perg==1){
			    		   
			    		   if(data.doc!=$('#documento').val()){
			    			  alert('ERRO: Esse domínio não pertence a entidade(CPF/CNPJ) informado'); 
			    			  $('#carregamento').html("");
			    			 error = 0;
			    		   }else{
			    			 error = 1; 
			    		   }
			    		   
			    		   
			    		   
			    	   }else{
			    		   alert('ERRO: Não é possível registrar esse domínio, pois o mesmo já esta registrado em outra entidade');
			    		   $('#carregamento').html("");
			    		   error = 0;
			    	   }
			    	   
			       }else{
			    	   error = 1;
			       }
			       
			       
			 });
		}
		
	 return true;	
	 });

	


	/*$('#assinar').click(function(){
		
	});*/
	
	$(".tipodominio").click(function() {
		$("#tipodominiosel").val(this.value);
	});
	
	$(".tipopessoa").click(function() {
		$("#tipopessoasel").val(this.value);
		//alert($("#tipopessoa").val());
		$("#lbCampo").fadeIn("slow");
		if(this.value=='F'){
			$("#lbPessoa").html('CPF: ');
		}else{
			$("#lbPessoa").html('CNPJ: ');
		}
		//alert($("#tipopessoasel").val());
	});
	
	$("#btVerificar").click(function () { 
		  
		  if($('#strdominio').val()!=""){
			  var img = "<img src='imagens/ajax.gif' width='24' height='24' />";
		      $("#resp").html(img);
			  $.ajax({
					   type: "POST",
					   url: "br.com.splicenet.util/api_dominio.php",
					   data: "dominio="+$('#strdominio').val()+"&sufixo="+$('#sufixo').val(),
					   success: function(msg){
						 //alert(msg);
                         if(msg==1){
							 $("#resp").html('<font color=blue size=2><b>Disponível</b></font>');
							 //$("#contracao").fadeIn("fast");
							 //$("#btContratar").fadeIn("fast");
							 var str = $('#strdominio').val()+'|.'+$('#sufixo').val();
							 $("#dominio").html(str);
						 }else{
							 $("#resp").html('<font color=red size=2><b>Indisponível</b></font>');
							 //$("#contracao").fadeOut("fast");
							 //$("#btContratar").fadeOut("fast");
						 }
						 
						 
					   }
				});
		  }else{
			  alert('Por favor digite um domínio valido');  
		  }
	   });
	
});


function VerificaCPF () {
	if (vercpf(document.getElementById('documento').value)){
		 return true;
	}else{
		errors="1";
		if (errors){ 
			alert('CPF NÃO VÁLIDO');
			return false;
		}
	    document.retorno = (errors == '');
	    }
	}
function vercpf (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")
			return false;
		add = 0;
		for (i=0; i < 9; i ++)
			add += parseInt(cpf.charAt(i)) * (10 - i);
		rev = 11 - (add % 11);
		if (rev == 10 || rev == 11)
			rev = 0;
		if (rev != parseInt(cpf.charAt(9)))
			return false;
		add = 0;
		for (i = 0; i < 10; i ++)
			  add += parseInt(cpf.charAt(i)) * (11 - i);
		rev = 11 - (add % 11);
		if (rev == 10 || rev == 11)
			   rev = 0;
		if (rev != parseInt(cpf.charAt(10)))
				return false;
			//alert('O CPF INFORMADO É VÁLIDO.');
		return true;
	}

 function valida_cnpj(campo)  
       {  
       //Declaração as variáveis  
       var numeros, digitos, soma, i, resultado, pos, tamanho, digitos_iguais, cnpj;  
       cnpj = campo.value;  
           //Verificando se o campo é nulo  
       if (cnpj.length == 0) {  
             return false;  
             }  
   
     //Filtrar o campo para verificar se está com máscara  
    /*var filtro = /\d{2,3}.\d{3}.\d{3}\/\d{4}-\d{2}/;  
    if(!filtro.test(cnpj)){  
      window.alert("CNPJ inválido. Tente novamente.");  
      return false;  
    }  */
       //Ultilização expressão regular para retirar o que não for número  
       cnpj = cnpj.replace(/\D+/g, '');  
       digitos_iguais = 1;  
   
       for (i = 0; i < cnpj.length - 1; i++)  
             if (cnpj.charAt(i) != cnpj.charAt(i + 1))  
                   {  
                   digitos_iguais = 0;  
                   break;  
                   }  
       if (!digitos_iguais)  
             {  
             tamanho = cnpj.length - 2  
             numeros = cnpj.substring(0,tamanho);  
             digitos = cnpj.substring(tamanho);  
             soma = 0;  
             pos = tamanho - 7;  
             for (i = tamanho; i >= 1; i--)  
                   {  
                   soma += numeros.charAt(tamanho - i) * pos--;  
                   if (pos < 2)  
                         pos = 9;  
                   }  
             resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;  
             if (resultado != digitos.charAt(0)){  
                 alert('CNPJ inválido');  
                   return false;  
                   }  
             tamanho = tamanho + 1;  
             numeros = cnpj.substring(0,tamanho);  
             soma = 0;  
             pos = tamanho - 7;  
             for (i = tamanho; i >= 1; i--)  
                   {  
                   soma += numeros.charAt(tamanho - i) * pos--;  
                   if (pos < 2)  
                         pos = 9;  
                   }  
   
             resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;  
             if (resultado != digitos.charAt(1)){  
                     alert('CNPJ inválido');  
                   return false;  
                   }  
             return true;  
             }  
       else  
             alert('CNPJ inválido');  
           return false;  
 }