$(document).ready(function() {
  
  var fadeTime = 600;
  var animateSpeed = 1000;
  var maxWidth = 630;
  var thumbsContainerSelector = '#galleryThumbs';
  var currentPage = 1
  var currentPosition = 0;
  var innerWidth;
  var totalPages;
  var categorySwitchToFirst = true; // If true: resets each category to the first thumbnail when a category is selected
  var categoriesDynamic = false; // If true: generates the categories dynamically. WILL throw an error if set to false and no categories are in the HTML.
  
  //## Do this stuff on load: ##
  
  // Add the arrows and position them.
  $(thumbsContainerSelector).append('<img src="/gallery-left.gif" alt="" id="slideLeft" /><img src="/gallery-right.gif" alt="" id="slideRight" />');
  $('#slideLeft,#slideRight').css({'position':'absolute','top':'30px','z-index':'100'});
  $('#slideLeft').css({'left':'10px'});
  $('#slideRight').css({'right':'10px'});  

  if (categoriesDynamic) {
    $('#galleryCategories').append('<ul></ul>');
    generateCategories()
  }
  function generateCategories() {
    var categoryName = '';
    $('#galleryThumbs div.slider').each(function() {
      categoryName = $(this).find('span.category').html();
      $('#galleryCategories ul').append('<li><a href="#' + categoryName + '>' + categoryName + '</a>');
    });
  }
  
  $(thumbsContainerSelector).find('.category').hide();
  
  var loc = location.href.substring(location.href.lastIndexOf('#'), location.href.length);;
  
  
  if (loc.indexOf('#') > -1) {
    loadThumbnails(loc);
    $("a[href='" + loc + "']").parent().addClass('current');
  } else {
    // Load the first deck of thumbnails:
    loadThumbnails($('#galleryCategories ul li:first a').attr('href'));
    $('#galleryCategories ul li:first').addClass('current');
    
    // Hide the categories; then show just the first deck:
    $(thumbsContainerSelector).find('.category').hide();
    $(thumbsContainerSelector).find('.slider:first')
      .show()
      .addClass('current');
  }
  
  //## End: do this stuff on load: ##
  
  // Load Switches the deck of thumnmails and displays / calculates width of container.
  function loadThumbnails(category) {
    // Reset the display of thumbnails:
    $(thumbsContainerSelector).find('.inner').css('margin-left','0');
    currentPage = 1;
    currentPosition = 0;
    $(".category").parent().parent().removeClass('current');
    $(thumbsContainerSelector).find('div.current div.item.current').removeClass('current');
    $(thumbsContainerSelector).find('div.current div.item:first').addClass('current');
    
    // Hide:
    $(thumbsContainerSelector).find('.slider').hide();
    $(thumbsContainerSelector).find('.category').hide();
    
    // This is the selected category; replace the '#' to match the string in the .category span:
    category = category.replace('#',''); 
    
    // Display selected category; mark it 'current':
    $(".category:contains('" + category + "')").parent().parent().show();
    $(".category:contains('" + category + "')").parent().parent().addClass('current');
    
    // Calculate the width of the thumbnail container and set it:
    innerWidth = $(thumbsContainerSelector).find('.slider.current .inner .item').width() * $(thumbsContainerSelector).find('.slider.current .inner .item').size(); // Calculate!
    $(thumbsContainerSelector).find('.slider.current .inner').width(innerWidth); // Set!
    
    // Calculate the number of 'pages':
    totalPages = Math.ceil(innerWidth / maxWidth);
    
    if (categorySwitchToFirst) {
      $('.slider.current .item.current').removeClass('current');
      $('.slider.current .item:first').addClass('current');
      showImage($('.slider.current .item:first a').attr('href'),$('.slider.current .item:first a').find('span.desc').html());
    }
    
    // Finally, re-draw the arrows:
    reloadArrows();
  }
  
  // When the "right" arrow is clicked:
  $('#slideRight').click(function() {
    if (currentPage <= totalPages && currentPage >= 1) {
      currentPosition = currentPosition + maxWidth;
      currentPage++;
      slidePanel(currentPosition);
    }
  });
  
  // When the "left" arrow is clicked:
  $('#slideLeft').click(function() {
    if (currentPage <= totalPages && currentPage >= 1) {
      currentPosition = currentPosition - maxWidth;
      currentPage--;
      slidePanel(currentPosition);
    }
  });
  
  // Reload / redraw arrows based on where we're at in the deck position:
  function reloadArrows() {
    if (currentPage == totalPages) {
      $('#slideRight').hide();
    } else {
      $('#slideRight').show();
    }
    if (currentPage == 1) {
      $('#slideLeft').hide();
    } else {
      $('#slideLeft').show();
    }
    if (currentPage == 1 && totalPages == 1) {
      $('#slideRight').hide();
    }
  }
  
  // Do the animation / Slide the panel:
  function slidePanel(direction) {
    $(thumbsContainerSelector).find('.slider.current .inner').animate({
      'marginLeft':'-' + direction
    }, animateSpeed, function(){/* callback here when finished animating */});
    reloadArrows();
  }
  
  // Gallery Category Tabs
  $('#galleryCategories ul li').each(function() {
    $(this).find('a').click(function() {
      $('#galleryCategories ul li.current').removeClass('current');
      $(this).parent().addClass('current');
      loadThumbnails($(this).attr('href'));
      return false;
    });
  });
  
  // Gallery Item Thumbnails
  $('#galleryThumbs div.item:first').addClass('current');
  $('#galleryThumbs div.item').each(function() {
    $(this).find('a').click(function() {
      if (!$(this).parent().hasClass('current')) {
        $('#galleryThumbs div.item.current').removeClass('current');
        $(this).parent().addClass('current');
        showImage($(this).attr('href'), $(this).find('span.desc').html());
      }
      return false;
    });
  });
  
  // Photo Swapping:
  
  //$('#galleryLargeImage').append('<img id="largeImage" />');
  
  function showImage(url,desc) {
    if (url) {
      $('#galleryLargeImage').addClass('loading');
      $('#galleryImageDescription').html('')
      $('#galleryLargeImage img').remove();
      
      var largeImage = new Image();
      $(largeImage).load(function() {
        $(this).hide();
        $('#galleryLargeImage').append(this).removeClass('loading');
        $(this).fadeIn(fadeTime);
        
        $('#galleryImageDescription').html(desc);
        
      });
      $(largeImage).attr('src', url);
    }
  }
  
  // Load the first image IF categorySiwtchToFirst is false:
  if (!categorySwitchToFirst) {
    showImage($('#galleryThumbs div.item:first a').attr('href'),$('#galleryThumbs div.item:first a').find('span.desc').html());
  }
  
});
