﻿var microbubble = window.microbubble || {}; // namepsace

/**
*  JQuery plugin
*/
jQuery.fn.getPipe = function (url, NumItems) {
	var currentDate = new Date();
	if (this.attr("LastLoadedDate") == undefined || this.attr("LastLoadedDate") < currentDate.getTime() - 1000 * 60 * 10) {
		this.attr("LastLoadedDate", currentDate.getTime());
		this.html("<img src='/styles/images/loading_gif.gif' alt='loading' width='100px' height=100px' style='padding-left:50px;padding-top:50px;' />");

		var pipeFeed = new microbubble.PipeFeed(this, NumItems);
		pipeFeed.parse(url);
	}
};

/**
*  PipeFeed Class
*  Returns an ordered list of feed items
*/
microbubble.PipeFeed = function (htmlElement, NumItems) {
	htmlElement.html('<ul id="feed-results"></ul>');
	var listElement = $("#feed-results");

	return {
		parse: function (url) {
			if (!url) {
				htmlElement.html("No url provided");
			}

			$.getJSON('http://pipes.yahoo.com/pipes/pipe.run?_id=7fb367ac08121794f7891581fedb9334&url=' + url + '&t=' + htmlElement.attr("LastLoadedDate").substring(0, 7) + '&_render=json&_callback=?',
				function (json) {
					parseFeed(json, NumItems);
				}
			);
		}
	};

	function parseFeed(json, NumItems) {
		var i = 0;
		if (json.count > 0) {
			$(json.value.items).each(function () {
				if (i < NumItems) {
					i++;
					var itemDetail = createTitle(this) + createDescription(this) + createLink(this) + "<br /><br />";
					$(listElement).append('<li>' + itemDetail + '</li>');
				}
			});
		} else {
			htmlElement.html("Sorry, there are no items to display at this time, please come back soon.");
		}
	}

	//we are showing the date instead of the title on the twitter feed due to it being duplicated data
	function createTitle(item) {
		return '<strong>' + dateFormat(item.pubDate, "ddd, mmm. d, yyyy") + '</strong>';
	}

	function createDescription(item) {
		return item.description + '<br />';
	}

	function createMeta(item) {
		return '<span style="color: #A0A0A0;">' + dateFormat(item.pubDate, "ddd, mmm. d, yyyy") + '</span>';
	}

	function createLink(item) {
		return '<a href="' + item.link + '" target="_blank" style="float:right;">More</a>';
	}

};
