;(function($) {

$( document ).ready( function() {

  // Slideshow on home page

  var slideshow = $('.slideshow');
  if (slideshow.length) slideshow.cycle( { fx: 'fade', timeout: 5000 } );

  // Carousel control on image gallery page
  // TODO quick hack, refactor into separate jquery plugin

  var carousel_pagesize = 4;
  var carousel_index = 0;
  var carousel_items = $('.carousel-lister .carousel-item');
  var carousel_count = carousel_items.length;
  var carousel_animating = false;

  $('.carousel-pagination > a').click( function() {

    if (carousel_animating)
      return false;

    // Determine direction of scroll
 
    var dir = 0;

    if ($(this).hasClass( 'carousel-next' ))
      dir = +1;
    else if ($(this).hasClass( 'carousel-prev' ))
      dir = -1;

    // Don't scroll if there are no more items in that directoin
 
    var new_index = carousel_index + dir * carousel_pagesize;

    if (new_index < 0 || new_index >= carousel_count)
      return false;

    // Okay to scroll. Compute offset of new leftmost item
    // after the scroll, and slide animate to it.

    carousel_index = new_index;
    carousel_animating = true;

    var left = -$(carousel_items[carousel_index]).position().left;

    $('.carousel-lister').animate(
      { left: left + 'px' },
      800,           // duration
      'swing',       // easing function
      function() {   // completion callback
        $( 'a', carousel_items[carousel_index] ).click();
        carousel_animating = false;
      }
    );

    // Update pagination controls

    if (carousel_index > 0)
      $('.carousel-prev').addClass('active');
    else
      $('.carousel-prev').removeClass('active');

    if (carousel_index < carousel_count - 1)
      $('.carousel-next').addClass('active');
    else
      $('.carousel-next').removeClass('active');

    return false;

  } );

  $('.carousel-item a').click( function() { 
    carousel_items.removeClass('active');
    $(this).parents('.carousel-item').addClass('active');
    $('.gallery-preview img').attr('src', $(this).attr('href'));
    $('.gallery-preview .caption').html($(this).attr('title'));
    return false;
  } );

  $('.carousel-next').addClass('active'); // FIXME only if enough items
  $('.carousel-item a:first').click();

} );

})(jQuery);

