
////////////////////
// Slide vars
var timeout = -1;
var moveDist = 3;
var moveFrequency = 30;
var dirLeft = -1;
var dirRight = 1;
var slideMovement = 200;
var slideOuterX;
var slideOuterWidth;
//
////////////////////

// The cookie name to keep the scale checkbox value in.
var galleryScaleImage = "galleryScaleImageFlag";

var firstImage = new Image();

// Show the full image and thumbnails when the first image has loaded
firstImage.onload = function() {
  changeFullImage(document.getElementsByName("thumbnailImage")[0]);

  hideLoadingGif();

  // Make the full image and thumbnails visible once the first full image has loaded
  document.getElementById("imageHider").style.visibility = "visible";

  calcSlideMovement();
}

function noPics() {
  // If there are no pictures for this gallery then show a message

  hideLoadingGif();

  elNoPics = document.getElementById("pageNoPics");
  if (elNoPics) elNoPics.style.display = "";
}

function hideLoadingGif() {
  // Hide the 'page loading' div
  elPageLoading = document.getElementById("pageLoading");
  if (elPageLoading) elPageLoading.style.display = "none";
}


var fullImages = new Array();

var elSlideInner;
var elSlideOuter;


function pageInit() {
  var scaleImage = readCookie(galleryScaleImage);

  setScaleImage((scaleImage === "true"));

  // Work out what the max height the full image can be to keep everything on the screen
  calculateMaxImageHeight();

  // Setup sliding triggers for the thumbnails
  slideInit();

  // Setup the thumbnails so you can click them for the full image
  setupThumbnailLinks();

  // Update image dimensions when page is resized.
  window.onresize = resizeCalcs;

  // Setup scale checkbox to resize full image when changed
  document.getElementById("scaleImageText").onclick = scaleImageChanged;

  // Preload the full images
  preloadImages();
}

function resizeCalcs() {
  calculateMaxImageHeight();
  calcSlideMovement();
  slide(0);
}

function setupThumbnailLinks() {
  var els = document.getElementsByName("thumbnailImage");

  // How many thumbnails?
  var elCount = els.length;
  var elCurr = 0;

  // Loop through the thumbnails
  while (elCurr < elCount) {
    if (elCurr == 0) {
      // Show the full image for the first one
      firstImage.src = getFullImageFileName(els[elCurr]);
    }
    else {
      // Add to image preloading array
      var imageNamePrefix = document.getElementById("imagePrefix").value;
      fullImages[fullImages.length] = imageNamePrefix + els[elCurr].id + ".jpg";
    }

    els[elCurr].onclick = changeFullImageTrigger;
    els[elCurr].onmouseover = triggerSlide;
    els[elCurr].onmousemove = triggerSlide;
    els[elCurr].onmouseout = function() { clearTimeout(timeout); timeout = -1; }
    els[elCurr].style.cursor = "pointer";

    elCurr++;
  }

  if (elCurr == 0) noPics();
}

function changeFullImageTrigger(e) {
  // Make sure we have the event (for IE)
  if (!e) var e = window.event;
  // What element was changed?
  if (e.target) targ = e.target;
  else if (e.srcElement) targ = e.srcElement;
  // defeat Safari bug
  if (targ.nodeType == 3) targ = targ.parentNode;

  changeFullImage(targ);

}

function changeFullImage(newImageThumbnail) {
  // Get the full image element
  var fullImage = document.getElementById("fullImage");

  // Hide the image while we change and resize it
  if (document.getElementById("imageHider").style.visibility == "visible")
    fullImage.style.visibility = "hidden";

  // Set name of current full image
  document.getElementById("imageName").value = newImageThumbnail.id;

  // Set new image
  fullImage.src = getFullImageFileName(newImageThumbnail);
  // Adjust dimensions of new image
  adjustImageSize();

  // Show the image again
  if (document.getElementById("imageHider").style.visibility == "visible")
    fullImage.style.visibility = "visible";
}


function calculateMaxImageHeight() {
  var x,y;
  if (self.innerHeight) // all except Explorer
  {
    x = self.innerWidth;
    y = self.innerHeight;
  }
  else if (document.documentElement && document.documentElement.clientHeight)
    // Explorer 6 Strict Mode
  {
    x = document.documentElement.clientWidth;
    y = document.documentElement.clientHeight;
  }
  else if (document.body) // other Explorers
  {
    x = document.body.clientWidth;
    y = document.body.clientHeight;
  }

  var visibleX = x;
  var visibleY = y;

  // Get the full image element
  var elfullImage = document.getElementById("fullImage");
  if (!elfullImage) return;

  // The highest an image can be
  var imageMaxHeight = document.getElementById("fullImageMaxHeight").value;
  var imageMinHeight = 50;

  // Get the amount of the page's visble height that is not part of the full image
  var otherHeight = document.getElementById("otherHeight").value;
  if (otherHeight == 0) {
    calculateOtherHeight();
    var otherHeight = document.getElementById("otherHeight").value;
  }

  // The image height is whatever the page height is, minus the height of all the other stuff
  var imageHeight = visibleY - otherHeight - 10;

  // Check that the height isn't beyond the max or min heights.
  imageHeight = (imageHeight > imageMaxHeight ? imageMaxHeight : imageHeight);
  imageHeight = (imageHeight < imageMinHeight ? imageMinHeight : imageHeight);

  // Save the image height value to the input
  document.getElementById("fullImageHeight").value = imageHeight;

  // Adjust current full image
  adjustImageSize();

  displayImageScaleOption();
}


function calculateOtherHeight() {
  // The full image element
  var elfullImage = document.getElementById("fullImage");

  // Find out how high the page is
  var x,y;
  var test1 = document.body.scrollHeight;
  var test2 = document.body.offsetHeight
  if (test1 > test2) // all but Explorer Mac
  {
    x = document.body.scrollWidth;
    y = document.body.scrollHeight;
  }
  else // Explorer Mac;
      //would also work in Explorer 6 Strict, Mozilla and Safari
  {
    x = document.body.offsetWidth;
    y = document.body.offsetHeight;
  }

  var totalX = x;
  var totalY = y;

  // Height of the page loading bit
  var elPageLoading = document.getElementById("pageLoading");
  if (elPageLoading.style.pixelHeight) pageLoadingHeight = elPageLoading.style.pixelHeight;
  else pageLoadingHeight = elPageLoading.offsetHeight;

  // How much page height is not the image?
  var otherHeight = totalY - pageLoadingHeight - 4000;

  var elOtherHeight = document.getElementById("otherHeight");
  if (elOtherHeight) elOtherHeight.value = otherHeight;
}

function adjustImageSize() {
  // Get the full image element
  var elFullImage = document.getElementById("fullImage");
  if (!elFullImage) return;

  var imageName = document.getElementById("imageName").value;

  if (imageName.length > 0) {

    var imageHeight;
    if (document.getElementById("scaleImageFlag").value == 1)
      imageHeight = document.getElementById("fullImageHeight").value;
    else
      imageHeight = document.getElementById(imageName +"_height").value;

    var aspectRatio = document.getElementById(imageName +"_ratio").value;

    var newImageX = imageHeight * aspectRatio;
    var newImageY = imageHeight;

    elFullImage.width = newImageX;
    elFullImage.height = newImageY;
  }
}

function preloadImages() {
  // Start preloading
  for (var i=0; i < fullImages.length; i++) {
    var imageObj = new Image();
    imageObj.src = fullImages[i];
  }
}

function scaleImageChanged() {
  // Switch the current scale setting when the option is clicked.
  scale = (document.getElementById("scaleImageFlag").value == 0);

  if (scale) scroll(0,0);

  setScaleImage(scale);

  resizeCalcs();

  // Store scale selection in a cookie so user keeps their choice when changing gallery
  createCookie(galleryScaleImage, scale);
}

function setScaleImage(scaleImage) {
  // If scaleImage is true then we are fitting to the window, so the text should be
  // 'full size', as it's showing the alternate option, not the current setting.
  document.getElementById("scaleImageFlag").value = (scaleImage ? "1" : "0");
  document.getElementById("scaleImageText").innerHTML = (scaleImage ? "full size" : "fit to window");
}

function displayImageScaleOption() {
  var fullImageHeight = document.getElementById("fullImageHeight").value;
  var fullImageMaxHeight = document.getElementById("fullImageMaxHeight").value;
  var displayVal = "";

  if (fullImageMaxHeight == fullImageHeight) {
    displayVal = "none";
  }

  document.getElementById("scaleImageText").style.display = displayVal;
}

function getFullImageFileName(elThumbnail) {
  // Get the image name file prefix
  var imageNamePrefix = document.getElementById("imagePrefix").value;

  retVal = imageNamePrefix + elThumbnail.id + ".jpg";

  return retVal;
}


function slideInit() {
  // Get the thumbnail sliding div element
  elSlideInner = document.getElementById("innerHolderOfThumbnails");
  // Get the thumbnail holding div element
  elSlideOuter = document.getElementById("outerHolderOfThumbnails");

  calcSlideMovement();

  if (elSlideOuter) {
    // Setup start and stop events for slide left activator
    elSlideOuter.onmouseover = triggerSlide; // This is also triggered by each thumbnail
    elSlideOuter.onmousemove = triggerSlide; // This is also triggered by each thumbnail
    elSlideOuter.onmouseout = function() { clearTimeout(timeout); timeout = -1; }
  }
}

function calcSlideMovement() {
  // This function is called when the window is resized.

  // Total width of the thumbnails
  var slideInnerWidth = document.getElementById("slideWidth").value;

  // Width of the thumbnail area
  slideOuterWidth = (elSlideOuter.style.width ? elSlideOuter.style.width : elSlideOuter.offsetWidth);

  // Pos of the thumbnail area
  slideOuterX = findPosX(elSlideOuter);

  // Calculate how far the thumbnails can slide given how wide they are and how big the holder is
  slideMovement = (slideInnerWidth > slideOuterWidth ? slideInnerWidth - slideOuterWidth : 0);

}

function triggerSlide(e) {
  // Make sure we have the event (for IE)
  if (!e) var e = window.event;

  if (timeout == -1 && slideMovement > 0) {
    if ((parseInt(e.clientX) - slideOuterX) < ((slideOuterWidth/5) * 2))
      timeout = self.setTimeout("slide(dirRight)", moveFrequency);
    else if ((parseInt(e.clientX) - slideOuterX) > ((slideOuterWidth/5) * 3))
      timeout = self.setTimeout("slide(dirLeft)", moveFrequency);
  }
}

function slide(dir) {
  // Calculate the adjustment factor
  var slideVal = (moveDist * dir);

  // Get it's left value and subtract the adjustment value (default to 5px)
  var currLeft = (elSlideInner.style.left ? parseInt(elSlideInner.style.left) : 5);
  var newLeft = currLeft + slideVal;

  // Check new left is within the sliding boundaries
  if (newLeft > 5) {
    newLeft = 5;
  }
  else if (newLeft < ((slideMovement * -1) - 5)) {
    newLeft = (slideMovement * -1) - 5;
  }

  // If the value has changed then move
  if (currLeft != newLeft) {
    // Set the new left value
    elSlideInner.style.left = newLeft + "px";

    // Set timer to call this function again.
    // timeout holds id of the timer so it can be stopped.
    timeout = self.setTimeout("slide("+ dir +")", moveFrequency);
  }
}

// Thanks Quirksmode.org...
function findPosX(obj) {
  var curleft = 0;
  if (obj.offsetParent)
  {
    while (obj.offsetParent)
    {
      curleft += obj.offsetLeft
      obj = obj.offsetParent;
    }
  }
  else if (obj.x)
    curleft += obj.x;
  return curleft;
}

