﻿jQuery.fn.slideshow = function (speed) {

  var ul = $(this[0]);

  //append a LI item to the UL list for displaying caption
  ul.append('<li class="caption"><div class="slideshow-caption-container"><p></p></div></li>');

  ul.find('li').css({ opacity: 0.0 });

  //Get the first image and display it (set it to full opacity)
  ul.find('li:first').css({ opacity: 1.0 });
  ul.find('li:first').addClass('show');
  ul.slideDown(500);

  //Get the caption of the first image from REL attribute and display it
  var desc = $.trim(ul.find('li:first').find('div').attr('innerHTML'));

  //Display the caption if not blank
  if (desc != "") {
    ul.find('li.caption p').html(desc);
    ul.find('li.caption').slideUp(0);
    ul.find('li.caption').css({ opacity: 0.7, bottom: 0 });
    ul.find('li.caption').slideDown(500);
  }

  //Call the gallery function to run the slideshow   
  var timer = setInterval(function () { ul.gallery(); }, speed);

  //pause the slideshow on mouse over
  ul.hover(
        function () {
          clearInterval(timer);
        },
        function () {
          timer = setInterval(function () { ul.gallery(); }, speed);
        }
  )

}

jQuery.fn.gallery = function () {

  var ul = $(this[0]);

  //if no IMGs have the show class, grab the first image
  var current = (ul.find('li.show') ? ul.find('li.show') : ul.find('li:first'));

  //Get next image, if it reached the end of the slideshow, rotate it back to the first image
  var next = ((current.next().length) ? ((current.next().attr('class') == 'caption') ? ul.find('li:first') : current.next()) : ul.find('li:first'));

  //Get next image caption
  var title = next.find('img').attr('title');
  var desc = $.trim(next.find('div').attr('innerHTML'));

  //Set the fade in effect for the next image, show class has higher z-index
  next.css({ opacity: 0.0 }).addClass('show').animate({ opacity: 1.0 }, 1000);

  //Hide the caption first, and then set and display the caption
  ul.find('li.caption').slideUp(300, function () {
    ul.find('li.caption p').html(desc);
    if (desc != "") {
      ul.find('li.caption').css({ opacity: 0.7, bottom: 0 });
      ul.find('li.caption').slideDown(500);
    }
  });

  //Hide the current image
  current.animate({ opacity: 0.0 }, 1000).removeClass('show');
}

