/*
 * JavaScript Prettier Date
 * by Øyvind Smestad
 *
 * based on:
 * JavaScript Pretty Date
 * Copyright (c) 2008 John Resig (jquery.com)
 *
 * Licensed under the MIT license.
 */

// Takes an ISO time and returns a string representing how
// long ago the date represents.
function prettierFutureDate(time){
  var targetTime = new Date(time),
     currentTime = new Date(),
     sec_diff = ((targetTime.getTime() - currentTime.getTime()) / 1000);

  currentTime.setHours(0, 0, 0, 0);
  targetTime.setHours(0, 0, 0, 0);
  var day_diff = Math.floor((targetTime.getTime() - currentTime.getTime()) / 86400000);

  currentTime.setDate(1);
  targetTime.setDate(1);
  var month_diff = Math.floor((targetTime.getTime() - currentTime.getTime()) / (86400000 * 30)); //just an estimate with 30 day months
  var year_diff = targetTime.getFullYear() - currentTime.getFullYear();

  return sec_diff < 0 && "Conference has started!" ||
    day_diff == 0 &&
    (sec_diff < 60 && "Just now" ||
    sec_diff < 120 && "One minute from now" ||
    sec_diff < 3600 && Math.floor(sec_diff / 60) + " minutes from now" ||
    sec_diff < 7200 && "One hour from now" ||
    sec_diff < 86400 && Math.floor(sec_diff / 3600) + " hours from now") ||
    day_diff < 2 && "One day from now" ||
    day_diff < 30 && day_diff + " days from now" ||
    day_diff < 60 && Math.ceil(day_diff / 7) + " weeks from now" ||
    month_diff == 1 && "A month from now" ||
    month_diff < 12 && month_diff + " months from now" ||
    year_diff == 1 && "A year from now" ||
    year_diff && year_diff + " years from now";
}

// If jQuery is included in the page, adds a jQuery plugin to handle it as well
if (typeof jQuery != "undefined")
  jQuery.fn.prettierFutureDate = function(){
    return this.each(function(){
      var date = prettierFutureDate(this.title);
      if (date)
          jQuery(this).text(date);
  });
};

