$(document).ready(function() {
  var cont              = $("#thumbs");                 // the element that contains the thumbnail track
  var large             = $("#photo-large");            // the element that contains the image tag for the enlarged version of a photo
  var styleThumbSelect  = {border: "0px solid #666"};   // the style applied to the thumbnail of the current image being viewed
  var styleThumbDefault = {border: "none"};             // the default style applied to thumbnails that are currently not being viewed
  var next              = $("#thumbScrollNext");        // the scroll next button used to navigate through the thumbnails
  var prev              = $("#thumbScrollPrev");        // the scroll prev button used to navigate through the thumbnails
  var pNext             = $("#photo-next");             // the next photo button
  var pPrev             = $("#photo-prev");             // the previous photo button
  var track             = $("#thumb-track");            // the element that represents the thumb track and enables the track to be moved
  var scrollIndex       = 0;
  var imageIndex        = 0;
  var maxWidth          = 500;
  var maxHeight         = 400;
  var images = new Array();
  
  $("#photo-large").css("opacity", 0);  
  
  // get images from image server
  $.getJSON('imageServer_waterfeatures.php', function(data) {
    var ob = '';
    $.each(data, function(i) {
      var newRow = (((i + 1) % 10) == 0) && i < data.length - 1 && i != 0;
      if(i == 0) {
        ob += "<tr>";  
      }
      var style = 'style="width: 70px;"';
      if(this.width < this.height) {
        style = 'style="height: 70px;"';  
      }
      ob += "<td class='thumb'><img " + style + " src='" + this.loc + "' /></td>";
      if(newRow) {
        ob += "</tr><tr>";
      }
      if(i == data.length - 1) {
        ob += "</tr>";
      }
      images.push(this); 
    });
    $(ob).appendTo($("#thumbs table"));
    $("#thumb-track .thumb").css("opacity", 0);
    execGallery(images);
  });
  
  function changeImage(index, ref) {
    var ci = images[index];
    imageIndex = index;
    ref = (ref == 'undefined') ? false : ref;
    if(ref) {
      $("#thumb-track .thumb").children("img").css(styleThumbDefault);
      $(ref).children("img").css(styleThumbSelect);
    }
    large.fadeTo(0, 0, function() {
      large.children("img").css({top: 0});
      large.children("img").attr("src", ci.loc).attr("alt", ci.loc);
      if((ci.width > maxWidth) || (ci.height > maxHeight)) {
        if(ci.width > ci.height) {  
          large.children("img").css({width: maxWidth, height: "auto"});
        }
        else if(ci.height > ci.width) {
          large.children("img").css({width: "auto", height: maxHeight});
        } else {
          large.children("img").css({width: maxWidth, height: "auto"});
        }
      } else {
        large.children("img").css({width: ci.width, height: ci.height});
      }
      centerImage();
      $(this).show(0);
    });
  }
  
  function centerImage() {
    var i = large.children("img");
    var h = i.height();
    var o = (large.height() - h) / 2;
    i.css({position: "relative", top: o + "px"});
  }

  function execGallery() {
    var thumbs            = $("#thumbs table tr .thumb");     // the elements representing each thumbnail inside the thumbnail track
    var trackX            = track.css("left");            // the initial track offset
    var offset            = thumbs.width();               // the offset required to move the track by one image
    var offsetMin         = 0;                            // the minimum offset allowed
    var offsetMax         = (thumbs.length - 5);          // the maximum offset allowed
    
    
    // when large version of default image has loaded fade the photo canvas in
    thumbs.children("img").load(function() {
      $(this).parent(".thumb").css("opacity", 1); 
    });
    // when each thumbnail image has loaded fade thumbnail in
    large.children("img").load(function() {
      $(this).parent("#photo-large").fadeTo(0, 1);
      centerImage();
    });
    
    // initial setup: setting the first enlarged image, applying css style to default thumbnail etc
    changeImage(imageIndex);
    $(thumbs[imageIndex]).children("img").css(styleThumbSelect);
    prev.css("opacity", 0);
    
    // if there less then seven images navigation buttons are not required
    if(thumbs.length < 7) {
      next.css("opacity", 0);
    }
    
    // change photo to next photo
    pNext.click(function() {
      if(imageIndex == thumbs.length - 1) {
        imageIndex = 0;
        changeImage(imageIndex);
      } else {
        changeImage(++imageIndex);
      }
    });
    
    // change photo to previous photo
    pPrev.click(function() {
      if(imageIndex == 0) {
        imageIndex = thumbs.length - 1;
        changeImage(imageIndex);
      } else {
        changeImage(--imageIndex);
      }
    });
    
    // scroll next by one thumbnail
    next.click(function() {
      if($(this).css("opacity") == 1) {
        prev.css("opacity", 1);
        var currOffset = track.css("left"); var newOffset; 
        currOffset = parseInt(currOffset.substring(0, currOffset.lastIndexOf("px")));
        newOffset = currOffset - offset;
        track.animate({left: newOffset + "px"}, 500);
        scrollIndex++;
        if(scrollIndex == offsetMax) {
          $(this).css("opacity", 0);
        }
        return false;
      }
    });
    // scroll previous by one thumbnail
    prev.click(function() {
      if($(this).css("opacity") == 1) {
        next.css("opacity", 1);
        var currOffset = track.css("left"); var newOffset; 
        currOffset = parseInt(currOffset.substring(0, currOffset.lastIndexOf("px")));
        newOffset = currOffset + offset;
        track.animate({left: newOffset + "px"}, 500);
        scrollIndex--;
        if(scrollIndex == offsetMin) {
          $(this).css("opacity", 0);
        }
        return false;
      }
    });
    // clicking behaviour for each thumbnail
    thumbs.click(function() {
      var index = thumbs.index(this);
      changeImage(index, this);  
    });
    
    // thumbs hover cursor override
    thumbs.mouseover(function() {
      $(this).css("cursor", "pointer");
    });
    // navigational hover cursor override
    prev.mouseover(function() {
      if($(this).css("opacity") == 1) {
        $(this).css("cursor", "pointer");
      }
    });
    next.mouseover(function() {
      if($(this).css("opacity") == 1) {
        $(this).css("cursor", "pointer");
      }
    });
  }
});
