var scroller = (function ()
{
  var semafor = false;
  var time = 300;

  function releaseSemafor()
  {
    semafor = false;
  }

  return {
    init: function ()
    {
      $('.next').click(function ()
      {
        scroller.scroll('next');
      });
      $('.prev').hide().click(function ()
      {
        scroller.scroll('prev');
      });
    },

    scroll: function (dir)
    {
      var margin = parseInt($('#subpages').css('marginLeft'), 10);
      var width  = parseInt($('#subpages').children('li.subpage:first').width(), 10);
          width += parseInt($('#subpages').children('li.subpage:first').css('marginRight'), 10);
      var newMargin = margin + ((dir == 'next') ? (-width) : width);

      if (semafor) {
        return;
      }

      semafor = true;

      if ((dir == 'next') && (Math.abs(newMargin / width) == $('#subpages li.subpage').length - 1)) {
        $('.next').hide();
        $('.prev').show();
      } else if ((dir == 'prev') && newMargin === 0) {
        $('.prev').hide();
        $('.next').show();
      } else {
        $('.prev, .next').show();
      }

      $('#subpages').animate({
        'marginLeft': newMargin + 'px'
      });

      setTimeout(releaseSemafor, time + 50);
    }
  };
})();


