var kxGalleryIndex = -1;
var kxGalleryCollection = null;
var kxImageHtml = "";
var kxGalleryResizer = "i.php";
var kxGalleryShowTitles = true;
var kxGalleryShowDescriptions = false;

$(document).ready(function() {
  // Get the images we're interested in
  kxGalleryCollection = $('a[rel=thumbnail]');
  // Create a holder for the image
  $("<div id='kxGalleryHidden' style='display:none'><img id='kxGalleryHiddenImage'/></div>").appendTo('body');
  // Create a div for the image list
  kxImageHtml = "<table cellpadding='0' cellspacing='1px'><tbody><tr>"
  kxGalleryCollection.each(function(index) {
    kxImageHtml = kxImageHtml + "<td><img src='/" + kxGalleryResizer + "?url=" + 
      $(this).attr('href') + "&amp;height=" + parseInt($('#kxGalleryList').css('height')) + "' pos='" + index + "'/></td>";    
  });
  kxImageHtml += "</tr></tbody></table>";
  // Insert the image list html
  $('#kxGalleryList').html(kxImageHtml);
  // Hide descriptions and titles as required
  if ((kxGalleryShowDescriptions == false) && (kxGalleryShowTitles == false)) {
    $('#kxGalleryContent').remove();
  }
  else if (kxGalleryShowDescriptions == false) {
    $('#kxGalleryDescription').remove();
  }
  else if (kxGalleryShowTitles == false) {
    $('#kxGalleryHeading').remove();
  }
  
  // Show the gallery on a click
  $('a[rel=thumbnail]').click(function() {
    // show the image
    showGalleryImage(this);
    return false;
  });

  // Show the previous images
  $('.kxGalleryPrevious').click(function() {
    kxGalleryIndex--;
    if (kxGalleryIndex < 0) kxGalleryIndex = kxGalleryCollection.length - 1;
    $('a[rel=thumbnail]:nth(' + kxGalleryIndex + ')').trigger('click');
  });

  // Show the next image
  $('.kxGalleryNext').click(function() {
    kxGalleryIndex++;
    if (kxGalleryCollection.length <= kxGalleryIndex) kxGalleryIndex = 0;
    $('a[rel=thumbnail]:nth(' + kxGalleryIndex + ')').trigger('click');
  });
  
  // Close the viewer
  $('#kxGalleryCloseSrc').click(function() {
    $('#kxGalleryViewer').fadeOut();
    $('#kxGalleryNavigation').fadeOut();
  });
  
  // Recentralise the viewer when the window is resized
  $(window).resize(function() { 
    moveGallery(); 
  });
  
  // Recentralise the viewer when the window is scrolled
  $(window).scroll(function() {
    moveGallery();
  });
  
  // Recentralise the viewer when the image is loaded
  $('#kxGalleryHiddenImage').load(function() {
    resizeGallery();
  });

  // Select the new image
  $('#kxGalleryList img').click(function() {
    $('a[rel=thumbnail]:nth(' + $(this).attr('pos') + ')').trigger('click');
  });
});

// Show the gallery with the appropriate content
function showGalleryImage(me) {
    try {
      // Set the image in the viewer
      $('#kxGalleryImageSrc').attr('src', $(me).attr('href')).end().hide();
      // Set the source of the hidden image
      $('#kxGalleryHiddenImage').attr('src', $(me).attr('href'));
      // Set the title (if there is one)
      if (kxGalleryShowTitles) {
        $('#kxGalleryHeading').text($(me).attr('title'));
      }
      // Set the description (if there is one)
      if (kxGalleryShowDescriptions) {
        $('#kxGalleryDescription').text($(me).attr('desc'));
      }
      // Find out where we are
      kxGalleryCollection.each(function(index) {
        if ($(this).attr('href') == $('#kxGalleryImageSrc').attr('src'))
          kxGalleryIndex = index;
      });
    } catch(e) { }
}

function moveGallery() {
  // Calculate the left and top position of the gallery viewer when resized
  var left = (parseInt($(window).width()) 
    - parseInt($('#kxGalleryViewer').width())) / 2 
    + $(window).scrollLeft();  
  var top = (parseInt($(window).height()) 
    - parseInt($('#kxGalleryViewer').height())
    + parseInt($('#kxGalleryNavigation').height())) / 2 
    + $(window).scrollTop();
  // Ensure the close button can be seen
  if (top < $(window).scrollTop()) top = $(window).scrollTop();
  if (left + parseInt($('#kxGalleryViewer').width()) > $(window).width())
    left = $(window).width() - parseInt($('#kxGalleryViewer').width());
  // Change its position
  $('#kxGalleryViewer').css('left', left);
  $('#kxGalleryViewer').css('top', top);
  // Calculate the left and top position of the gallery navigation
  left = (parseInt($(window).width()) - parseInt($('#kxGalleryNavigation').width())) / 2;
  top = $(window).scrollTop();
  $('#kxGalleryNavigation').css('left', left).css('top', top);
}

// Resize the gallery
function resizeGallery() {
  try {
    // If we've not got the gallery showing
    if ($('#kxGalleryViewer').css('display') == 'none') {
      // Set all the sizes
      var width = $('#kxGalleryHidden').width();
      $('#kxGalleryImage').width(width);
      $('#kxGalleryImage').height($('#kxGalleryHidden').height());
      if (kxGalleryShowTitles || kxGalleryShowDescriptions) {
        $('#kxGalleryContent').width(width);
      }
      //$('#kxGalleryList').width(width);
      $('#kxGalleryImageSrc').show();
      // Centre the gallery before we show it
      moveGallery();
      // Show the gallery
      $('#kxGalleryViewer').fadeIn();
      $('#kxGalleryNavigation').fadeIn();
    }
    else {
      $('#kxGalleryImageSrc').show();
      // Calculate new left and top position of the gallery viewer when resized
      var left = (parseInt($(window).width()) 
        - parseInt($('#kxGalleryViewer').width()) 
        + parseInt($('#kxGalleryImage').width()) 
        - parseInt($('#kxGalleryHidden').width())) / 2 
        + $(window).scrollLeft();  
      var top = (parseInt($(window).height()) 
        - parseInt($('#kxGalleryViewer').height()) 
        + parseInt($('#kxGalleryImage').height())
        - parseInt($('#kxGalleryHidden').height())
        + parseInt($('#kxGalleryNavigation').height())) / 2 
        + $(window).scrollTop();
      // Ensure the close button is visible  
      if (top < $(window).scrollTop()) top = $(window).scrollTop();
      if (left + parseInt($('#kxGalleryViewer').width()) > $(window).width())
        left = $(window).width() - parseInt($('#kxGalleryViewer').width());
      // Change the div width for the content and image list
      if (kxGalleryShowTitles || kxGalleryShowDescriptions) {
        $('#kxGalleryViewer')
          .find('#kxGalleryContent').stop()
            .animate( {'width' : $('#kxGalleryHidden').width()} ).end()
          //.find('#kxGalleryList')
            //.animate({ 'width' : $('#kxGalleryHidden').width()} ).end()
          .stop().animate({ 'left' : left, 'top' : top })
          .find('#kxGalleryImage').stop()
            .animate({ 'width' : $('#kxGalleryHidden').width(),
              'height' : $('#kxGalleryHidden').height()}).end();
      }
      else {
        $('#kxGalleryViewer')
          //.find('#kxGalleryList')
            //.animate({ 'width' : $('#kxGalleryHidden').width()}).end()
          .stop().animate({ 'left' : left, 'top' : top })
          .find('#kxGalleryImage').stop()
            .animate({ 'width' : $('#kxGalleryHidden').width(),
              'height' : $('#kxGalleryHidden').height()}).end();
      }
    }
    // Calculate the new position of the image list
    var gleft = parseInt(($('#kxGalleryList').width() / 2) - 
      $('#kxGalleryList td:nth(' + kxGalleryIndex + ')').offset({border:true, padding:true}).left
      - ($('#kxGalleryList img:nth(' + kxGalleryIndex + ')').width() / 2)
      + parseInt($('#kxGalleryList table').css('margin-left'))
      + $('#kxGalleryNavigation').offset({border:true, padding:true}).left);
    // Centre the appropriate gallery image
    $('#kxGalleryList table').css('marginLeft', gleft + "px");
 } catch(e) { }
}
