var sTwitterName = 'stevenspass';
var sFacebookName = 'stevenspass';
var iFacebookPhotoAlbumID = '492344070597';
var iFeedsToGet = 2;
var iFeedsRetrieved = 0;
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
var chatterArray = new Array();
var iChatterIndex = 0;
var iChatterCount = 0;
var iChatterPages = 0;
var iCurrentChatterPage = 0;
var iChatterItemsPerPage = 4;
var heightContainerInterval;
var iHeroIndex = 0;	
var bOkToClick = false;

$(function(){
	$('#heroInfoBubble .caption').text(caption);
	$('#heroInfoBubble .credits').text(credits);
			
	bOkToClick = true;
	$('.heroPrev').click(showPrevHero);
	$('.heroNext').click(showNextHero);

	$('#hero-loading').hide();
	$('.heroPrev').show();
	$('.heroNext').show();
	
	$('#heroInfoIcon').click(function() {
		var $heroInfoBubble = $('#heroInfoBubble');
		if ($heroInfoBubble.hasClass('visible')) {
			$heroInfoBubble.removeClass('visible');
			$heroInfoBubble.fadeOut('fast');
		}
		else {
			$heroInfoBubble.addClass('visible');
			$heroInfoBubble.fadeIn('fast');
		}
	});	
	$('.showHideContent').click(function() {
		if ($('#heroInfoIcon').hasClass('minimized')) {
			$('#heroInfoIcon').removeClass('minimized');
		}
		else {
			$('#heroInfoIcon').addClass('minimized');
		}
		showHideContentArea(500);
	});	
	
	$('#homepageWeatherPlus').click(function() {
		$('#homepageWeatherPopup').toggle();
	});


	$('#hoursDiv').click(function() {
		$('#hoursPopup').toggle();
	});	

	// homepage Promos
	if ($('#homepagePromo').length > 0) {
		$('#homepagePromoNext').click(function(){
			clearInterval(intervalHomePromos);
			showNextPromoPage();
		});	
		
		$('#homepagePromoPrev').click(function(){
			clearInterval(intervalHomePromos);
			showPrevPromoPage();
		});		
		
		if ( $('#homepagePromo li').length > 1 ) {
			$('#homepagePromoCount .total').html( $('#homepagePromo li').length );
			$('#homepagePromoNav').show();
		} else {
			$('#homepagePromoNav').hide();
		}
				
		// start homepage promo rotation
		intervalHomePromos = setInterval('showNextPromoPage();', 7000);
	}
	
	// facebook widget
	$('#facebookFacepile').html('<iframe src="http://www.facebook.com/plugins/likebox.php?href=http%3A%2F%2Fwww.facebook.com%2Fstevenspass&amp;width=295&amp;colorscheme=light&amp;connections=15&amp;stream=false&amp;header=false&amp;height=318" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:295px; height:318px;" allowTransparency="true"></iframe>');
	
	// facebook photos
	$.ajax({
		url: sAppPath  + '/SiteBase/includes/feedHandler.ashx?feedName=fbphotos&feedUrl=http://graph.facebook.com/' + iFacebookPhotoAlbumID + '/photos',
		dataType: 'json',
		success: function(data) {
			createSnaps(data);
		},
		error: function(request, status, errorMsg) {
			//alert("error retrieving photos " + errorMsg);
		}
	});	
	// twitter feed
	$.ajax({
		url: sAppPath + '/SiteBase/includes/feedHandler.ashx?feedName=twitter&feedUrl=http://twitter.com/statuses/user_timeline/' + sTwitterName + '.json',
		dataType: 'json',
		success: function(data) {
			iFeedsRetrieved++;
			createChatterObjects(data, 'twitter');
		},
		error: function(request, status, errorMsg) {
			//alert("error retrieving twitter " + errorMsg);
		}
	});
	// facebook feed
	$.ajax({
		url: sAppPath + '/SiteBase/includes/feedHandler.ashx?feedName=fbfeed&feedUrl=http://graph.facebook.com/' + sFacebookName + '/posts',
		dataType: 'json',
		success: function(data) {
			iFeedsRetrieved++;
			createChatterObjects(data, 'facebook');
		},
		error: function(request, status, errorMsg) {
			//alert("error retrieving facebook " + errorMsg);
		}
	});	
	

		
});

function showNextPromoPage() {
	var $current = ($('#homepagePromo li.active'));
	var $next = $current.next();
	if (!$next.length) $next = $('#homepagePromo li:first');
	
	$next.fadeIn('slow');		
	$next.addClass('active');
	$current.hide();
	$current.removeClass('active')

	$('#homepagePromoCount .showing').html( $('#homepagePromo li').index($next)+1 );
}

function showPrevPromoPage() {
	var $current = ($('#homepagePromo li.active'));
	var $next = $current.prev();
	if (!$next.length) $next = $('#homepagePromo li:last');
	
	$next.fadeIn('slow');		
	$next.addClass('active');
	$current.hide();
	$current.removeClass('active')
	
	$('#homepagePromoCount .showing').html( $('#homepagePromo li').index($next)+1 );
}

function createSnaps(data) {
	$('#loadingSnaps').hide();
	// just grab the first 12 photos for now. Long-term add pagination like we did for chatter
	var photos = data.data.reverse().slice(0, 12);
	var template = $('#homepageSnaps .thumbnail');
	$.each(
		$(photos),
		function(pIndex, pItem) {
			var smallImage = pItem.images[3];
			var largeImage = pItem.images[0];

			var thumbContainer = $(template).clone();
			var thumbLink = $(thumbContainer).find('.thumbnailLink');
			$(thumbLink).attr('href', largeImage.source);
			$(thumbLink).attr('rel', 'snaps');
			$(thumbContainer).find('.thumbnailImg').attr('src', smallImage.source);

			$('#divSnaps').append($(thumbContainer));
			$(thumbContainer).fadeIn('fast');
		}
	);
	$('#divSnaps a.thumbnailLink').fancybox();
}

function showNextHero() {
	if (bOkToClick) {
		bOkToClick = false;
		iHeroIndex++;
		if (iHeroIndex > heroImgs.length - 1) {
			iHeroIndex = 0;
		}
		updateHero();
	}
}
function showPrevHero() {
	if (bOkToClick) {
		bOkToClick = false;
		iHeroIndex--;
		if (iHeroIndex < 0) {
			iHeroIndex = heroImgs.length - 1;
		}
		updateHero();
	}
}

function updateHero() {
	/*
	$('.heroPrev').unbind('click');
	$('.heroNext').unbind('click');

	
	var oldBgImage = $('.bgImage');
	var newBgImage = $(oldBgImage).clone();
	$(newBgImage).css('z-index', 1);
	var img = $(newBgImage).find('img.hero');
	$(img).remove();
	var newImg = $('<img></img>');
	$(newImg).addClass('hero');
	$(newImg).show();
	$(newImg).load(function() {
		$(oldBgImage).fadeOut(700, function() {
			$(this).remove();
			$(newBgImage).css('z-index', 3);
			$('#heroInfoBubble .caption').text(heroImgs[iHeroIndex].caption);
			$('#heroInfoBubble .credits').text(heroImgs[iHeroIndex].credits);

			$('.heroPrev').click(showNextHero);
			$('.heroNext').click(showPrevHero);
				
		});
	});
	$(newBgImage).append($(newImg));
	$('.bgWrap').append($(newBgImage));
	$(newImg).attr('src', heroImgs[iHeroIndex].img);
	*/
	$('#hero-loading').show();
	
	var oldBgImage = $('.bgImage');
	var newBgImage = $(oldBgImage).clone();
	$(newBgImage).css('z-index', 5);
	var img = $(newBgImage).find('img.hero');
	$(img).remove();
	var newImg = $('<img></img>');
	$(newImg).addClass('hero');
	$(newImg).load(function() {
		$(oldBgImage).fadeOut(700, function() {
			$(this).remove();
			$(newBgImage).css('z-index', 10);
			$('#heroInfoBubble .caption').text(heroImgs[iHeroIndex].caption);
			$('#heroInfoBubble .credits').text(heroImgs[iHeroIndex].credits);
			//$('.heroPrev').click(showNextHero);
			//$('.heroNext').click(showPrevHero);
			bOkToClick = true;
			$('#hero-loading').hide();
		});
	});
	$(newBgImage).append($(newImg));
	$('.bgWrap').append($(newBgImage));
	$(newImg).attr('src', heroImgs[iHeroIndex].img);
}

$(window).bind('resize', function() {
	if ($('#heroInfoIcon').hasClass('minimized')) {
		showHideContentArea(0);
	}
});

function showHideContentArea(duration) {

	var paginationTop;
	var iconTop;
	var bubbleTop;
	var revealText = "View full image";
	
	if ($('#heroInfoIcon').hasClass('minimized')) {

		contentTop = $(window).height() - 6;
		iconTop = $(window).height() - 30;
		bubbleTop = $(window).height() - 130;
		revealText = "Return to content";
		paginationTop = ($(window).height() - $('#heroPagination').height()) / 2;
		$('#galleryBox').css('visibility','hidden');
		$('#footer').fadeOut(duration);
		$('#logoBar').fadeOut(duration);
		$('#contentDivOuterHomepage').fadeOut(duration, function() {
			$('#heroInfoIcon').animate({
				top:iconTop
			}, duration);
			$('#heroInfoBubble').animate({
				top:bubbleTop
			}, duration, function() {
				$('.showHideContent').text(revealText);
			});
			$('#heroPagination').animate({
				top:paginationTop
			}, duration);
		});
	}
	else {
	
		paginationTop = 215;
		iconTop = 342;
		bubbleTop = 243;
		
		$('#logoBar').fadeIn(duration);
		$('#heroInfoIcon').animate({
			top:iconTop
		}, duration, function() {
			$('#contentDivOuterHomepage').fadeIn(duration, function() {
				$('#galleryBox').css('visibility','visible');
			});
			$('#footer').fadeIn(duration);
		});
		$('#heroInfoBubble').animate({
			top:bubbleTop
		}, duration, function() {
			$('.showHideContent').text(revealText);
		});
		$('#heroPagination').animate({
			top:paginationTop
		}, duration);
		
	}
}

function setChatterHeight(container) {
	$(container).fadeIn('fast', function() {
		var newHeight = $(this).height();
		$('#homepageChatterPosts').animate({
			height: newHeight
		}, 'fast');
	});
}

function updateChatterPagination() {
	$('#homepageChatterCount .showing').html(eval(iCurrentChatterPage + 1));
	if (iCurrentChatterPage > 0) {
		$('#homepageChatterPrev').show();
	} else {
		$('#homepageChatterPrev').hide();
	}
	if (iCurrentChatterPage < iChatterPages - 1) {
		$('#homepageChatterNext').show();
	} else {
		$('#homepageChatterNext').hide();
	}
	updateChatter();
}

function bindChatterPagination() {
	$('#homepageChatterPrev').click(function() {
		iCurrentChatterPage--;
		iChatterIndex = iCurrentChatterPage * iChatterItemsPerPage;
		updateChatterPagination();
	});
	$('#homepageChatterNext').click(function() {
		iCurrentChatterPage++;
		iChatterIndex = iCurrentChatterPage * iChatterItemsPerPage;
		updateChatterPagination();
	});
}
// need a special parse date function for IE
function parseDate(str) {
  var v=str.split(' ');
  return new Date(Date.parse(v[1]+" "+v[2]+", "+v[5]+" "+v[3]+" UTC"));
} 

function createChatterObjects(data, socialType) {
	if (socialType == 'twitter') {
		$.each(
			$(data),
			function(tIndex, tItem) {
				var t = {
					"socialType": socialType,
					"created": parseDate(tItem.created_at),
					"description": ify.clean(tItem.text).replace(/<a href/gi, '<a target="_blank" href'),
					//"relativeTime": relative_time(tItem.created_at),
					"relativeTime": new Date(tItem.created_at).toRelativeTime(),
					"postId": tItem.id,
					"tweet": tItem.text
				};
				chatterArray.push(t);
			}
		);
	}
	else {
		// facebook has potentially a lot more data points
		$.each(
			$(data.data),
			function(fIndex, fItem) {
				var newCreated = new Date(formatFBTime(fItem.created_time));
				var f = {
					"socialType": socialType,
					"created": newCreated,
					"message": ify.clean(fItem.message).replace(/<a href/gi, '<a target="_blank" href'),
					//"message": fItem.message,
					//"relativeTime": relative_time(dateFormat(newCreated, 'ddd mmm dd HH:MM:ss +0000 yyyy', false)),
					"relativeTime": newCreated.toRelativeTime(),
					"picture": fItem.picture,
					"link": fItem.link,
					"name": fItem.name,
					"source": fItem.source,
					"type": fItem.type,
					"likes": fItem.likes,
					"caption": fItem.caption,
					"description": fItem.description,
					"postId": fItem.id.split("_")[1] // the id value contains the ID of the user/page + the id of the post, e.g. 30213905597_103716613032151
				};

				if (fItem.type == 'video' && fItem.properties != undefined && fItem.properties.text != undefined) {
					f.length = fItem.properties.text;
				}
				chatterArray.push(f);
			}
		);
	}
	
	// finally, if we're done, build the content on the screen
	if (iFeedsRetrieved == iFeedsToGet) {
		buildChatter();
	}
}
function cleanFbLinks(t) {
	return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
		return '<a href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
	});
}
function buildChatter() {
	// sort
	chatterArray.sort(function(a, b) {
		var dateA = new Date(a.created);
		var dateB = new Date(b.created);
		if (dateA.valueOf() > dateB.valueOf()) return -1;
		if (dateA.valueOf() < dateB.valueOf()) return 1;
		return 0;
	});
	iChatterCount = chatterArray.length;
	iChatterPages = Math.ceil(iChatterCount / iChatterItemsPerPage);
	$('#homepageChatterCount .total').html(iChatterPages);
	bindChatterPagination();
	updateChatterPagination();
}

function updateChatter() {
	$('#homepageChatterNav').show();
	$('#homagepageChatterLoading').hide();
	clearInterval(heightContainerInterval);
	var subChatter = chatterArray.slice(iChatterIndex, iChatterIndex + iChatterItemsPerPage);
	var template = $('#homepageChatterPosts .blogPostContainer.template');
	var subContainer = $('<div></div>');
	$(subContainer).addClass('subContainer');
	$(subContainer).hide();
	// remove old ones
	$('#homepageChatterPosts .subContainer').fadeOut('fast', function() {
		$.each(
			$(subChatter),
			function(sIndex, item) {
				var description = item.description;
				var pubDate = item.created;
				// clone our template
				var newBlog = $(template).clone();
				$(newBlog).removeClass('template');
//				$(newBlog).find('img.socialIcon').attr('src', '/images/' + item.socialType + '.png');
				$(newBlog).find('.relativeTime').text(item.relativeTime);
				if (item.socialType == 'twitter') {
					$(newBlog).find('.tweet').html(description);
					$(newBlog).find('.relativeTime').attr('href', 'http://twitter.com/#!/' + sTwitterName + '/status/' + item.postId);
					$(newBlog).find('.twReply').attr('href', 'http://twitter.com/?status=@' + sTwitterName + '%20&in_reply_to_status_id=' + item.postId + '&in_reply_to=' + sTwitterName);
					$(newBlog).find('.twRetweet').attr('href', 'http://twitter.com/?status=RT%20@' + sTwitterName + '%20' + item.tweet + '&in_reply_to_status_id=' + item.postId + '&in_reply_to=' + sTwitterName);
					$(newBlog).find('.fbContent').remove();
				}
				else {
					// this is facebook, capable of several different types of content
					// first, hide the twitter stuff
					$(newBlog).find('.twReply').remove();
					$(newBlog).find('.twRetweet').remove();
					$(newBlog).find('.middot').remove();
					$(newBlog).find('.relativeTime').attr('href', 'http://www.facebook.com/' + sFacebookName + '/posts/' + item.postId);
					$(newBlog).find('.message').html(item.message);
					if (item.picture != null && item.picture != '') {
						$(newBlog).find('img.fbImage').attr('src', item.picture);
					}
					else {
						$(newBlog).find('img.fbImage').remove();
					}
					switch (item.type) {
						case "link":
							$(newBlog).find('.fbContent').addClass('fbLink');
							$(newBlog).find('.fbHyperlink').attr('href', item.link);
							$(newBlog).find('.fbImageLink').attr('href', item.link);
							$(newBlog).find('.fbHyperlink').text(item.name);
							$(newBlog).find('.fbCaption').html(item.caption);
							$(newBlog).find('.fbDescription').html(item.description);
							break;
						case "photo":
							$(newBlog).find('.fbContent').addClass('fbPhoto');
							$(newBlog).find('.fbImageLink').attr('href', item.link);
							break;
						case "video":
							var vidLink = $(newBlog).find('.fbImageLink');
							// http://www.facebook.com/v/781646836503
							if (item.source.indexOf('vimeo') > -1 || item.source.indexOf('youtube') > -1) {
								$(vidLink).attr('href', item.source);
							}
							else {
								$(vidLink).attr('href', 'http://www.facebook.com/v/' + item.postId);
							}
							$(vidLink).fancybox({
								'titleShow': false,
								'transitionIn': 'elastic',
								'transitionOut': 'elastic',
								'href': this.href,
								'type': 'swf',
								'swf': { 'wmode': 'transparent', 'allowfullscreen': 'true' }
							});
							break;
						case "status":
							$(newBlog).find('.fbContent').remove();
							break;
					}
				}
				$(newBlog).find('.blogDateMonth').text(dateFormat(pubDate, 'mmm'));
				$(newBlog).find('.blogDateDay').text(dateFormat(pubDate, 'd'));
				$(newBlog).show();
				$(subContainer).append($(newBlog));
			}
		);
		$(this).remove();
		$('#homepageChatterPosts').append($(subContainer));
		setChatterHeight($(subContainer));

		// in case the images haven't finished loading, set an interval to ensure we end up with the correct height eventually
		heightContainerInterval = setInterval(function() {
			setChatterHeight($(subContainer));
		}, 1000);
	});
}

window.ify = function() {
	var entities = {
		'"': '&quot;',
		'&': '&amp;',
		'<': '&lt;',
		'>': '&gt;'
	};

	return {
		"link": function(t) {
			return t.replace(/[a-z]+:\/\/[a-z0-9-_]+\.[a-z0-9-_:~%&\?\/.=]+[^:\.,\)\s*$]/ig, function(m) {
				return '<a href="' + m + '">' + ((m.length > 25) ? m.substr(0, 24) + '...' : m) + '</a>';
			});
		},
		"at": function(t) {
			return t.replace(/(^|[^\w]+)\@([a-zA-Z0-9_]{1,15})/g, function(m, m1, m2) {
				return m1 + '@<a href="http://twitter.com/' + m2 + '">' + m2 + '</a>';
			});
		},
		"hash": function(t) {
			return t.replace(/(^|[^\w'"]+)\#([a-zA-Z0-9_]+)/g, function(m, m1, m2) {
				return m1 + '#<a href="http://search.twitter.com/search?q=%23' + m2 + '">' + m2 + '</a>';
			});
		},
		"clean": function(tweet) {
			if (tweet != undefined && tweet != '') {
				return this.hash(this.at(this.link(tweet))).replace('\n', '<br />');
			}
			else {
				return "";
			}
		}
	};
} ();
function relative_time(time_value) {
	// Tue Feb 01 12:44:15 +0000 2011
	var values = time_value.split(" ");
    var parsed_date = Date.parse(values[1] + " " + values[2] + ", " + values[5] + " " + values[3]);
	var date = new Date(parsed_date);
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	var r = '';
	
	function formatTime(date) {
		var hour = date.getHours(),
                min = date.getMinutes() + "",
                ampm = 'AM';

		if (hour == 0) {
			hour = 12;
		} else if (hour == 12) {
			ampm = 'PM';
		} else if (hour > 12) {
			hour -= 12;
			ampm = 'PM';
		}

		if (min.length == 1) {
			min = '0' + min;
		}

		return hour + ':' + min + ' ' + ampm;
	}

	function formatDate(date) {
		var ds = date.toDateString().split(/ /),
                mon = months[date.getMonth()],
                day = date.getDate() + '',
                dayi = parseInt(day),
                year = date.getFullYear(),
                thisyear = (new Date()).getFullYear(),
                th = 'th';

		// anti-'th' - but don't do the 11th, 12th or 13th
		if ((dayi % 10) == 1 && day.substr(0, 1) != '1') {
			th = 'st';
		} else if ((dayi % 10) == 2 && day.substr(0, 1) != '1') {
			th = 'nd';
		} else if ((dayi % 10) == 3 && day.substr(0, 1) != '1') {
			th = 'rd';
		}

		if (day.substr(0, 1) == '0') {
			day = day.substr(1);
		}

		return mon + ' ' + day + th + (thisyear != year ? ', ' + year : '');
	}

	delta = delta + (relative_to.getTimezoneOffset() * 60);
	//alert(date + " ::: " + relative_to + " ::: delta:" + delta);

	if (delta < 5) {
		r = 'less than 5 seconds ago';
	} else if (delta < 30) {
		r = 'half a minute ago';
	} else if (delta < 60) {
		r = 'less than a minute ago';
	} else if (delta < 120) {
		r = '1 minute ago';
	} else if (delta < (45 * 60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if (delta < (2 * 90 * 60)) { // 2* because sometimes read 1 hours ago
		r = 'about 1 hour ago';
	} else if (delta < (24 * 60 * 60)) {
		r = 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else {
		if (delta < (48 * 60 * 60)) {
			r = formatTime(date) + ' yesterday';
		} else {
			r = formatTime(date) + ' ' + formatDate(date);
			// r = (parseInt(delta / 86400)).toString() + ' days ago';
		}
	}

	return r;
}
function formatFBTime(fbDate) {
	//2010-11-29T17:23:24+0000
	var arrDateTime = fbDate.split("T");
	var strTimeCode = arrDateTime[1].substring(0, arrDateTime[1].indexOf("+"));

	var arrDateParts = arrDateTime[0].split("-");
	var year = arrDateParts[0];
	var month = parseInt(arrDateParts[1] - 1);
	var day = arrDateParts[2];
	
	//var valid_date = new Date(arrDateTime[0]);
	//var valid_date = new Date(year, month, day);
	
	
	var valid_date = new Date();
	valid_date.setUTCFullYear(year);
	valid_date.setUTCMonth(month);
	valid_date.setUTCDate(day);
	
	var arrTimeCode = strTimeCode.split(":");
	valid_date.setUTCHours(arrTimeCode[0]);
	valid_date.setUTCMinutes(arrTimeCode[1]);
	valid_date.setUTCSeconds(arrTimeCode[2]);
	
	/*
	var valid_date = new Date();
	valid_date.setFullYear(year);
	valid_date.setMonth(month);
	valid_date.setDate(day);
	
	var arrTimeCode = strTimeCode.split(":");
	valid_date.setHours(arrTimeCode[0]);
	valid_date.setMinutes(arrTimeCode[1]);
	valid_date.setSeconds(arrTimeCode[2]);
	*/
	return valid_date;
}
Date.prototype.toRelativeTime = function(now_threshold) {
  var delta = new Date() - this;

  now_threshold = parseInt(now_threshold, 10);

  if (isNaN(now_threshold)) {
    now_threshold = 0;
  }

  if (delta <= now_threshold) {
    return 'Just now';
  }

  var units = null;
  var conversions = {
    millisecond: 1, // ms    -> ms
    second: 1000,   // ms    -> sec
    minute: 60,     // sec   -> min
    hour:   60,     // min   -> hour
    day:    24,     // hour  -> day
    month:  30,     // day   -> month (roughly)
    year:   12      // month -> year
  };
  var conversions = { millisecond:1 }
/*
  for (var key in conversions) {
    if (delta < conversions[key]) {
      break;
    } else {
      units = key; // keeps track of the selected key over the iteration
      delta = delta / conversions[key];
    }
  }
  */
  delta = delta / 1000;
  var r = "";
  
  if (delta < 5) {
		r = 'less than 5 seconds ago';
	} else if (delta < 30) {
		r = 'half a minute ago';
	} else if (delta < 60) {
		r = 'less than a minute ago';
	} else if (delta < 120) {
		r = '1 minute ago';
	} else if (delta < (45 * 60)) {
		r = (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if (delta < (2 * 90 * 60)) { // 2* because sometimes read 1 hours ago
		r = 'about 1 hour ago';
	} else if (delta < (24 * 60 * 60)) {
		r = 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else {
		if (delta < (48 * 60 * 60)) {
			//r = formatTime(date) + ' yesterday';
			r = dateFormat(this, "h:MM TT") + ' yesterday';
		} else {
			//r = formatTime(date) + ' ' + formatDate(date);
			r = dateFormat(this, "h:MM TT") + ' ' + dateFormat(this, "mmm d");
			// r = (parseInt(delta / 86400)).toString() + ' days ago';
		}
	}

	return r;
  // pluralize a unit when the difference is greater than 1.
  /* 
  delta = Math.floor(delta);
  if (delta !== 1) { units += "s"; }
  return [delta, units, "ago"].join(" ");
  */
};

/*
 * Wraps up a common pattern used with this plugin whereby you take a String
 * representation of a Date, and want back a date object.
 */
Date.fromString = function(str) {
  return new Date(Date.parse(str));
};

