$(document).ready(function() {

	// TOP MENU (CATEGORIES):
	
	// Define variables
	var categories		= $('div#header div.categories ul.categories');
	var top_categories	= categories.children('li');
	var sub_categories	= categories.find('div.sub_categories');
	var sub_categories_timeout;
	
	// Close open boxes on click outside
	$(this).mousedown(function(e) {
		var clickTarget = $(e.target);
		if ( clickTarget.parents('div#header div.categories ul.categories').size() === 0 )
		{
			hide_sub_categories();
		}
	});
	
	// Bind mouseover event
	top_categories.bind('mouseenter', function() {
	
		// Reset all timeouts
		clearTimeout(sub_categories_timeout);
		
		// Re-define variables
		var sub_category_box			= $(this).children('div.sub_categories');
		var sub_category_top_link		= $(this).children('a');
		var sub_categories_top_arrow	= sub_category_box.children('div.sub_categories_top');
		
		// Hide all sub category boxes
		hide_sub_categories();
		
		// Show the sub category box for this one
		sub_category_box.show();
		
		// Set left offset
		sub_category_box.css('left', sub_category_top_link.offset().left + 'px');
		
		// Also set left offset for arrow
		sub_categories_top_arrow.css('left', (sub_category_top_link.width()/2)-4 + 'px');
		
	}).bind('mouseleave', function() {
		
		// Give the user some time before the box closes
		sub_categories_timeout = setTimeout(hide_sub_categories, 200);
		
		
	});
	
	// Hide all sub category boxes
	function hide_sub_categories() {
		sub_categories.hide();
	}
	
});
