var initHeaderCategories = function(){
	
	$("#headerCategories > ul li").hover(
		function () {
			var firstUls = $(this).find('ul:first');
			firstUls.css('position', 'absolute').show();
			
			var positionLeft = $(this).position().left;
			var positionTop = $(this).position().top + $(this).outerHeight();
			var offsetLeft = $(this).offset().left + $(this).outerWidth();
			// Find the position that the box is going to end in.
			var wouldEnd = offsetLeft + firstUls.outerWidth();
			
			// If the box ends out of the body we move the box on the left side.
			if (wouldEnd > $('body').innerWidth()) {
				positionLeft = $(this).position().left + $(this).outerWidth()- firstUls.outerWidth();
			}
			
			firstUls.css('top', positionTop + 'px')
				.css('left', positionLeft + 'px');
		},
		function () {
			$(this).find('ul:first').hide();
		}
	);
};

jQuery(function(){
	initHeaderCategories();
});
