﻿(function($){
  var settings;

  $.fn.calendarList = function(options) {
    var defaults = {
          displayLimit: 4,
          fadeDelay: 1, // Time in seconds for an event to fade
          wait: 4        // Time in seconds between event scrolls
        };
        
    settings = $.extend({}, defaults, options);
    
    // Turn seconds into milliseconds
    settings.wait *= 1000;
    settings.fadeDelay *= 1000;

    this.each(function() {
      var $list = $(this),
        items = [],
        currentItem = settings.displayLimit,
        total = 0,
        intervalID = 0;

      // Cache all the list items into an array
      $list.find('> li').each(function () {
        items.push('<li>' + $(this).html() + '</li>');
      });
      total = items.length;

      // Chomp the list down to limit li elements
      $list.find('> li').filter(':gt(' + (settings.displayLimit - 1) + ')').remove();

      // Add some extra padding along the bottom for the CSS drop shadow effect.
      $list.wrap('<div class="listWrapper" />').parent().css('height', $list.height() + 5);

      // If there aren't enough items to overflow the display limit, leave - no scrolling required.
      if (total <= settings.displayLimit) return false;

      // Setup the hover effect on the list items
      $list.find('> li').each(function () {
        $(this).hover(function() {
          clearInterval(intervalID);
        }, function() {
          intervalID = setTimeout(displayNextItem, settings.fadeDelay);
        });
      });

      function displayNextItem() {
        // No need to animate the list if it isn't visible (hidden on another tab).
        if (!$list.is(':visible')) {
          // Keep the timer going though in case it does become visible.
          intervalID = setTimeout(displayNextItem, settings.wait);
          return false;
        }
        
        // Insert a new item with opacity set to zero and the hover effect
        var $insert = $(items[currentItem])
          .css('opacity', 0)
          .hover(function() {
            clearInterval(intervalID);
          }, function() {
            intervalID = setTimeout(displayNextItem, settings.fadeDelay);
          })
          .appendTo($list);
                        
        var $li = $list.find('> li:first');
        $li.animate({
          'opacity': 0,
          'margin-top': -($li.outerHeight(true))
        }, settings.fadeDelay, function() {
          $(this).remove();
        });
        $insert.animate({'opacity': 1}, settings.fadeDelay);
            
        currentItem++;
        if (currentItem >= total) currentItem = 0;
            
        intervalID = setTimeout(displayNextItem, settings.wait);
      }
        
      intervalID = setTimeout(displayNextItem, settings.wait);

    });

    // returns the jQuery object to allow for chainability.
    return this;
  }
  
})(jQuery);

