$(document).ready(function(){
	
	//add javascript dependent elements
	$("#synopbox").css('display', 'none');
	$("#thumbholder div a").eq(0).addClass("current");
		
	$("#synopsis").hover(
		function(){
			$("#synopbox").fadeIn("slow")
		},
		function(){
			$("#synopbox").fadeOut("slow");
		});
		
		$("#synopsis").click(function(){
			return false;
	});
	
	var curpage = 1;
	var totalwidth = $("#thumbholder div").width();
	if (totalwidth < 696){
		var pages = 1;
	}else{
		var pages = Math.ceil(totalwidth/696);
	}
	
	$("#nav-r").click(function() {
		
		if(curpage < pages){
			var movement = curpage*696*-1;
			$("#thumbholder div").animate({marginLeft: movement+"px"}, 500);
			curpage++;	
		}

		return false;
		
	});
    
    $("#nav-l").click(function() {
    	
		if(curpage > 1){
			curpage--;
			var movement = (curpage*696-696)*-1;
			$("#thumbholder div").animate({marginLeft: movement+"px"}, 500);
		}

		return false;
			
	});
    
    $("#thumbholder div a").click(function(){
    	
    	if($("#mainimg").attr("src") != $(this).attr("href")){
    		if($("#slideshowstart").text() == "pause slideshow"){
	    		$("#slideshowstart").trigger("click");
    		}
    		if(timer!=""){
		    	clearTimeout(timer);
    		}
	    	$(".loader").show();
	        $("#mainimg").attr("src", $(this).attr("href"));
	        $("#mainimg").attr("name", $(this).attr("name"));
	        var icaption = $(this).attr("title");
	        $("p.caption").html(icaption).hide();
			$("#thumbholder div a.current").removeClass("current").fadeTo("fast", 1);
			$(this).addClass("current").fadeTo("slow", 0.6);
    	}
        return false;
    });
    
    $("#mainimg").load(function(){
    	$(".loader").hide();
    	$("p.caption").fadeIn("slow");
    });
    
    
    //define variables for slideshow
    $slidelist = $("#thumbholder div a");
    total = $slidelist.length;
    
    $("#slideshowstart").toggle(
	    function(){
	    	$("#slideshowstart").text("pause slideshow");
	    	initSlide();
	    	return false;
	    },
	    function(){
	    	$("#slideshowstart").text("slideshow");
	    	clearTimeout(timer);
	    	return false;
	    }
    );    

});

var timer = "";

function initSlide(){
	var curIndex = parseInt($("#mainimg").attr("name"));
	var nextIndex = curIndex + 1;
	
	if(nextIndex >= total){
		$("#slideshowstart").trigger("click");
		clearTimeout(timer);
	}else{
		timer = window.setTimeout('doChange('+nextIndex+')', 4000);
	}
}

function doChange(whichPic){
	$("#mainimg").attr("name", whichPic);
	$(".loader").show();
	//alert($("#mainimg").attr("name"));
	$("#mainimg").attr("src", $("#thumbholder div a").eq(whichPic).attr("href"));
	$("#thumbholder div a").eq(whichPic-1).removeClass("current").fadeTo("fast", 1);
	$("#thumbholder div a").eq(whichPic).addClass("current").fadeTo("slow", 0.6);
	if(whichPic%8 == 0){
		$("#nav-r").trigger("click");
	}
	initSlide();
}