var scrollableWidth = 0;
var scrollCurrentPosition = 0;
var scrollSpeed = 25;

// $(document).ready won't work because we really need all the thumbs to load so that we can calculate stuff
window.onload = function() {
	scrollableWidth = $("table#thumbnail_container").width() - 856;
	scrollSpeed = Math.round( 300 / ($('.thumbnail').size() - 3.5) );	// that is, scroll about three thumbnails by at a time!
	$('#thumbnail_label').css('top', $("table#thumbnail_container").offset().top + 30 + 'px' );

	$(".thumbnail").mouseenter(function() {
		var titleElement = $(this).children(".thumbnail_title");
		var descriptionElement = $(this).children(".thumbnail_description");
		var title = $(titleElement[0]).html();
		var description = $(descriptionElement[0]).html();
		$().mousemove(function(e){
			var left = e.pageX;
			$("#thumbnail_label").css("left", left);
		});
		$("#thumbnail_label #title").html(title);
		$("#thumbnail_label #description").html(description);
		$("#thumbnail_label").fadeIn(100);
	});

	$(".thumbnail").mouseleave(function() {
		$("#thumbnail_label").hide();
	});

	$(".slider").slider({
		handle: '.ui-slider-handle',
		min: 0,
		max: scrollableWidth,
		animate: true,
		stop: function(event, ui) {
			$("table#thumbnail_container").animate({ 'left' : '-' + ui.value + 'px' });
			//$("table#thumbnail_container").animate({left: ui.value * -1}, 500);
			this.lastact='stop';
		},
		slide: function(event, ui) {
			if (this.lastact == 'slide') {
				$("table#thumbnail_container").css('left', '-' + ui.value + 'px');
				//$("table#thumbnail_container").css('left', ui.value * -1);
				//scrollCurrentPosition = $(".ui-slider-handle").css('left');
			}
			this.lastact='slide';
		}
	});

	$(".right_arrow").click(function() {
		var n = parseInt($(".ui-slider-handle").css('left'))+scrollSpeed;
		if (n > 100) n = 100;
		$("table#thumbnail_container").animate({left: (-scrollableWidth * n/100)+'px'});
		$(".ui-slider-handle").animate({left: n+"%"});
		return;
	});

	$(".left_arrow").click( function() {
		var n = parseInt($(".ui-slider-handle").css('left'))-scrollSpeed;
		if (n < 0) n = 0;
		$("table#thumbnail_container").animate({left: (-scrollableWidth * n/100)+'px'});
		$(".ui-slider-handle").animate({left:n+"%"});
		return;
	});

	$(".thumbnail img", ".thumbnail_container").bind("mouseleave", function() {
		$("#thumbnail_label").css("display", "none");
		
	});
};