// Generated by CoffeeScript 1.3.3

define(['jquery', 'underscore'], function($, _) {
  /*
      jQuery plugin for triggering a scroll event once a certain threshold is
      reached. A use case of this is the "infinite" scrolling element in which
      data is being populated in the element on-demand.
  
      Options:
        `threshold` - Percent scrolled from the top of the element which triggers
          the event. Once this thresholder has been reached the `reset` method
          must be called to reset this state.
  
      Methods are invoked by passing the method name as a string in the
      constructor method, e.g. `$(...).panel('open')`.
  
      Methods:
        `reset` - Resets the pre-calculated aboslute dimensions and thresholds.
          Use this when the element size changes.
  */

  var Scroller, defaultOptions;
  defaultOptions = {
    threshold: 0.75
  };
  Scroller = function(element, options) {
    var _this = this;
    this.element = $(element);
    this.options = options;
    if (options.relative) {
      this.height = this.element.find(options.relative).innerHeight() - this.element.innerHeight();
    } else {
      this.height = this.element.innerHeight();
    }
    this.threshold = this.height * options.threshold;
    this.element.on('scroll', _.debounce(function() {
      if (!_this.reached && _this.element.scrollTop() >= _this.threshold) {
        _this.reached = true;
        return _this.element.trigger('scroller');
      }
    }, 50));
    if (options.trigger) {
      this.element.on('scroller', options.trigger);
    }
    return this;
  };
  Scroller.prototype = {
    constructor: Scroller,
    reset: function() {
      this.reached = false;
      if (this.options.relative) {
        this.height = this.element.find(this.options.relative).innerHeight() - this.element.innerHeight();
      } else {
        this.height = this.element.innerHeight();
      }
      this.threshold = this.height * this.options.threshold;
      return this;
    }
  };
  $.fn.scroller = function(option) {
    var options;
    if ($.isPlainObject(option)) {
      options = $.extend({}, option, defaultOptions);
    } else {
      options = $.extend({}, defaultOptions);
    }
    return this.each(function() {
      var $this, data;
      $this = $(this);
      data = $this.data('scroller');
      if (!data) {
        $this.data('scroller', (data = new Scroller(this, options)));
      }
      if (typeof option === 'string') {
        return data[option]();
      }
    });
  };
  return $.fn.scroller.Constructor = Scroller;
});
