var timeoutId;
$(document).ready(function() {
   	setUpGallery();

	timeoutId = setTimeout(rotateThumbnail, 8000);
});

function setUpGallery()
{
	$.post("/ourStory", { id: 1 },
	  function(data){
		var $detailImg = "<img src='" + data[0] + "'/>";

		$(".main-image-container").hide();
		$(".main-image-container  table tr td").html($detailImg);
		$(".main-image-container").fadeIn('fast');
		$(".title-container").html(data[1]);

	  }, "json");

    $("a.thumb").click(
	function ()
	{
    	var $this = $(this);

		clearTimeout(timeoutId);

        if (!$this.hasClass("selected"))
		{
			removeSelected();
			$this.addClass("selected");
			$this.html('<span class="thumb-border"/>');

			var $id = $(this).attr('id');

			$.post("/ourStory", { id: $id },
			  function(data){
				var $detailImg = "<img src='" + data[0] + "'/>";

				$(".main-image-container").fadeOut('fast', function(){
					$(".main-image-container table tr td").html($detailImg);
					$(".main-image-container").fadeIn('fast');
				});

				timeoutId = setTimeout(rotateThumbnail, 5000);

				$(".title-container").html(data[1]);

			  }, "json");
        }
    });
}

function removeSelected()
{
    $(".thumbnail-container a.thumb").each(function(e)
	{
		var $this = $(this);

		if($this.hasClass("selected"))
		{
			$this.removeClass("selected");
			$this.html('');
		}
   	});
}

function rotateThumbnail()
{
	var nextThumbnail = $('a.selected').next();
	if ($(nextThumbnail).attr('id') == undefined) {
		nextThumbnail = $('a.thumb:first');
	}

	$(nextThumbnail).click();
}
