(function($) {
	/**
	 * Displays RSS/Atom feed. Requires Google Feed API.
	 * @param url url to rss or atom feed
	 * @param maxEntries max number of entries to display
	 * @param view name of the view. Currently the following are supported:
	 * - full: title + full content
	 * - short: only titles
	 */
	$.fn.gkFeedReader = function(url, maxEntries, view) {
		maxEntries = maxEntries ? maxEntries : 4;

		var outerContainer = $('<div></div>').addClass('feedContainer');
		var container = $('<div></div>').addClass('feedEntries');
		this.first().append(outerContainer);
		outerContainer.append(container);

		var feed = new google.feeds.Feed(url);
		feed.setNumEntries(maxEntries);
		feed.load(function(result) {
			if (!result.error) {
				for (var i = 0; i < result.feed.entries.length; ++i) {
					var entry = result.feed.entries[i];
					var domEntry = $('<div></div>').addClass('feedEntry');
					var link, title, content;
					if(view == 'full') {
						link = $('<a></a>').attr('href', entry.link).html(entry.title);
						title = $('<div></div>').addClass('title').append(link);
						content = $('<div></div>').addClass('content').html(entry.content);
						domEntry.append(title, content);
						// fix images
						content.find('img').removeAttr('width').removeAttr('height').
						css('width', '100%').css('height', 'auto').css('vertical-align', 'middle');
						// fix content
						content.contents().filter(function() {
							return this.nodeType == 3;
						}).wrap('<p></p>').end().filter('br').remove();
					} else if(view == 'short') {
						link = $('<a></a>').attr('href', entry.link).html(entry.title);
						title = $('<div></div>').addClass('title').append(link);
						domEntry.append(title);
					}
					container.append(domEntry);
				}
			}
		});
		return this;
	};

	var animate = function() {
		var entries = this.find('.feedEntries').first();
		if(entries.find('.feedEntry').length > 0) {
			if(entries.position().left != 0) {
				entries.css('left', '0');
				entries.append(entries.find('.feedEntry').first());
			}
			var first = entries.find('.feedEntry').first();
			entries.animate({
				'left': -first.outerWidth(true)
			}, first.outerWidth(true) * 35, 'linear', $.proxy(animate, this));
		} else {
			setTimeout($.proxy(animate, this), 100);
		}
	};

/**
 * Animates the feeds at the top of the page.
 * This function must be called on the feed reader module.
 */
	$.fn.gkFeedReaderAnimate = function() {
		animate.call(this);
		return this;
	};

})(jQuery);
