﻿

// Converts any links in text to valid URLs
function urlToLink(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp,"<a href='$1'>$1</a>");
}

// Converts time into a relative time
function relTime(time) {
    var date = new Date(time), diff = (((new Date()).getTime() - date.getTime()) / 1000), day_diff = Math.floor(diff / 86400);
	if (day_diff == 0) {
	    if (diff < 60) return "just now";
	    else if (diff < 120) return "1 minute ago";
	    else if (diff < 3600) return Math.floor(diff / 60) + " minutes ago";
	    else if (diff < 7200) return "1 hour ago";
	    else return Math.floor(diff / 3600) + " hours ago";
	}
	else if (day_diff == 1) return "Yesterday";
	else if (day_diff < 7) return day_diff + " days ago";
	else return Math.ceil(day_diff / 7) + " weeks ago";
}

/* setInputField
*  sets the input field's (identified by id) default value to defvalue and its initial value to initvalue (which may or not be present in which case initvalue = defvalue)
*  and also sets up the focus and blur events to clear the input field and return to its default setting respectively, depending on the contents of the field at the time. 
*/
function setInputField(initialise, id, defvalue, initvalue) {
    if ((typeof (initvalue) == "undefined") || (initvalue == "")) initvalue = defvalue;
    var field = "#" + id;
    if (initialise == true) $(field).val(initvalue);
    else $(field).val($(field).val() == "" ? defvalue : $(field).val());
    $(field).addClass('greyed');
    $(field).focus(function () { $(field).val($(field).val() == defvalue ? "" : $(field).val()); $(field).removeClass('greyed'); });
    $(field).blur(function () { $(field).val($(field).val() == "" ? defvalue : $(field).val()); $(field).addClass('greyed'); });
}
