// date formatting function
Date.DEFAULT_FORMAT = 'd/m/Y';

// get the minutes with leading zeros
Date.prototype.getFullMinutes = function() {
	var dateMinutes = this.getMinutes();
	if (dateMinutes < 10) {
		dateMinutes = '0' + new String(dateMinutes);
	}

	return dateMinutes;
}

// get the hours with leading zeros
Date.prototype.getFullHours = function() {
	var dateHours = this.getHours();
	if (dateHours < 10) {
		dateHours = '0' + new String(dateHours);
	}

	return dateHours;
}

// get the day with leading zeros
Date.prototype.getFullDate = function() {
	var dateDay = this.getDate();
	if (dateDay < 10) {
		dateDay = '0' + new String(dateDay);
	}

	return dateDay;
}

// get the month with leading zeros
Date.prototype.getFullMonth = function() {
	var dateMonth = this.getMonth() + 1;
	if (dateMonth < 10) {
		dateMonth = '0' + new String(dateMonth);
	}

	return dateMonth;
}

// formats a date according to the specified format
Date.prototype.getFormattedDate = function(format) {
	if (format == null) {
		format = Date.DEFAULT_FORMAT;
	}

	// dd = day (0..31)
	// mm = month name (0..12)
	// yy = 4-digit year
	var tokens = {};
	tokens.i = "getFullMinutes";
	tokens.H = "getFullHours";
	tokens.d = "getFullDate"
	tokens.m = "getFullMonth";
	tokens.Y = "getFullYear";

	// copy the format to a new string object
	var formattedDate = format;
	
	// replace each token by %%token%% for further replacements
	for (var token in tokens) {
		formattedDate = formattedDate.replace(
			new RegExp(token, 'g'),
			"%%" + token + "%%"
		);
	}

	// now replace each %%token%% by its meaning by calling the appopriate
	// function on the current date object
	for (token in tokens) {
		formattedDate = formattedDate.replace(
			new RegExp("%%" + token + "%%", 'g'),
			eval("this." + tokens[token] + "()")
		);
	}

	return formattedDate;
}

// passes a date from dd/mm/yyyy to mm/dd/yyyy format
Date.toCanonicalFormat = function(oldDate) {
	var dateParts = oldDate.split('/');
	return dateParts[1] + '/' + dateParts[0] + '/' + dateParts[2];
}

// input the number of days between 2 dates
Date.prototype.daysBetween = function( pastDate ) {
	var diff        = this.getTime() - pastDate.getTime();
	var daysBetween = Math.floor(diff / (1000 * 60 * 60 * 24) );
	return daysBetween;
}

// parses a UTC date and returns a local date object
Date.fromUTC = function(UTCString) {
	// first convert the string to a UTC date
	var UTCDate   = new Date( Date.parse(UTCString) );

	// then convert to the client's local date
	var localDate = new Date( Date.UTC(
		UTCDate.getFullYear(),
		UTCDate.getMonth(),
		UTCDate.getDate(),
		UTCDate.getHours(),
		UTCDate.getMinutes()
	));

	return localDate;
}

Date.fromUnixTimestamp = function(unixTimestamp) {
	return new Date(unixTimestamp * 1000);
}
