/*
 * Copyright (c) 2011 by dr. ir. R.T.H. Chin, The Netherlands.
 */

$(document).ready( function() {
	var numberOfImages = $(".images img").size();
	var loadedImages = 0;
	var totalWidth = 0;
	// Size of the window around the images.
	var windowLeft = $(".window").offset().left;
	var windowWidth = $(".window").width();
	var maxSlide = 0;

	// Loop through all images and update the total width when each of them is loaded.
	$(".images img").each( function(index) {
		var img = this;
		$("<img/>") // Make in memory copy of image to avoid css issues
		.attr("src", $(img).attr("src"))
		.load( function() {
			// Note 10 is the left + right padding
			totalWidth = totalWidth + this.width + 10;
			loadedImages = loadedImages + 1;
			if (loadedImages == numberOfImages) {
				// When all images are loaded then initialoize the slider.
				initialize();
			}
		});
	});
	
	// Hide the descriotions
	$("#description span").hide();
	
	/*
	 * Initializes the slider.
	 */
	function initialize() {
		$(".images").css({
			'width' : totalWidth
		});
	    
	    $("#goLeft").hide();
	    
	    $("#goRight").mousedown(function(){
	    	var d = (totalWidth - windowWidth);
	    	if (d > windowWidth) {
	    		d = windowWidth;
	    	} else {
	    		$("#goRight").hide();
	    	}
	    	var x = -d;
	    	$(".images").animate({ 'left' : x + 'px' }, 500, 'linear');
	    	$("#goLeft").show();
	    });
	    
	    $("#goLeft").mousedown(function(){
	    	var d = $(".images").position().left + windowWidth;
	    	if (d > 0) {
	    		d = 0;
	    		$("#goLeft").hide();
	    	}
	    	var x = d;
	    	$(".images").animate({ 'left' : x + 'px' }, 500, 'linear');
	    	$("#goRight").show();
	    });
	    
	    $(".images img").mouseover(function() {
		    $(this).addClass("image_highlight");
		    
		    var descriptionID = "#" + $(this).attr("id") + "_description";
		    //$("#debug").text("show=" + descriptionID);
		    $(descriptionID).show();
		}).mouseout(function(){
		    $(this).removeClass("image_highlight")
		    var descriptionID = "#" + $(this).attr("id") + "_description";
		    $(descriptionID).hide();
		});

	    
	    maxSlide = totalWidth - windowWidth;
	    if (maxSlide < 0) {
	    	maxSlide = 0;
	    }
	}
});
