(function($){

	jQuery.fn.createFeedWidget = function(options) {
		// Set default arguments
		options = jQuery.extend({
			feed: null,
			interval: 10000,
			width: 300,
			height: 300
		}, options);

		this.each(function(){
			// DOM elements
			var container = jQuery(this);
			var list = jQuery('<ol style="height: ' + (options.height - 89) + 'px;"></ol>');

			container.append('<div class="feedwidget" style="width: ' + options.width + 'px; height: ' + options.height + 'px;"><div class="header"></div><div class="content" style="height: ' + (options.height - 89) + 'px;"></div><div class="footer"></div></div>')
			container.find('div.feedwidget div.content').append(list);

			// Feed content
			var feed = null;
			var i = 0;

			// Load the feed content
			jQuery.ajax({
				type: 'GET',
				cache: false,
				url: ('widgets/FeedWidget/rss_to_json.php?input=' + escape(options.feed)),
				success: function(response, status)
				{
					// Store the data in the grades array
					feed = response;

					// Add the first item
					addNewItem();

					// Start updating the feed widget
					window.setInterval(updateFeedWidget, options.interval);
				},
				dataType: 'json'
			});

			// Function to add a new item to the feed widget
			var addNewItem = function() {
				// Write the item
				list.prepend('<li><a href="' + feed.items[i].link + '" target="_blank" class="title">' + feed.items[i].title + '</a>' + feed.items[i].description + '</li>');

				// Increment the index counter
				if (i == feed.items.length - 1)
				{
					i = 0;
				}
				else
				{
					i++;
				}
			}

			// Function to update a feed widget on each tick
			var updateFeedWidget = function() {
				// Function to fade in a list item
				var showItemContent = function() {
					// Hide the item again, then restore the opacity and fade it in
					list.find('li:first-child').hide().css('opacity', 1).fadeIn('slow');
				}

				// Add a new item to the widget
				addNewItem();

				// Make the item invisible and then hide it
				list.find('li:first-child').css('opacity', 0.00001).hide();

				// Slide the item down (although it will still be invisible) then fire the callback
				list.find('li:first-child').slideDown('slow', showItemContent);
			}
		});
	};
})(jQuery);