var microbubble = window.microbubble || {}; // namepsace

/**
 *  JQuery plugin
 */
jQuery.fn.getPipe = function(url) {
	var pipeFeed = new microbubble.PipeFeed(this);
	pipeFeed.parse(url);
};

/**
 *  PipeFeed Class
 *  Returns an ordered list of feed items
 */
microbubble.PipeFeed = function(htmlElement) {
	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=Lh5grVhL3RG9artmMlrX_Q&url=" + url +  "&_render=json&_callback=?",
				function(json) { 
					parseFeed(json);
				}
			);
		}
	};
	
	function parseFeed(json) {
		if(json.count > 0) {
			i = 0;
			 $(json.value.items).each( function() {
				i++;
				if(i < 4){
				var itemDetail = createTitle(this) ;
				
				$(listElement).append('<li>' + itemDetail + '</li>');
				};
			});
	     } else {
			htmlElement.html("The request did not return results");
	     }		
	}
	
	function createTitle(item) {
		return '<a title="link to original article" href="' + item.link + '">' + item.title + '</a>';
	}

	function createDescription(item) {
		return '<p class="item-details">' + item.description + '</p>';
	}

	function createMeta(item) {
		return '<span class="item-meta">Published: ' + Date.parse(item.pubDate).toString("MMMM dS yyyy h.mm tt")  + '</span>';
	}

};