/*
 * A simple JQuery plugin for an RSS-fed news box
 *
 * @author Francesco Vivoli <f.vivoli@gmail.com> - http://atalayasec.org
 * Based on code found on the JQuery mailing list
 *
 * @modified-by Jon Ursenbach <jon@decorati.com>
 */
(function($) {
    $.fn.feedreader = function(options) {
        var defaults = {
            targeturl: '',
            items: 3,
            descLength: 15
        };

        if (!options.targeturl || options.targeturl == '') {
            return false;
        }
        
        var opts = $.extend(defaults, options);
        $(this).each(function() {
            var container = this;
            $.get(opts.targeturl,function(xml) {
                var posts = [];
                var i = 0;
                $("item", xml).each(function() {
                    if (i > opts.items - 1)	return;
                    var post = {};
                    
                    $(this).find("link").each(function() {
                        post.link = getNodeText(this);
                    });

                    $(this).find("title").each(function() {
                        post.title = getNodeText(this);
                    });

                    $(this).find("description").each(function() {
                        var t = getNodeText(this);
                        post.desc = trimtext(t,opts.descLength) + '';
                    });

                    posts[i++] = post;
                });
                
                writeposts(container, posts);					
            });
        });
        
        return true;
    };

    function trimtext(text, length) {
        var t = text.replace(/\s/g, ' ');
        var words = t.split(' ');
        if (words.length <= length) {
            return text;
        }
        
        var ret='';
        for (var i=0; i<length; i++){
            ret += words[i] + ' ';
        }
        
        return ret;
    }

    function writeposts(container, posts) {
        $(container).empty();
        var html = '<dl>';
        for(var k in posts){
            html += format(posts[k]);
        }
        
        html += '</dl>';
        $(container).append(html);
    }
 
    function format(post) {
        var html;
        
        html = '<h5>';
        html += '<a href="' + post.link + '">' + post.title + '</a><br />';
        html += '</h5>';
        
        html += '<dd>';
        html += post.desc + '<a href="' + post.link + '"> &#40;more&#41;</a>';
        html += '</dd>';
        
        return html;	
    }

    function getNodeText(node) {
        var text = "";
        if (node.text) text = node.text;
        if (node.firstChild) text = node.firstChild.nodeValue;
        return text;
    }
})(jQuery);