﻿(function($){$(function(){
  var base = this;
  
  var defaults = { slideMethod: 'margin', itemSelector: 'li' };
  
  $.slider = function(container, left, right, mask, options) {

    var options, items, page_width, all_items_width;

    options = $.extend( {}, defaults, options );

    var calculate_widths = function() {
      items = container.find(options.itemSelector);
      var visible_items = items.filter(':visible');
      var mask_width = mask.width();
      var an_item_width = visible_items.slice(0,1).outerWidth(true);
      var items_per = Math.floor( mask_width / an_item_width );
      page_width = items_per * an_item_width;
        
      // round to whole page number
      all_items_width = Math.ceil(visible_items.length / items_per) * items_per * an_item_width;
    }
    
    var getPosition = function(position) {
      if( options.slideMethod == 'margin' ) {
        return parseFloat(container.css('marginLeft'));
      } else if( options.slideMethod == 'scroll' ) {
        return -container.scrollParent()[0].scrollLeft;
      }
    }
    var animateTo = function(position) {
      if( options.slideMethod == 'margin' ) {
        container.animate({'marginLeft': position});
      } else if( options.slideMethod == 'scroll' ) {
        $(container.scrollParent()[0]).animate({scrollLeft: -position});
      }
    }
    
    var _update_arrows = function(position) {
      if( position >= 0 ) {
        left.addClass("inactive");
      } else {
        left.removeClass("inactive");
      }
      if( position <= -all_items_width + page_width ) {
        right.addClass("inactive");
      } else {
        right.removeClass("inactive");
      }
    }
    var update = function() {
      calculate_widths();
      var position = getPosition();
      var new_position = Math.min( 0, Math.max( -all_items_width + page_width, position));
      animateTo(new_position);
      _update_arrows(new_position);
    }
    // make this function public
    this.update = update;
      
    right.click(function(e){
      calculate_widths();
      var position = getPosition();
      var new_position = Math.max( -all_items_width + page_width, position-page_width );
      animateTo(new_position);
      _update_arrows(new_position);
      return false;
    });
    left.click(function(e){
      calculate_widths();
      var position = getPosition();
      var new_position = Math.min( 0, position+page_width);
      animateTo(new_position);
      _update_arrows(new_position);
      return false;
    });

    update();
    
    return this;
  }
  
})})(jQuery);

