var pSlideShowInterval;
if (pSlideShowInterval == undefined)
  pSlideShowInterval = 6000; // msecs between images.

var pAutoStartSlideShow;
if (pAutoStartSlideShow == undefined)
  pAutoStartSlideShow = true;

var pBehaviorsArray = [];
var pSlideShowOn = false;
var pSlideShowTimer = null;
var pImageLoader = null;
var pFirstRun = true;

// Register a callback on the dsPhotos data set so we can turn
// off the slide show before it attempts to load new data.

dsRSSpromo.addObserver(function(nType, notifier, data) {
  //alert(nType);
  if (nType == "onPreLoad")
    pStopSlideShow();
});

// Register a callback on the thumbnails region so we can show the first
// image in the data set after all the thumbnails have loaded.

Spry.Data.Region.addObserver("promobox", function(nType, notifier, data) {
  if (nType == "onPostUpdate")
  {
    pShowCurrentImage();
    if (pAutoStartSlideShow)
      pStartSlideShow(true);
  }
});

// Trigger the transition animation from the current image
// being displayed to the image at imgPath.

function pSetMainImage(imgPath, width, height, txtDesc, urlLink)
{
  var img = document.getElementById("promoimage");
  if (!img)
    return;

  pCancelBehavior("promoimage");

  if (pImageLoader)
  {
    pImageLoader.onload = function() {};
    pImageLoader = null;
  }

  pBehaviorsArray["promoimage"] = new Spry.Effect.Opacity(img, Spry.Effect.getOpacity(img), 0, { duration: 400,
    finish: function()
	{
      pBehaviorsArray["promoimage"] = new Spry.Effect.Size(img.parentNode, Spry.Effect.getDimensions(img.parentNode), { width: width, height: height, units:"px"}, {duration: 400,
	    finish: function()
	    {
          // Use an image loader to make sure we only fade in the new image after
          // it is completely loaded.
          pImageLoader = new Image();
          pImageLoader.onload = function()
          {
            img.src = pImageLoader.src;
			document.getElementById("promotext").innerHTML = txtDesc;
			document.getElementById("promolink").href = urlLink;
            pImageLoader = null;
            pBehaviorsArray["promoimage"] = new Spry.Effect.Opacity(img, 0, 1, { duration: 400,
              finish: function()
              {
                pBehaviorsArray["promoimage"] = null;

                // Our new image is fully visible now. If the slide show
                // is on, fire off the timer for the next image.

                if (pSlideShowOn)
					pSetSlideShowTimer();
              }});
            pBehaviorsArray["promoimage"].start();
          };
          pImageLoader.src = imgPath;
        }
      });
      pBehaviorsArray["promoimage"].start();
    }
  });
  pBehaviorsArray["promoimage"].start();
}

// Cancel the animation behavior of the object with the given id.

function pCancelBehavior(id)
{
  if (pBehaviorsArray[id])
  {
    pBehaviorsArray[id].cancel();
    pBehaviorsArray[id] = null;
  }
}

function pSizeAndPosition(id, toX, toY, toWidth, toHeight, callback)
{
  pCancelBehavior(id);
  var effectCluster = new Spry.Effect.Cluster( { finish: callback } );
  var ele = Spry.Effect.getElement(id); 
  var moveEffect = new Spry.Effect.Move(ele, Spry.Effect.getPosition(ele), { x: toX, y: toY, units: "px" }, { duration: 400 });
  var sizeEffect = new Spry.Effect.Size(ele, Spry.Effect.getDimensions(ele), { width: toWidth, height: toHeight, units: "px" }, { duration: 400 });
  
  effectCluster.addParallelEffect(moveEffect);
  effectCluster.addParallelEffect(sizeEffect);

  //effectCluster.finish = callback;
 
  pBehaviorsArray[id] = effectCluster;
  pBehaviorsArray[id].start();
}

// Trigger the animation of the thumbnail growing.

function pGrowThumbnail(img, width, height)
{
  Spry.Utils.addClassName(img, "inFocus");
  img.style.zIndex = 150;

  var id = img.getAttribute("id");

  var twidth = Math.floor(width * .75);
  var theight = Math.floor(height * .75);
  var tx = (gThumbWidth - twidth) / 2;
  var ty = (gThumbHeight - theight) / 2;

  SizeAndPosition(id, tx, ty, twidth, theight, function(b){gBehaviorsArray[id] = null;});
}

// Trigger the animation of the thumbnail shrinking.

function pShrinkThumbnail(img)
{
  Spry.Utils.addClassName(img, "inFocus");
  img.style.zIndex = 1;

  var id = img.getAttribute("id");

  SizeAndPosition(id, 0, 0, gThumbWidth, gThumbHeight, function(b){gBehaviorsArray[id] = null; Spry.Utils.removeClassName(img, "inFocus");});
}

// Show the image of the current selected row inside the dsPhotos data set.

function pShowCurrentImage()
{
	if (pFirstRun) {
		var rows = dsRSSpromo.getData();
		var rowCount = rows.length - 1;
		var randomRow = Math.floor(Math.random() * rowCount);
		dsRSSpromo.setCurrentRow(randomRow);
		pFirstRun = false;
	}
	var curRow = dsRSSpromo.getCurrentRow();
	pSetMainImage(curRow["k:img_url"], 200, 88, curRow["description"], curRow["k:ad_url"]);
}

// Utility function to advance (forwards or backwards) the current selected row
// in dsPhotos. This has the side effect of "selecting" the thumbnail and image
// of the new current row.

function pAdvanceToNextImage(moveBackwards)
{
  var rows = dsRSSpromo.getData();
  var curRow = dsRSSpromo.getCurrentRow();
  
  if (rows.length < 1)
    return;

  for (var i = 0; i < rows.length; i++)
  {
    if (rows[i] == curRow)
    {
      if (moveBackwards)
        --i;
      else
        ++i;
      break;
    }
  }

  if (!moveBackwards && i >= rows.length)
    i = 0;
  else if (moveBackwards && i < 0)
    i = rows.length - 1;

  curRow = rows[i];
  dsRSSpromo.setCurrentRow(curRow["ds_RowID"]);
  pShowCurrentImage();
}

function pSetSlideShowTimer()
{
  pKillSlideShowTimer();
  pSlideShowTimer = setTimeout(function(){ pSlideShowTimer = null; pAdvanceToNextImage(false); }, pSlideShowInterval);
}

function pKillSlideShowTimer()
{
  if (pSlideShowTimer)
    clearTimeout(pSlideShowTimer);
  pSlideShowTimer = null;
}

// Start the slide show that runs forwards through all
// the rows in dsPhotos.

function pStartSlideShow(skipTimer)
{
  pSlideShowOn = true;
  if (!skipTimer)
  	pSetSlideShowTimer();
}

// Kill any slide show that is currently running.

function pStopSlideShow()
{
  pSlideShowOn = false;
  pKillSlideShowTimer();
}

function pHandleThumbnailClick(id)
{
  pStopSlideShow();
  dsRSSpromo.setCurrentRow(id);
  pShowCurrentImage();
}
