/* 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  = Math.floor(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 1: return "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, text, newtext, textnode;

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

// alert(datetime2human('2008-02-06 4:30'));

MochiKit.DOM.addLoadEvent(rewrite_all_datetimes);
