// A file full of small functions for taking care of small task

// Takes the unix epoch time in MILLISECONDS and converts it to the format 
// n hour/s n minute/s ago. There's a good example of it in action at 
// http://www.abc.net.au/news/justin/ 
// The other parameter specifies whether to use short or long time units
// pass in true for short and false (or nothing) for full length
// Originally written by Andrew Kesper
// Modified by Jim Whimpey
function timeSince(ts, shortWords, agoBool) {
	
	if (typeof shortWords == "undefined") var shortWords = false;
	
	var ago = "";
	(typeof agoBool == "undefined" || agoBool == true) ? ago = " ago" : ago = "";
	
	var date = window.servertimestamp;
	var time = date.getTime();
	var sec = (time-ts)/1000;
	
	// Working out the unit names
	var stringSec = (shortWords) ? "sec" : "second";
	var stringMin = (shortWords) ? "min" : "minute";
	var stringHr = (shortWords) ? "hr" : "hour";
	
	if (sec < 0) {
		time = '';
	} else if (sec <= 60) {
		var seconds = Math.floor(sec);
		time = seconds+' ' + stringSec +(seconds==1 ? '' : 's');
	} else if (sec <= 60*60) {
		var minutes = Math.floor(sec/60);
		time = minutes+' '+ stringMin + (minutes==1 ? '' : 's');
	} else if (sec <= 60*60*24) {
		var hours = Math.floor(sec/60/60);
		var minutes = Math.floor(sec/60)%60;
		time = hours+' ' + stringHr +(hours==1 ? '' : 's')+' '+minutes+' ' + stringMin +(minutes==1 ? '' : 's');
	} else {
		var days = Math.floor(sec/60/60/24);
		var hours = Math.floor(sec/60/60)%24;
		time = days+' day'+(hours==1 ? '' : 's')+' '+hours+' '+ stringHr +(hours==1 ? '' : 's');
	}
	if (time == '') { return ''; } else { return time + ago; }
}

// Takes a string, looks for URLs within that string, converts them 
// to HTML anchors and returns the whole block of text. Taken from:
// http://stackoverflow.com/questions/37684/replace-url-with-html-links-javascript
function replaceURLWithHTMLLinks(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>"); 
}