// declare the object type
function pipeRenderer() {};

// factory method
pipeRenderer.run = function(pipeId, messageContainerId, listId) {
	var rss = new pipeRenderer();
	rss.storageKey = ('yahooPipe' + pipeId);
	rss.pipeId = pipeId;
	rss.messageContainerId = messageContainerId;
	rss.listId = listId;
	
	jQuery(document).ready(function() {
		rss.init();
	});
};

// static util
pipeRenderer.isValidData = function(data) {
	return data && data.value && data.value.items;
};

// prototype methods
pipeRenderer.prototype.init = function() {
	jQuery('#' + this.messageContainerId).hide();
	jQuery('#' + this.listId).hide();

	var localData = null;
	var sessionData = null;
	
	try {
		localData = JSON.parse(localStorage.getItem(this.storageKey));
	} catch(e) {
	}
	
	if( pipeRenderer.isValidData(localData) ) {
		this.displayNews(localData);
		try {
			sessionData = JSON.parse(sessionStorage.getItem(this.storageKey));
		} catch(e) {
		}
		if( !pipeRenderer.isValidData(sessionData) ) {
			this.getJSON();
		}
		return;
	}
	
	this.displayMessage('Loading...');
	this.getJSON();
};

pipeRenderer.prototype.getJSON = function() {
	var rss = this; // save a copy
	var url = 'http://pipes.yahoo.com/pipes/pipe.run?_id=' + this.pipeId + '&_render=json&_callback=?';
	jQuery.getJSON(url, function(data) {
		if( pipeRenderer.isValidData(data) ) {
			rss.displayNews(data);
			try {
				sessionStorage.setItem(rss.storageKey, JSON.stringify(data));
				localStorage.setItem(rss.storageKey, JSON.stringify(data));
			} catch(e) {
			}
		} else if( jQuery('#' + rss.listId).not(':visible') ) {
			rss.displayMessage('Temporarily unavailable...');
		}
	});
};

pipeRenderer.prototype.displayNews = function(data) {
	var rss = this; // save a copy
	jQuery('#' + this.listId).empty();
	jQuery.each(data.value.items, function(ix, item) {
		jQuery('<a></a>')
			.attr('href', item.link)
			.text(item.title)
			.wrap('<li></li>')
			.parent()
			.appendTo('#' + rss.listId);
			
	});
	if( jQuery('#' + this.messageContainerId).is(':visible') ) {
		jQuery('#' + this.messageContainerId).fadeOut('fast', function() {
			jQuery('#' + rss.listId).fadeIn('fast');
		});
	} else {
		jQuery('#' + this.listId).show();
	}
};

pipeRenderer.prototype.displayMessage = function(message) {
	jQuery('#' + this.messageContainerId).text(message).show();
};

