

Array.prototype.implode = function(separator, start, length) {
	if (start === undefined) start = 0;
	var end = start + length - 1;
	var output = "";
	for (var i = start; i <= end; i++) {
		output += (i == start ? "" : separator) + this[i];
	}
	return output;
}

Date.prototype.difference = function(anotherDate) {
	return (anotherDate.getTime() - this.getTime());
};

Date.prototype.getElapsedHours = function() {
	return Math.floor(this.getTime() / 3600000);
}

Date.prototype.daysDifference = function(anotherDate) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24;

    // Convert both dates to milliseconds
    var date1_ms = this.getTime();
    var date2_ms = anotherDate.getTime();

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms);

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY);
}

Date.prototype.format = function(format) {
	var tokens = format.match(/((.)\2*)/g);
	for (var i = 0; i < tokens.length; i++) {
		var replace;
		switch (tokens[i].charAt(0)) {
			case "H":
				replace = this.getUTCHours();
				break;
			case "M":
				replace = this.getUTCMinutes();
				break;
			case "S":
				replace = this.getUTCSeconds();
				break;
			case "U":
				replace = this.getUTCMilliseconds();
				break;
			case "h":
				replace = sprintf("%0" + tokens[i].length + "s", this.getUTCHours()).substr(-tokens[i].length);
				break;
			case "m":
				replace = sprintf("%0" + tokens[i].length + "s", this.getUTCMinutes()).substr(-tokens[i].length);
				break;
			case "s":
				replace = sprintf("%0" + tokens[i].length + "s", this.getUTCSeconds()).substr(-tokens[i].length);
				break;
			case "u":
				replace = sprintf("%0" + tokens[i].length + "s", this.getUTCMilliseconds()).substr(-tokens[i].length);
				break;
			default:
				replace = tokens[i];
				break;
		}
		tokens[i] = tokens[i].replace(tokens[i], replace);
    }
	return tokens.join("");
}

var FontUtils = {

	maxCharWidth: function(fontFamily, fontSize) {
		var testDiv = $(document.createElement('span'));
		testDiv.css("position", "fixed");
		testDiv.css("visibility", "hidden");
		testDiv.css("margin", 0);
		testDiv.css("padding", 0);
		testDiv.css("font-family", fontFamily);
		testDiv.css("font-size", fontSize);
		$('body').append(testDiv);

		var i, width, maxCharWidth = 0;
		var chars = ((arguments.length === 3) ? arguments[2] : "0123456789");
		for (i = 0; i < chars.length; i++) {
			testDiv.text(chars.charAt(i));
			width = testDiv.width();
			if (width > maxCharWidth) {
				maxCharWidth = width;
			}
		}
		return maxCharWidth;
	}

};
