if (typeof Fox == 'undefined') {
	Fox = {};
}

Fox.Utils = {
	composeDate: function(mysqlTimestamp) {
		var parts = mysqlTimestamp.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
		return new Date(parts[1], parts[2] - 1, parts[3], parts[4], parts[5], parts[6]);
	},
	
	dateFormat: function(format, timestamp) {
		function pad(number) {
			return number.toString().replace(/^([0-9])$/, '0$1');
		}
		var date = new Date(timestamp),
			hours = date.getUTCHours(),
			day = date.getUTCDay(),
			dayOfMonth = date.getUTCDate(),
			month = date.getUTCMonth(),
			fullYear = date.getUTCFullYear(),
			weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
			months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
			
			// list all format keys
			replacements = {
				// Day
				'a': weekdays[day].substr(0, 3), // Short weekday, like 'Mon'
				'A': weekdays[day], // Long weekday, like 'Monday'
				'd': pad(dayOfMonth), // Two digit day of the month, 01 to 31 
				'e': dayOfMonth, // Day of the month, 1 through 31 
				
				// Week (none implemented)			
				
				// Month
				'b': months[month].substr(0, 3), // Short month, like 'Jan'
				'B': months[month], // Long month, like 'January'
				'm': pad(month + 1), // Two digit month number, 01 through 12
				
				// Year
				'y': fullYear.toString().substr(2, 2), // Two digits year, like 09 for 2009
				'Y': fullYear, // Four digits year, like 2009
				
				// Time
				'H': pad(hours), // Two digits hours in 24h format, 00 through 23
				'I': pad((hours % 12) || 12), // Two digits hours in 12h format, 00 through 11
				'l': (hours % 12) || 12, // Hours in 12h format, 1 through 11
				'M': pad(date.getUTCMinutes()), // Two digits minutes, 00 through 59
				'p': hours < 12 ? 'AM' : 'PM', // Upper case AM or PM
				'P': hours < 12 ? 'am' : 'pm', // Lower case AM or PM
				'S': pad(date.getUTCSeconds()) // Two digits seconds, 00 through  59
			};
		
		// do the replaces
		for (var key in replacements) {
			format = format.replace('%' + key, replacements[key]);
		}
			
		return format;
	},
	
	str_replace: function(search, replace, subject, count) {
		indexOfMatch = 0;
		
		if (typeof count == 'undefined') {
			do {
				subject = subject.replace(search, replace);
				indexOfMatch = subject.indexOf(search);
			} while (indexOfMatch != -1)
		} else {
			matchNumber = 0;
			do {
				subject = subject.replace(search, replace);
				matchNumber++;
				indexOfMatch = subject.indexOf(search);
			} while (indexOfMatch != -1 && matchNumber != count)
		}
		
		
		return subject;
	},
}
