/*
  Bob Schalkwijk Photography
  http://www.bobschalkwijkphotography.com
  
  Please note that this is a mashup of various technologies.
  The derivation is based on the following licenses:
  
  http://www.bobschalkwijkphotography.com/credits/Ext-License.html
  http://www.bobschalkwijkphotography.com/credits/Spry-License.html
  http://docs.jquery.com/License (MIT)

  The slideshow scrolling mechanism was derived from:
  http://www.kellishaver.com/misc/slideshow2/

  @author Dieter Wimberger (dieter at wimpi dot net)
*/

// Global variables:
var doscroll;
var tOffset;
var allThumbs;
var thumbLength;
	
var gThumbWidth;
if (gThumbWidth == undefined) {
	gThumbWidth = 75;
}
var gThumbHeight;
if (gThumbHeight == undefined) {
	gThumbHeight = 75;
}
var gSlideShowInterval;
if (gSlideShowInterval == undefined) {
	gSlideShowInterval = 5000; // msecs between images.
}

var gAutoStartSlideShow = false;
if (gAutoStartSlideShow == undefined) {
	gAutoStartSlideShow = true;
}

var gBehaviorsArray = [];
var gSlideShowOn = false;
var gSlideShowTimer = null;
var gImageLoader = null;
var thumbnailsInit = false;


if($.cookie('bsp_language') == "es") {
  var sr_play = "Iniciar";
  var sr_pause = "Detener";
} else {
  var sr_play = "Play";
  var sr_pause = "Pause";
}

// 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") {
	    if(!thumbnailsInit) {
	      initThumbnailsNav();
	      thumbnailsInit = true;
	    }
		ShowCurrentImage();
		if (gAutoStartSlideShow) {
			StartSlideShow(true);
	    }
	}
});

// Trigger the transition animation from the current image
// being displayed to the image at imgPath.
function SetMainImage(imgPath, width, height, tnID) {
	var img = document.getElementById("mainImage");
    
	if (!img) {
	  img = $('#mainImage')[0];
	  console.log("Returning." + img);
	  return;
    }
	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()
					{
						img.src = gImageLoader.src;
						gImageLoader = null;
						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;
	}
}


// Show the image of the current selected row inside the dsPhotos data set.
function ShowCurrentImage() {
    var largebase = dsGallery.data[0]['large/@base'];
	var curRow = dsPhotos.getCurrentRow();
	SetMainImage(largebase + 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;
			  var ml = $('#thumbnails').css('margin-left').split('px')[0];
			  tOffset = parseInt(ml) + gThumbWidth + 16;
			  $('#thumbnails').css('margin-left',  tOffset + 'px');
			} else {
		      ++i;
		      var ml = $('#thumbnails').css('margin-left').split('px')[0];
			  tOffset = (ml - gThumbWidth - 16);
			  $('#thumbnails').css('margin-left', tOffset + 'px');
			}
			break;
		}
	}
	
	if (!moveBackwards && i >= rows.length) {
		i = 0;
		//scroll to start
		$('#thumbnails').css('margin-left','0px');
		tOffset = 0;
    } else if (moveBackwards && i < 0) {
		i = rows.length - 1;
		//scroll to end
		tOffset = -(thumbLength-4) * (gThumbWidth + 16);
		$('#thumbnails').css('margin-left', tOffset + 'px');
	}
	
	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) {
	gSlideShowOn = true;
	if (!skipTimer)
		SetSlideShowTimer();
	var playLabel = document.getElementById("playLabel");
	if (playLabel)
		playLabel.firstChild.data = sr_pause;
}

// Kill any slide show that is currently running.

function StopSlideShow() {
	gSlideShowOn = false;
	KillSlideShowTimer();
	var playLabel = document.getElementById("playLabel");
	if (playLabel)
		playLabel.firstChild.data = sr_play;
}

function HandleThumbnailClick(id) {
	StopSlideShow();
	dsPhotos.setCurrentRow(id);
	ShowCurrentImage();
}

function leftScroll() {
	if(tOffset < 10) {
		tOffset = tOffset + 10;
		$('#thumbnails').css('margin-left',tOffset + "px");
		doscroll = setTimeout("leftScroll()", 30);
	}
}

function rightScroll() {
    var lll = (thumbLength * (gThumbWidth + 16));
	if(tOffset > ((lll) - ((lll) * 2) - 10) + 510) {
		tOffset = tOffset - 10;
		$('#thumbnails').css('margin-left',tOffset + "px");
		doscroll = setTimeout("rightScroll()", 30);
	}
}

function stopScroll() {
	if(doscroll) clearTimeout(doscroll);
}

function initThumbnailsNav() {
  tOffset = 0;
  allThumbs = $("#thumbnails div").get();
  thumbLength = allThumbs.length;
  tnSize =  (thumbLength * (gThumbWidth + 16));
  $('#thumbnails').css('margin-left',tOffset + "px");
  $('#thumbnails').css('width', tnSize + "px"); 
}
