var EndlessPage = {
  start: null,
  limit: null,
  total: null,
  in_progress: false,

  check_scroll: function() {
    if (EndlessPage.near_bottom()) {
      EndlessPage.in_progress = true;
      var params = {start: EndlessPage.start, limit: EndlessPage.limit, total: EndlessPage.total, blank_template: 1};
      
      $("NewsSpinner").show();
      new Ajax.Updater("NewsArticles", document.location.pathname + "listing/", {
        method: "get",
        parameters: params,
        insertion: "bottom",
        evalScripts: true,
        onSuccess: function(transport) {
          $("NewsSpinner").hide();
        },
        onComplete: function(status) {
          EndlessPage.in_progress = false;
        }
      });
    } else {
      EndlessPage.queue_check_scroll();
    }
  },

  queue_check_scroll: function() {
    setTimeout("EndlessPage.check_scroll()", 100);
  },

  near_bottom: function() {
    return (EndlessPage.scroll_distance_from_bottom() < 100 && EndlessPage.in_progress != true);
  },

  scroll_distance_from_bottom: function(argument) {
    return EndlessPage.page_height() - (EndlessPage.get_scroll_height() + EndlessPage.get_inner_height());
  },

  page_height: function() {
    return Math.max(document.body.scrollHeight, document.body.offsetHeight);
  },

  get_scroll_height: function() {
    var h = window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop;
    return h ? h : 0;
  },

  get_inner_height: function() {
    var h = self.innerHeight || document.body.clientHeight;
    return h ? h : 0;
  }
}
