var cpTO; //For timeout

function cyclePhotos(i, maxPhotos) {
	if (i >= 3) $("#small-photos img:visible:first").hide();
	if (i == 0) $("#small-photos img:hidden").show();
	
	$("#small-photos img.thumb").removeClass("highlighted");
	$("#small-photos img.thumb:eq("+i+")").addClass("highlighted");
				
	$("#large-photos div.fphoto").hide();
	$("#large-photos div.fphoto:eq("+i+")").show();
	var nextphoto = (i+1) % maxPhotos;
	cpTO = setTimeout("cyclePhotos(" + nextphoto + ", " + maxPhotos + ");", 4000);
}

$(document).ready(function() {
	var $leftArrow = $("#left-photo-arrow");
	var $rightArrow = $("#right-photo-arrow");

	var startPosition = 0;
       
	var slide = function(amount) {
		$("#small-photos img").css({left: amount});
	};

	var viewerWidth = parseInt($("#small-photos").css("width"));
	// size of photo plus space on either side
	var thumbWidth = 69 + 4;
	var nbrPhotosVisible = Math.floor(viewerWidth/thumbWidth);
	var maxSlide = -1 * ($("#small-photos img").size() - nbrPhotosVisible) * thumbWidth;

	var animateInterval = {};

	$("#small-photos img").each(function(i) {
		$(this).click(function(e) {
			e.preventDefault();
			clearTimeout(cpTO); //Stop auto-cycling slide show
			$("#small-photos img.thumb").removeClass("highlighted");
			$(this).addClass("highlighted");
			$("#large-photos div.fphoto").hide();
			$("#large-photos div.fphoto:eq("+i+")").show();
		});
	});

	$leftArrow.hover(function() {
		clearTimeout(cpTO); //Stop auto-cycling slide show
		animateInterval = setInterval(function() {
			if (startPosition < 0) {
				slide(startPosition += 5);
			}
		}, 10); 
	},
	function () {
		clearInterval(animateInterval);
	});

	$rightArrow.hover(function() {
		clearTimeout(cpTO); //Stop auto-cycling slide show
		animateInterval = setInterval(function() {
			if (startPosition > maxSlide) {
				slide(startPosition -= 5);
			}
		}, 10); 
	},
	function () {
		clearInterval(animateInterval);
	});
	
	// Start slide show
	cyclePhotos(0, $("#small-photos img").length);
});
