////////////////////////////////////////////////////////
//
// Poematic, v. 1.2
// Copyright 2006, Fletcher Moore
//
// Huge chunks covered by GPL, which I suppose means the
// whole damn thing is GPL. I have no idea. What do I
// look like, a lawyer?
//
// fletcher@saltydogdesign.com
// http://saltydogdesign.com
//
////////////////////////////////////////////////////////

////////////////////////////////////////////////////////
//
// config
//
// clockTimer = length of agon in seconds
var clockTimer = 900;
//
// packetFreq = number of seconds per db call
var packetFreq = 20;
//
////////////////////////////////////////////////////////
//
// defaults and globals
var poet;
var start = 0;
var keyCount = 0;
var digitRx = /digit\d/;
var keybuffer = "";
var bdbuffer = "";
var clockFunction = 0;
var clockHandler;
var warningHandler;
var clockMinutes = clockTimer / 60;
var playbackArray;
var needData = 1;
var richtext = 0;
var poemContainer;
//
// constants
var modePoematic = 0;
var modePlayback = 1;



////////////////////////////////////////////////////////
//
// general purpose stuff
//
////////////////////////////////////////////////////////

function rollover(me) { // Takes optional 2 args for before/after
	if (typeof me == "string") { me = $(me); }
	if (!me.src) { me = me.firstChild; }
	if (arguments.length > 1) {
		me.src = me.src.replace(arguments[1], arguments[2]);
	} else {
		me.src = me.src.replace("/there", "/over");
	}
}

function rollout(me) {
	if (typeof me == "string") { me = $(me); }
	if (!me.src) { me = me.firstChild; }
	if (arguments.length > 1) {
		me.src = me.src.replace(arguments[2], arguments[1]);
	} else {
		me.src = me.src.replace("/over", "/there");
	}
}

function populateBlogList() {
	blogEntries = {
		url: "blogPopper.php?cmd=blogEntries",
		mimetype: "text/plain",
		error: function(type, errObj) { /*alert(errObj['message']) + " (1)";*/ },
		load: function(type, data, evt) {
			eval(data);
			i = 0; while ( $('blog').offsetHeight < 360 && i < blogEntries.length ) {
				$('blogEntryContainer').innerHTML += blogEntries[i];
				i++;
			}
			//populateBlogroll();
		}
	};
	request = dojo.io.bind(blogEntries);
	//window.location = blogEntries['url'];
}

function populateBlogroll() {
	blogrollEntries = {
		url: "blogPopper.php?cmd=blogrollEntries",
		mimetype: "text/plain",
		error: function(type, errObj) { /*alert(errObj['message']) + " (1)";*/ },
		load: function(type, data, evt) {
			eval(data);
			i = 0; while ( $('blog').offsetHeight < 365 && i < blogroll.length - 1 ) {
				$('blogrollEntryContainer').innerHTML += blogroll[i];
				i++;
			}
		}
	};
	request = dojo.io.bind(blogrollEntries);
}



////////////////////////////////////////////////////////
//
// poematic, driver's seat
//
////////////////////////////////////////////////////////

function launchPoematic(poetFromQuery) {
	// Who's going at it?
	poet = poetFromQuery;
	
	// Start the clock
	clockHandler = new PeriodicalExecuter(decrementClock, 1);

	// What time is it right this millisecond?
	d = new Date();
	start = d.getTime();
	
	return false;
}

function twoMinuteWarning() {
	warningHandler = new PeriodicalExecuter(toggleWarning, .5);
}

function killTwoMinuteWarning() {
	warningHandler.currentlyExecuting = true;
	toggleWarning();
}

function standby() {
	window.location = "standby.php?poet=" + poet;
	// need to set db flag
}

function cachePoem() {
	if (tinyMCE && tinyMCE.getContent()) {
		keybuffer += tinyMCE.getContent() + "|||";
	} else {
		keybuffer += $('poem').value + "|||";
	}
	if (clockTimer % 60 == 40 ||
		clockTimer % 60 == 20 ||
		clockTimer % 60 == 0) {
			// Flush buffer to database.
			dbbuffer = keybuffer;
			keybuffer = "";
			bindArgs = {
				url: "bufferData.php",
				method: "POST",
				content: { packet: dbbuffer, poet: poet, minute: clockMinutes },
				mimetype: "text/plain",
				error: function(type, errObj) { /*alert(errObj['message']) + " (1)";*/ },
				load: function(type, data, evt) { }
			};
			request = dojo.io.bind(bindArgs);
		//	window.location = bindArgs['url'];
	}		
}

function closeAgon() {
	clockHandler.currentlyExecuting = true;
	
	if (tinyMCE && tinyMCE.getContent()) {
		keybuffer += tinyMCE.getContent() + "|||";
	} else {
		keybuffer += $('poem').value + "|||";
		richtext = 0;
	}

	// Flush buffer to database.
	dbbuffer = keybuffer;
	keybuffer = "";

	bindArgs = {
		url: "bufferData.php",
		method: "POST",
		content: { packet: dbbuffer, poet: poet, minute: clockMinutes, richtext: richtext, cmd: "close" },
		mimetype: "text/plain",
		error: function(type, errObj) { /*alert(errObj['message']) + " (2)";*/ },
		load: function(type, data, evt) { window.location = "finished.php?poem=" + poet; }
	};
	request = dojo.io.bind(bindArgs);
//	window.location = bindArgs['url'];
}

function countdownPendingInit(poetFromQuery, seconds) {
	clockTimer = seconds;
	clockFunction = modePlayback;
	poet = poetFromQuery;
	
	// Calculate the clock time.
	clockMinutes = Math.floor(seconds / 60);
	clockSeconds = (seconds - (clockMinutes * 60)).toString();
	clockMinutes = clockMinutes.toString();
	
	// Must have a two-digit second, minute value.
	if (clockSeconds.length < 2) { clockSeconds = "0" + clockSeconds; }
	if (clockMinutes.length < 2) { clockMinutes = "0" + clockMinutes; }
	
	// Get each second and minute.
	second1 = clockSeconds.substr(0, 1);
	second2 = clockSeconds.substr(1, 1);
	minute1 = clockMinutes.substr(0, 1);
	minute2 = clockMinutes.substr(1, 1);
	
	// Set the clock
	swapDigit('clock4', second2);
	swapDigit('clock3', second1);
	swapDigit('clock2', minute2);
	swapDigit('clock1', minute1);

	// Start decrementing
	new PeriodicalExecuter(decrementClock, 1);
}

function toggleWarning() {
	if ($('warning').style.visibility == "hidden") { $('warning').style.visibility = "visible"; }
	else { $('warning').style.visibility = "hidden"; }
}

function showPoem() {
	$('themeTab').style.visibility = "visible";
	$('poemTab').style.visibility = "hidden";
	$('themeWrapper').style.left = "-5000px";
	$('poematicWrapper').style.left = "0px";
}

function showTheme() {
	$('themeTab').style.visibility = "hidden";
	$('poemTab').style.visibility = "visible";
	$('themeWrapper').style.left = "0px";
	$('poematicWrapper').style.left = "-5000px";
}



////////////////////////////////////////////////////////
//
// poematic, passenger's seat
//
////////////////////////////////////////////////////////

function playback(poetFromQuery) {
	poet = poetFromQuery;
	clockFunction = modePlayback;
	playbackArray = text.split("|||");
	playbackArray.pop();

	poemContainer = 'columnMid';

	// Jump to beginning
	firingBlanks = new RegExp("[a-zA-Z0-9<]");
	while (playbackArray[0] == "" || playbackArray[0] == "null" || (playbackArray[0].search(firingBlanks))) {
		if (playbackArray.length > 0) { 
			playbackArray.shift(); 
			clockTimer--;

			// Calculate the clock time.
			clockMinutes = Math.floor(clockTimer / 60);
			clockSeconds = (clockTimer - (clockMinutes * 60)).toString();
			clockMinutes = clockMinutes.toString();

			if (clockSeconds.length < 2) { clockSeconds = "0" + clockSeconds; }
			if (clockMinutes.length < 2) { clockMinutes = "0" + clockMinutes; }
		}
		if ( needData == 1 ) {
			if (clockSeconds < "30" && clockMinutes != "00") { 
				appendOneMinute(true);
				needData = 0;
			}
		} else {
			if (clockSeconds > "30") { needData = 1; }
		}
	}

	// Start outputting characters.
	if (clockHandler && clockHandler.currentlyExecuting == true) {
		clockHandler.currentlyExecuting = false;
	} else {
		clockHandler = new PeriodicalExecuter(playbackSecond, 1);
	}
}

function playbackSecond() {
	if (playbackArray.length == 1) {
		clockHandler.currentlyExecuting = true;
		return;
	}
	clockTimer--;

	if (richtext == 0) {
		$(poemContainer).innerHTML = '<pre>' + playbackArray.shift() + '</pre>';
	} else {
		$(poemContainer).innerHTML = playbackArray.shift();
	}
	$(poemContainer).scrollTop = $(poemContainer).scrollHeight - $(poemContainer).clientHeight;
	
	// Calculate the clock time.
	clockMinutes = Math.floor(clockTimer / 60);
	clockSeconds = (clockTimer - (clockMinutes * 60)).toString();
	clockMinutes = clockMinutes.toString();
	
	// Must have a two-digit second, minute value.
	if (clockSeconds.length < 2) { clockSeconds = "0" + clockSeconds; }
	if (clockMinutes.length < 2) { clockMinutes = "0" + clockMinutes; }
	
	if ( needData == 1 ) {
		if (clockSeconds < "30" && clockMinutes != "00") { 
			appendOneMinute(false);
			needData = 0;
		}
	} else {
		if (clockSeconds > "30") { needData = 1; }
	}
	
	// Get each second and minute.
	second1 = clockSeconds.substr(0, 1);
	second2 = clockSeconds.substr(1, 1);
	minute1 = clockMinutes.substr(0, 1);
	minute2 = clockMinutes.substr(1, 1);
	
	// Set the clock
	swapDigit('clock4', second2);
	swapDigit('clock3', second1);
	swapDigit('clock2', minute2);
	swapDigit('clock1', minute1);
}

function changeSpeed(speed, altSpeed, onButton, offButton) {
	// swap images as necessary
	$(onButton).src = $(onButton).src.replace("/there", "/over");
	$(offButton).src = $(offButton).src.replace("/over", "/there");

	// blur
	if ($(onButton).parentNode.blur) { $(onButton).parentNode.blur(); }

	// clear handlers
	$(onButton).parentNode.onmouseout = null;
	$(onButton).parentNode.onmouseover = null;
	$(onButton).parentNode.onclick = null;

	// set handlers on opposite button
	$(offButton).parentNode.onmouseout = function() { rollout($(offButton).parentNode); }
	$(offButton).parentNode.onmouseover = function() { rollover($(offButton).parentNode); }
	$(offButton).parentNode.onclick = function() { changeSpeed(altSpeed, speed, offButton, onButton); }

	// set speed
	clockHandler.setFrequency(speed);
}

function rewindPoem() {
	clockHandler.currentlyExecuting = true;

	// reset pause/resume if necessary
	$('pause').src = $('pause').src.replace("play", "pause");
	$('pause').parentNode.onclick = function() { pausePoem(); }

	if ($('rewind').parentNode.blur) { $('rewind').parentNode.blur(); }
	$(poemContainer).innerHTML = "";
	playbackArray = "";
	clockTimer = 900;
	clockMinutes = clockTimer / 60;
	needData = 1;
	playback(poet);
}

function pausePoem() {
	clockHandler.currentlyExecuting = true;
	$('pause').src = $('pause').src.replace("pause", "play");
	if ($('pause').parentNode.blur) { $('pause').parentNode.blur(); }
	$('pause').parentNode.onclick = function() { resumePoem(); }
}

function resumePoem() {
	clockHandler.currentlyExecuting = false;
	$('pause').src = $('pause').src.replace("play", "pause");
	if ($('pause').parentNode.blur) { $('pause').parentNode.blur(); }
	$('pause').parentNode.onclick = function() { pausePoem(); }
}

function appendOneMinute(syncMode) {
	bindArgs = {
		url: "returnMinute.php",
		sync: syncMode,
		method: "POST",
		content: { minute: clockMinutes, poet: poet },
		mimetype: "text/plain",
		error: function(type, errObj) { /*alert(errObj['message']) + " (3)";*/ },
		load: function(type, data, evt) {
			newPacket = data.split("|||");
			playbackArray = playbackArray.concat(newPacket);
			playbackArray.pop();
		}
	};
	request = dojo.io.bind(bindArgs);
//	window.location = bindArgs['url'];
}



////////////////////////////////////////////////////////
//
// poematic, shared functions
//
////////////////////////////////////////////////////////

function decrementClock() {
	// not really a shared function, but probably should be
	clockTimer--;

	// Is this a waypoint?
	//if (clockTimer == 120) { twoMinuteWarning(); }
	//if (clockTimer == 118) { killTwoMinuteWarning(); }
	if (clockFunction == modePoematic && clockTimer == 0) { 
		clockHandler.currentlyExecuting = true; // suspend periodical executor
		closeAgon();
	}
	if (clockFunction == modePlayback && clockTimer == 0) { standby(); }

	// Cache current state
	if (clockFunction == modePoematic) { cachePoem(); }

	// Calculate the clock time.
	clockMinutes = Math.floor(clockTimer / 60);
	clockSeconds = (clockTimer - (clockMinutes * 60)).toString();
	clockMinutes = clockMinutes.toString();
	
	// Must have a two-digit second, minute value.
	if (clockSeconds.length < 2) { clockSeconds = "0" + clockSeconds; }
	if (clockMinutes.length < 2) { clockMinutes = "0" + clockMinutes; }
	
	// Get each second and minute.
	second1 = clockSeconds.substr(0, 1);
	second2 = clockSeconds.substr(1, 1);
	minute1 = clockMinutes.substr(0, 1);
	minute2 = clockMinutes.substr(1, 1);
	
	// Swap second images (both if needed).
	swapDigit('clock4', second2);
	if (second2 == "9") {
		swapDigit('clock3', second1);
		if (second1 == "5") {
			swapDigit('clock2', minute2);
			if (minute2 == "9") {
				swapDigit('clock1', minute1);
			}
		}
	}
}

function swapDigit(myDigit, newValue) {
	if ($(myDigit).src.indexOf("old") > -1) {
		$(myDigit).src = "../images/poematic/digit" + newValue + ".old.gif";
	} else {
		$(myDigit).src = "../images/poematic/digit" + newValue + ".gif";
	}
}
