dojo.require("dojo.date.locale");
function getRealDate(when, which) {
	if (!when) {
		throw new Error('Must specify a date');
	}
	var base = new Date(2011, 3, 25);
	base.setUTCHours(12);
	base.setUTCMinutes(-2);
	base.setUTCMilliseconds(0);

// c = "Tannorat'h, Ice Moon 12, CR 503"
// t = "Lor, Indigo 15, TR 1571"
// a = "Moku, Shiwasu 12, AR 2334"

	var	newIdx = {},
		parser = new RegExp(/([a-z']+)+, ([a-z ]+) ([0-9]+), (CR|TR|AR)? ?([0-9]+)/i),
		results = parser.exec(when),
		dow = results[1],
		month = results[2],
		day = results[3],
		which = results[4],
		year = results[5],
		which = (which == 'CR' ? 'common' : (which == 'TR' ? 'thorpian' : (which == 'AR' ? 'adachian' : null))),
		idx = {	
			'common': {	'dow': 3, 'month': 11, 'day': 13, 'year': 502, 'abbr': 'CR' },
			'thorpian': { 'dow': 1,	'month': 4, 'day': 10, 'year': 1571, 'abbr': 'TR' },
			'adachian': { 'dow': 3, 'month': 7, 'day': 13, 'year': 2334, 'abbr': 'AR' }
		},
		scale = {
			'common': { 'minute': 1/6, 'hour': 10, 'day': 240, 'month': 3600, 'year': 43200, 'dim': 15 },
			'thorpian': { 'minute': 1/6, 'hour': 10, 'day': 240, 'month': 5760, 'year': 46080, 'dim': 24 },
			'adachian': { 'minute': 1/6, 'hour': 10, 'day': 240, 'month': 3600, 'year': 43200, 'dim': 15 }
		},
		months = {
			'common': ['FrostFlower', 'Ice Moon', 'Wolfmoon', 'Wintersebb', 'Saprise', 'Petalspread', 'Greentide', 'Midsummer', 'Berrymoon', 'Cornripe', 'Harvestmoon', 'Winnowing'],
			'thorpian': ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet', 'Octarine'],
			'adachian': ['Yayoi', 'Uzuki', 'Satsuki', 'Minazuki', 'Fumizuki', 'Hazuki', 'Nagazuki', 'Kannazuki', 'Shimotsuki', 'Shiwasu', 'Mutsuki', 'Kisaragi']
		},
		days = {
			'common': ['Martin', 'Mahasa', "Tannorat'h", 'Anastasia', 'Sulamar', 'Dannika'],
			'thorpian': ['Flic', 'Ic', 'Mla', 'Orl', 'Dri', 'Sic', 'Lor', 'Cim'],
			'adachian': ['Homura', 'Mizu', 'Moku', 'Kane', 'Seki', 'Kuu']
		},
		dim = scale['dim'],
		miy = months.length,
		diw = days.length;

	if (!which) {
		for(var i=0;i<3;i++){
			var type = ['common', 'thorpian', 'adachian'][i];
			if (dojo.indexOf(months[type].concat(days[type]), month) > -1 || dojo.indexOf(months[type].concat(days[type]), day) > -1) {
				which = type;
				break;
			}
		}
	}
	month = dojo.indexOf(months[which], month);
	dow = dojo.indexOf(days[which], dow);
	
	console.debug(which, dow, month, day, year);
	
	// 	start = (base < when ? base : when),
	// 	end = (base < when ? when : base),
	// 	deltas = { 'year':0, 'month':0, 'day':0, 'hour':0, 'minute':dojo.date.difference(start, end, "minute") };
	// 
	// dojo.forEach(['year', 'month', 'day', 'hour'], function(part, idx, arr) {
	// 	var sPart = scale[part];
	// 	deltas[part] = Math.floor(deltas['minute']  / sPart);
	// 	deltas['minute'] %= sPart;
	// });
	// deltas['minute'] = Math.floor(deltas['minute'] / scale['minute']);
	// if (timeOnly) {
	// 	var hour = deltas['hour'],
	// 		min = deltas['minute'];
	// 
	// 	return (hour == 0 ? '0' + hour : hour) + ':' + (min == 0 ? '0' + min : min);
	// }
	// newIdx['day'] = idx['day'] + deltas['day'];
	// deltas['month'] += Math.floor(newIdx['day'] / dim);
	// newIdx['day'] = newIdx['day'] % dim;
	// newIdx['month'] = idx['month'] + deltas['month'];
	// // common and adachian months have 2 patterns for days of week
	// day = (which != 'thorpian' && newIdx['month'] % 2 ? day.slice(3).concat(day.slice(0,3)) : day);
	// newIdx['dow'] = newIdx['day'] % (diw+1);
	// deltas['year'] += Math.floor(newIdx['month'] / miy);
	// newIdx['month'] = newIdx['month'] % miy;
	// newIdx['year'] = idx['year'] +deltas['year'];
	// return day[newIdx['dow']] + ', ' + month[newIdx['month']] + ' ' + newIdx['day'] + ', ' + idx['abbr'] + ' ' + newIdx['year'];
}
function getDartmudDate(which, when) {
	which = which || 'common';
	which = which.toLowerCase();
	if (which !== 'common' && which !== 'thorpian' && which !== 'adachian' && which !== 'time') {
		which = 'common';
	}
	when = when || new Date();
	var base = new Date(2011, 3, 25);
	base.setUTCHours(12);
	base.setUTCMinutes(-2);
	base.setUTCMilliseconds(0);

	var	newIdx = {},
		timeOnly = (which == 'time' ? true : false),
		which = (which == 'time' ? 'common' : which),
		idx = {	
			'common': {	'dow': 3, 'month': 11, 'day': 13, 'year': 502, 'abbr': 'CR' },
			'thorpian': { 'dow': 1,	'month': 4, 'day': 10, 'year': 1571, 'abbr': 'TR' },
			'adachian': { 'dow': 3, 'month': 7, 'day': 13, 'year': 2334, 'abbr': 'AR' }
		}[which],
		scale = {
			'common': { 'minute': 1/6, 'hour': 10, 'day': 240, 'month': 3600, 'year': 43200, 'dim': 15 },
			'thorpian': { 'minute': 1/6, 'hour': 10, 'day': 240, 'month': 5760, 'year': 46080, 'dim': 24 },
			'adachian': { 'minute': 1/6, 'hour': 10, 'day': 240, 'month': 3600, 'year': 43200, 'dim': 15 }
		}[which],
		month = {
			'common': ['FrostFlower', 'Ice Moon', 'Wolfmoon', 'Wintersebb', 'Saprise', 'Petalspread', 'Greentide', 'Midsummer', 'Berrymoon', 'Cornripe', 'Harvestmoon', 'Winnowing'],
			'thorpian': ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet', 'Octarine'],
			'adachian': ['Yayoi', 'Uzuki', 'Satsuki', 'Minazuki', 'Fumizuki', 'Hazuki', 'Nagazuki', 'Kannazuki', 'Shimotsuki', 'Shiwasu', 'Mutsuki', 'Kisaragi']
		}[which],
		day = {
			'common': ['Martin', 'Mahasa', "Tannorat'h", 'Anastasia', 'Sulamar', 'Dannika'],
			'thorpian': ['Flic', 'Ic', 'Mla', 'Orl', 'Dri', 'Sic', 'Lor', 'Cim'],
			'adachian': ['Homura', 'Mizu', 'Moku', 'Kane', 'Seki', 'Kuu']
		}[which],
		dim = scale['dim'],
		miy = month.length,
		diw = day.length,
		start = (base < when ? base : when),
		end = (base < when ? when : base),
		deltas = { 'year':0, 'month':0, 'day':0, 'hour':0, 'minute':dojo.date.difference(start, end, "minute") };
	
	dojo.forEach(['year', 'month', 'day', 'hour'], function(part, idx, arr) {
		var sPart = scale[part];
		deltas[part] = Math.floor(deltas['minute']  / sPart);
		deltas['minute'] %= sPart;
	});
	deltas['minute'] = Math.floor(deltas['minute'] / scale['minute']);
	if (timeOnly) {
		var hour = deltas['hour'],
			min = deltas['minute'];

		return (hour < 10 ? '0' + hour : hour) + ':' + (min < 10 ? '0' + min : min);
	}
	newIdx['day'] = idx['day'] + deltas['day'];
	if (newIdx['day'] > dim) {
		deltas['month'] += Math.floor(newIdx['day'] / dim);
		newIdx['day'] = newIdx['day'] % dim;
	}
	newIdx['month'] = idx['month'] + deltas['month'];
	// common and adachian months have 2 patterns for days of week
	day = (which != 'thorpian' && newIdx['month'] % 2 ? day.slice(3).concat(day.slice(0,3)) : day);
	// console.debug(idx, newIdx, deltas, day);
	newIdx['dow'] = (newIdx['day'] == 0 ? day.length : newIdx['day']-1) % diw;
	deltas['year'] += Math.floor(newIdx['month'] / miy);
	newIdx['month'] = newIdx['month'] % miy;
	newIdx['year'] = idx['year'] +deltas['year'];
	return day[newIdx['dow']] + ', ' + month[newIdx['month']] + ' ' + newIdx['day'] + ', ' + idx['abbr'] + ' ' + newIdx['year'];
}

var cache = {};
function capitalize(word) {
	return word.charAt(0).toUpperCase() + word.slice(1);
}
function update(timeOnly) {
	var formats = ['time', 'common', 'thorpian', 'adachian'];
	formats = (timeOnly ? formats.slice(0,1) : formats);
	dojo.forEach(formats, function(calendar) {
		var current = getDartmudDate(calendar);
		if(!cache[calendar] || cache[calendar] != current) {
			console.debug('updating:', calendar);
			dojo.attr('dm_' + calendar + '_date', 'innerHTML', (calendar != 'time' ? capitalize(calendar) + ' day: ' : 'Time: ') + current);
			cache[calendar] = current;
		}
	});
}
dojo.ready(function() {
	update();
	setInterval(update, 1000);
});
