// see http://apiwiki.twitter.com/Twitter-REST-API-Method:-statuses-user_timeline
// for API documentation

function makeLinks(txt){
	txtparts = txt.split(' ');
	for(x in txtparts){
		wrd = txtparts[x];
		// make http:// strings into links
		if(wrd.substring(0, 7)=='http://'){
			tlink = wrd.substring(7);
			txtparts[x] = '<a href="http://' + tlink + '">http://' + tlink + '</a>';
		}
		// make @user tags into links to them on twitter
		if(wrd.substring(0, 1)=='@'){
			tname = wrd.substring(1);
			txtparts[x] = '@<a href="http://twitter.com/' + tname + '">' + tname + '</a>';
		}
		// make hash tags into search links
		if(wrd.substring(0, 1)=='#'){
			thash = wrd.substring(1);
			txtparts[x] = '<a href="http://twitter.com/search?q=%23' + thash + '">#' + thash + '</a>';
		}
	}
	txt = txtparts.join(' ');
	return txt;	
}

(function($){
	$.fn.twitterize = function(username,options){
		if (username){
			var defaultSettings = {
				count:'1'
			}
			var settings = $.extend(defaultSettings, options);
			var url = "http://twitter.com/status/user_timeline/"+username+".json?count="+settings.count+"&callback=?";
			var holder = this;
			$.getJSON(url, function(data){
				$.each(data, function(i, item) {
					twit_entry = makeLinks(item.text);
					twit_created = jQuery.timeago(new Date(item.created_at)) + " via " + item.source;
					holder.append("<p class='twitterize_entry_" + i + "'>" + twit_entry + "<br /><span class='twitterize_created_at'>" + twit_created + "</span></p>\n");
				});
			});
		}
		else{
			console.debug("jquery plugin twitterize requires a username! Check your parameters");
		}
	};
})(jQuery);
