/*
 * A simple JQuery plugin for an RSS-fed news box
 */
(function($) {
	
/**
 * Configure the news box container with url, maximum number of posts
 * to be fetched and their text length.
 * @example $('#newsbox').feedreader({
 *		targeturl: 'http://blogs.atalayasec.org/atalaya/?feed=rss2',
 *		items: 3,
 *		descLength: 15
 *	});
 * @desc fill the #newsbox element with at most 3 posts taken from the above url, and showing
 * a teaser of at most 15 words.
 *	
 */	
$.fn.feedreader = function(options) {
	var defaults = {
    targeturl: '',
		items: 2,
		descLength: 8
	}
	if(!options.targeturl)	return false;
	var opts = $.extend(defaults, options);
	$(this).each(function(){
  var container = this;
    $.ajax({
      url: opts.targeturl,
      cache: false,
      success: 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("pubDate").each(function(){
                  post.date=getNodeText(this);
                });
                posts[i++]=post;
         });
        writeposts(container,posts);
      },
      error: function (xhr, ajaxOptions, thrownError){
        var posts=[];
        var post={};
        $(container).empty();
        $(container).append("<p><br />The newsfeed is currently unavailable.</p><br />");
      }
    });
  });
};

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 = '<p>';
	for(var k in posts){
    if(k<jQuery('numOfNewsArticlesToDisplay'))
    {
      html+=format(posts[k])
    }
	}
	html += '</p>';
	$(container).append(html);
}

function format(post){
  var pubDate = "";
  pubDate  = post.date.substr(8,4);
  pubDate += post.date.substr(5,3);
  pubDate += post.date.substr(12,4);
	var html='<a href="'+post.link+'">'+post.title+'</a><br /><span class="date">- '+pubDate+'</span><br/><br/>';
	return html;
}

function getNodeText(node)
{
        var text = "";
        if(node.text) text = node.text;
        if(node.firstChild) text = node.firstChild.nodeValue;
        return text;
}

})(jQuery);