﻿

var numGalleryItems, currentShownItem, galleryInterval, galleryMoveDelay;
var galleryItems, galleryItemWidth, galleryPaused = true;

$(document).ready(function() {

   galleryItems = $(".galleryItem");
   numGalleryItems = galleryItems.length;
   currentShownItem = 0;
   galleryItemWidth = 450;
   galleryMoveDelay = 6000;

   // set the item container to total width of all items
   //$(".galleryWrapper").css("width", numGalleryItems * galleryItemWidth + "px");

   galleryItems.eq(currentShownItem).show();

   $(".start").click(function() {

      galleryInterval = setInterval("moveGalleryItems()", galleryMoveDelay);
      galleryPaused = false;
   });

   $(".stop").click(function() {
      clearInterval(galleryInterval);
   });

   $(".next").click(function() {
      moveGalleryItemsForward();
   });

   $(".previous").click(function() {
      moveGalleryItemsBack();
   });

   $(".galleryItem").click(function() {
      pauseGallery();
   });

   setTimeout("pauseGallery()", galleryMoveDelay);

});

function pauseGallery() {
   if (galleryPaused) {
      galleryPaused = false;
      galleryInterval = setInterval("moveGalleryItemsForward()", galleryMoveDelay);
      moveGalleryItemsForward();
   } else {
      galleryPaused = true;
      clearInterval(galleryInterval);
   }
}


function moveGalleryItemsBack() {

   if (currentShownItem == 0) {
      galleryItems.eq(currentShownItem).fadeOut("slow", function() {
         currentShownItem = numGalleryItems - 1;
         galleryItems.eq(currentShownItem).fadeIn("slow");
      });

   } else {

      galleryItems.eq(currentShownItem).fadeOut("slow", function() {
         --currentShownItem;
         galleryItems.eq(currentShownItem).fadeIn("slow");
      });

   }
}

function moveGalleryItemsForward() {

   if (currentShownItem == numGalleryItems - 1) {
      galleryItems.eq(currentShownItem).fadeOut("slow", function() {
         currentShownItem = 0;
         galleryItems.eq(currentShownItem).fadeIn("slow");
      });

   } else {

      galleryItems.eq(currentShownItem).fadeOut("slow", function() {
         ++currentShownItem;
         galleryItems.eq(currentShownItem).fadeIn("slow");
      });

   }
}
