$(function(){
	// dirty hack because of our css layout. Grrrrr!
	$(".submit-button").click(function() {
		$(this).parents("form").submit();
		return false;
	});
	// edit button
	$(".profile-edit-button").click(function() {
		var self = $(this);
		$("#" + self.attr("rel") + "-view").hide();
		$("#" + self.attr("rel") + "-edit")
			.show()
			.find("input").focus().keyup(function(e) {
				// Esc key is pressed
				if (e.keyCode == 27) {
					$("#" + self.attr("rel") + "-edit").hide();
					$("#" + self.attr("rel") + "-view").show();
				}
			});
		return false;
	});
	// profile forms for each field
	$(".profile-form").submit(function() {
		var self = $(this);
		$.post(
			self.attr("action"),
			self.serialize() + "&ajax=1",
			function(data){
				if (!data.success) {
					$.SaexPopup({
						message: data.message
					});
				} else {
					// popup notification and restore view form
					$.SaexPopup({
						message: $("#profile-changes-saved").text()
					});
					$("#" + self.attr("id") + "-edit").hide();
					$("#" + self.attr("id") + "-view").show();
					$("#" + self.attr("id") + "-text").text($("#" + self.attr("id") + "-input").val());
				}
			});
		return false;
	});
});

