// gallery.js - version 0.5 - Spry Pre-Release 1.6.1
//
// 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;
if (gThumbWidth == undefined)
	gThumbWidth = 40;
  
var gThumbHeight;
if (gThumbHeight == undefined)
	gThumbHeight = 40;

var gSlideShowInterval;
if (gSlideShowInterval == undefined)
	gSlideShowInterval = 2000; // msecs between images.

var gAutoStartSlideShow;
if (gAutoStartSlideShow == undefined)
	gAutoStartSlideShow = true;

var gBehaviorsArray = [];
var gSlideShowOn = false;
var gSlideShowTimer = null;
var gImageLoader = null;
var gContainer = 0;

var checkint = null;

// 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")
	{
		slideshow = 1;
		dsPhotos = dsPhotos1; 
		dsGalleries = dsGalleries1;
		ShowCurrentImage();
		if (gAutoStartSlideShow)
			StartSlideShow(true);
	}
});

Spry.Data.Region.addObserver("thumbnails2", function(nType, notifier, data) {
	if (nType == "onPostUpdate")
	{
		document.getElementById("thumbnails2").style.visibility = "visible";
		CheckThumbnails();
	}
});

function CheckThumbnails() {
	var rows = dsPhotos2.getData();
	if (rows.length < 1) return;
	var loaded = 0;
	for (var i = 0; i < rows.length; i++)
	{
		if (document.getElementById("tn"+parseInt(i)).complete) ++loaded;
	}
	if (loaded == rows.length) {
		document.getElementById("galleryarrow").style.visibility = "visible";
		clearTimeout(checkint);
	}else{
		clearTimeout(checkint);
		checkint = setTimeout("CheckThumbnails()",100);
	}
}

// Trigger the transition animation from the current image
// being displayed to the image at imgPath.

function SetMainImage(imgPath, width, height, tnID)
{
	if (!gContainer) {
		var mainImg = "mainImage";
		var img = document.getElementById("mainImage");
		var altimg = document.getElementById("altImage");
	}else{
		var mainImg = "altImage";
		var img = document.getElementById("altImage");
		var altimg = document.getElementById("mainImage");
	}
	if (!img)
		return;

	CancelBehavior(mainImg);

	Spry.Utils.SelectionManager.clearSelection("thumbnailSelection");

	if (tnID && !slideshow) {
		Spry.Utils.SelectionManager.select("thumbnailSelection", document.getElementById(tnID), "selectedThumbnail");
	}

	if (gImageLoader)
	{
		gImageLoader.onload = function() {};
		gImageLoader = null;
	}

	gImageLoader = new Image();
	gImageLoader.onload = function() {
		if (loadingtimeout)	clearTimeout(loadingtimeout);
		document.getElementById("loading").style.visibility = "hidden";
		img.src = gImageLoader.src;
		if (!img.style.width) {
			img.style.width=width;
			img.style.height=height;
			altimg.style.width="0%";
			altimg.style.height="0%";
			img.style.opacity = 0;
			img.style.filter = "alpha(opacity=0)";
		}else{
			img.style.width=width;
			img.style.height=height;
		}
		gImageLoader = null;
		var opacity = Spry.Effect.getOpacity(img);
		gBehaviorsArray[mainImg] = new Spry.Effect.Opacity(img, opacity, 1-opacity, { duration: 800,
			finish: function() {
				gBehaviorsArray[mainImg] = null;								
				if (gSlideShowOn) SetSlideShowTimer();
			}
		});
		var obs = new Object;
		obs.onStep = function(ef) {
			var opacity1 = 0;
			if(/MSIE/.test(navigator.userAgent)){
				opacity1 = Spry.Effect.getStyleProp(ef.element, 'filter').replace(/alpha\(opacity=([0-9]{1,3})\)/, '$1');
				altimg.style.filter = "alpha(opacity=" + (100 - opacity1) + ")";
			}else{
				opacity1 = Spry.Effect.getStyleProp(ef.element, 'opacity');
				altimg.style.opacity = (1 - opacity1);
			}
		}
		obs.onPostEffect = function(ef) {
			if(/MSIE/.test(navigator.userAgent)){
				img.style.filter = "alpha(opacity="+100*(1-opacity)+")";
				altimg.style.filter="alpha(opacity="+100*opacity+")";
			}else{
				img.style.opacity = 1-opacity;
				altimg.style.opacity=opacity;
			}
			if (tnID && !slideshow) {
				var curRow = dsPhotos.getCurrentRow();
				document.getElementById("toptext").innerHTML = curRow["@title"];
			}
		}
		obs.onCancelEffect = function(ef) {
			if(/MSIE/.test(navigator.userAgent)){
				img.style.filter = "alpha(opacity="+100*(1-opacity)+")";
				altimg.style.filter="alpha(opacity="+100*opacity+")";
			}else{
				img.style.opacity = 1-opacity;
				altimg.style.opacity=opacity;
			}
			if (tnID && !slideshow) {
				var curRow = dsPhotos.getCurrentRow();
				document.getElementById("toptext").innerHTML = curRow["@title"];
			}
		}
		gBehaviorsArray[mainImg].addObserver(obs);
		gBehaviorsArray[mainImg].start();
	};
	gImageLoader.src = imgPath;
}

// 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)
{
	CancelBehavior(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: 350 });
	var sizeEffect = new Spry.Effect.Size(ele, Spry.Effect.getDimensions(ele), { width: toWidth, height: toHeight, units: "px" }, { duration: 350 });
	
	effectCluster.addParallelEffect(moveEffect);
	effectCluster.addParallelEffect(sizeEffect);
	
	effectCluster.finish = callback;
	
	gBehaviorsArray[id] = effectCluster;
	gBehaviorsArray[id].start();
}

// Trigger the animation of the thumbnail growing.

function GrowThumbnail(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 ShrinkThumbnail(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 ShowCurrentImage()
{
	var curRow = dsPhotos.getCurrentRow();
	SetMainImage("galleries/" + dsGalleries.getCurrentRow()["@base"] + "images/" + curRow["@path"], curRow["@width"], curRow["@height"], "tn" + curRow["ds_RowID"]);
}

// 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 = dsPhotos.getData();
	var 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"]);
	if (!gContainer) gContainer=1; else gContainer=0;
	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)
{
	gSlideShowOn = true;
	if (!skipTimer) SetSlideShowTimer();
/*	var playLabel = document.getElementById("playLabel");
	if (playLabel)
		playLabel.firstChild.data = "Pause";
*/
}

// Kill any slide show that is currently running.

function StopSlideShow()
{
	gSlideShowOn = false;
	KillSlideShowTimer();
/*	var playLabel = document.getElementById("playLabel");
	if (playLabel)
		playLabel.firstChild.data = "Play";
*/
}

function HandleThumbnailClick(id)
{
	StopSlideShow();
	dsPhotos.setCurrentRow(id);
	if(!gContainer) gContainer = 1; else gContainer = 0;
	ShowCurrentImage();
}
