/**
 * Converts the date object into a string. The format of the string
 * returned is "dd-mm-yyyy hh:mm [am|pm]"
 * 
 * NOTE That the "dd/mm/yyyy" format causes problems (to RoR, to the DB??)
 * a = Accommodation.new
 * a.available_from.to_s => "2007-09-05"
 * a.available_from = "05/09/2007"
 * a.available_from.to_s => "2007-05-09" OOPS
 * a.available_from = "05-09-2007"
 * a.available_from.to_s => "2007-09-05" OK
 * 
 * @param {Boolean} include_time
 * @return The Date object as a formatted string
 */
Date.prototype.toFormattedString = function(include_time) {
	str = Date.padded2(this.getDate()) + "-" + Date.padded2(this.getMonth() + 1) + "-" + this.getFullYear();

  	if (include_time) { 
		hour=this.getHours(); 
		str += " " + this.getAMPMHour() + ":" + this.getPaddedMinutes() + " " + this.getAMPM() 
	}

	return str;
};

/**
 * Parses the date string from the input field 
 * in order to construct the calendar.
 * 
 * @param {String} string
 * @return A Date object representing the given string
 */
Date.parseFormattedString = function(string) {
	var regexp = "([0-9]{2})(-([0-9]{2})(-([0-9]{4})" +
	  "( ([0-9]{1,2}):([0-9]{2})? *(pm|am)" +
	  "?)?)?)?";
	var d = string.match(new RegExp(regexp, "i"));
	if (d == null) return Date.parse(string); // at least give javascript a crack at it.
	
	var offset = 0;
	var date = new Date(d[5], 0, 1);
	if (d[3]) { date.setMonth(d[3] - 1); }
	if (d[1]) { date.setDate(d[1]); }
	if (d[7]) {
		hours = parseInt(d[7]);
		offset = 0;
		is_pm = (d[9].toLowerCase() == "pm")
		if (is_pm && hours <= 11) hours += 12;
		if (!is_pm && hours == 12) hours = 0;
		date.setHours(hours);
	}
	if (d[8]) { date.setMinutes(d[8]); }
	if (d[10]) { date.setSeconds(d[10]); }
	if (d[12]) { date.setMilliseconds(Number("0." + d[12]) * 1000); }
	if (d[14]) {
		offset = (Number(d[16]) * 60) + Number(d[17]);
		offset *= ((d[15] == '-') ? 1 : -1);
	}
	
	return date;
};