
$(function(){
	var slides = $('.slides')
	var hoverStop = false;
	var currentIcon;
	var originalPosition;
	var thenContinue;
	slides.css('visibility', 'visible').children()/*.not(':eq(1)')*/.hide()
	
	var iconItems = $('.icon_item')
	var icon = 0;
	var currentIcon = iconItems.eq(0);
	function iconFliper() {
	
		if(currentIcon.length == 0){
			currentIcon = iconItems.eq(0);
		};
		
		originalPosition = currentIcon.css('bottom')
		
		currentIcon.queue(function(next){
						
						$(this)
							.addClass('current')
							.fly().delay(500)
							openSlide(iconItems.index($(this)));
							next();
							})
						.queue(function(next){
							// store the next function globaly for the hover state
							thenContinue = next
							if(!hoverStop){next()}
							})
					  .queue(function(next){
							closeSlide(iconItems.index($(this)));
							next()
							})
							.queue(function(next){
							
								fallingIcon();
								next();
							})
							
							
	}
	
	function fallingIcon(isClicked, clickedIcon) {
		var getOut = 0;
		$('.current').animate({bottom: originalPosition}, 
									 {duration: 400, easing: "easeOutExpo", 
									  step: function(){
																//getOut set the moment the next icon pops up
															  if(getOut==0) {
																		$(this).removeClass('current')
																		if(isClicked){
																			currentIcon = clickedIcon
																			iconFliper()
																		} else {
																			currentIcon = currentIcon.next()
																			iconFliper()
																		}
																	}	
																	getOut++
																}})
															}
	
	jQuery.fn.fly = function(){
			var baseMiddle = 5;
			var bounsSize = 1.2;
			var repeats = 5;
			var bounsSpeed = 300; 
			var high, low;
			var i = 0;
			this.delay(0)
			while(i!=repeats){
				
				high = (baseMiddle + bounsSize);
				low = (baseMiddle - bounsSize);
				
				if(i==0) {
					var speed = 200
 				}
				else if(i==1) {
					speed = bounsSpeed
				}
				 
				this
					 .animate({bottom: high+"em"}, {duration:speed, easing:"easeInOutSine"})
				if(i<(repeats-1)) this.animate({bottom: low+"em" }, {duration:300, easing:"easeInOutSine"})
				
				bounsSize *= 0.49 ; i++; 
				
			}
			
		return this
	}
	
	
	
	
	function openSlide(currentSlide) {
		slides.eq(currentSlide).children().delay(0).fadeIn(1000)
	}
	
	function closeSlide(currentSlide) {
		slides.eq(currentSlide).children().delay(250).fadeOut(500)
	}
	
	
	iconItems.click(function(){
	  if($(this).hasClass('current')) return;
		$('.current').clearQueue()
		closeSlide(iconItems.index($('.current')))
		fallingIcon(true, $(this));
	})
	
	$('.banner').hover(function(){
			hoverStop = true
		}, function(){
			hoverStop = false
			
			// on mouseOut activate the next()
			thenContinue()
		});
	
	setTimeout(iconFliper, 500)
})




