$(window).load(function(){
	// Slider					   
	$("#slider").slider({
		animate: true,
		slide: handleSliderSlide
	});		
	
	// Change size of scroller 
	var scrollerWidth = 0;
	$("#items a img").each(function() {
		scrollerWidth += parseInt($(this).width());
	});
	$("#items").css("width", scrollerWidth + 5); // Not sure why it's not calculating this right
	
	// Change marginLeft of slideshow at start
	/*var slideshowMarginLeft = 1024;
	$("#slideshow img").each(function() {
		slideshowMarginLeft -= parseInt($(this).width());
	});
	$("#slideshow").css("marginLeft", slideshowMarginLeft);*/
	
	// Add a hover div to each image
	$("#items a").each(function() {
		var hover = $("<div></div>");
		hover.css("width", $(this).find("img").css("width")); // Set hover div width equal to image width		
		$(this).prepend(hover);	
	});
	
	// On hover, add hover class
	$("#items a").hover(
		function() {
			$(this).find("div").addClass("hover");	
		},
		function() {
			$(this).find("div").removeClass("hover");	
		}
	);
	
	// On click,
	var animating = false; // Made my own lock (queue in jquery was fussy)
	var lastClick;
	
	$("#items a").click(function(event) {
		event.preventDefault();								 
		
		if(!animating) {
			// Set the image source
			var imageSource = $(this).find("img").attr("src");
			
			if(lastClick != imageSource) {			
				animating = true;
				
				// Add active class
				$("#items a div.active").removeClass("active");		
				$(this).find("div").addClass("active");
				
				// Add image to main window
				var image = $("<img />");			
				image.attr("src", imageSource);
				$("#slideshow").append(image);
				$("#slideshow").animate({
						marginLeft:parseInt($("#slideshow").css("margin-left")) - parseInt(image.css("width"))
					}, 
					{
						duration: 600, 
						speacialEasing: {
							width:"easeOut"
						},
						queue: true,
						complete: function() {
							animating = false;
						}
					}
				);
				
				lastClick = imageSource;
			}
		}
		
		return false;
	});
});

function handleSliderSlide(e, ui) {
	var maxScroll = $("#scroller").attr("scrollWidth") - $("#slider").width();
	$("#scroller").attr({scrollLeft: ui.value * (maxScroll / 100) });
}