/*
 * 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($) {
	
/**
 * 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 showig
 * a teaser of at most 15 words.
 *	
 */	
$.fn.feedreader = function(options) {
	var defaults = {
		targeturl: 'http://blogs.atalayasec.org/atalaya/?feed=rss2',
		items: 1,
		descLength: 15
	}
	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("rel").each(function(){
										post.rel=getNodeText(this);
									});
									$(this).find("title").each(function(){
										post.title=getNodeText(this);
									});
									$(this).find("pubDate").each(function(){
										post.date=getNodeText(this);
										//alert(opts.targeturl);
										if((post.date != "") && (opts.targeturl.search(/news/i) > 0))
										{
										var time = new Date(strtotime(post.date));
										var months = new Array(13);

										   months[0]  = "01";
										   months[1]  = "02";
										   months[2]  = "03";
										   months[3]  = "04";
										   months[4]  = "05";
										   months[5]  = "06";
										   months[6]  = "07";
										   months[7]  = "08";
										   months[8]  = "09";
										   months[9]  = "10";
										   months[10] = "11";
										   months[11] = "12";
										   var monthnumber = time.getMonth();
										   var monthname   = months[monthnumber];
										if(opts.targeturl.substr(0,2) == "fr")
										{
											post.date = time.getDate()+'/'+monthname+'/'+time.getFullYear();
										}else{
											post.date = monthname+'/'+time.getDate()+'/'+time.getFullYear();
										}
										
										}
									});
									$(this).find("description").each(function(){
										var t=getNodeText(this);
										post.desc=trimtext(t,opts.descLength)+'[...]';
									});
									posts[i++]=post;
					 });
					writeposts(container,posts);					
				
			})
	});	
	
}; 

function strtotime(str, now)
{

	str = str.replace(/\s{2,}|^\s|\s$/g, ' '); // unecessary spaces
	str = str.replace(/[\t\r\n]/g, ''); // unecessary chars 

	if (str == 'now') return (new Date()).getTime();
	else if (!isNaN(parse = Date.parse(str))) return parse;
	else if (now) now = new Date(now);
	else now = new Date();

	str = str.toLowerCase();

	var __is =
	{
		day:
		{
			'sun': 0, 'mon': 1, 'tue': 2, 'wed': 3,
			'thu': 4, 'fri': 5, 'sat': 6
		},
		mon:
		{
			'jan': 0, 'feb': 1, 'mar': 2, 'may': 3, 'apr': 4,  'jun': 5,
			'jul': 6, 'aug': 7, 'sep': 8, 'oct': 9, 'nov': 10, 'dec': 11
		}
	}

	var match = str.match(/^(\d{2,4}-\d{2}-\d{2})(\s\d{1,2}:\d{1,2}(:\d{1,2})?)?$/);

	if (match != null)
	{
		if (!match[2])
			match[2] = '00:00:00';
		else if (!match[3])
			match[2] += ':00';

		var s = match[1].split(/-/g);

		for (var i in __is.mon)
			if (__is.mon[i] == s[1] - 1)
				s[1] = i;

		return strtotime(s[2] + ' ' + s[1] + ' ' + s[0] + ' ' + match[2]);
	}

	var regex = '([+-]?\\d+\\s'
			  + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'
			  + '|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'
			  + '|thu\.?|thursday|fri\.?|friday|sat\.?|saturday)'
			  + '|(last|next)\\s'
			  + '(years?|months?|weeks?|days?|hours?|min|minutes?|sec|seconds?'
			  + '|sun\.?|sunday|mon\.?|monday|tue\.?|tuesday|wed\.?|wednesday'
			  + '|thu\.?|thursday|fri\.?|friday|sat\.?|saturday))'
			  + '(\\sago)?';

	match = str.match(new RegExp(regex, 'g'));

	if (match == null)
	{
		return false;
	}

	for (var i in match)
	{
		if (!process(match[i].split(' ')))
		{
			return false;
		}
	}

	return now;

	function process(m)
	{
		var ago = (m[2] && m[2] == 'ago');
		var num = (num = m[0] == 'last' ? -1 : 1) * (ago ? -1 : 1);

		switch (m[0])
		{
			case 'last':
			case 'next':

				switch (m[1].substring(0, 3))
				{
					case 'yea':
						now.setFullYear(now.getFullYear() + num);
						break;
					case 'mon':
						now.setMonth(now.getMonth() + num);
						break;
					case 'wee':
						now.setDate(now.getDate() + (num * 7));
						break;
					case 'day':
						now.setDate(now.getDate() + num);
						break;
					case 'hou':
						now.setHours(now.getHours() + num);
						break;
					case 'min':
						now.setMinutes(now.getMinutes() + num);
						break;
					case 'sec':
						now.setSeconds(now.getSeconds() + num);
						break;
					default:

						var day;

						if (typeof (day = __is_day[m[1].substring(0, 3)]) != 'undefined')
						{
							var diff = day - now.getDay();

							if (diff == 0)
							{
								diff = 7 * num;
							}
							else if (diff > 0)
							{
								if (m[0] == 'last') diff -= 7;
							}
							else
							{
								if (m[0] == 'next') diff += 7;
							}

							now.setDate(now.getDate() + diff);
						}
				}

				break;

			default:

				if (/\d+/.test(m[0]))
				{
					num *= parseInt(m[0]);

					switch (m[1].substring(0, 3))
					{
						case 'yea':
							now.setFullYear(now.getFullYear() + num);
							break;
						case 'mon':
							now.setMonth(now.getMonth() + num);
							break;
						case 'wee':
							now.setDate(now.getDate() + (num * 7));
							break;
						case 'day':
							now.setDate(now.getDate() + num);
							break;
						case 'hou':
							now.setHours(now.getHours() + num);
							break;
						case 'min':
							now.setMinutes(now.getMinutes() + num);
							break;
						case 'sec':
							now.setSeconds(now.getSeconds() + num);
							break;
					}
				}
				else
				{
					return false;
				}

				break;

		}

		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 = '';
	for(var k in posts){
		html+=format(posts[k])
	}
	html += '';
	$(container).append('<ul>'+html+'</ul>');
}

function format(post){
	if(post.link.length>0)
	{
		if(post.link.indexOf(".pdf") != -1)
		{
			var html='<li><em>'+post.date+'</em><a href="'+post.link+'" target="_blank" class="menuitem-search" rel='+post.rel+'>'+post.title+'</a></li>';
		}
		else
		{
			var html='<li><em>'+post.date+'</em><a href="'+post.link+'" class="menuitem-search" rel='+post.rel+'>'+post.title+'</a></li>';
		}
	}
	else var html='<li><em>'+post.date+'</em>'+post.title+'</li>';
	
	return html;	
}

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



})(jQuery);
