$(document).ready(function() {
    var next;
    var play=true;
    var playTurn = 0;
    var current;
    /* Fade in thumbs */    
    $("#thumbs > img").fadeTo(500,0.3);
    
    /* Fade in on hover thumb */
    $("#thumbs > img").hover(
	function(){
	    $(this).fadeTo(300,1.0);
	},
	function(){
	    $(this).fadeTo(300,0.3);
	}
    );
    
    /* Choose image */
    var fading=false; 
    $("#thumbs > img").click(function(){
	if(play==true){
	    next = $("#thumbs > img").index(this);
	    $("#thumbs > img").css("border","solid #ffffff 1px");
	    $("#thumbs > img:eq("+next+")").css("border","solid #000000 1px");
	}else if(play==false){
	    var tmp=$("#thumbs > img").index(this);
	    /* To fade out before play */
	    current=tmp;
	    if(fading==false){
		$("#thumbs > img").css("border","solid #ffffff 1px");
		$("#thumbs > img:eq("+tmp+")").css("border","solid #000000 1px");
		fading=true;
		$("#pic > img:visible").fadeOut(1500,function(){
		    fading=false;
		    $("#pic > img:eq("+tmp+")").fadeIn(1500);
		});		
	    }	    
	}
    });
    
    /* Pause */
 
    $("#pic > img , #play > p").click(function(){
	$("#play > p").toggle();
	if(play==true){
	    play=false;
	}else{
	    play=true;
	    playTurn++;
	    /* Fade out */
	    /* Get the actual image */
	    $("#pic > img:visible").fadeOut(1500,function(){
		test((current+1)%$("#thumbs > img").length);
	    });
	}
    });

    function test(index){
	next=(index+1)%$("#thumbs > img").length;
	$("#thumbs > img").css("border","solid #ffffff 1px");
	$("#thumbs > img:eq("+index+")").css("border","solid #000000 1px");
	var localCheck = playTurn;
	$("#pic > img:eq("+index+")").fadeIn(1500,function(){
	    setTimeout(function(){
		if(play==true && localCheck==playTurn){
		    $("#pic > img:eq("+index+")").fadeOut(1500,function(){
			test(next);
		    });
		}
	    },4500)
	});
    }

    test(0);
});

