(function($) {
   $(function() {
      var showcase = $('#showcase'),
            showCaseMenuElements = $("#showcase nav li"),
            showCaseWindow = $("#showcase-window"),
            showCaseArticles = $("#showcase-window article"),
            showCaseHeight = $("#showcase nav").height(),
            current = $(':visible', showCaseArticles).closest('article'),
            scrollIndex = 1,
            fadeSpeed = 500,
            delay = 5000;

      var interval = window.setInterval(scrollCases, delay);

      showcase.height(showCaseHeight);
      showCaseArticles.height(showCaseHeight - 50);

      function animateShowcase(elem) {
         var self = $(elem),
               index = self.index();

         current.find('.image').fadeOut(fadeSpeed, function() {
            current.siblings().each(function() {
               $(this).find('.image').hide();
            });
            showCaseArticles.show();

            var animateOffset = showCaseHeight * index,
                  indexOffset = Math.abs(index - current.index());

            showCaseWindow.animate({
               top: "-" + (animateOffset) + "px"
            }, (fadeSpeed * (indexOffset)), function() {
               current = showCaseArticles.eq(index);
               current.find('.image').fadeIn(fadeSpeed);
            });
            self.addClass("active").siblings().removeClass("active");
         });
      }

      function scrollCases() {
         if (scrollIndex >= showCaseArticles.length) {
            scrollIndex = 0;
         }
         scrollIndex++;
         var elem = showCaseMenuElements[scrollIndex - 1];
         animateShowcase(elem);
      }

      showCaseMenuElements.click(function(e) {
         window.clearInterval(interval);
         if ($(this).index() == current.index()) {
            e.preventDefault();
            return;
         }
         animateShowcase(this);
         e.preventDefault();
      });
   });
})(jQuery);
