/* Author: Andrew Le
   URL: http://andrewdle.com
*/

(function ($) {

  if (!$('body').hasClass('press')) { return; }

  var Scroller = {
    init: function () {
      this.el = $('#main nav ul');
      this.bindEvents();
      this.scrollToCurrentPage();
    },

    bindEvents: function () {
      var that = this,
          nav  = $('#main nav');

      nav.find('a.prev').click(function (event) {
        that.prev(event);
      });

      nav.find('a.next').click(function (event) {
        that.next(event);
      });
    },

    scrollToCurrentPage: function () {
      if (!$('body').hasClass('press-post')) { return; }
      this.scrollTo(this.currentPostId());
    },

    prev: function (event) {
      event.preventDefault();
      if (this.atStart()) { return; }
      this.scroll('left');
    },

    next: function (event) {
      event.preventDefault();
      if (this.atEnd()) { return; }
      this.scroll('right');
    },

    scroll: function (direction) {
      this.el.animate({
        'left': this.nextPosition(direction)
      }, 750);
    },

    scrollTo: function (elem_id) {
      this.el.animate({
        'left': this.pagePosition(elem_id)
      }, 750);
    },

    nextPosition: function (direction) {
      var curPosition = this.currentPosition(),
          stepSize    = this.stepSize(),
          dirFactor   = (direction == 'left') ? 1 : -1,
          step        = stepSize * dirFactor * 3,
          newPosition = curPosition + step;
      return newPosition;
    },

    pagePosition: function (elem_id) {
      var elemIndex   = this.indexOfElem(elem_id),
          stepSize    = this.stepSize(),
          dirFactor   = -1,
          step        = stepSize * dirFactor * 3;
      if (elemIndex < 3) { return 0; }
      return Math.floor(elemIndex / 3) * step;
    },

    currentPostId: function () {
      return $('body').attr('class').replace(/.*(press-post-\d+)\s.*/, '$1');
    },

    currentPosition: function () {
      return parseInt(this.el.css('left').replace('px', ''), 10);
    },

    stepSize: function () {
      return this.el.find('li:first').outerWidth(true);
    },

    atStart: function () {
      return this.currentPosition() === 0;
    },

    atEnd: function () {
      var numPosts = this.el.find('li').length,
          stepSize = this.stepSize(),
          maxPosition = (-1) * (numPosts * stepSize);
      return this.nextPosition() < maxPosition;
    },

    indexOfElem: function (elem_id) {
      var index = -1;
      $.each(this.el.find('li'), function (i, e) {
        if ($(e).attr('id') == elem_id) {
          index = i;
          return false;
        }
      });
      return index;
    }
  };

  $(function () {
    Scroller.init();
  });

})(jQuery);

