/**
 * Ações para a seção cadastro
 * 
 * @author João (jpaulo@gadbrivia.com.br)
 */

function Cadastro()
{
	$("#cadastro a.bt-fechar").click(Cadastro.Exibir);
	$("a.lk-cadastro").click(Cadastro.Exibir);
	
	// FOCO
	$("#" + Cadastro.Campos.ids.join(", #"), "#frmCadastro").unbind().blur(function()
	{
		if ($.trim($(this).val()).length == 0)
		{
			$(this).val(Cadastro.Campos.valores[$.inArray($(this).attr("id"), Cadastro.Campos.ids)]);
		}
	}).focus(function()
	{
		if ($.inArray($.trim($(this).val()), Cadastro.Campos.valores) > -1)
		{
			$(this).val("");
		}
	});
	
	// MÁSCARA
	$("#txtCadastroTelefone", "#frmCadastro").focus(function()
	{
		$(this).mask("(99) 9999.9999");
	});
	
	
	$("#txtCadastroTelefone", "#frmCadastro").blur(function()
	{
		$(this).unmask();
	});
	
	$("#txtCadastroCelular", "#frmCadastro").focus(function()
	{
		$(this).mask("(99) 9999.9999");
	});
	
	$("#txtCadastroCelular", "#frmCadastro").blur(function()
	{
		$(this).unmask();
	});
	
	$("#txtCadastroCEP", "#frmCadastro").focus(function()
	{
		$(this).mask("99999-999");
	});
	
	$("#txtCadastroCEP", "#frmCadastro").blur(function()
	{
		$(this).unmask();
	});
	
	$("#txtCadastroDataNascimento", "#frmCadastro").focus(function()
	{
		$(this).mask("99/99/9999");
	});
	
	$("#txtCadastroDataNascimento", "#frmCadastro").blur(function()
	{
		$(this).unmask();
	});
	
	$("#txtCadastroNumero", "#frmCadastro").focus(function()
	{
		$(this).numeric();
	});
	
	$("#txtCadastroNumero", "#frmCadastro").blur(function()
	{
		$(this).numeric();
	});
	
	$("#txtCadastroNpe").keypress(function(evento)
	{
		evento = $.event.fix(evento || window.event);
		var digito = String.fromCharCode(evento.charCode);
		
		if($(this).val().length == 2 && !isNaN(digito) && evento.charCode != 32)
		{
			$(this).val($(this).val()+"."+digito);

		}
        else if(evento.charCode == 46)
        {
        	 return false;
        }
        else if($(this).val().length > 2 && evento.keyCode == 8)
        {
			$(this).val($(this).val().substr(0,2));
			return false;
		}
	});
	
	
	// OPÇÕES DE PAÍS, ESTADO E CIDADE
	$("#selCadastroPais", "#frmCadastro").change(function()
	{		
		if($(this).val() !== '')
		{
			if ($.trim($(this).val()) == SITE_BRASIL_ID)
			{
				Cadastro.Brasil = true;
				
				$("#selCadastroEstado, #selCadastroCidade", "#frmCadastro").parent("li").removeClass("hidden");
				
				$("#txtCadastroCidade", "#frmCadastro").parent("li").addClass("hidden");
				
				Cadastro.CarregarEstados($(this).val());
			}
			else
			{
				Cadastro.Brasil = false;
				
				$("#selCadastroEstado", "#frmCadastro").attr({
					disabled: true
				}).html("<option value=\"\" selected=\"selected\">Estado:</option>");
				
				$("#selCadastroCidade", "#frmCadastro").attr({
					disabled: true
				}).html("<option value=\"\" selected=\"selected\">Cidade:</option>");
				
				$("#selCadastroEstado, #selCadastroCidade", "#frmCadastro").parent("li").addClass("hidden");
				
				$("#txtCadastroCidade", "#frmCadastro").parent("li").removeClass("hidden");
			}
		}
	});
	
	$("#selCadastroEstado", "#frmCadastro").change(function()
	{
		if ($.trim($(this).val()).length > 0)
		{
			Cadastro.CarregarCidades($(this).val());
		}
		else
		{
			$("#selCadastroCidade", "#frmCadastro").attr({
				disabled: true
			}).html("<option value=\"\" selected=\"selected\">Cidade:</option>");
		}
	});
	
	$('#msg-atualizar .bt-atualiza.bt-sim').click(function() 
	{
		Cadastro.Cadastrar();
		
		$('#msg-atualizar').addClass('hidden');
	});
	
	$('#msg-atualizar .bt-atualiza.bt-nao').click(function() 
	{
		$('#msg-atualizar').addClass('hidden');
	});
	
	// VALIDAÇÃO
	$("#frmCadastro").validate({
		submitHandler: function()
		{
		
			$("#mensagem").html("Enviando...").attr({
				"class": ""
			});
			
			/**
			 * Verifica se o email já está cadastrado
			 */
			
			var Enviar = false;
			$.ajax({
				cache: false,
				data: 
				{
					txtCadastroEmail: $("#txtCadastroEmail", "#frmCadastro").val(),
					Acao: 'Verificar'
					
				},
				success: function(resposta)
				{
					if( $.trim(resposta) == 'DUPLICADO')
					{
					 	$('#msg-atualizar').removeClass('hidden');
					}
					else
					{
						Cadastro.Cadastrar();						
					}
				},
				async: true,
				type: "post",
				url: "acao/Cadastro.php"
			});
			
			
			if(Enviar)
			{
				alert(conteudo);
	
			}
		},
		errorPlacement: function(error, element)
		{
			$("#mensagem-cadastro").html(error).addClass('erro');
		},
	    errorElement: "span",
		highlight: function(element, errorClass)
		{
			$(element).css("border", "1px solid #FF0000");
		},
		unhighlight: function(element, errorClass)
		{
			$(element).css("border", "1px solid #E4E4E4");
		},
		rules: 
		{
			txtCadastroNome: 
			{
				required: function()
				{
					if ($.inArray($.trim($("#txtCadastroNome").val()), Cadastro.Campos.valores) > -1)
					{
						$("#txtCadastroNome").val("");
					}
					
					return true;
				}
			},
			txtCadastroEmail: 
			{
				required: function()
				{
					if ($.inArray($.trim($("#txtCadastroEmail").val()), Cadastro.Campos.valores) > -1)
					{
						$("#txtCadastroEmail").val("");
					}
					
					return true;
				},
				email: true
			},
			txtCadastroTelefone: 
			{
				required: function()
				{
					if ($.inArray($.trim($("#txtCadastroTelefone").val()), Cadastro.Campos.valores) > -1)
					{
						$("#txtCadastroTelefone").val("");
					}
					
					return true;
				}
			},
			txtCadastroEndereco: 
			{
				required: function()
				{
					if ($.inArray($.trim($("#txtCadastroEndereco").val()), Cadastro.Campos.valores) > -1)
					{
						$("#txtCadastroEndereco").val("");
					}
					
					return true;
				}
			},
			txtCadastroCEP: 
			{
				required: function()
				{
					if ($.inArray($.trim($("#txtCadastroCEP").val()), Cadastro.Campos.valores) > -1)
					{
						$("#txtCadastroCEP").val("");
					}
					
					return true;
				}
			},
			txtCadastroNumero :
			{
				required: function()
				{
					if ($.inArray($.trim($("#txtCadastroNumero").val()), Cadastro.Campos.valores) > -1)
					{
						$("#txtCadastroNumero").val("");
					}
					
					return true;
				}
			},
			selCadastroPais:
			{
				required: true
			},
			selCadastroEstado:
			{
				required: function () 
				{
					if($('#selCadastroPais').val() == SITE_BRASIL_ID)
					{
						return true;
					}
					else
					{
						return false;
					}
				}
			},
			selCadastroCidade:
			{
				required: function () 
				{
					if($('#selCadastroPais').val() == SITE_BRASIL_ID)
					{
						return true;
					}
					else
					{
						return false;
					}
				}
			},
			txtCadastroCidade:
			{
				required: function () 
				{
					if($('#selCadastroPais').val() != SITE_BRASIL_ID)
					{
						if ($.inArray($.trim($("#txtCadastroCidade").val()), Cadastro.Campos.valores) > -1)
						{
							$("#txtCadastroCidade").val("");
						}
						return true;
					}
					else
					{
						return false;
					}
				}
			},
			txtCadastroDataNascimento:
			{
				required: function()
				{
					if ($.inArray($.trim($("#txtCadastroDataNascimento").val()), Cadastro.Campos.valores) > -1)
					{
						$("#txtCadastroDataNascimento").val("");
					}
					
					return true;
				},
				data: true
			},
			selCadastroSexo:
			{
				required: true
			},
			txtCadastroNpe:
			{
				required: function()
				{
					if ($.inArray($.trim($("#txtCadastroNpe").val()), Cadastro.Campos.valores) > -1)
					{
						$("#txtCadastroNpe").val("");
					}
					
					return true;
				}
			}
		},
		messages: 
		{
			txtCadastroNome: 
			{
				required: MSG04
			},
			txtCadastroEmail: 
			{
				required: MSG04,
				email: MSG27.replace(/\{CAMPO\}/gim, "e-mail")
			},
			txtCadastroTelefone: 
			{
				required: MSG04
			},
			txtCadastroEndereco: 
			{
				required: MSG04
			},
			txtCadastroCEP: 
			{
				required: MSG04
			},
			txtCadastroNumero :
			{
				required: MSG04
			},
			selCadastroPais:
			{
				required: MSG04
			},
			selCadastroEstado:
			{
				required: MSG04
			},
			selCadastroCidade:
			{
				required: MSG04
			},
			txtCadastroCidade:
			{
				required: MSG04
			},
			txtCadastroDataNascimento:
			{
				required: MSG04
			},
			selCadastroSexo:
			{
				required: MSG04
			},
			txtCadastroNpe:
			{
				required: MSG04
			}
		}
	});
}

Cadastro.Brasil = false;
Cadastro.Cadastrar = function ()
{
	var conteudo = $("#frmCadastro").serialize();
	$.ajax({
		cache: false,
		data: 'Acao=Salvar&'+conteudo,
		success: function(resposta)
		{
			switch($.trim(resposta))
			{
				case 'ERRO':
					$('#frmCadastro #mensagem-cadastro').html('Ocorreu um erro ao tentar efetuar a operação!').addClass('erro');
					break;
				case 'ATUALIZADO':
					$('#frmCadastro #mensagem-cadastro').html(MSG02).addClass('sucesso');
					Cadastro.Limpar();
					break;
				case 'CADASTRADO':
					$('#frmCadastro #mensagem-cadastro').html(MSG42).addClass('sucesso');
					Cadastro.Limpar();
					break;
			}
		},
		async: true,
		type: "post",
		url: "acao/Cadastro.php"
	});

}
Cadastro.CarregarEstados = function(pais)
{
	if(pais !== '')
	{
		$("#selCadastroEstado", "#frmCadastro").attr({
			disabled: true
		}).html("<option value=\"\" selected=\"selected\">Carregando...</option>");
		
		$.ajax({
			cache: false,
			success: function(opcoes)
			{
				$("#selCadastroEstado", "#frmCadastro").html("<option value=\"\" selected=\"selected\">Estado:</option>" + opcoes).attr({
					disabled: false
				});
			},
			data: {
				PaisID: pais
			},
			type: "post",
			url: "acao/Estado.php"
		});
	}
}

Cadastro.CarregarCidades = function(estado)
{
	if(estado !== '')
	{
		$("#selCadastroCidade", "#frmCadastro").attr({
			disabled: true
		}).html("<option value=\"\" selected=\"selected\">Carregando...</option>");
		
		$.ajax({
			cache: false,
			success: function(opcoes)
			{
				$("#selCadastroCidade", "#frmCadastro").html("<option value=\"\" selected=\"selected\">Cidade:</option>" + opcoes).attr({
					disabled: false
				});
			},
			data: {
				UnidadeFederativaID: estado
			},
			type: "post",
			url: "acao/Cidade.php"
		});
	}
}

Cadastro.Exibir = function()
{
	Cadastro.Limpar();
	
	$("a.lk-cadastro").parent(".primeira").toggleClass("ativo");
	$("div#cadastro").toggleClass("hidden");
}

Cadastro.Limpar = function()
{
	$("#" + Cadastro.Campos.ids.join(", #")).each(function()
	{
		if(($(this)[0].tagName).toLowerCase() == 'input')
		{
			$(this).val('').blur();
		}
		if(($(this)[0].tagName).toLowerCase() == 'select')
		{
			$(this).children('option').removeAttr('selected');
			$(this).children('option:first').attr('selected','selected');
		}
		
	});
}



Cadastro.Campos = {
	ids: ["txtCadastroNome", "txtCadastroEmail", "txtCadastroTelefone", "txtCadastroCelular", "txtCadastroEndereco", "txtCadastroNumero", "txtCadastroComplemento", "txtCadastroBairro", "txtCadastroCEP", "selCadastroPais", "selCadastroEstado", "txtCadastroEstado", "selCadastroCidade", "txtCadastroCidade", "txtCadastroDataNascimento", "selCadastroSexo", "txtCadastroNpe"],
	valores: [SITE_FORM_NOME, SITE_FORM_EMAIL, SITE_FORM_FONE, SITE_FORM_CELULAR, SITE_FORM_ENDERECO, SITE_FORM_NUMERO, SITE_FORM_COMPLEMENTO, SITE_FORM_BAIRRO, SITE_FORM_CEP, SITE_FORM_PAIS, SITE_FORM_ESTADO, SITE_FORM_ESTADO, SITE_FORM_CIDADE, SITE_FORM_CIDADE, SITE_FORM_DATA_NASCIMENTO, SITE_FORM_SEXO, SITE_FORM_N]
}