// Scroller - Must target the UL or OL!!
// TODO: needs documentation
// TODO: Compare to previous version. Can probably create a hook on the calculate method to meet different kinds of scrolling business rules.
var nZ = [];
(function($){

  $.widget('ui.scroller', {    
    options:{
      slideSelector: '> li',       
      channel: '/feed/push',
      itemsShown: 12      
    },
    
    _init:function(){            
      var widget = this, parent = this.element.parent(), wrap, element;
     
      var next = $('<a class="action action-next">&laquo;</a>'), 
          prev = $('<a class="action action-prev">&raquo;</a>');
                    
      element = this.element.detach();
        parent.append(next)
              .append(prev)
              .append(element);
            
      element.wrap('<div class="ui-clip"></div>');
            
      next.bind('click', {widget:this, direction:'next'}, this._handleScroll);
      prev.bind('click', {widget:this, direction:'prev'}, this._handleScroll);
                        
      widget.viewSize = $('.ui-clip', parent).innerWidth();

      this.calculate();      
      
      this.options.ready && 
        this.options.ready.call(this);        
    },
    
    calculate:function(){
      var widget = this;
      this._items = $(widget.options.slideSelector, this.element);
      this._sectionIndex = this._sectionIndex || 0;
      this._locationCache = [0];
      
      var max = widget.viewSize, total = 0;
      this._items.each(function(){
        var size = $(this).outerWidth();
        total+=size;

        if (total>max){
          widget._locationCache.push($(this).position().left*-1);
          total = size;
        }
      });
      
      this._sectionCount = widget._locationCache.length;   
    },
    
    /* Events
    /******************************/        
    
    _handleScroll:function(e){
      var widget = e.data.widget; widget.element.clearQueue();           
      e.data.direction==='prev' ? 
        ((widget._sectionIndex+1)!==widget._sectionCount && widget._sectionIndex++) :            
        ((widget._sectionIndex!==0) && widget._sectionIndex--);        
      widget.element.animate({left:widget._locationCache[widget._sectionIndex]},1000);
    }
        
  });
  
})(jQuery);
