// default settings of some kind should go here for original startup
//October 19, 2006 00:00:00
var event_time = new Date("Fri Aug 08 2008 00:00:00 EDT");
var event_name = "2008 Olympic Games";
var event_smallest_unit = "seconds";

var update_timer = null;

function oncountdownloaded() {
	if (window.widget) {
		var pref_event_time = widget.preferenceForKey(createkey("time"));
		var pref_event_name = widget.preferenceForKey(createkey("name"));
		var pref_event_smallest_unit = widget.preferenceForKey(createkey("smallest"));

		if (pref_event_time)
			event_time = new Date(pref_event_time);

		if (pref_event_name)
			event_name = pref_event_name;

		if (pref_event_smallest_unit)
			event_smallest_unit = pref_event_smallest_unit;

		widget.onhide = stopTimer;
		widget.onshow = startTimer;
	}

	startTimer();
}

function startTimer() {
	if (update_timer)
		return;

	updateTimer();
	update_timer = window.setInterval(updateTimer, 1000);
}

function stopTimer() {
	if (!update_timer)
		return;

	window.clearInterval(update_timer);
	update_timer = null;
}

function updateTimer() {
	var my_time = new Date();
	if (my_time > event_time) {
		document.getElementById('count').innerHTML = "We're Already There!";
		return;
	}

	var dDays    = 0;
	var dHours   = 0;
	var dMintes  = 0;
	var dSeconds = 0;

	var dSeconds = (event_time - my_time) / 1000;
	var dDays = Math.floor(dSeconds / (24*3600));
	dSeconds = Math.floor(dSeconds % (24*3600));
	var dHours = Math.floor(dSeconds / 3600);
	dSeconds = Math.floor(dSeconds % 3600);
	var dMinutes = Math.floor(dSeconds / 60);
	dSeconds = Math.floor(dSeconds % 60);

	if (dHours < 10) dHours = "0" + dHours;
	if (dMinutes < 10) dMinutes = "0" + dMinutes;
	if (dSeconds < 10) dSeconds= "0" + dSeconds;

	var sDays = "<strong>" + dDays + "</strong>";
	var sHours = "<strong>" + dHours + "</strong>";
	var sMinutes = "<strong>" + dMinutes + "</strong>";
	var sSeconds = "<strong>" + dSeconds + "</strong>";

	var a = [];
	if (event_smallest_unit == "days")
		a = [sDays];
	if (event_smallest_unit == "hours")
		a = [sDays, sHours];
	if (event_smallest_unit == "minutes")
		a = [sDays, sHours, sMinutes];
	if (event_smallest_unit == "seconds")
		a = [sDays, sHours, sMinutes, sSeconds];

	document.getElementById('countdownHome').innerHTML = a.join(' : ') + '<br/><div id=lower>(DAYS : HOURS : MINS : SECS)</div>';
}

function showbackside(event) {
	var front = document.getElementById("front");
	var back = document.getElementById("behind");

	if (window.widget)
		widget.prepareForTransition("ToBack");

	displaybottomline();
	front.style.display="none";
	back.style.display="block";

	document.getElementById('hour').value   = event_time.getHours();
	document.getElementById('minute').value = event_time.getMinutes();
	document.getElementById('second').value = event_time.getSeconds();
	document.getElementById('year').value   = event_time.getFullYear();
	document.getElementById('month').value  = event_time.getMonth();
	onmonthchange();
	document.getElementById('day').value    = event_time.getDate();

	document.getElementById('event_name').value = event_name;
	document.getElementById('show-to').value = event_smallest_unit;

	if (window.widget)
		setTimeout ('widget.performTransition();', 0);  
        
	document.getElementById('fliprollie').style.display = 'none';
}

function doneClicked() {
	var year = document.getElementById('year').value;
	var month = document.getElementById('month').value;
	var day = document.getElementById('day').value;
	var hour = document.getElementById('hour').value;
	var minute = document.getElementById('minute').value;
	var second = document.getElementById('second').value;

	event_time = new Date(year, month, day, hour, minute, second);
	event_name = document.getElementById('event_name').value;
	event_smallest_unit = document.getElementById('show-to').value;

	if (window.widget) {
		widget.setPreferenceForKey(event_time.toString(), createkey("time"));
		widget.setPreferenceForKey(event_name,            createkey("name"));
		widget.setPreferenceForKey(event_smallest_unit,   createkey("smallest"));
	}

	var front = document.getElementById("front");
	var back = document.getElementById("behind");

	if (window.widget)
		widget.prepareForTransition("ToFront");

	front.style.display="block";
	back.style.display="none";

	if (window.widget)
		setTimeout("widget.performTransition();", 0);
}

var flipShown = false;

var animation = {duration:0, starttime:0, to:1.0, now:0.0, from:0.0, element:null, timer:null};

function clamp(val, min, max) {
	return val < min ? min : (val > max ? max : val);
}

function computeNextFloat (from, to, ease) {
	return from + (to - from) * ease;
}

function animate() {
	var T;
	var ease;
	var time = (new Date).getTime();

	T = clamp(time-animation.starttime, 0, animation.duration);

	if (T >= animation.duration) {
		clearInterval(animation.timer);
		animation.timer = null;
		animation.now = animation.to;
	} else {
		ease = 0.5 - (0.5 * Math.cos(Math.PI * T / animation.duration));
		animation.now = computeNextFloat(animation.from, animation.to, ease);
	}

	animation.element.style.opacity = parseInt(animation.now*100)/100;
}

function mousemove (event) {
	if (!flipShown) {
		// fade in the flip widget
		if (animation.timer != null) {
			clearInterval (animation.timer);
			animation.timer  = null;
		}

		var starttime = (new Date).getTime() - 13; // set it back one frame

		animation.duration = 500;
		animation.starttime = starttime;
		animation.element = document.getElementById ('flip');
		animation.timer = setInterval ("animate();", 13);
		animation.from = animation.now;
		animation.to = 1.0;
		animate();
		flipShown = true;
	}
}

function mouseexit (event) {
	if (flipShown) {
		// fade out the flip widget
		if (animation.timer != null) {
			clearInterval (animation.timer);
			animation.timer  = null;
		}

		var starttime = (new Date).getTime() - 13; // set it back one frame

		animation.duration = 500;
		animation.starttime = starttime;
		animation.element = document.getElementById ('flip');
		animation.timer = setInterval ("animate();", 13);
		animation.from = animation.now;
		animation.to = 0.0;
		animate();
		flipShown = false;
	}
}

function enterflip(event) {
	document.getElementById('fliprollie').style.display = 'block';
}

function exitflip(event) {
	document.getElementById('fliprollie').style.display = 'none';
}

function displaybottomline(select) {
	var select = document.getElementById('whichpref');

	var ids = ['smallest', 'date', 'time', 'name', 'credits'];

	for (i in ids)
		document.getElementById(ids[i]).style.display = 'none';

	document.getElementById(select.value).style.display = 'block';
}

function onyearchange() {
	onmonthchange();
}

function onmonthchange() {
	var day_select = document.getElementById('day');

	var event_month = document.getElementById('month').value;

	var now = new Date();
	var event_year = parseInt(document.getElementById('year').value);

	var days = [ 31,
	             (event_year % 4 == 0 && event_year % 100 != 0) ? 29 : 28,
	             31,
	             30,
	             31,
	             30,
	             31,
	             31,
	             30,
	             31,
	             30,
	             31 ];

	var old_day = day_select.value;

	while (day_select.hasChildNodes())
		day_select.removeChild(day_select.firstChild);

	for (var i = 1; i <= days[event_month]; ++i) {
		var option = document.createElement('option');
		option.appendChild(document.createTextNode(i));
		option.value = i;
		day_select.appendChild(option);
	}

	day_select.value=clamp(old_day, 1, days[event_month]);
}

function keyRestrict(k) {
	if (k >= 48 && k <= 57)
		return true;

	// These we're found by trial and error...
	// Included are tab, backspace, delete and left and right cursor keys.
	if (k == 9 || k == 8 || k == 63234 || k == 63235 || k == 63272)
		return true;

	return false;
}

function createkey(key) {  
	return widget.identifier + "-" + key;
}
