/*!
 * @copyright 2010-Present Advanced Care Solutions
 * @author Christopher Rahauiser <crahauiser@acs-web.com>
 */
(function($) {
  $.fn.newsEvents = function(options) {
    var opts = $.extend({}, $.fn.newsEvents.defaults, options);

    return this.each(function() {
      var bottomZIndex = opts.topZIndex - 1,
          current = 0,
          next,
          sideEvents = $('.side-event', this),
          sideEventsLen = sideEvents.length,
          currentDisplay = $('span.current', this);
      if (sideEventsLen < 2) {
        return;
      }

      function fade(fadeInPos, fadeOutPos) {
        sideEvents
          .eq(fadeInPos)
            .fadeIn(opts.fadeDuration, function() {
              $(this).css('z-index', opts.topZIndex);
            })
          .end()
          .eq(fadeOutPos)
            .fadeOut(opts.fadeDuration, function() {
              $(this).css('z-index', bottomZIndex);
            });
      }

      $('.side-event-prev', this).click(function(event) {
        event.preventDefault();
        next = current - 1;
        if (next < 0) {
          next = sideEventsLen - 1;
        }
        fade(next, current);
        currentDisplay.text(next + 1);
        current = next;
      });

      $('.side-event-next', this).click(function(event) {
        event.preventDefault();
        next = current + 1;
        if (next == sideEventsLen) {
          next = 0;
        }
        fade(next, current);
        currentDisplay.text(next + 1);
        current = next;
      });
      $('.side-event-controls', this).show();
    });
  };
  $.fn.newsEvents.defaults = {
    fadeDuration: 500,
    topZIndex: 2
  };
})(jQuery);
