$(function() {
	$.getJSON("http://twitter.com/statuses/user_timeline/runevillage.json?count=5&callback=?", function(data) {
		$("#tweets p.twitter-loading").remove();
		$.each(data, function(i, tweet) {
			var p = $("<p />").css('display', ((i > 0) ? 'none' : 'block')).html(parseTwitterMsg(tweet.text)).appendTo("#tweets").get(0);
			p.date =  new Date(tweet.created_at);
		});
		updateDate();
	});

	$("#next-tweet").click(function() {
		$("#tweets p:first").css("display", "none").remove().appendTo("#tweets");
		$("#tweets p:first").css("display", "block");
		updateDate();
		return false;
	});

	$("#prev-tweet").click(function() {
		$("#tweets p:first").css("display", "none");
		$("#tweets p:last").css("display", "block").remove().prependTo("#tweets");
		updateDate();
		return false;
	});
});

function parseTwitterMsg(text) {
	return text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(str) {
		return shortenURL(str).link(str);
	});
}

function updateDate() {
	var p = $("#tweets p").get(0);
	$("#tweet-time").text(timeAgo(p.date));
}

function shortenURL(text) {
	var maxlength = 18
	text = text.replace('http://', '');
	if (text.length > maxlength) {
		var linelength = 0;
		for (var i = 0; i < text.length; i++) {
			if (linelength > maxlength || (text.charAt(i) == '/' && linelength > (maxlength-4))) {
				text = text.substring(0, i+1) + ' ' + text.substring(i+1, text.length);
				linelength = 0;
			}
			linelength++;
		}
	}
	return text;
}

function timeAgo(date) {
	var diff = (((new Date()).getTime() - date.getTime()) / 1000);
	var day_diff = Math.floor(diff / 86400);

	if ( isNaN(day_diff) || day_diff < 0 )
		return "";

	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 8 && day_diff + " days ago" ||
		Math.ceil( day_diff / 7 ) + " weeks ago";
}
