/* Converts a 'YYYY-MM-DD HH:MM' string to a human-readable timestamp
 * */
function datetime2human(timestamp)
{
	now = new Date();
	other = MochiKit.DateTime.isoTimestamp(timestamp);

	// Get time difference in seconds
	diff = (now - other) / 1000.;
	secs  = diff % 60;
	mins  = Math.floor(diff / 60) % 60;
	hours = Math.floor(diff / 3600) % 24;
	days  = Math.floor(diff / 86400);

	if(days == 0) {
		switch(hours) {
			case 0:
				switch(mins) {
					case 0: return secs + " seconds ago";
					case 1: "A minute ago";
					default: return mins + " minutes ago";
				}
			case 1: return "An hour ago";
			default: return hours + " hours ago";
		}
	} else if(days < 7) {
		switch(days) {
			case 0: return secs + " days ago";
			case 1: "A day ago";
			default: return days + " days ago";
		}
	}
			
	return timestamp;
}

/* Rewrite all dates in the current document. They must be in <span>
 * tags with 'datetime' as class. */
function rewrite_all_datetimes()
{
	var list;

	list = MochiKit.DOM.getElementsByTagAndClassName('span', 'humandate');
	for(index=0; index<list.length; index++) {
		text = MochiKit.DOM.scrapeText(list[index]);
		newtext = datetime2human(text);
		textnode = document.createTextNode(newtext)
		MochiKit.DOM.replaceChildNodes(list[index], textnode);
	}
}

// alert(datetime2human('2005-11-10 14:30'));

MochiKit.DOM.addLoadEvent(rewrite_all_datetimes);
