(function($) {
    $.endlessPageScroll = function(options) {
        var defaults = {
            url: null
        };

        var opts = $.extend(defaults, options);

        var win = $(window);
        var doc = $(document);

        var currentPage = 1;
        var morePages = true;
        var active = false;

        function onScroll() {
            if (!morePages) {
                return;
            }

            var pageHeight = doc.height()
            var scrollBottom = win.scrollTop() + win.height();

            var remainingHeight = pageHeight - scrollBottom;

            if (remainingHeight < 100) {
                if (!active) {
                    currentPage++;
                    active = true;

                    $.ajax({
                        url: opts.url + currentPage,
                        dataType: 'json',
                        cache: false,
                        
                        success: function(json) {
                            if (json.nr_items > 0) {
                                $.handleJSON(json);
                            }

                            morePages = json.more_pages;
                            active = false;
                        }
                    });
                }
            }
        }

        win.unbind("scroll", onScroll);
        win.scroll(onScroll);
    };
})(jQuery);
