$(document).ready(function() {

  // Gallery thumbnail click.

  $('p#gallery-main-image img').bind('load', function() {
    if ($(this).is(':hidden')) {
      $(this).fadeIn('fast');
    }
  });

  $('div#gallery-scroller div.thumbnails ul li a').click(function() {

    var largeImageSrc = $(this).attr('href');
    var largeImageAlt = $(this).attr('title');

    $('p#gallery-main-image img').fadeOut('fast', function() {
      $('p#gallery-main-image img')
        .attr('src', largeImageSrc)
        .attr('title', largeImageAlt)
        .attr('alt', largeImageAlt);

      $('#gallery-main-image-title h2').text(largeImageAlt);
    });

    return false;

  });

  // Gallery scroller.

  if ($('div#gallery-scroller div.thumbnails ul').width() > 524) {
    $('div#gallery-scroller div.thumbnails ul').jcarousel({
      scroll: 1,
      auto: 1.5,
      initCallback: initGalleryThumbnailSelector,
      buttonNextHTML: null,
      buttonPrevHTML: null,
      wrap: 'circular',
      animation: 1000
    });
  }

});

// Gallery callback.

function initGalleryThumbnailSelector(carousel) {

  // Handle left/right buttons (disable auto-scroll and move forward/back)

  $('div#gallery-scroller p.move-left img').bind('click', function() {
    carousel.startAuto(0);
    carousel.prev();
    return false;
  });

  $('div#gallery-scroller p.move-right img').bind('click', function() {
    carousel.startAuto(0);
    carousel.next();
    return false;
  });

  // Handle hovering over the items (pause auto-scroll).

  carousel.clip.hover(function() {
    carousel.stopAuto()
  }, function() {
    carousel.startAuto();
  });

}
