$j(function(){
	$j('#formLogin').validate({
		ignoreTitle:true,
		messages:{},
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? '1 campo obrigatório não foi preenchido!'
					: errors + ' campos obrigatórios não foram preenchidos!';
					
				$j.alert({ type:'error', html:message, width:350 });
			}
		},
		submitHandler: function(form) {				
			Clientes.login(form);
		},
		errorClass: "invalido"
	});
	
	$j('#formVerificaEmail').validate({
		ignoreTitle:true,
		messages:{},
		rules:{
			confirmaEmail:{
				equalTo: "#emailNovo"
			}
		},
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? '1 campo obrigatório não foi preenchido!'
					: errors + ' campos obrigatórios não foram preenchidos!';
					
				$j.alert({ type:'error', html:message, width:350 });
			}
		},
		submitHandler: function(form) {				
			Clientes.verificaEmail(form);
		},
		errorClass: "invalido"
	});
	
	$j('#formCadastroCliente').validate({
		ignoreTitle:true,
		messages:{
			email:"E-mail inválido",
			senha:"Mínimo de 6 digitos"
		},
		rules:{
			senha:{
				minlength:6
			},
			cpf:{
				required: "#pessoa_fisica:checked",
				cpf:true
			},
			sexo:{
				required: "#pessoa_fisica:checked"
			},
			cnpj:{
				required: "#pessoa_juridica:checked",
				cnpj:true
			},
			senha:{
				minlength:6
			},
			tipoPessoa: "required"
		},
		invalidHandler: function(e, validator) {
			var errors = validator.numberOfInvalids();
			if (errors) {
				var message = errors == 1
					? '1 campo obrigatório não foi preenchido!'
					: errors + ' campos obrigatórios não foram preenchidos!';
					
				$j.alert({ type:'error', html:message, width:350 });
			}
		},
		submitHandler: function(form) {				
			Clientes.cadastrar(form);
		},
		errorClass: "invalido"
	});
});
var Clientes={		
	acoes:'/clientes/Clientes.actions.php?',
	
	login:function(form){
		$j.alert({ type:'loading', html:'Aguarde, efetuando login...', hide:false });
		$j.ajax({
			url: Clientes.acoes+'login', type: "post", data: $j(form).serialize(),
			success:function(response){
				if(response == ""){
					location = form.url.value;
				}else{
					$j.alert({
						type:'error', html:response
					});
				}
			}
		});
	},	
	cadastrar:function(form){
		$j.ajax({
			url:Clientes.acoes+'cadastrar', type: 'post', data: $j(form).serialize(),
			success: function(response){ //alert(response);
				if(response==""){
					$j.alert({
						type:'success', html:'Cadastro Realizado com sucesso.', width:250, 'timeout':5000,  
						out:function() { location = form.url.value; }
					});
				} else {
					$j.alert({type:'error', html:'Erro ao tentar salvar seus dados. Entre em contato.', 'timeout':5000});
				}
			}
		});
	},	
	recuperarSenha:function(){
		form= $j('#formLogin');
		if($j('#email').val() != ""){
			$j.ajax({
				url:Clientes.acoes+'recuperarSenha', type: 'post', data: $j(form).serialize(),
				success:function(response){
					if(response == ""){
						$j.alert({
							type:'success', html:'Sua nova senha foi enviada para o seu e-mail.'
						});
					}else{
						$j.alert({
							type:'error', html:'Cadastro não localizado.'
						});
						
					}
				}
			});
		}else{
			$j.alert({
				type:'error', html:'Preencha o campo e-mail para poder recuperar sua senha.'
			});
			$j('#email').addClass('invalido');
		}
	},	
	verificaEmail:function(form){
		$j.ajax({
			url:Clientes.acoes+'verificaEmail', type: 'post', data: $j(form).serialize(),
			success: function(response){ //alert(response);
				if(response==""){
					form.action="/cadastro.php";
					form.submit();
				} else {
					$j.alert({type:'error', html:'Este e-mail já possui cadastro, utilize o recuperar senha caso não lembre dela.', 'timeout':7000});
				}
			}
		});
	},	
	tipo_pessoa:function(tipo){
		if(tipo=="F"){
			$j('.containerPF').show();
			$j('#containerPJ').hide();
			$j('#cnpj').val('');
		}else{
			$j('.containerPF').hide();
			$j('#containerPJ').show();
			$j('.containerPF input:text').val('');
			$j('.containerPF input:radio').removeAttr('checked');
		}
	}
};
