(function($){
  $.fn.sitevalleySlider = function(options, callback){
    var $this = this;
    $.extend(options, {
      prevent_click: false,
      left: this.offset().left,
      top: this.offset().top,
      min: options.ticks[0],
      max: options.ticks[options.ticks.length - 1]
    });
    $.extend(this, options);
    this.css('cursor', 'pointer').mousedown(function(e){
      e.preventDefault();
      return false;
    }).bind('tickchange', callback).click(function(e){
      if($this.prevent_click) {
        $this.prevent_click = false;
      } else {
        var pos = e.clientX - $this.left;
        var tick_index = 0;
        var slider = $this.slider;
        while($this.tickranges[tick_index] < pos) tick_index++;
        slider.tick_index = tick_index-1;
        slider.position = $this.ticks[slider.tick_index];
        slider.animate({marginLeft: slider.position + 'px'}, 300, function(){
          $this.trigger('tickchange', [slider.tick_index]);
        });
      }
    });
    $(document).mousemove(function(e){
      if($this.slider.moving) {
        var pos = e.clientX - $this.left - 5;
        var slider = $this.slider;
        slider.position = pos < $this.min ? $this.min : pos > $this.max ? $this.max : pos;
        if(slider.position >= $this.tickranges[slider.tick_index + 1]) {
          slider.tick_index += 1;
          $this.trigger('tickchange', [slider.tick_index]);
        } else if( slider.position < $this.tickranges[slider.tick_index]) {
          slider.tick_index -= 1;
          $this.trigger('tickchange', [slider.tick_index]);
        }
        slider.css('margin-left', slider.position + 'px');
      }
    }).mouseup(function(e){
      if($this.slider.moving) {
        $this.slider.getBack();
        $this.slider.moving = false;
      };
    });
    var slider_options = {
      moving: false,
      position: 0,
      tick_index: 0,
      getBack: function(){
        var self = this;
        this.animate({marginLeft: $this.ticks[this.tick_index] + 'px'}, 300, function(){
          self.position = $this.ticks[self.tick_index];
        });
      }
    }
    $.extend(this.slider, slider_options);
    this.slider.mousedown(function(e){
      $this.prevent_click = true;
      $this.slider.moving = true;
      e.preventDefault();
    }).mouseup(function(e){
      $this.slider.moving = false;
      $this.slider.getBack();
    });
    return this;
  }
})(jQuery);