/*
* 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 prettyDate(e){
  var date = new Date((e.title || "").replace(/-/g,"/").replace(/PST|\/28800/g," ")),
  diff = (((new Date()).getTime() - date.getTime()) / 1000),
  day_diff = Math.floor(diff / 86400);

  if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 31 ){
    return;
  }

  if(day_diff < 1){
    if(diff < 30){
      smartUpdate(e,5);
      return "just now";
    }else if(diff < 60){
      smartUpdate(e,30);
      return "a moment ago";
    }else if(diff < 120){
      smartUpdate(e,30);
      return "1 minute ago";
    }else if(diff < 3600){ 
      smartUpdate(e,60);
      return Math.floor( diff / 60 ) + " minutes ago";
    }else if(diff < 7200){ 
      smartUpdate(e,3600);
      return "1 hour ago";
    }else if(diff < 86400){ 
      smartUpdate(e,7200);
      return Math.floor( diff / 3600 ) + " hours ago";
    }
  }else if(day_diff==1){
    smartUpdate(e,86400);
    return "Yesterday";
  }else if(day_diff < 7){
    smartUpdate(e,86400);
    return day_diff + " days ago";
  }else if(day_diff < 31){
    smartUpdate(e,7*86400);
    return Math.ceil( day_diff / 7 ) + " weeks ago";
  }else{
    return;
  }
}

function smartUpdate(e,updateIn){
  setTimeout(function(){ $(e).prettyDate(); }, updateIn*1000);
}

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