// 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;
}

function loadRemainingItems(){
  // compute amount of page below the current scroll position
  var remaining = ($('characters-wrapper').viewportOffset()[1] + $('characters-wrapper').getHeight()) 
                      - Position.GetWindowSize().height;
  //compute height of bottom element
  var last = $$(".character").last().getHeight();


  if(remaining < last*2 && !$('complete')){
    if(Ajax.activeRequestCount == 0){
      var url = "/characters";
      var last = $$(".character").last().className.match(/[0-9]+/)[0];
      var production_id = window.location.search.get('production_id');
      
      var parameters = 'last=' + (last);
      if (production_id != false) {
        parameters = parameters + "&production_id=" + (production_id);
      }
      
      new Ajax.Request(url, {
        method: 'get',
        parameters: parameters,
        onLoading: function(){
          $('loading').show();
        },
        onSuccess: function(xhr){
          $('loading').hide();
          $('loading').insert({before : xhr.responseText});
		  charactersIndexLayout();
		  setFooter();
        }
      });
    }
  }
}

// hide the pagination links
document.observe("dom:loaded", function(){
  var last = $$(".pagination").last();
  if (last) {
    last.hide();
  }
  $('loading').hide();
});

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

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

String.prototype.get = function(p){
	return (match = this.match(new RegExp("[?|&]?" + p + "=([^&]*)"))) ? match[1] : false;
}

