/* ---------------------------------------------------------------- 
 @name:     hScroller
 @version:  0.1 
 @release:  2009-09-09
 @type:     jQuery plugin
 @author:   Jan Panschab
---------------------------------------------------------------- */

jQuery(function($) {
  
  $.fn.hScroller = function(options) {
    var opts = $.extend({}, $.fn.hScroller.defaults, options);
    return this.each(function() {
      $this = $(this);
      $this.addClass(opts.pluginClass);
      var oneItem = $this.find('li:first');
      var itemCount = $this.find('li').size();
      var itemMargin = parseInt(oneItem.css('margin-left')) + parseInt(oneItem.css('margin-right'));
      var itemWidth = oneItem.width();
      var scrollerWidth = itemCount * (itemWidth + itemMargin);
      var boxWidth = $this.width();
      var scroller = $this.children('ul');
      
      scroller.width(scrollerWidth);
      
      // centering selected item
      var selected = $('li.selected:first', $this);
      var itemIndex = $this.find('li').index(selected);
      var left = (itemIndex * (itemWidth + itemMargin)) - (boxWidth / 2) + ((itemWidth + itemMargin) / 2);
      var maxLeft = ((itemCount - 1) * (itemWidth + itemMargin)) - (boxWidth - (itemWidth + itemMargin));
      if (left > maxLeft) { left = maxLeft; }
      if (left < 0) { left = 0; }
      scroller.css({'left': -left});
      
      // mousemove action
      $this.mousemove(function(e){
        var left = (e.pageX - $this.offset().left) * (scrollerWidth - boxWidth) / boxWidth;
        scroller.css({'left': -left});
      });
      
      // workaround of visual bug when click on link
      $this.mousedown(function(e) {
        var $el = $(e.target);
        if ($el.is('a')) {
          window.location = $el.attr('href');
        }
        return false;
      });

      //console.log('scrollerWidth - ' + scrollerWidth);
    });
  };
  
  // hScroller defaults
  $.fn.hScroller.defaults = {
    pluginClass: 'hScroller'
  };
  
});
