if (typeof(shcp) == 'undefined') shcp = {};

/* ref_element has title attribute containing timestamp string 
 *
 * e.g. batch update can be like
 * jQuery('#karea span.ago').each(function() { shcp.set_html_as_timestamp_diff_in_words(this); })
 */
shcp.set_html_as_timestamp_diff_in_words = function(ref_element, set_element) {
  var timestamp_string = shcp.attribute_title_value(ref_element).replace(/^.*xxx /, "");
  var timestamp = new Date(); timestamp.setTime(Date.parse(timestamp_string));
  jQuery(set_element || ref_element).html(shcp.timestamp_diff_in_words(timestamp.toGMTString()) + " ago");
};

shcp.set_all_timestamp_diff_in_words = function(jelements) {
  (jelements || jQuery('#karea span.ago')).each(function() { 
    shcp.set_html_as_timestamp_diff_in_words(this); 
  });
};

shcp.timestamp_diff_in_words = function(str_value, base_value) {
  if (! base_value) {
    var timenow = (new Date()).getTime();
  } else {
    var timenow = Date.parse(base_value);
  }  
  var timethen = Date.parse(str_value);
  var diff_minutes = (timenow - timethen) / 1000 / 60;
  return shcp.minutes_diff_in_words(diff_minutes);
};

shcp.minutes_diff_in_words = function(diff_minutes) { 
  function qualified_num(num, unit) {
    return parseInt(num) + " " + unit + (num >= 2 ? "s" : "");
  }

  if (diff_minutes == 0) {
    return "";
  } else if (diff_minutes < 1) {
    return "less than a minute";
  } else if (diff_minutes < 60) {
    return qualified_num(diff_minutes, "minute");
  } else if (diff_minutes < 1440) {
    return qualified_num((diff_minutes / 60), "hour");
  } else if (diff_minutes < 43200) {
    return qualified_num((diff_minutes / 1440), "day");
  } else {
    return "about " + qualified_num((diff_minutes / 43200), "month");
  }
};

shcp.attribute_title_value = function(element) {
  var value = (element.title || (element.attributes["title"] && element.attributes["title"].nodeValue));
  if (value && value.match(/^title=/)) {
    value = value.replace(/^title='(.*)\'>/, '$1')
  }
  return value;
};

