String.prototype.linkify = function() {
	var text = this.replace(/([A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+)/,"<a href='$1'>$1</a>");
	var text = text.replace(/(@([\w]+))/g,"<a href='http://twitter.com/$2'>$1</a>");
	var text = text.replace(/(#([\w]+))/g,"<a href='http://twitter.com/#search?q=$2'>$1</a>");
	return text
};

function relative_time(time) {
	var d = Date.parse(time)
	var dateFunc = new Date();
	var timeSince = dateFunc.getTime() - d;
	var inSeconds = timeSince / 1000;
	var inMinutes = timeSince / 1000 / 60;
	var inHours = timeSince / 1000 / 60 / 60;
	var inDays = timeSince / 1000 / 60 / 60 / 24;
	var inYears = timeSince / 1000 / 60 / 60 / 24 / 365;

	// in seconds
	if(Math.round(inSeconds) == 1){
		return ("1 second ago");
	}
	else if(inMinutes < 1.01){
		return (Math.round(inSeconds) + " seconds ago");
	}

	// in minutes
	else if(Math.round(inMinutes) == 1){
		return ("1 minute ago");
	}
	else if(inHours < 1.01){
		return (Math.round(inMinutes) + " minutes ago");
	}

	// in hours
	else if(Math.round(inHours) == 1){
		return ("1 hour ago");
	}
	else if(inDays < 1.01){
		return (Math.round(inHours) + " hours ago");
	}

	// in days
	else if(Math.round(inDays) == 1){
		return ("1 day ago");
	}
	else if(inYears < 1.01){
		return (Math.round(inDays) + " days ago");
	}

	// in years
	else if(Math.round(inYears) == 1){
		return ("1 year ago");
	}
	else
	{
		return (Math.round(inYears) + " years ago");
	}
}

$(document).ready(function(){
	
	var url = "http://twitter.com/status/user_timeline/robinjfisher.json?count=3&callback=?";
	$.getJSON(url, function(data) {
		$.each(data, function(i, item) {
			$("#tweets").append('<li>' + item.text.linkify() + '&nbsp<span class="tweet-posted-at">' + relative_time(item.created_at) + '</span></li>');
		});
	});
 
});
