$(function() {
	/* position of the <li> that is currently shown */
	var current = 0;
	
	var loaded  = 0;
	for(var i = 1; i <5; ++i)
		$('<img />').load(function(){
			++loaded;
			if(loaded == 3){
				$('#bg1,#bg2,#bg3,#bg4').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 or bg4, depending where we are hovering */
					var item = e.target.id;

					if(item == 'bg1' || current == 2 || current == 3){
						/* if we hover the first <li> or if we come from the last one, then the images should move left -> right */
						$('#menu > li').animate({backgroundPosition:"(-935px 0)"},0).removeClass('bg1 bg2 bg3 bg4').addClass(item);
						move(1,item);
					}
					else{
						$('#menu > li').animate({backgroundPosition:"(935px 0)"},0).removeClass('bg1 bg2 bg3 bg4').addClass(item);
						move(0,item);
					}

					/* change the current element */
					current = $this.parent().index();
					
				});
			}	
		}).attr('src', 'images/'+i+'.jpg');
	
				
	/*
	dir:1 - move left->right
	dir:0 - move right->left
	 */
	function move(dir,item){
		if(dir){
			$('#bg1').parent().stop().animate({backgroundPosition:"(0px 0px)"},300);
			$('#bg2').parent().stop().animate({backgroundPosition:"(-234px 0px)"},400);
			$('#bg3').parent().stop().animate({backgroundPosition:"(-468px 0px)"},500);
			$('#bg4').parent().stop().animate({backgroundPosition:"(-702px 0px)"},600,function(){
				$('#menuWrapper').removeClass('bg1 bg2 bg3 bg4').addClass(item);
			});
		}
		else{
			$('#bg1').parent().stop().animate({backgroundPosition:"(0px 0px)"},600,function(){
				$('#menuWrapper').removeClass('bg1 bg2 bg3 bg4').addClass(item);
			});
			$('#bg2').parent().stop().animate({backgroundPosition:"(-234px 0px)"},500);
			$('#bg3').parent().stop().animate({backgroundPosition:"(-468px 0px)"},400);
			$('#bg4').parent().stop().animate({backgroundPosition:"(-702px 0px)"},300);
		}
	}
});

