// gallery.js - version 0.5 - Spry Pre-Release 1.5
//
// Copyright (c) 2006. Adobe Systems Incorporated.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   * Redistributions of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//   * Redistributions in binary form must reproduce the above copyright notice,
//     this list of conditions and the following disclaimer in the documentation
//     and/or other materials provided with the distribution.
//   * Neither the name of Adobe Systems Incorporated nor the names of its
//     contributors may be used to endorse or promote products derived from this
//     software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.

// Global variables:
var gThumbWidth, gThumbHeight, gSlideShowInterval, gAutoStartSlideShow, gBehaviorsArray, 
    gSlideShowOn, gSlideShowTimer, gImageLoader, gZIndex, gAnimationLock, gCurrentEffects;

if (gThumbWidth == undefined)
{
	gThumbWidth = 40;
}
if (gThumbHeight == undefined)
{
	gThumbHeight = 40;
}
if (gSlideShowInterval == undefined)
{	
	gSlideShowInterval = 4000; // msecs between images.
}
if (gAutoStartSlideShow == undefined)
{	
	gAutoStartSlideShow = false;
}

gBehaviorsArray = [];
gSlideShowOn    = false;
gSlideShowTimer = null;
gImageLoader    = null;
gZIndex         = 350;

//Flag to lock animations on change events
gAnimationLock=false;
gCurrentEffects = $A([]);

// Register a callback on the dsPhotos data set so we can turn
// off the slide show before it attempts to load new data.
dsPhotos.addObserver(function(nType, notifier, data) 
	{
		if (nType == "onPreLoad")
		{
			StopSlideShow();
		}
	});

// 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("thumbnails", function(nType, notifier, data) {
	if (nType == "onPostUpdate")
	{
		//arrange thumbnails
		adjustAll();
		
		ShowCurrentImage();
		if (gAutoStartSlideShow)
		{
			StartSlideShow(true);
		}
		//Ensure animations are loaded to prevent firefox overlap on effect issue
		setTimeout("TriggerPaneDisplay()", 1000 );	
		unlockAnimations();
	}
});

// Register a callback on the ecommerce thumbnails so we can load first image in dataset after
//ecommerce thumnails have been loaded
var myObserver = new Object;
myObserver.onPostLoad = function(dataSet, data)
{
	ShowCurrentImage();
};
dsPhotos.addObserver(myObserver);

function lockAnimations()
{
	gAnimationLock=true;
}

function unlockAnimations()
{
	gAnimationLock=false;
}

function TriggerPaneDisplay(){
	//Display the gallery pane
	var gPane = document.getElementById("galleryPane");
	
	gPane.style.display = 'block';
	gPane.style.overflow = 'visible';
}

// Trigger the transition animation from the current image
// being displayed to the image at imgPath.

function SetMainImage(imgPath, width, height, tnID, photoName, photoCaption)
{
	var img, titleDiv, captionDiv;
	
	img = document.getElementById("mainImage");
	if (!img)
	{
		return;
	}
	titleDiv   = $("mainImageTitle");
	captionDiv = $("mainImageCaption");
	
	CancelBehavior("mainImage");

	Spry.Utils.SelectionManager.clearSelection("thumbnailSelection");

	if (tnID)
	{
		Spry.Utils.SelectionManager.select("thumbnailSelection", document.getElementById(tnID), "selectedThumbnail");
	}
	if (gImageLoader)
	{
		gImageLoader.onload = function() {};
		gImageLoader = null;
	}

	gBehaviorsArray["mainImage"] = new Spry.Effect.Opacity(img, Spry.Effect.getOpacity(img), 0, { duration: 400,
		finish: function()
		{
			gBehaviorsArray["mainImage"] = 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.
					gImageLoader = new Image();
					gImageLoader.onload = function()
					{
						//set the source
						img.src = gImageLoader.src;
						gImageLoader = null;
						
						//set teh name and captions
						//add in the title and caption as well
						titleDiv.innerHTML = photoName;
						captionDiv.innerHTML = photoCaption;
						
						gBehaviorsArray["mainImage"] = new Spry.Effect.Opacity(img, 0, 1, { duration: 400,
							finish: function()
							{
								gBehaviorsArray["mainImage"] = null;
								
								// Our new image is fully visible now. Remove any opacity related
								// style properties on the img to workaround the IE bug that creates
								// white dots/holes in the images. Removing the properties forces
								// IE to re-render the image correctly.

								img.style.opacity = "";
								img.style.filter = "";

								// If the slide show is on, fire off the timer for the next image.

								if (gSlideShowOn)
								{
									SetSlideShowTimer();
								}
							}});
						gBehaviorsArray["mainImage"].start();
					};
					gImageLoader.src = imgPath;
				}
		  });
		  gBehaviorsArray["mainImage"].start();
		}
	});
	gBehaviorsArray["mainImage"].start();
}

// Cancel the animation behavior of the object with the given id.

function CancelBehavior(id)
{
	if (gBehaviorsArray[id])
	{
		gBehaviorsArray[id].cancel();
		gBehaviorsArray[id] = null;
	}
}

function SizeAndPosition(id, toX, toY, toWidth, toHeight, callback)
{
	var effectCluster, ele, moveEffect, sizeEffect;
	
	CancelBehavior(id);
	effectCluster = new Spry.Effect.Cluster( { finish: callback } );
	ele           = Spry.Effect.getElement(id); 
	moveEffect    = new Spry.Effect.Move(ele, Spry.Effect.getPosition(ele), { x: toX, y: toY, units: "px" }, { duration: 400 });
	sizeEffect    = new Spry.Effect.Size(ele, Spry.Effect.getDimensions(ele), { width: toWidth, height: toHeight, units: "px" }, { duration: 400 });
	
	effectCluster.addParallelEffect(moveEffect);
	effectCluster.addParallelEffect(sizeEffect);
	
	gBehaviorsArray[id] = effectCluster;
	gBehaviorsArray[id].start();
}

//Trigger jump animation
function JumpUp(img)
{
	var id, jh, ele, tmpLen, moveup;

	//if animations are locked then exit right away
	if (gAnimationLock)
	{
		return false;	
	}
	
	Spry.Utils.addClassName(img, "inFocus");
	img.style.zIndex = gZIndex;
	gZIndex++;
	
	id = img.getAttribute("id");
	jh = -4;
	
	img.focus();
	img.blur();
	
	ele = Spry.Effect.getElement(id); 
	//Spry.Effect.makePositioned(document.getElementById(id));
	//var moveDown = new Spry.Effect.Move(id, Spry.Effect.getPosition(ele), { x: 0, y: -jh, units: "px" }, { duration: 200, toggle:true});
	
	//only trigger effects of ones not already running
	if (!(gCurrentEffects.member(img.id)))
	{
		//add to this to array so the effect does not trifgger again till finished
		tmpLen = gCurrentEffects.push(img.id);
		moveUp = new Spry.Effect.Move(id, Spry.Effect.getPosition(ele), { x: 0, y: jh, units: "px" }, { duration: 200, finish: function tmpT(){JumpDown(img);}});
		moveUp.start();
	}

	
}
//function to jump back down
function JumpDown(img)
{
	var id, jh, ele, moveEffect;

	//if animations arelocked then exit right away
	if (gAnimationLock)
	{
		return false;	
	}
	
	id = img.getAttribute("id");
	jh = 4;
	img.style.zIndex = 1;
	
	ele = Spry.Effect.getElement(id); 

	moveEffect = new Spry.Effect.Move(id, Spry.Effect.getPosition(ele), { x: 0, y: jh, units: "px" }, { duration: 200});
	moveEffect.start();
	
	//remove this element from the array & remove empty spaces
	gCurrentEffects = gCurrentEffects.without(img.id);
}

//function to adjust all thumbnails to remove "fly away" effect on initial mouse over
function adjustAll()
{
	var thumbImgs, imgs, img, id, ele, moveEffect, i;
	
	thumbImgs = document.getElementById("thumbnails");
	imgs = thumbImgs.getElementsByTagName('img');
	
	for(i = 0; i < imgs.length; i++)
	{
		img = imgs[i];
		id = img.getAttribute("id");
		ele = Spry.Effect.getElement(id);
		if ((img != null) && (id !=null) && (ele !=null))
		{
			moveEffect = new Spry.Effect.Move(id, Spry.Effect.getPosition(ele), { x: 0, y: 0, units: "px" }, { duration: 1});
			moveEffect.start();
		}
		img.style.zIndex = 1;
	}
}

// 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 AdvanceToNextImage(moveBackwards)
{
	var rows, curRow;
	
	rows   = dsPhotos.getData();
	curRow = dsPhotos.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];
	dsPhotos.setCurrentRow(curRow["ds_RowID"]);
	ShowCurrentImage();
}

function SetSlideShowTimer()
{
	KillSlideShowTimer();
	gSlideShowTimer = setTimeout(function(){ gSlideShowTimer = null; AdvanceToNextImage(false); }, gSlideShowInterval);
}

function KillSlideShowTimer()
{
	if (gSlideShowTimer)
	{
		clearTimeout(gSlideShowTimer);
	}
	gSlideShowTimer = null;
}

// Start the slide show that runs forwards through all
// the rows in dsPhotos.

function StartSlideShow(skipTimer)
{
	var playIcon;
	
	gSlideShowOn = true;
	if (!skipTimer)
	{
		SetSlideShowTimer();
	}
	playIcon = document.getElementById("playIcon");
	if (playIcon)
	{
		playIcon.src = "/images/pause.gif";
	}
}

// Kill any slide show that is currently running.

function StopSlideShow()
{
	var playIcon;
	
	gSlideShowOn = false;
	KillSlideShowTimer();
	playIcon = document.getElementById("playIcon");
	
	if (playIcon)
	{
		playIcon.src= "/images/play.gif";
	}
}

function HandleThumbnailClick(id)
{
	StopSlideShow();
	dsPhotos.setCurrentRow(id);
	ShowCurrentImage();
}


