function appendTime(time, timestr, ago)
{
    if(time > 0) { ago = ago + " " + time + " " + timestr; }
    if(time > 1) { ago = ago + "s"; }
    return ago;
}

function tsToAgo(tresult, maxdepth)
{
    // Make the X time ago format.
    var tcurtime = new Date().getTime()/1000;
    var tago = Math.round(tcurtime - tresult);

    if(typeof(maxdepth) == "undefined") {
        var maxdepth = 255;
    }

    var year = 0, month = 0, week = 0, day = 0, hour = 0, min = 0;
    while(tago > 60) {
        if(tago >= 31557600) {  year++; tago -= 31557600; continue; }
        if(tago >= 2678400)  { month++; tago -= 2678400;  continue; }
        if(tago >= 604800)   {  week++; tago -= 604800;   continue; }
        if(tago >= 86400)    {   day++; tago -= 86400;    continue; }
        if(tago >= 3600)     {  hour++; tago -= 3600;     continue; }
        if(tago >= 60)       {   min++; tago -= 60;       continue; }
    }

    var ago = "", depth = 0;
    if       (year && depth++ < maxdepth) {
        ago = appendTime(year, "year", ago);
    }  if(month && depth++ < maxdepth) {
        ago = appendTime(month, "month", ago);
    }  if(week && depth++ < maxdepth) {
        ago = appendTime(week, "week", ago);
    }  if(day && depth++ < maxdepth) {
        ago = appendTime(day, "day", ago);
    }  if(hour && depth++ < maxdepth) {
        ago = appendTime(hour, "hour", ago);
    }  if(min && depth++ < maxdepth) {
        ago = appendTime(min, "minute", ago);
    }  if(depth++ < maxdepth) {
        ago = appendTime(tago, "second", ago);
    }

    return ago;
}
