/**
 * Cognito Twitter jQuery plugin 
 * 
 * version: 1.0
 * author: Petr Janu (janu@cognito.cz)
 * date: 24.11.2009
 * 
 */

/* USAGE
 * 
 *	$(document).ready(function() {     
 *	  $('#twitter a').cTwitter(
 *	  { 
 *	  	userId: '86768521'
 *	  });  
 *	});
 * 
 */
function cTwitterCallback(message)
{
	cTwitterCallbackStack = message;
}

(function($)
{
	$.fn.cTwitter = function(settings)
	{
		var el = this;
		var ctw = {
			config: {
				userId: '',
				remoteUrlMask: 'http://twitter.com/statuses/user_timeline/{userId}.json?count=1&callback=cTwitterCallback',
				messageLinkMask: 'http://twitter.com/{userName}/statuses/{messageId}'
			},
			init: function(tlink)
			{
				ctw.prepareConfig();
				ctw.getMessage();
				ctw.tlink = tlink;
			},
			updateMessage: function(message)
			{
				ctw.message = message[0];
				ctw.config.messageLink = ctw.config.messageLinkMask.replace('{messageId}', ctw.message.id).replace('{userName}', ctw.message.user.screen_name);
				ctw.tlink.attr('href', ctw.config.messageLink).text(ctw.message.text);
			},
			getMessage: function()
			{
				$.getScript(ctw.config.remoteUrl, function(){
					ctw.updateMessage(cTwitterCallbackStack);
				});
			},
			prepareConfig: function()
			{
				ctw.config.remoteUrl = ctw.config.remoteUrlMask.replace('{userId}', ctw.config.userId);		
			}
		};
		$.extend(ctw.config, settings);
		ctw.init(el);
	};
})(jQuery);