(function(){
	$(function()
	{
		// Hide the form
		var contactformtable = $("#contactformtable").hide();
		var formmsg = $("#formmsg");
		formmsg.text("");
		
		// Create form activator
		var contact = $("#contact");
		contact.prepend('<a href="#contact" class="activator">Write me</a>');

		// Form activator event handler
		var inputs = $("#contactformtable input").not(".submit");
		$("#contact .activator").click(function()
		{
			var me = $(this);
			me.css("width",me.width()).slideUp(200);
			contactformtable.slideDown(300,function(){inputs[0].focus();});
		});
		
		// Add hover effect to submit button
		var submitbutton = $("#contactformtable input.submit");
		submitbutton.hover(function(){$(this).css("text-decoration","underline");},function(){$(this).css("text-decoration","none");});
		
		// Add focus effects to form fields
		var focushandler = function() { $(this).addClass("selected"); };
		var blurhandler = function() { $(this).removeClass("selected"); };
		inputs.focus(focushandler).blur(blurhandler);
		$("#contactformtable textarea").focus(focushandler).blur(blurhandler);

		// On-the-Fly validation closures
		function validate(validation)
		{
			return function()
			{
				var me = $(this);
				me.next().attr("class","icon " + (validation(me[0].value) ? "tick" : "exclamation"));
			}
		}
		
		// Non-empty validation
		function nonempty(value) {
			var retval = value != "";
			return retval; 
		};

		// E-mail validation
		var emailregexp = /[\w\+\_\.-]+@[\w\+\_\.-]+\.\w{2,4}$/;
		function validemail(value) { return emailregexp.test(value); };
		
		// Apply validation functions
		var validateempty = $(".validateempty");
		var validateemail = $(".validateemail");
		validateempty.keyup(validate(nonempty)).keydown(validate(nonempty)).blur(validate(nonempty));
		validateemail.keyup(validate(validemail)).keydown(validate(validemail)).blur(validate(validemail));
		
		// Functions for disabling / enabling the form
		function disable()
		{
			submitbutton.addClass("disabled").attr("disabled","disabled");
			$("#loadericon").addClass("loader");			
		}
		function enable(jq)
		{
			submitbutton.removeClass("disabled").removeAttr("disabled");
			$("#loadericon").removeClass("loader");
		}
		enable();
		
		// Submission validation closure
		var passed;
		function sbvalidate(validation)
		{
			return function()
			{
				var me = $(this);
				if (!validation(me[0].value))
				{
					var me = $(this);
					me.next(".icon").attr("class","icon " + (validation(me[0].value) ? "tick" : "exclamation"));
					me.siblings(".error").text("Please check this field");
					passed = false;
				}
			}
		}
		
		// Form submission event handler
		var error = $(".error");
		function writeerror(message)
		{
			enable();
			formmsg.html('<span class="error" id="errmsg" style="display:none;">' + message + '</span>');
			$("#errmsg").slideDown(300);
		}
		$("#contactform").submit(function()
		{
			// Reset validation
			passed = true;
			error.text("");
			formmsg.html("");

			// Validate on submission
			validateempty.each(sbvalidate(nonempty));
			validateemail.each(sbvalidate(validemail));
			
			if (!passed)
				return false;

			disable();

			var x = $.ajax({
				type : "POST",
				url : "/contactajax.php",
				data : 
				{
					name : document.getElementById("contactname").value,
					email : document.getElementById("contactemail").value,
					body : document.getElementById("contactbody").value,
					recaptcha_challenge_field : document.getElementById("recaptcha_challenge_field").value,
					recaptcha_response_field : document.getElementById("recaptcha_response_field").value
				},
				success : function(response)
				{
					if (response == "ok")
					{
						contactformtable.slideUp(300);
						contact.append('<span id="thanks" style="display:none;">Thank you for your message.</span>');
						$("#thanks").slideDown(300);
					}
					else if (response == "captcha")
					{
						writeerror('Sorry. Failed to validate <a href="http://en.wikipedia.org/wiki/CAPTCHA" title="Find out what CAPTCHA is.">CAPTCHA</a>. Please try again.');
						Recaptcha.reload();
					}
					else
					{
						writeerror("Sorry. Your message was not sent.");
					}
				},
				error : function() { writeerror("Sorry. The server did not respond. Please check your connection and try again."); }
			});
			
			return false;
		});
	});
})();
