﻿(function($) {

	$.fn.feedreader = function(options) {
		var defaults = {
			servurl: '',
			feed: '',
			items: 3,
			length: 5
		}

		if (!options.feed) return false;  //FIXME Fail gently:

		var opts = $.extend(defaults, options);

		$(this).each(function() {
			var container = this;

			$.ajax({
				type: "POST",
				data: { feedURL: opts.feed },
				url: opts.servurl + "/FeedRequest",
				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);
						});
						$(this).find("description").each(function() {
							var t = getNodeText(this);
							post.desc = trimtext(t, opts.length);
						});
						posts[i++] = post;
					});
					
					writeposts(container, posts);
				}
			});

		});
	};

	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 = '<ul class="RSSFeed">';
		for (var k in posts) {
			html += format(posts[k])
		}
		html += '</ul>';
		$(container).append(html);
	}

	function format(post) {
		var html = '<li class="RSSFeed-Line"><a class="RSSFeed-Link outbound" href="' + post.link + '" target="_blank" rel="News">' + post.title + '</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);

