$(function() {
	/* position of the <li> that is currently shown */
	var current = -1;
	
	$('#bg1,#bg2,#bg3,#bg4,#bg5').mouseover(function(e){
		
		var $this = $(this);
		/* if we hover the current one, then don't do anything */
		if($this.parent().index() == current)
			return;
	
		/* item is bg1 or bg2 or bg3, depending where we are hovering */
		var item = e.target.id;
	
		/*
		this is the sub menu overlay. Let's hide the current one
		if we hover the first <li> or if we come from the last one,
		then the overlay should move left -> right,
		otherwise right->left
		 */
		if(item == 'bg1' || ((current > 1 && current < 5) && item != 'bg5'))
			$('#sliderMenu .sub'+parseInt(current+1)).stop().animate({backgroundPosition:"(-350px 0)"},300,function(){
				$(this).find('li').hide();
			});
		else
			$('#sliderMenu .sub'+parseInt(current+1)).stop().animate({backgroundPosition:"(350px 0)"},300,function(){
				$(this).find('li').hide();
			});
	
		if(item == 'bg1' || ((current > 1 && current < 5) && item != 'bg5')){
			/* if we hover the first <li> or if we come from the last one, then the images should move left -> right */
			$('#sliderMenu > li').animate({backgroundPosition:"(-710px 0)"},0).removeClass('bg1 bg2 bg3 bg4 bg5').addClass(item);
			move(1,item);
		}
		else {
			/* if we hover the first <li> or if we come from the last one, then the images should move right -> left */
			$('#sliderMenu > li').animate({backgroundPosition:"(710px 0)"},0).removeClass('bg1 bg2 bg3 bg4 bg5').addClass(item);
			move(0,item);
		}
		
		/* change the current element */
		current = $this.parent().index();
		
		/* let's make the overlay of the current one appear */
		$('#sliderMenu .sub'+parseInt(current+1)).stop().animate({backgroundPosition:"(0 0)"},300,function(){
			$(this).find('li').fadeIn();
		});
	});
	/*
	dir:1 - move left->right
	dir:0 - move right->left
	 */
	function move(dir,item){
		if(dir){
			$('#bg1').parent().stop().animate({backgroundPosition:"(0 0)"},200);
			$('#bg2').parent().stop().animate({backgroundPosition:"(-175px 0)"},300);
			$('#bg3').parent().stop().animate({backgroundPosition:"(-350px 0)"},400);
			$('#bg4').parent().stop().animate({backgroundPosition:"(-525px 0)"},500);
			$('#bg5').parent().stop().animate({backgroundPosition:"(-710px 0)"},600,function(){
				$('#sliderWrapper').removeClass('bg1 bg2 bg3 bg4 bg5').addClass(item);
			});
		}
		else{
			$('#bg1').parent().stop().animate({backgroundPosition:"(0 0)"},600,function(){
				$('#sliderWrapper').removeClass('bg5 bg4 bg3 bg2 bg1').addClass(item);
			});
			$('#bg2').parent().stop().animate({backgroundPosition:"(-175px 0)"},500);
			$('#bg3').parent().stop().animate({backgroundPosition:"(-350px 0)"},400);
			$('#bg4').parent().stop().animate({backgroundPosition:"(-525px 0)"},300);
			$('#bg5').parent().stop().animate({backgroundPosition:"(-710px 0)"},200);
		}
	}
});
