/* gallery.js - Revision: Spry Preview Release 1.4 */

// 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 = 48;

var gThumbHeight;
if (gThumbHeight == undefined)
  gThumbHeight = 48;

var gSlideShowInterval;
if (gSlideShowInterval == undefined)
  gSlideShowInterval = 3000; // msecs between images.

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

var gBehaviorsArray = [];
var gSlideShowOn = false;
var gSlideShowTimer = null;
var gImageLoader = null;

// Register a callback on the dsPhotos data set so we can turn
// off the slide show before it attempts to load new data.
if ( dsPhotos )
{
	dsPhotos.addObserver(function(nType, notifier, data)
								{
  									if (nType == "onPreLoad")
    								StopSlideShow();
								});
}

function ShowRecord(rowid)
{
  	var tnID = "tn" + rowid;
  	var textDetails = document.getElementById("TextDetails");
  	var img = document.getElementById("MainImage");
  	if (!img)
    	return;

  CancelBehavior("fadeout_Text");
  CancelBehavior("fadeout_MainImage");
  CancelBehavior("sizemorph_MainImage");

  Spry.Utils.SelectionManager.clearSelection("thumbnailSelection");
  Spry.Utils.SelectionManager.clearSelection("thumbnailCaptionSelection");

  if (tnID)
    Spry.Utils.SelectionManager.select("thumbnailSelection", document.getElementById(tnID), "selectedThumbnail");
    Spry.Utils.SelectionManager.select("thumbnailCaptionSelection", document.getElementById(tnID), "selectedThumbnailCaption");

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


	// do morph
	
	// fadeout text
  	gBehaviorsArray["fadeout_Text"] = new Spry.Effect.Opacity( textDetails, Spry.Effect.getOpacity(textDetails), 0, { duration: 800 } );
	gBehaviorsArray["fadeout_Text"].start();

	// fadeout image
	gBehaviorsArray["fadeout_MainImage"] = new Spry.Effect.Opacity( img, Spry.Effect.getOpacity(img), 0, { duration: 800,
		finish: function()
				{
					// get record
					dsPhotos.setCurrentRow(rowid);
					var curRow 		= dsPhotos.getCurrentRow();
					
				  	// get new image dimensions
				  	var imgPath 	= curRow["photo"];
				  	var width 		= curRow["photo/@width"];
				  	var height 		= curRow["photo/@height"];
				  	var aspectRatio = width / height;
				  	
					// get the div we're applying the morph to
					img 			= document.getElementById("MainImage");
				  	var morphHandle = img.parentNode;
				  	
					// get viewbox dimensions (available display area for image)
					var boxDims 	= Spry.Effect.getDimensions(morphHandle.parentNode);
					var boxWidth 	= boxDims.width;
					var boxHeight 	= boxDims.height;
				
					// set any paddings here
					boxWidth 		-= 0;
					boxHeight 		-= 0;
					var boxAspect 	=  boxWidth / boxHeight;

					// fit image to viewbox					  
					var newWidth 	= 0;
					var newHeight	= 0;
										
					if( aspectRatio > boxAspect )
					{
						newWidth 	= boxWidth;
						newHeight 	= newWidth / aspectRatio;
					}
					else
					{
						newHeight 	= boxHeight;
						newWidth 	= newHeight * aspectRatio;
					}
					  
	  
	  
	  // original target-size arg: { width: width, height: height, units:"px"}
	  gBehaviorsArray["sizemorph_MainImage"] = new Spry.Effect.Size(morphHandle, Spry.Effect.getDimensions(morphHandle), { width: newWidth, height: newHeight, 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()
			  {
					// swap in fully-loaded image and clean up
					img.src = gImageLoader.src;
					gImageLoader = null;
					
					// fade in main image
					gBehaviorsArray["fadein_MainImage"] = new Spry.Effect.Opacity(img, 0, 1, { duration: 800,
					  finish: function()
					  {
					    	// load text details into display
							$('details_title').innerHTML = curRow["title"];
							$('details_description').innerHTML = curRow["description"];
							//var linkylink='<a href="http://' + curRow['link'] + '">' + curRow['link'] +'</a>';
							var linkylink = '<a href="' + curRow['link'] + '" title="' + curRow['link'] + '">' + curRow['nicelinktext'] +'</a>';
							$('details_link').innerHTML = linkylink;
							
							// fade in text
							gBehaviorsArray["TextDetailsView"] = new Spry.Effect.Opacity(textDetails, 0, .9999, { duration: 400,
							  finish: function()
							  {
								gBehaviorsArray["TextDetailsView"] = null;
				
								// Our new details are fully visible now. If the slide show
								// is on, fire off the timer for the next image.
				
								if (gSlideShowOn)
									SetSlideShowTimer();
							  }});
							gBehaviorsArray["TextDetailsView"].start();
			
				
					  }});
					gBehaviorsArray["fadein_MainImage"].start();
					
				
				
				
				
			  };
			  gImageLoader.src = imgPath;
		}
	  });
	  gBehaviorsArray["sizemorph_MainImage"].start();
	



				}					
	});
	gBehaviorsArray["fadeout_MainImage"].start();



}



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: 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;
  gBehaviorsArray[id] = effectCluster;
  gBehaviorsArray[id].start();
}



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;});
}



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");});
}



function AdvanceToNextRecord(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];
  ShowRecord(i);
}


function SetSlideShowTimer()
{
  KillSlideShowTimer();
  gSlideShowTimer = setTimeout(function(){ gSlideShowTimer = null; AdvanceToNextRecord(false); }, gSlideShowInterval);
}


function KillSlideShowTimer()
{
  if (gSlideShowTimer)
    clearTimeout(gSlideShowTimer);
  gSlideShowTimer = null;
}


function StartSlideShow(skipTimer)
{
  $('buttonPlayPause').firstChild.data = "<img src='img/play2.gif' />";
  gSlideShowOn = true;
  if (!skipTimer)
  	SetSlideShowTimer();
  else
  	AdvanceToNextRecord(false);
}

function StopSlideShow()
{
  gSlideShowOn = false;
  KillSlideShowTimer();
  $('buttonPlayPause').firstChild.data = "<img src='img/play1.gif' />";
}

function HandleThumbnailClick(id)
{
  StopSlideShow();
  ShowRecord(id);
}