//
// Created by ThisSideUp Software Inc.
//
// Copyright 2010 ThisSideUp Software Inc. http://www.thissideupsoftware.com
// All Rights Reserved. Permission to use, copy, modify, and distribute this
// software is hereby granted provided that the full text of this copyright
// notice appears in all copies.
//
// THIS SOFTWARE AND DOCUMENTATION IS PROVIDED "AS IS," AND COPYRIGHT HOLDERS
// MAKE NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO, WARRANTIES OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR
// PURPOSE OR THAT THE USE OF THE SOFTWARE OR DOCUMENTATION WILL NOT INFRINGE
// ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS.
//
// COPYRIGHT HOLDERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR
// CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THE SOFTWARE OR
// DOCUMENTATION.
//

var imgId;
var imgIdx = null;
var loadImg;
var errImg;

function incrImg()
{
   // Increment the index into the row
   ++(imgIdx[imgId]);
   if (imgIdx[imgId] >= gallery[imgId].length) imgIdx[imgId] = 0;
   // Increment the row
   ++imgId;
   if (imgId >= gallery.length) imgId = 0;
}

function swapImg()
{
   var img = $("#gallery-img-"+(imgId+1));
   $(img).fadeOut(500, function(){
      $(img)
         .load(loadImg)
         .error(errImg)
         .attr("src", gallery[imgId][imgIdx[imgId]]);
   });
}

errImg = function() {
   $(this).unbind("load", loadImg);
   $(this).unbind("error", errImg);
   if ($(this).complete) {
      $(this).fadeIn(500);
   }
   incrImg();
   $(document).oneTime(5000, "swap", function(){swapImg();});
}

loadImg = function() {
   $(this).unbind("load", loadImg);
   $(this).unbind("error", errImg);
   $(this).fadeIn(500);
   incrImg();
   $(document).oneTime(5000, "swap", function(){swapImg();});
}

function startGallery()
{
   imgId = 0;
   if (imgIdx == null )
   {
      imgIdx = new Array();
      for ( var i = 0; i < gallery.length; ++i )
      {
         imgIdx[i] = 1;
      }
   }

   // Kick-start the gallery effect
   $(document).oneTime(5000, "swap", function(){swapImg();});
}

function stopGallery()
{
   // Stop the gallery effect
   $(document).stopTime("swap");
   for( var i = 0; i < gallery.length; ++i )
   {
      $("#gallery-img-"+i).unbind("load", loadImg);
      $("#gallery-img-"+i).unbind("error", errImg);
   }
}

