$(document).ready(function() {
	var left = -1;
	var menus = new Menus($('#page'));

	$('#header-menu > li').each(function() {
		if($(this).children('ul').length) {
			menus.add($(this), $(this).children('ul'), left);
		}
		left += $(this).children('a').width();
	});
	
});

var Menus = function($container, overlayHeight) {
	this.$container = this.createObject($container, 'menu-container');
	this.$overlay = this.createObject(this.$container, 'menu-overlay');
	this.$decorator = this.createObject(this.$container, 'menu-decorator');

	this.$overlay.css({opacity: 0});
	this.menus = new Array();
}

Menus.prototype.createObject = function($container, id) {
	$container.append('<div id="' + id + '"></div>');
	return $container.children('#' + id);
}

Menus.prototype.add = function($container, $menu, left) {
	var self = this;

	$menu.data('menu', {height: $menu.height(), opened: false, timer: null});
	$menu.css({left: left, top: 0, height: 0, opacity: 1, overflow: 'hidden'});

	$container.hover(
		function() { self.open($menu); },
		function() { self.close($menu); }
	);

	$menu.hover(
		function() { self.open($menu); },
		function() { self.close($menu); }
	);

	this.$container.append($menu);
}

Menus.prototype.open = function($menu) {
	var self = this;
	
	//this.$overlay.css('height', $('#page').height() - $('#footer').height() - 131);

	clearTimeout($menu.data('menu').timer);
	if(! $menu.data('menu').opened) $menu.data('menu').timer = setTimeout(function() {
		$menu.data('menu').opened = true;
		$menu.stop()
			.animate({height: $menu.data('menu').height, opacity: 1}, 300, 'easeOutQuint');
	}, 50);

	/*self.$overlay.stop()
		.css({display: 'block'})
		.animate({opacity: 0.8}, 300, 'easeOutQuint');*/
}

Menus.prototype.close = function($menu) {
	var self = this;

	clearTimeout($menu.data('menu').timer);
	if($menu.data('menu').opened) $menu.data('menu').timer = setTimeout(function() {
		$menu.data('menu').opened = false;
		$menu.stop()
			.animate({height: 0, opacity: 0}, 300, 'easeOutQuint', function() {
				$(this).css({display: 'none'});
			});
	}, 50);

	/*self.$overlay.stop()
		.animate({opacity: 0}, 300, 'easeOutQuint', function() {
			$(this).css({display: 'none'});
		});*/
}
