/*
 * GeoMOOSE Conversion Date Library
 * (c) 2008 Dan "Ducky" Little
 */


function strfdate(fDate, fFormat) {
	var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
	var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December');

	var formatString = new String(fFormat); /* Convert to string 'in case' */
	var replacementStrings = new Array();

	var currentToken = new String();
	var readToken = false;
	for(var i = 0; i < formatString.length; i++) {
		var currentChar = formatString.substring(i,i+1);
		if(currentChar == '%') { /* Start of format String */
			readToken = true;
			currentToken = new String();
		} else if(readToken) {
			var formatWidth;
			var widthSpecified = currentToken.length != 0;
			if(!widthSpecified) {
				formatWidth = 0;
			} else {
				formatWidth = parseInt(currentToken);
			}
			currentToken += currentChar;

			var dateValue = false;
			if(currentChar == 'M') {
				dateValue = fDate.getMonth() + 1;
			} else if(currentChar == 'D') {
				dateValue = fDate.getDate();
			} else if(currentChar == 'Y') {
				dateValue = fDate.getFullYear();
			} else if(currentChar == 'A') {
				dateValue = days[fDate.getDay()];
			} else if(currentChar == 'B') {
				dateValue = months[fDate.getMonth()];
			} else if(currentChar == 'H') { /* 24 Hour Date */
				dateValue = fDate.getHours() + 1;
			} else if(currentChar == 'I') { /* 12 Hour Date */
				var hours = fDate.getHours() + 1;
				if(hours > 12) { hours -= 12 }
				dateValue = hours;
			} else if(currentChar == 'm') { /* Minutes */
				dateValue = fDate.getMinutes();
			} else if(currentChar == 'S') { /* Seconds */
				dateValue = fDate.getSeconds();
			}

			if(dateValue) {
				var subString = new String(dateValue);
				var strLength = subString.length;
				for(var m = 0; m < formatWidth - strLength; m++) {
					subString = '0'+subString;
				}
				if(formatWidth < strLength && widthSpecified) {
					subString = subString.substring(subString.length - formatWidth);
				}
				replacementStrings['%'+currentToken] = subString;
			}
		} else {
			readToken = false;
		}
	}

	for(var s in replacementStrings) {
		formatString = formatString.replace(s,replacementStrings[s]);	
	}

	return formatString;
}
	
