$(function(){

	//alert("aaa");

	$("#estado").livequery('change', function(){doBusca();});

	$("#cpfcnpj").maskedinput("999.999.999-99", {placeholder : " "});
	$("#dtnascimento").maskedinput("99/99/9999", {placeholder : " "});
	$("#cep").maskedinput("99999-999", {placeholder : " "});
	$("#ddd1").maskedinput("99", {placeholder : " "});
	$("#ddd2").maskedinput("99", {placeholder : " "});
	$("#ddd3").maskedinput("99", {placeholder : " "});
	$("#telefone1").maskedinput("(99) 9999-9999", {placeholder : " "});
	$("#telefone2").maskedinput("(99) 9999-9999", {placeholder : " "});
	$("#telefone3").maskedinput("(99) 9999-9999", {placeholder : " "});

	$("#formClientes").validate(
	{
		rules: {
			pf: "required",
			nome:  "required",
			sobrenome: "required",
			cpfcnpj: "required",
			email: {
				required: true,
				email: true
			},
			senha: "required",
			repitaSenha: "required",
			cep: "required",			
			tipo_endereco: "required",
			identifique_end: "required",
			nomeendereco: "required",
			sobrenomeendereco: "required",
			logradouro: "required",
			endereco_cadastro: "required",
			numero: "required",
			bairro: "required",
			telefone1: "required",
			email_entrega: "required"

		},
		messages: {
			pf: "Obrigatório",
			nome:  "Obrigatório",
			sobrenome: "Obrigatório",
			cpfcnpj: "Obrigatório",
			email: "Obrigatório",
			senha: "Obrigatório",
			repitaSenha: "Obrigatório",
			cep: "Obrigatório",
			tipo_endereco: "Obrigatório",			
			identifique_end: "Obrigatório",
			nomeendereco: "Obrigatório",
			sobrenomeendereco: "Obrigatório",
			logradouro: "Obrigatório",
			endereco_cadastro: "Obrigatório",
			numero: "Obrigatório",
			bairro: "Obrigatório",
			telefone1: "Obrigatório",
			email_entrega: "Obrigatório"
		}
	});

    $('#tipopessoaF, #tipopessoaJ').click(function(){


    	setTipoPessoa($(this).val());
    	
    });
	

	$("#botaocep").click(function(){

		var optionst = {
			url     : 'http://' + window.location.hostname + window.location.pathname.replace('cadastro/novo', 'frete/consultarendereco/'),
			success:       showResponseCalcFrete,
			beforeSubmit:  calcFretePreSubmit,
			clearForm: false,
			resetForm: false,
			dataType: 'xml'
		};

		$("#formClientes").ajaxSubmit(optionst);
	});


	function calcFretePreSubmit(xml)
	{

	}

	function showResponseCalcFrete(xml)
	{
		nodes = xml.getElementsByTagName('resposta');
		for(i=0; i< nodes[0].childNodes.length; i++)
		{
			if(nodes[0].childNodes[i].tagName == 'endereco')
			$("#endereco_cadastro").attr('value', nodes[0].childNodes[i].textContent);
			else if(nodes[0].childNodes[i].tagName == 'bairro')
			$("#bairro").attr('value', nodes[0].childNodes[i].textContent);
			else if(nodes[0].childNodes[i].tagName == 'erro')
			{
				if(nodes[0].childNodes[i].childNodes[0].textContent != '00')
				{
					switch(nodes[0].childNodes[i].childNodes[0].textContent)
					{
						case '01':
						alert('CEP inválido.');
						break;
						case '02':
						alert('Serviço inválido.');
						break;
						case '03':
						alert('Peso acima do permitido.');
						break;
						case '04':
						alert('CEP não encontrado.');
						break;
						case '05':
						alert('Serviço não disponivel para esta localidade.');
						break;
					}
				}
			}
		}
	}

});

function Valida(){

	var reDate = /^((0?[1-9]|[12]\d)\/(0?[1-9]|1[0-2])|30\/(0?[13-9]|1[0-2])|31\/(0?[13578]|1[02]))\/(19|20)?\d{2}$/;
	var dtnascimento = document.getElementById('dtnascimento').value;

	if (reDate.test(dtnascimento) == false) {
		//alert(pStr + " ï¿½ uma data vï¿½lida.");

		alert(dtnascimento + " não é uma data válida.");
		document.getElementById('dtnascimento').focus();
		return false;
	}

	return true;
}

function setTipoPessoa(valor)
{
	if(valor == 'F' || valor == ''){
        $('#p_nome').html('Nome');
        $('#p_sobrenome').html('Sobrenome');
        $('#p_cpf').html('CPF');
        $('#p_rg').html('RG');
        a = $("#cpfcnpj").val();
        $("#cpfcnpj").unmaskedinput();
        $("#cpfcnpj").maskedinput("999.999.999-99", {placeholder : " "});
        $("#cpfcnpj").val(a); 

        $('#p_dtnas').show();
        $('#label_dtnas').show();
        $('#dtnascimento').attr('disabled', false);

        $('#p_labelsexo').show();
        $('#p_sexo').show();
        

     }
     else{
  	   $('#p_nome').html('Nome Fantasia');
  	   $('#p_sobrenome').html('Razão Social');
  	   $('#p_cpf').html('CNPJ');
         $('#p_rg').html('IE');
         a = $("#cpfcnpj").val();
         $("#cpfcnpj").unmaskedinput();
         $("#cpfcnpj").maskedinput("99.999.999/9999-99", {placeholder : " "});
         $("#cpfcnpj").val(a);

         $('#p_dtnas').hide();
         $('#label_dtnas').hide();
         $('#dtnascimento').attr('disabled', true);

         $('#p_labelsexo').hide();
         $('#p_sexo').hide();
         
     }
}



function checkAge(data)
{
	/* the minumum age you want to allow in */
	var min_age = 18;

	var array_data = data.split("/")

	var year = parseInt(array_data[2]);
	var month = parseInt(array_data[1]) - 1;
	var day = parseInt(array_data[0]);

	var theirDate = new Date((year + min_age), month, day);
	var today = new Date;

	if ( (today.getTime() - theirDate.getTime()) < 0) {
		alert("É proibido o cadastro para menores de 18 anos!");
		document.formClientes.dtnascimento.focus();
		return false;
	}
	else {
		return true;
	}
}


function validaCPF(cpf) {

   if($('#tipopessoaJ').attr('checked') == true)return;

	cpfString = cpf.split(".");
	digito = cpfString[2].split("-");

	cpf = cpfString[0]+cpfString[1]+digito[0]+digito[1];


	erro = new String;
	if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n";
	var nonNumbers = /\D/;
	if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n";
	if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999"){
		erro += "Numero de CPF invalido!"
	}
	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])){
		erro +="Digito verificador com problema!";
	}
	if (erro.length > 0){
		alert(erro);
		document.formClientes.cpfcnpj.focus();
		return false;
	}
	return true;
}

try{
	xmlhttp = new XMLHttpRequest();
}catch(ee){
	try{
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}catch(e){
		try{
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}catch(E){
			xmlhttp = false;
		}
	}
}

function doBusca(){

	var tuf = $('#estado').val();

	if(document.getElementById('carregando'))
	{
		document.getElementById('carregando').style.visibility = 'visible';
	}

	xmlhttp.open("POST", "./cadastro/jsonCidades",true);
	xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	try{
		xmlhttp.send("estado="+tuf);
	} catch(ee) {
		xmlhttp.abort();
	}

	xmlhttp.onreadystatechange=function() {
		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200) {
				if(document.getElementById('carregando'))
				{
					document.getElementById('carregando').style.visibility = 'hidden';
				}
				//$("#spancidade").html(xmlhttp.responseText);
				$("select#cidade").livequery(function(){
					//alert('chegou aqui');
					$(this).html(xmlhttp.responseText);					
				});
			}
		}
	}
}