/**
 *  Plugin which uses the Google AJAX Feed API for creating feed content
 *  @author:  M. Alsup (malsup at gmail dot com)
 *  @version: 1.0.1 (4/24/2007)
 *  Documentation and examples at: http://www.malsup.com/jquery/gfeed/
 *  Free beer and free speech. Enjoy!
 */
(function($) {

if (!window.google)  {
    alert('You must include the Google AJAX Feed API script');
    return;
}    

if (!google.feeds) google.load("feeds", "1");

$.fn.toFeed = function(options) {
    return this.each(function() {
        var $this = $(this);
        var opts = jQuery.extend({
            title: this.title || $this.text(), // title (used if titleOverride is true)
            titleOverride: 0,   // if true, use opts.title
            url:   this.href,   // url of the feed
            cls:   'feed',      // class name of the feed div
            snip:  1,           // 1 for item snippets, 0 for full articles
            max:  3            // max number of items per feed
        }, options || {});
        
        var g = new google.feeds.Feed(opts.url);
        g.setNumEntries(opts.max);
        g.load(function(result) {
            if (result.error) return;
            var t = (opts.titleOverride && opts.title) ? opts.title : result.feed.title;
            var f = $('<div class="'+ opts.cls +'"><h1>'+t+'</h1></div>');
            var max = Math.min(result.feed.entries.length, opts.max);
            if (!max) 
                f.append("No feeds available");
            for (var i=0; i < max; i++) {
                var entry = result.feed.entries[i];
                var content  = opts.snip ? entry.contentSnippet : entry.content;
                $('<div class="item"></div>')
                    .append('<h2><a href="'+entry.link+'">'+entry.title+'</a></h2>')
                    .append('<div class="date">'+entry.publishedDate+'</div>')
                    .append('<div class="snip">'+content+'</div> ')
                    .appendTo(f);
            }
            $this.after(f).remove();
        });
    });
};

})(jQuery);
