/**
 * in celebration of the gamecubes 20th anniversary
 * here is a script to play animal crossing music
 * on the hour!
 */

var hour;				// the current hour
var playing = false;	// status of player

// paths
var music_path = "acmusic";

$(function() {

	// get the current time
	var date = new Date();
	hour = date.getHours();

	// setup the player on the correct hour
    $("#jquery_jplayer_1").jPlayer( {
        ready: function(event) {
            play(hour)
        },
        play: function() { playing = true; },		// watch for state changes
        pause: function() { playing = false; },		// so we don't start playing
        ended: function() { playing = false; },		// on an hour change
        swfPath: "/scripts",
        supplied: "oga, mp3",
        loop: true
    });

    // watch the clock to advance the track
    checkHour();
});

/**
 * checks every second whether the hour has changed
 */
function checkHour()
{
	var date = new Date();
	var current = date.getHours();

	if (hour != current)	// hour has passed
	{
		hour = current; hour %= 24;
		play(hour);
	}

	setTimeout(checkHour, 1000);
}

/**
 * converts 24 hour into a 12 hour string
 */
function hourToString(hour)
{
	var real_hour = hour % 12;
	real_hour = real_hour == 0 ? 12 : real_hour;
	var ampm = hour > 12 ? 'pm' : 'am';

	return real_hour + '-' + ampm;
} 

/**
 * play the music for the hour
 */
function play(hour)
{
	// determine whether to play christmas tracks
	var date = new Date();
	var december = date.getMonth() == 11;		// 0 - 11
	var dir = december ? "christmas" : "normal";
	var postfix = december ? "-christmas" : "";

	var filename = hourToString(hour);

	// play the next track, right away!
	// could create an eventhandler to play at the end
	// of a current play that crosses the hour...
	var player = $("#jquery_jplayer_1");

	player
		.jPlayer("stop")
		.jPlayer("setMedia", {
			oga: "/" + music_path + "/" + dir + "/" + filename + postfix + ".oga",
			mp3: "/" + music_path + "/" + dir + "/" + filename + postfix + ".mp3"
		});
	
	if (playing)
		player.jPlayer("play");
}
