$j(function(){
	if($j('#formDadosCliente').html() != null){
		$j('#formDadosCliente').validate({
			ignoreTitle:true,
			messages:{
				email:"E-mail inválido",
				cep:"CEP inválido",
				fone: 'Númerio incorreto'
			},
			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.salvar(form);
			},
			errorClass: "invalido"
		});
	}
	$j('#formLoginTopo').validate({
		ignoreTitle:true,
		messages:{
			email:""
		},
		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) {				
			form.submit();
		},
		errorClass: "invalido"
	});
	
	//Validação do formulário de cadastro de clientes
	$j('#formCadastroCliente').validate({
		messages:{
			email:"E-mail inválido",
			senha:"Mínimo de 6 digitos"
		},
		rules:{
			cpf:{
				required: "#pessoa_fisica:checked"
			},
			senha:{
				minlength:6
			},
			dataNascimento:{
				required: "#pessoa_fisica:checked",
				dateBR:true
			},
			sexo:{
				required: "#pessoa_fisica:checked"
			},
			sitProfissional:{
				required: "#pessoa_fisica:checked"
			},
			cnpj:{
				required: "#pessoa_juridica:checked"
			},
			tipoPessoa: "required",
			
			nomeEmpresa:{
				required: "#empregado:checked"
			},
			ramo:{
				required: "#empregado:checked"
			},
			cargo:{
				required: "#empregado:checked"
			},
			foneEmpresa:{
				required: "#empregado:checked"
			}
			
		},
		ignoreTitle:true,
		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){
		if ($Form.validar(form)) {
			form.submit();
		}	
		return false;
	},
	logout:function(){
		$j.alert({
			type:'loading', html:'Aguarde...', hide:false
		});
		$j.ajax({
			type: "post", url:  this.acoes+'logout',
			success:function(response){
				location = "/index.php";
			}
		});
	},
	recuperar_senha_cancelar:function(paranetro){
		if(paranetro == 'recuperar'){
			$j('#senha, #acessar, #cadastra-se, #recuperar-a').hide();
			$j('#senha').val('').prev().hide();
			$j('#senha').next().hide();
			$j('#btRecuperar, #cancelar, #frase-recuperar').show();
		}else{
			$j('#senha, #acessar, #cadastra-se, #recuperar-a').show();
			$j('#senha').val('').prev().show();
			$j('#senha').next().show();
			$j('#btRecuperar, #cancelar, #frase-recuperar').hide();
		}
	},
	recuperarSenha:function(origem){
		var form = origem == "topo" ? $j('#formLoginTopo') : $j('#FormRecuperarSenha');
		$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.'
					});
					Clientes.recuperar_senha_cancelar('cancelar');
				}else if(response == "varios-cadastros"){
					$j.alert({
						type:'alert', width:'550', timeout:7000,
						html:'Não foi possível recuperar sua senha, pois este e-mail possui mais de um cadastro. <br /> Por favor, entre em contato e solicite uma nova senha.'
					});
				}else{
					$j.alert({
						type:'error', html:'Cadastro não localizado.'
					});
					
				}
			}
		});
	},
	
	verificaEmail:function(form){
		if($j('#emailNovo').val() != $j('#confirmaEmail').val()){
			$j.alert({type:'error', html:'Os e-mails não são iguais!', 'timeout':5000});
		}else{
			if($Form.validate(form) != false){
				$j.ajax({
					url:Clientes.acoes+'verificaEmail', type: 'post', data: $j(form).serialize(),
					success: function(response){ //alert(response);
						if(response==""){
							form.submit();
						} else {
							$j.alert({type:'error', html:'Este e-mail já possui cadastro, utilize o recuperar senha caso nã a lembre.', 'timeout':5000});
						}
					}
				});
			}
		}
		return false;
	},
	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.', '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});
				}
			}
		});
	},
	
	salvar:function(form){
		$j.ajax({
			url:Clientes.acoes+'salvar', type: 'post', data: $j(form).serialize(),
			success: function(response){ //alert(response);
				if(response==""){
					$j.alert({type:'success', html:'Cadastro atualizado com sucesso.', '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});
				}
			}
		});
	},
	
	tipo_pessoa:function(tipo){
		if(tipo=="F"){
			$j('#container-cpf').show();
			$j('#container-cnpj').hide();
			$j('#num_cnpj').val('');
		}else{
			$j('#container-cpf').hide();
			$j('#container-cnpj').show();
			$j('#container-cpf input:text').val('');
			$j('#container-cpf input:radio').removeAttr('checked');
			Clientes.sitProfissional(''); // caso tenha preenchido alguma coisa nos dados da empresa
		}
	},
	
	sitProfissional:function(sit){
		//alert($j('input:radio[name=sitProfissional]:checked').val());
		if(sit == "E"){
			$j('#dadosEmpresa').show();
		}else{
			$j('#dadosEmpresa').hide();
			$j('#dadosEmpresa input:text').val('');
		}
	},
	
	formEmpresas:function(cnpj){
		$j('#dialogEmpresas').remove();
		$j('<div id="dialogEmpresas">').load('/clientes/Clientes.formEmpresas.php?cnpj='+cnpj).dialog({
			title:'Cadastrar Empresa', width:530, height:420, modal:true,
			resizable: false, 
			beforeClose: function(event, ui){ 
				$j('#pagante').val('A');
				Inscricao.verificaEmpresa('A');
			},
			open:function(event, ui){
				
			},
			buttons:{
				'Salvar':function(){
					$j("#formCadastroEmpresa").validate({
						ignoreTitle:true,
						messages:{
							email:"E-mail inválido",
							cep:"CEP inválido",
							fone: 'Númerio incorreto'
						},
						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 });
							}
						},
						errorClass: "invalido"
					});
					if($j("#formCadastroEmpresa").valid()){
						Clientes.cadastrarEmpresa($j("#formCadastroEmpresa"))
					}
				},
				'Fechar':function(){
					if($j('#pagante').length>0){
						$j('#pagante').val('A');
						Inscricao.verificaEmpresa('A');
					}					
					$j('#dialogEmpresas').remove();
				}
			}
		});
	},
	cadastrarEmpresa:function(form){
		if($Form.validate(form) != false) {
			$j.alert({
				type:'loading', html:'Agurde...'
			});
			$j.ajax({
				url:Clientes.acoes+'salvarEmpresa', type:'post', data:$j(form).serialize(),
				success:function(response) {
					if(response == ""){
						$j.alert({
							type:'success', html:'Cadastro realizado com sucesso!', timeout:5000
						});
						Clientes.getEmpresa($j('#formCadastroEmpresa #cnpj').val());
						$j('#dialogEmpresas').remove();
					}else{
						$j.alert({
							type:'error', html:response
						});
					}
				}
			});
		}
	},
	
	formFuncionarios:function(){
		$j('#dialogFuncionarios').remove();
		$j('<div id="dialogFuncionarios">').load('/clientes/Clientes.formFuncionarios.php').dialog({
			title:'Cadastrar Funcionário', width:550, height:470,
			resizable: false, modal:true,
			buttons:{
				'Salvar':function(){
					$j("#formCadastroFuncionario").validate({
						ignoreTitle:true,
						messages:{
							email:"E-mail inválido",
							cep:"CEP inválido",
							fone: 'Númerio incorreto',
							dataNascimento:""
						},
						rules:{
							sexo:"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 });
							}
						},
						errorClass: "invalido"
					});
					if($j("#formCadastroFuncionario").valid()){
						Clientes.cadastrarFuncionario($j('#formCadastroFuncionario'));
					}
				},
				'Fechar':function(){
					$j('#dialogFuncionarios').remove();
				}
			}
		});
	},
	
	cadastrarFuncionario:function(form){
		if($Form.validate(form) != false) {
			$j.alert({
				type:'loading', html:'Aguarde...'
			});
			$j.ajax({
				url:Clientes.acoes+'salvarFuncionario', type:'post', data:$j(form).serialize(),
				success:function(response) {
					if(response == ""){
						$j.alert({
							type:'success', html:'Cadastro realizado com sucesso!', timeout:5000
						});
						Clientes.getFuncionariosInscricao();
						$j('#dialogFuncionarios').remove();
					}else{
						$j.alert({
							type:'error', html:response
						});
					}
				}
			});
		}
	},
	
	getFuncionariosInscricao:function(){
		var sel = '';
		//pega os funcionários já selecionados
		$j("input[name='funcionarios[]']:checked").each(function(){
			sel = sel + this.value+',';
		});
		
		$j.ajax({
			url:Clientes.acoes+'getFuncionariosInscricao&funcionarios='+sel,
			success:function(response) {
				$j('#containerFuncionarios').html(response);
			}
		});
	},
	
	getEmpresa:function(cnpj){
		$j.alert({
			type:'loading', html:'Agurde...'
		});
		$j.ajax({
			url:Clientes.acoes+'getEmpresa&cnpj='+cnpj,
			success:function(response) {
				if(response != ""){
					$j('#dadosEmpresa').html(response).show();
					$j('#novaEmpresa').hide();
				}else{
					Clientes.formEmpresas(cnpj);
				}
				$j.alert('hide');
			}
		});
	},
	
	validarGetEmpresa:function(obj){
		if(validaCNPJ($j(obj).val())){
			Clientes.getEmpresa($j(obj).val());			
		}else{
			$j(obj).addClass('invalido');
			$j(obj).next().show();
		}
		return false;
	}
};
