$(function () { 
	for (var i = 1; i <= 4; i++) {
		// Stack initialize
		var openspeed = 300;
		var closespeed = 300;
		$('.stack' + i + '>a').click(function(evt) {
			var $el = $(this);
			$el.next().show();
			if ($el.next().hasClass('openStack') == false) {
				var vertical = 0;
				var horizontal = 0;
				$el.next().children().each(function(){
					$(this).animate({top: '-' + vertical + 'px', left: horizontal + 'px'}, openspeed);
					vertical = vertical + 55;
					horizontal = (horizontal-1)*0;
				});
				$el.next().animate({top: '-55px', left: '0px'}, openspeed).addClass('openStack')
				   .find('li a>img').animate({width: '50px', marginLeft: '0px'}, openspeed);
				$el.animate({paddingTop: '0'});
				$('.stack1>a, .stack2>a, .stack3>a, .stack4>a').each(function() {
					if ($(this)[0] != $el[0]) {
						$nel = $(this);
						$nel.next().removeClass('openStack').children('li').animate({top: '90px', left: '-10px'}, closespeed, null, function() {
							$(this).parent().hide();
						});
						$nel.next().find('li a>img').animate({width: '10px', marginLeft: '30px'}, closespeed);
						$nel.animate({paddingTop: '0px'});
					}
				});
			} else {
				$el.next().removeClass('openStack').children('li').animate({top: '90px', left: '-10px'}, closespeed, null, function() {
					$el.next().hide();					
				});
				$el.next().find('li a>img').animate({width: '10px', marginLeft: '30px'}, closespeed);
				$el.animate({paddingTop: '0px'});
			}
			evt.preventDefault();
		});
		// Stacks additional animation
		$('.stack' + i + ' li a').hover(function(){
			$("img",this).animate({width: '53px'}, 150);
			$("span",this).animate({marginLeft: '0px'}, 150);
		},function(){
			$("img",this).animate({width: '50px'}, 150);
			$("span",this).animate({marginLeft: '0'}, 150);
		});
		$('#stack' + i).hide();
	}
});

$(document).click(function(evt) {
	if ($(evt.target).parents().is('#nav-content') == false) {
		$('.stack1>a, .stack2>a, .stack3>a, .stack4>a').each(function() {
			var closespeed = 300;
			$nel = $(this);
			$nel.next().removeClass('openStack').children('li').animate({top: '90px', left: '-10px'}, closespeed, function() {
				$(this).parent().hide();				
			});
			$nel.next().find('li a>img').animate({width: '10px', marginLeft: '30px'}, closespeed);
			$nel.animate({paddingTop: '0px'});
		});
	}
});
