
$(document).ready(function() {
	/*métodos da validação*/

	jQuery.validator.addMethod("password", function( value, element ) {
		var result = this.optional(element) || value.length >= 6 && /\d/.test(value) && /[a-z]/i.test(value);
		if (!result) {
			element.value = "";
			var validator = this;
			setTimeout(function() {
				validator.blockFocusCleanup = true;
				element.focus();
				validator.blockFocusCleanup = false;
			}, 1);
		}
		return result;
	}, "Sua senha deve ter pelo menos 6 caracteres e conter pelo menos um número e uma letra.");

	jQuery.validator.addMethod("login", function( value, element ) {
		var result = this.optional(element) || value.length >= 4 && /^([0-9a-zA-Z\-\_]+)$/.test(value);
		if (!result) {
			element.value = "";
			var validator = this;
			setTimeout(function() {
				validator.blockFocusCleanup = true;
				element.focus();
				validator.blockFocusCleanup = false;
			}, 1);
		}
		return result;
	}, "O login deve ter pelo menos 4 caracteres e conter apenas letras e números.");

	jQuery.validator.addMethod("cpf", function(value, element) {  
		value = value.replace('.','');  
		 value = value.replace('.','');  
		 cpf = value.replace('-','');  
		 while(cpf.length < 11) cpf = "0"+ cpf;  
		 var expReg = /^0+$|^1+$|^2+$|^3+$|^4+$|^5+$|^6+$|^7+$|^8+$|^9+$/;  
		 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]) || cpf.match(expReg)) return false;  
		 return true;  
	 }, "Informe um CPF válido.");

	jQuery.validator.messages.required = "Campo obrigatório.";


	/* validação */
	
	$("#form_cadastro").validate({
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? 'Um campo obrigatório não foi preenchido'
					: errors + ' campos obrigatórios não foram preenchidos';
				$("div.error span").html(message);
				$("div.error").show();
			} else {
				$("div.error").hide();
			}
		},
		onkeyup: false,
			/*
		submitHandler: function() {
			$("div.error").hide();
			$.post('cadastro.php', $('#form_cadastro').serialize(), function(data){ 
				$(".chamada_dupla").html(data); 
			} );
		},
			*/
		messages: {
			email: {
				required: " ",
				email: "Digite um e-mail válido."
			},
			password2: {
				required: " ",
				equalTo: "Digite a mesma senha do campo acima."
			}
		}
	});
	

	/*máscaras da validação*/

	$("input.cep").mask("99999-999");
	$("input.tel").mask("(99) 9999-9999");
	aplicaTipo(false);
	$('input[name=tipo]').click(function() { aplicaTipo(true) });


});

function aplicaTipo(clear) {
	var tipo = $('input[name=tipo]:checked').val();
	if (clear) $("#div_cnpj").val('');
	$("input[name=cnpj]").unmask();
	if (tipo=='pf') {
		$("#div_empresa > label").html("Nome:");
		$("#div_cnpj > label").html("CPF:");
		if (!$("input[name=cnpj]").hasClass("cpf")) $("input[name=cnpj]").addClass("cpf");
		if ($("input[name=cnpj]").hasClass("cnpj")) $("input[name=cnpj]").removeClass("cnpj");
		$("input.cpf").mask("999.999.999-99");
		if (clear) $("#div_contato").slideUp();
		else $("#div_contato").hide();
		if ($("input[name=contato]").hasClass("required")) $("input[name=contato]").removeClass("required");
		if (clear) $("input[name=contato]").val('');
	} else { // PJ
		$("#div_empresa > label").html("Empresa:");
		$("#div_cnpj > label").html("CNPJ:");
		if (!$("input[name=cnpj]").hasClass("cnpj")) $("input[name=cnpj]").addClass("cnpj");
		if ($("input[name=cnpj]").hasClass("cpf")) $("input[name=cnpj]").removeClass("cpf");
		$("input.cnpj").mask("99.999.999/9999-99");
		$("#div_contato").slideDown();
		if (!$("input[name=contato]").hasClass("required")) $("input[name=contato]").addClass("required");		
	}
}
