$(document).ready(function()
{
	// Initial hide / show boxes
	$('div.box').hide();
	$('div.missing-data').openDiv();
	
	// Behavior of menu buttons
	$('ul#menu a.js').click(function(event)
	{
		var div = $('div#'+$(this).attr('id')+'-box');
		
		if (div.hasClass('box-open') == false)
		{
			div.closeOpenDiv();
			div.openDiv();
		}		
		
		event.preventDefault();
	});
	
	// Behavior of contact success message
	$('p.success')
		.hide()
		.fadeIn(1000)
		.append(' <em>Click to close</em>.')
		.click(function()
		{
			$(this).fadeOut(1000);
		});
	
	// Contact form consistency checkings
	$('form#form').submit(function()
	{
		$(this).attr('action', '');
		
		return $(this).checkForm();
	});
});

$.fn.openDiv = function()
{
	// Before displaying box, create the 'close' button
	$(this + 'p.close a').toggleCloseButton();
	
	$(this)
		.center()
		.fadeIn(700)
		.toggleClass('box-open');
}

$.fn.closeOpenDiv = function()
{
	$('div.box-open')
		.fadeOut(700)
		.toggleClass('box-open');
}

$.fn.toggleCloseButton = function()
{
	this
		.text('x')
		.click(function(event)
		{
			$(this).closeOpenDiv();
			
			event.preventDefault();
		});
	
	return this;
}

$.fn.center = function()
{
	this.css({
		'position' : 'absolute',
		'left' : (($('body').outerWidth() / 2) - (this.outerWidth() / 2)) + 'px',
		'top' : (($('body').outerHeight() / 2) - (this.outerHeight() / 2)) + 'px'
	});
	
	return this;
}

$.fn.checkForm = function()
{
	var valid = true;
	
	$('input, textarea').each(function()
	{
		if ($(this).attr('value') == '' && $(this).attr('type') != 'submit')
		{
			valid = false;
		}
		else
		{
			$(this).removeClass('invalid');
		}
	});
	
	if ($(this).prev().hasClass('error') == false && valid == false)
	{
		$(this).before('<p class=\'error\'>Some mandatory fields were left empty, cannot send message.</p>');
		$('p.error').hide().fadeIn(2000);
	}
	else if ($(this).prev().hasClass('error') == true && valid == true)
	{
		$(this).prev().fadeOut(500);
	}
	
	return valid;
}