// from http://codesnippets.joyent.com/posts/show/835
Position.GetWindowSize = function(w) {
    var width, height;
        w = w ? w : window;
        this.width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
        this.height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);

        return this;
}

var EndlessScroll = Class.create({

  loadRemainingItems : function(){
    // compute amount of page below the current scroll position
    var remaining = ($('container').viewportOffset()[1] + $('container').getHeight()) 
                        - Position.GetWindowSize().height;
    //compute height of bottom element
    var last = $$(".product_item").last().getHeight();
    
    var next_page_btn = $$("#pagination a.next_page").first();
    
    if(remaining < last*2 && Ajax.activeRequestCount == 0 && next_page_btn && next_page_btn.hasAttribute('href')){
      url = next_page_btn.href
      if (!url.endsWith(".js")) {
        url = url+".js"
      }
      new Ajax.Request(url, {method: 'get', onCreate: function(){
        $('pagination').addClassName('loading');
      }})
    }
  }
})

var endless = new EndlessScroll()

// hide the pagination links
document.observe("dom:loaded", function(){
});

// find to events that could fire loading items at the bottom
Event.observe(window, 'scroll', function(e){
  endless.loadRemainingItems();
});

Event.observe(window, 'resize', function(e){
  endless.loadRemainingItems();
});