// Turn a Unix seconds-since-epoch timestamp into a human friendly string
// such as "3 days ago" or "an hour ago". Format this clientside in Javascript
// rather than serverside so that the info looks right even if page is cached.
//
// By Nelson Minar <nelson@monkey.org>. License: public domain.
// http://www.nelson.monkey.org/~nelson/weblog/
//
// ref: the reference time you're evaluating. Seconds since epoch.
// now: optional parameter, current time. Leave blank to evaluate ref
//   according to browser's current time. Seconds since epoch.
//
// Example - ago(1125580859 - 60 * 3, 1125580859) == "3 minutes ago"

function ago (ref, now) {
  if (typeof(now) == "undefined") {
    now = Math.floor(new Date().getTime() / 1000);
  }
  delta = now - ref;
  if (delta < 0) {
    return "in the future";
  } else if (delta == 0) {
    return "now";
  } else if (delta < 60) {
    return "in the last minute";
  } else if (delta < 120) {
    return "1 minute ago";
  } else if (delta < 3600) {
    minutes = Math.floor(delta / 60);
    return minutes + " minutes ago";
  } else if (delta < 7200) {
    return "1 hour ago";
  } else if (delta < 86400) {
    hour = Math.floor(delta / 3600);
    return hour + " hours ago";
  } else if (delta < 172800) {
    return "1 day ago";
  } else if (delta <  1209600) {
    day = Math.floor(delta / 86400);
    return day + " days ago";
  } else if (delta < 2592000) {
    week = Math.floor(delta / 604800);
    return week + " weeks ago";
  } else if (delta < 5184000) {
    return "1 month ago";
  } else if (delta < 31536000) {
    month = Math.floor(delta / 2592000);
    return month + " months ago";
  } else if (delta < 63072000) {
    return "1 year ago"
  } else {
    year = Math.floor(delta / 31536000);
    return year + " years ago";
  }
}

