var GREENFEET = document.GREENFEET || {};

GREENFEET.fetch_more = function () {
      
    function fetchMore (button, quantity) {        
        container = button.parent().find('.index_container');
        var start = container.children().length;
        var end = start + quantity;
        var url = button.attr('href') + start + ':' + end + '/';

        button.addClass('deactivated');
        
        $.get(url, {}, function (data) {
            if (data.stat !== 'ok') { return; }
            if(data.length){
                // variation of .find which includes root?
                // workaround: wrap in a dummy div
                var extra = $('<div>').html(data.output);
                container.append(
                    extra.find('.index_container').html());
            }
            if (data.final) { button.remove(); }
            else { button.removeClass('deactivated'); }
        }, 'json');
    }
    
    return {
        init: function () {
            $('.fetch-more-button').css('visibility', 'visible');
            $('.fetch-more-button:not(.deactivated)').live('click', function(){
                fetchMore($(this), 10);
                return false;
            });
        }
    }
    
}();

