// 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 = 133;
var gThumbHeight = 100;

// Pour effet zoom selection de l image main
var gWidth = 333;
var gHeight = 250;
var gBehaviorsArray = [];
var gSlideShowTimer = null;
var gImageLoader = null;

var size = "norm";

// Register a callback on the dsPhotos data set so we can show the first
// image in the data set whenever the data changes.

dsPhotos.addDataChangedObserver("initPhoto", { onDataChanged: function(dataSet, odcType)
{
  if (odcType != Spry.Data.DataSet.ODC_DataChanged)
    return;
  StopSlideShow();
  setTimeout(function() { ShowCurrentImage(); }, 100);
}});

// Trigger the transition animation from the current image
// being displayed to the image at imgPath.

function SetMainImage(imgPath, width, height, tnID)
{

  // Trigger signalant que l'image est de tailler moyenne.
  /*size = "norm"; */
  
  var img = document.getElementById("mainImage");
  if (!img)
    return;

  CancelBehavior("mainImage");

  Spry.Utils.SelectionManager.clearSelection("thumbnailSelection");

  if (tnID)
  {
    // Select the thumbnail on a timer just in case the main image was
    // set before the thumbnail template was generated! This can happen
    // when initially loading the page or when switching between galleries.

    setTimeout(function() {
        Spry.Utils.SelectionManager.select("thumbnailSelection", document.getElementById(tnID), "selectedThumbnail");
    }, 100);
  }

  if (gImageLoader)
  {
    gImageLoader.onload = function() {};
    gImageLoader = null;
  }
  

  gBehaviorsArray["mainImage"] = new Spry.Effects.Opacity(img, 0, { duration: 200, steps: 10,
    onComplete: function(b)
	{
	gBehaviorsArray["mainImage"] = new Spry.Effects.SizeAndPosition(img.parentNode, 0, 0, width, height, {duration: 200, steps: 10,

		onComplete: function(b)
		{
		  // 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.Effects.Opacity(img, 1, { duration: 200, steps: 10, onComplete: function(b) { 
			gBehaviorsArray["mainImage"] = null; 
			}});
		  };
		gImageLoader.src = imgPath;
		
		}
	  });
    }
  });
}

// Cancel the animation behavior of the object with the given id.

function CancelBehavior(id)
{
  if (gBehaviorsArray[id])
  {
    gBehaviorsArray[id].stop();
    gBehaviorsArray[id] = null;
  }
}

// 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 * 1.25);
  var theight = Math.floor(height * 1.25);
  var tx = (gThumbWidth - twidth) / 2;
  var ty = (gThumbHeight - theight) / 2;

  CancelBehavior(id);

  gBehaviorsArray[id] = new Spry.Effects.SizeAndPosition(img, tx, ty, twidth, theight,{duration:200,steps:10,onComplete:function(b){gBehaviorsArray[id] = null;}});
}


function GrowImage(img, width, height)
{
  Spry.Utils.addClassName(img, "inFocus");
  img.style.zIndex = 150;

  var id = img.getAttribute("id");

  var twidth = Math.floor(width * 1.25);
  var theight = Math.floor(height * 1.25);
  var tx = (gWidth - twidth) / 2;
  var ty = (gHeight - theight) / 2;

  CancelBehavior(id);

  gBehaviorsArray[id] = new Spry.Effects.SizeAndPosition(img, tx, ty, twidth, theight,{duration:200,steps:10,onComplete: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");

  CancelBehavior(id);

  gBehaviorsArray[id] = new Spry.Effects.SizeAndPosition(img, 0, 0, gThumbWidth, gThumbHeight, {duration:200,steps:10,onComplete: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("components/com_finest/pictures/" + curRow["@path"], curRow["@width"], curRow["@height"], "tn" + curRow["ds_RowID"]);
  
  Spry.Data.updateRegion('imageInfo');
  Spry.Data.updateRegion('feedback');
  

}



// 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 (size == "norm") {
    ShowCurrentImage();
  }
  else if (size == "big") {
    ShowBigCurrentImage();
  }
}

// Start the slide show that runs forwards through all
// the rows in dsPhotos.

function StartSlideShow()
{
  if (gSlideShowTimer)
    clearInterval(gSlideShowTimer);
  gSlideShowTimer = setInterval(function(){ AdvanceToNextImage(false); }, 6000);
//  var playLabel = document.getElementById("playLabel");
//  if (playLabel)
//  	playLabel.firstChild.data = "||";
  var playLabel = document.getElementById("lect");
  // Modifier URL
  if (playLabel){
  	playLabel.src = '/components/com_finest/images/pause.gif';
  }
}

// Kill any slide show that is currently running.

function StopSlideShow()
{
  if (gSlideShowTimer)
    clearInterval(gSlideShowTimer);
  gSlideShowTimer = null;
//  var playLabel = document.getElementById("playLabel");
//  if (playLabel)
//  	playLabel.firstChild.data = ">";
  var playLabel = document.getElementById("lect");
  // Modifier URL
  if (playLabel){
  	playLabel.src = '/components/com_finest/images/lecture.gif';
  }
}


// Affiche l'image de taille moyenne lors d'un clic sur un thumbnail.
function HandleThumbnailClick(id)
{
  StopSlideShow();
  dsPhotos.setCurrentRow(id);
  ShowCurrentImage();
}





function SetBigImage(imgPath, width, height, tnID)
{ 
  var img = document.getElementById("mainImage");
  if (!img)
    return;

  CancelBehavior("mainImage");
  
  Spry.Utils.SelectionManager.clearSelection("thumbnailSelection");

  if (tnID)
  {
    // Select the thumbnail on a timer just in case the main image was
    // set before the thumbnail template was generated! This can happen
    // when initially loading the page or when switching between galleries.

    setTimeout(function() {
        Spry.Utils.SelectionManager.select("thumbnailSelection", document.getElementById(tnID), "selectedThumbnail");
    }, 100);
  }

  if (gImageLoader)
  {
    gImageLoader.onload = function() {};
    gImageLoader = null;
  }

  var curRow = dsPhotos.getCurrentRow();
  var center_x = (600-curRow["@bigwidth"])/2;
  
  gBehaviorsArray["mainImage"] = new Spry.Effects.Opacity(img, 0, { duration: 200, steps: 10,
    onComplete: function(b)
	{ 
	gBehaviorsArray["mainImage"] = new Spry.Effects.SizeAndPosition(img.parentNode, center_x, 0, width, height, {duration: 400, steps: 10,
	    onComplete: function(b)
	    {
		  // 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.Effects.Opacity(img, 1, { duration: 200, steps: 10, onComplete: function(b) { gBehaviorsArray["mainImage"] = null; }});
		  };
		  gImageLoader.src = imgPath;
	    }
	  });
    }
  });
}


function ShowBigCurrentImage()
{
  var curRow = dsPhotos.getCurrentRow();
  SetBigImage("components/com_finest/pictures/"+ curRow["@bigpath"], curRow["@bigwidth"], curRow["@bigheight"], curRow["ds_RowID"]);
  Spry.Data.updateRegion('imageInfo');
  Spry.Data.updateRegion('feedback');
}

// Fonction permettant de faire des zoom avant et
// arriere en cliquant sur l'image moyenne.
function HandleClick()
{
  StopSlideShow();
  var titre = document.getElementById("titre_desc");
  var texte = document.getElementById("texte_desc");
  var slct  = document.getElementById("select_desc");
  var thumb = document.getElementById("thumbnails");
  var t_img = document.getElementById("mainImage");
  if (size != "big") {
/*	gBehaviorsArray["titre_desc"]  = new Spry.Effects.Opacity(titre, 0, { duration: 400, steps: 10});
	gBehaviorsArray["texte_desc"]  = new Spry.Effects.Opacity(texte, 0, { duration: 400, steps: 10});
	gBehaviorsArray["select_desc"] = new Spry.Effects.Opacity(slct, 0, { duration: 400, steps: 10});
	gBehaviorsArray["thumbnails"]  = new Spry.Effects.Opacity(thumb, 0, { duration: 400, steps: 10, onComplete: function(b) { */
	titre.style.display='none';
	texte.style.display='none';
	slct.style.display ='none';
	thumb.style.display='none';
	if (urlParam("lang")=='en'){
		t_img.setAttribute("title","Reduce");
	}
	else {
		t_img.setAttribute("title","R\351duire");
	}
	ShowBigCurrentImage();
/*	}}); */
	size = "big";
  } else {
  // Affichage de l'image en taille moyenne.
	if (urlParam("lang")=='en'){
		t_img.setAttribute("title","Enlarge");
	}
	else {
		t_img.setAttribute("title","Agrandir");
	}
	ShowCurrentImage();
	setTimeout("afficheTexte()",1000);
	size = "norm";
  }
}




function afficheTexte(){
	var titre = document.getElementById("titre_desc");
	var texte = document.getElementById("texte_desc");
	var slct  = document.getElementById("select_desc");
	var thumb = document.getElementById("thumbnails"); 
	titre.style.display='block';
	texte.style.display='block';
	slct.style.display ='block';
	thumb.style.display='block';
/*	gBehaviorsArray["titre_desc"]  = new Spry.Effects.Opacity(titre, 1, { duration: 200, steps: 10 });
	gBehaviorsArray["texte_desc"]  = new Spry.Effects.Opacity(texte, 1, { duration: 200, steps: 10 });
	gBehaviorsArray["select_desc"] = new Spry.Effects.Opacity(slct, 1, { duration: 200, steps: 10 });
	gBehaviorsArray["thumbnails"]  = new Spry.Effects.Opacity(thumb, 1, { duration: 200, steps: 10, onComplete: function(b) {} }); */
}


function urlParam(param){
  var nom = new Array();
  var valeur = new Array();
  params =window.location.search.slice(1,window.location.search.length);
  first = params.split("&");
  for(i=0;i<first.length;i++){
    second = first[i].split("=");
    nom[i] = second[0];
    valeur[i] = second[1];
    if (nom[i]==param) {
      return valeur[i];
    }
  }
}

