var MENU_HIDE_TIMEOUT = 180,
	MENU_ANIMATION = 120;

jQuery(document).ready(function() {
	var timeout = false, active = -1, first_active,
		menu = jQuery('#menu > a'),
		bgcolor = 'b2cd29',
		bgcolor_active = '8a9a3c',
		set_active = function(index, leave_submenu) {
			if( index == active && leave_submenu )
				return;
			
			var link = jQuery(menu[active = index]),
				right_dot = link.next('.dot'),
				sub = link.next('.submenu'),
				pos, target_height, dots;
			
			if( !right_dot.length )
				right_dot = link.next().next('.dot');
			
			dots = link.prev().add(right_dot),
			
			jQuery('.dot.active').removeClass('active');
			
			/*
			jQuery('.dot').not(dots).children().animate({
				opacity: 1
			}, MENU_ANIMATION);
			dots.children('div').animate({
				opacity: 0
			}, MENU_ANIMATION);
			*/
			
			jQuery('.dot').not(dots).children('.faded').fadeIn(MENU_ANIMATION).removeClass('faded');
			dots.children(':not(.faded)').fadeOut(MENU_ANIMATION).addClass('faded');
			
			if( !leave_submenu ) {
				menu.not(link).each(function(i, other) {
					jQuery(other).data('hide_submenu')();
				});
				
				if( sub.length && sub.is(':hidden') ) {
					sub.height(0).animate({
						height: sub.data('target_height'),
						opacity: 1
					}, MENU_ANIMATION);
				}
			}
			
			if( index != first_active ) {
				jQuery(menu[first_active]).animate({
					backgroundColor: '#' + bgcolor
				}, MENU_ANIMATION, function() {
					jQuery(this).removeClass('first_active');
				});
			}
			
			link.animate({
				backgroundColor: '#' + bgcolor_active
			}, MENU_ANIMATION, index != first_active ? null : function() {
				link.addClass('active');
			});
		};
	
	jQuery('#menu')
		.mouseenter(function() {
			if( timeout ) {
				window.clearTimeout(timeout);
				timeout = false;
			}
		})
		.mouseleave(function() {
			timeout = window.setTimeout(function() {
				jQuery(menu[active]).data('hide_submenu')(active == first_active);
				active != first_active && set_active(first_active, true);
			}, MENU_HIDE_TIMEOUT);
		});
	
	menu.each(function(index, link) {
		var sub = (link = jQuery(link)).next('.submenu'),
			pos = link.offset();
		
		sub
			.css({
				top: pos.top + 39,
				left: pos.left,
				minWidth: link.innerWidth() - 20,
				backgroundPosition: (link.innerWidth() / 2 - 4) + 'px 0px'
			})
			.data('target_height', sub.height());
		
		link
			.mouseenter(function() {
				set_active(index);
			})
			.data('hide_submenu', function(leave_bg) {
				if( !sub.is(':hidden') ) {
					sub.animate({
						height: 0,
						opacity: 0
					}, MENU_ANIMATION, function() { sub.hide(); });
					
					!leave_bg && link.animate({backgroundColor: '#' + bgcolor}, MENU_ANIMATION);
				}
			});
		
		link.hasClass('active') && set_active(first_active = index, true);
	});
});
