/*
 * 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(time){

	var curdt = (new Date()).getTime(),
		date = new Date((time || "").replace(/-/g,"/").replace(/[TZ]/g," ")),
		diff = ((curdt - date.getTime()) / 1000);
		//baseline = (curdt/1000) - (((curdt/1000)%86400));
		//hours_diff = (((baseline*1000) - date.getTime()) / 1000)/3600;
		
	if ( isNaN(diff) || diff < 0 )
		return 'just now';
	
	var
		s = diff,
		i = s / 60,
		h = i / 60,
		d = Math.floor((diff/3600) / 24),
		w = d / 7,
		m = d / 30,
		y = m / 12,
		rel_m = Math.ceil( m - (Math.floor(y) * 12) ),
		r = d <= 0 && (
			s < 2 && "just now" ||
			s < 60 && Math.floor(s) + " seconds ago" ||
			i < 2 && "1 minute ago" ||
			h < 1 && Math.floor( i ) + " minutes ago" ||
			h < 2 && "1 hour ago" ||
			h > 2 && Math.floor( h ) + " hours ago"
		) ||
		w < 1 && (dateFormat(date,'dddd') + " at "+ dateFormat(date,'h:MM TT').toLowerCase()) ||
		d < 8 && Math.floor( w ) + " week ago"  ||
		d < 9 && Math.floor( w ) + " week and " + Math.ceil( d - (Math.floor(w) * 7) ) + " day ago"  ||				
		d < 14 && Math.floor( w ) + " week and " + Math.ceil( d - (Math.floor(w) * 7) ) + " days ago"  ||		
		m < 1 && Math.floor( w ) + " weeks ago" ||
		m < 2 && Math.floor( m ) + " month ago" ||
		m < 12 && Math.floor( m ) + " months ago" ||
		m > 12 && Math.floor( y ) + " year" + ((y >= 2)? 's' : '') + " and " + rel_m + " month" + ((rel_m >= 2)? 's' : '') + " ago"
	;
		
	//console.log(' s = ' + s + '\n i = ' + i + '\n h = ' + h + '\n d = ' + d + '\n w = ' + w + '\n m = ' + m + '\n y = ' + y + '\n r = ' + r );
		
	return r;
}

// 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.title);
			if ( date )
				jQuery(this).text( date );
		});
	};

