$(document).ready(function(){

//Functions
changeaddress = function()
{
	var addresstext = $("#address").text();
	var newaddresstext = addresstext.replace(" (remove all the z)","").replace(/z/g,"");
	$("#address").html(newaddresstext);
}

validate = function()
{
	//Let's gather the required form data
	var email = $("#email").val();
	var subject = $("#subject").val();
	//Now we check that the required fields are correctly filled
	var valid_email = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/.test(email);
	var error = "";
	if (!(valid_email))
	{
		error = "Your email address does not seem to be valid - please doublecheck it.";
	}
	else if ( subject == "" )
	{
		error = "Sorry, but you do not seem to have filled out the field subject. Please go back and fill out all the required fields!";
	}
	return error;
}

assignsubmit = function()
{
	$("form").submit(function() {
		var error = validate();
		if (error != "")
		{
			$("#error").remove();
			var errornode = $('<p id="error"></p>'); 
			$(errornode).insertAfter($("#message"));
			$(errornode).hide();
			$(errornode).html(error);
			$(errornode).slideDown();
			return false;
		}
	});
}

loadmail = function()
{
	var mailnode = $('<div id="mailstuff"></div>'); 
	$(mailnode).insertAfter($("#header"));
	$(mailnode).hide();
	$(mailnode).load("mail.html");
	$(mailnode).show(1200);
}

//Let's settle the address right at the beginning
changeaddress();

//This load the mail divs
$("#compose").click(function(event){
	event.preventDefault();
	loadmail();
});

//We need this to assign the submit function after the form has been loaded
$(document).click(function(event){
	if ($(event.target).is('button'))
	{
		assignsubmit();
		if ($(event.target).attr("id") == "cancel")
		{
			$("#mailstuff").remove();
		}
	}
});

})

