/*
 * 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
 */
(function($) {
	

$.fn.feedreader = function(options) {
	var defaults = {
		targeturl: 'http://feeds.news.com.au/public/rss/2.0/news_breaking_news_32.xml',
		items: 2,
		descLength: 110,
		headingLength: 66
	}
	if(!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(){									
										if(getNodeText(this).length > opts.headingLength)
										{										 
										    post.title = trimtext(getNodeText(this), opts.headingLength)+'...';
										}
										else
										{
										    post.title = getNodeText(this);
										}
									});
									$(this).find("pubDate").each(function(){
										post.date=getNodeText(this);
									});
									$(this).find("description").each(function(){
									    if(getNodeText(this).length > opts.descLength)
									    {
									       post.desc=trimtext(getNodeText(this),opts.descLength)+'...';
									     
										}
										else
										{
										    post.desc = getNodeText(this);
										}
									});
									posts[i++]=post;
					 });
					writeposts(container,posts);					
				
			})
	});	
	
};

function trimtext(text,length){
	if(text.length<=length)	return text;
	var ret='';
	for(var i=0;i<length;i++){
		ret+=text.charAt(i);
	}

	return ret;
}

function writeposts(container,posts){
	$(container).empty();
	var html = '<ul class="text-list">';
	for(var k in posts){
		html+=format(posts[k],k)
	}
	html += '</ul>';
	$(container).append(html);
}

function format(post,k){

if(k == 0){
	var html='<li id="newsitem" class="link first"><a href="'+post.link+'" target="_blank"><strong>'+post.title+'</strong>';
	html+='<br/>'+post.desc+'</a></li>'
	return html;	
	}
	else{
	var html='<li id="newsitem" class="link"><a href="'+post.link+'" target="_blank"><strong>'+post.title+'</strong>';
	html+='<br/>'+post.desc+'</a></li>'
	return html;
	}	
	
	}

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

})(jQuery);

