/**
 * Feedloader.js
 * Populates div with feed content as HTML
 *
 * @depends Mootools Core.js (tested v1.2.3)
 * @author Andrew Bredow <bredow@gmail.com>
 */
var FeedLoader = new Class({
    
    options: {
        url: 'http://www.gatewaychurch.com/media/scripts/feed.php'
    },
    
    _list: null,
    
    _enabled: true,
    
    initialize: function(listElement) {
        this._list = listElement;
        this._attachEvents();
        this._search();
    },
    
    _search: function() {
        var offset = this._list.childNodes.length;
        new Request.JSON({
            method: 'get',
            url: this.options.url,
            data: {start: offset},
            onSuccess: this._searchSuccess.bind(this),
            onFailure: this._searchFailure.bind(this)
        }).send();
        
    },
    
    _searchSuccess: function(json, text) {
        if (!$defined(json.error) || json.error) {
            /*this._showError(json.message);*/
            this._searchFailure();
            return;
        }
        var el = new Element('div', {html: json.results});
        this._list.adopt(el.getChildren());
        this._enabled = true;
    },
    
    _searchFailure: function(responseText) {
        this._showError('Unable to retrieve results. Please reload the page and try again.');
    },
    
    _showError: function(message) {
        this._list.getChildren().dispose();
        this._list.adopt(new Element('div', {
            id: 'error',
            text: message
        }));
    },
    
    _attachEvents: function(){
        this._list.addEvent('scroll', function() {
            if (this._enabled === false) return;
            var cur = this._list.getScroll().y + this._list.getSize().y;
            var max = this._list.getScrollSize().y;
            if (cur >= max ) {
                this._enabled = false;
                this._search();
            }
        }.bind(this));
    }
    
});

window.addEvent('domready', function() {
    if (! $('feedBlock')) return;
    new FeedLoader($('feedBlock'));
});