var microbubble = window.microbubble || {}; // namepsace

/**
 *  JQuery plugin
 */
jQuery.fn.getPipe = function(url, max, target) {
	var pipeFeed = new microbubble.PipeFeed(this, max, target);
	pipeFeed.parse(url);
};

/**
 *  PipeFeed Class
 *  Returns an ordered list of feed items
 */
microbubble.PipeFeed = function(htmlElement, max, target) {
	htmlElement.html('<ol id="' + target + '"></ol>');
	var listElement = $("#" + target);

	return {
		parse : function(url) {
		    if(!url) {
				htmlElement.html("No url provided");
			}
			
			$.getJSON(url,
				function(json) { 
					parseFeed(json);
				}
			);
		}
	};
	
	function parseFeed(json) {
		if(json.count > 0) {
			 i = 1;
			 $(json.value.items).each( function() {
				 if (i <= max)
				 {
					var itemDetail = createTitle(this) + createMeta(this) + createDescription(this);
					$(listElement).append('<li>' + itemDetail + '</li>');
				 }		
				 i++;
			});
	     } else {
			htmlElement.html("The request did not return results");
	     }		
	}
	
	function createTitle(item) {
		return '<a class="item-link" rel="nofollow" target="_mcLink" title="' + item.title + '" href="' + item.link + '">' + item.title + '</a>';
	}

	function createDescription(item) {
		var desc = "";
		if (item.summary == undefined)
		{
			desc = item.description;
		}
		else
		{
			desc = item.summary;
		}

		return '<p class="item-details">' + desc + '</p>';
	}

	function createMeta(item) {
		var str = '<p class="item-meta">';
		if (item.author != undefined)
		{
			str += '<strong>Published by:</strong> ' + item.author.name + ' on';
		}
		else
		{
			str += '<strong>Published:</strong>';
		}

		str += ' ' + Date.parse(item.pubDate).toString("MMMM dS yyyy h:mm tt")  + '</p>';

		return str;
	}

};
