//==============================================
// Form page
//==============================================
$(document).ready(function ()
{
	$("select[name=city]").change(function ()
	{
		$("input[name=crmunicipio]").val($("select[name=city] option:selected").val());
	});

	$("select[name=tipo]").change(function ()
	{
		$("input[name=tipoatendimento]").val($("select[name=tipo] option:selected").val());
	});

	$("#telefone").mask("(99) 9999-9999");

	$("#Enviar").click(function ()
	{
		var text = "";
		//alert($("select[name=objetivo] option:selected").val());
		if ($("select[name=objetivo] option:selected").val() == 0)
		{
			text += "Favor selecionar o objetivo!\n";
		}
		else if (!($("input[name=nome]").val()))
		{
			text += "Favor preencher o Nome!\n";
		}
		else if (($("input[name=email]").val() == "") ||
		$("input[name=email]").val() && // Possui algo digitado e
		($("input[name=email]").val().indexOf('@') < 0 || // Não possui '@' ou
			($("input[name=email]").val().indexOf('@') != $("input[name=email]").val().lastIndexOf('@')))) // Possui mais de um '@'
		{
			text += "Email com formato inválido!\n";
		}
		else if (!($("input[name=telefone]").val()))
		{
			text += "Favor preencher o Telefone!\n";
		}
		else if (!($("input[name=titulo]").val()))
		{
			text += "Favor preencher o Assunto!\n";
		}
		else if (!($("textarea[name=texto]").val()))
		{
			text += "Favor preencher a sua Mensagem!\n";
		}

		if(text != "")
		{
			alert("Foram encontrados erros no preenchimento do formulário:\n" + text);
		}
		else
		{
			$.ajax({
				data:
				{
					id: $("input[name=userid]").val(),
					tipoatendimento: $("input[name=tipoatendimento]").val(),
					crmunicipio: $("input[name=crmunicipio]").val(),
					email: $("input[name=email]").val(),
					mensagem: $("textarea[name=texto]").val(),
					assunto: $("input[name=titulo]").val(),
					nome: $("input[name=nome]").val(),
					telefone: $("input[name=telefone]").val(),
					objetivo: $("select[name=objetivo] option:selected").text()
				},
				dataType: "json",
				error: function(XMLHttpRequest, textStatus, errorThrown) {
					alert("Houve um erro ao salvar o registro no banco de dados. Contate o administrador.\n" + XMLHttpRequest.responseText);
				},
				success: function(data, textStatus) {
					alert("Sua mensagem foi enviada com sucesso e será analisada pelos administradores do site. O seu número de atendimento é: " + data.atendimento);
					$("input[name=email]").val("");
					$("textarea[name=texto]").val("");
					$("input[name=titulo]").val("");
					$("input[name=nome]").val("");
					$("input[name=telefone]").val("");
					//$("select[name=objetivo] option:selected").removeAttr("selected");
					$("select[name=objetivo] option[value=0]").attr("selected", "selected");
				},
				type: "POST",
				url: "./fale_conosco.php"
			});
		}
	});
});
