$(function () {
	$.getJSON(
		'http://twitter.com/status/user_timeline/cwtdigital.json?count=3&callback=?',
		function(data)
		{
			$('#tweets').html('');
			
			$.each(data, function(i, item) {
				
				// I literally can't believe this is necessary. LITERALLY.
				var _d = item.created_at.split(' ');
				item.parseable_date = _d[0] + ", " + _d[2] + " " + _d[1] + " " + _d[5] + " " + _d[3] + " " + _d[4];
				
				$("#tweets").append(
					'<li>'
					+ item.text.parse_urls().parse_usernames().parse_hashtags()
					+ '<span class="created_at">'
					+ new Date(item.parseable_date).relative_time()
					+ '</span>'
					+ '<hr />'
					+ '</li>'
				);
			}); 
		}
	);
});

String.prototype.parse_urls = function()
{
	return this.replace(
		/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=#]+/g,
		function(m) { return m.link(m); }
	);
};

String.prototype.parse_usernames = function() {
	return this.replace(
		/[@]+[A-Za-z0-9-_]+/g,
		function(m) { return m.link("http://twitter.com/" + m.replace("@","")); }
	);
};

String.prototype.parse_hashtags = function() {
	return this.replace(
		/[#]+[A-Za-z0-9-_]+/g,
		function(m) { return m.link("http://search.twitter.com/search?q=" + m.replace("#","%23")); }
	);
};
