$(function() {
var current = 0;

var loaded  = 0;
for(var i = 1; i <6; ++i)
$('<img />').load(function(){
++loaded;
if(loaded == 5){
$('#bg1,#bg2,#bg3,#bg4,#bg5').mouseover(function(e){

var $this = $(this);
if($this.parent().index() == current)
return;

var item = e.target.id;
if(item == 'bg1' || current == 4)
$('#menu .sub'+parseInt(current+1)).stop().animate({backgroundPosition:"(-192px 0)"},500,function(){
$(this).find('li').hide();
});
else
$('#menu .sub'+parseInt(current+1)).stop().animate({backgroundPosition:"(192px 0)"},500,function(){
$(this).find('li').hide();
});

if(item == 'bg1' || current == 4){
$('#menu > li').animate({backgroundPosition:"(-960px 0)"},0).removeClass('bg1 bg2 bg3 bg4 bg5').addClass(item);
move(1,item);
}
else{
$('#menu > li').animate({backgroundPosition:"(960px 0)"},0).removeClass('bg1 bg2 bg3 bg4 bg5').addClass(item);
move(0,item);
}

if(current == 4 && item == 'bg1'){
$('#menu .sub'+parseInt(current)).stop().animate({backgroundPosition:"(-192px 0)"},500);
}
if(current == 0 && item == 'bg5'){
$('#menu .sub'+parseInt(current+4)).stop().animate({backgroundPosition:"(192px 0)"},500);
}

current = $this.parent().index();  
$('#menu .sub'+parseInt(current+1)).stop().animate({backgroundPosition:"(0 0)"},500,function(){
$(this).find('li').fadeIn();
});
});
}
}).attr('src', 'tl_files/xpapa.de/images/menu/'+i+'.jpg');

function move(dir,item){
if(dir){
$('#bg1').parent().stop().animate({backgroundPosition:"(0 0)"},200);
$('#bg2').parent().stop().animate({backgroundPosition:"(-192px 0)"},300);
$('#bg3').parent().stop().animate({backgroundPosition:"(-384px 0)"},400);
$('#bg4').parent().stop().animate({backgroundPosition:"(-576px 0)"},500);
$('#bg5').parent().stop().animate({backgroundPosition:"(-768px 0)"},600,function(){
   $('#menuWrapper').removeClass('bg1 bg2 bg3 bg4 bg5').addClass(item);
});
}
else{
$('#bg1').parent().stop().animate({backgroundPosition:"(0 0)"},600,function(){
$('#menuWrapper').removeClass('bg1 bg2 bg3 bg4 bg5').addClass(item);
});
$('#bg2').parent().stop().animate({backgroundPosition:"(-192px 0)"},500);
$('#bg3').parent().stop().animate({backgroundPosition:"(-384px 0)"},400);
$('#bg4').parent().stop().animate({backgroundPosition:"(-576px 0)"},300);
$('#bg5').parent().stop().animate({backgroundPosition:"(-768px 0)"},200);
}
}
});
