 (($, window) ->
   # Define the plugin class
   class InfinitePages
-    
+
     # Default settings
     defaults:
       debug: false  # set to true to log messages to the console

          @_log "#{distance - @options.buffer}px remaining..."
        else
          @next() # load the next page
        
    # Load the next page
    next: ->
      if @options.state.done
        @_log "Loaded all pages"
      else
        @_loading()
        
        $.getScript(@$container.find(@options.navSelector).attr('href'))
          .done(=> @_success())
          .fail(=> @_error())
    
    _loading: ->
      @options.state.loading = true
      @_log "Loading next page..."
      if typeof @options.loading is 'function'
        @$container.find(@options.navSelector).each(@options.loading)
    
    _success: ->
      @options.state.loading = false
      @_log "New page loaded!"
      if typeof @options.success is 'function'
        @$container.find(@options.navSelector).each(@options.success)
    
    _error: ->
      @options.state.loading = false
      @_log "Error loading new page :("
      if typeof @options.error is 'function'
        @$container.find(@options.navSelector).each(@options.error)
    
    # Pause firing of events on scroll
    pause: ->
      @options.state.paused = true
      @_log "Scroll checks paused"
    
    # Resume firing of events on scroll
    resume: ->
      @options.state.paused = false
      @_log "Scroll checks resumed"
      @check()
    
  # Define the plugin
  $.fn.extend infinitePages: (option, args...) ->
    @each ->
      $this = $(this)
      data = $this.data('infinitepages')
      
      if !data
        $this.data 'infinitepages', (data = new InfinitePages(this, option))
      if typeof option == 'string'
        data[option].apply(data, args)
  
) window.jQuery, window

      else
        windowBottom = @$context.scrollTop() + @$context.height()
        distance = nav.offset().top - windowBottom

        if @options.state.paused
          @_log "Paused"
        else if @options.state.loading
