<?xml version="1.0" encoding="UTF-8"?>
<Module>
	<ModulePrefs title="The Button">
	</ModulePrefs>

	<Content type="html"><![CDATA[
		<!-- <script type="text/javascript" src="http://hyperthese.net/wave-gadgets/prototype-1.6.0.3.js"></script><!-- -->
<script type="text/javascript">
	alert("Button started");

	// Are data coherent ?
	var coherent = false;

	// -- WAVE KEYS --
	var lastTime = null;
	var clickHistory = new Array();
	var scoreBoard = new Hash();
	var lastWinner = null;
	// -- END OF WAVE KEYS --

	// Time at load
	var initial_time = new Date();
	var diff_to_ref = initial_time.getTime() - 1249985991.21 * 1000;

	function getRefTimestamp() {
		var now = new Date();
		return now.getTime() - diff_to_ref;
	}

	function updateTime() {
		if(coherent) {
			var timediv = document.getElementById('time');

			var diff = (getRefTimestamp() - lastTime) / 1000;

			var h = parseInt(diff/3600);
			var m = parseInt(diff/60) - h * 60;
			var s = parseInt(diff) - h * 3600 - m * 60;

			h = h.toString();
			m = m.toString();
			s = s.toString();

			if(h.length == 1) h = '0' + h;
			if(m.length == 1) m = '0' + m;
			if(s.length == 1) s = '0' + s;

			var by = new String();
			if(lastWinner != null) {
				by = " by " + wave.getParticipantById(lastWinner).getDisplayName();
			} else {
				by = "";
			}

			timediv.innerHTML = '<p>This button was last pressed ' + h + ':' + m + ':' + s + ' ago' + by + '</p>';
		}

		setTimeout('updateTime()', 1000);
	}

	function displayScoreboard() {
		var content = new String();

		// You first must convert data into an array
		var arSb = new Array();
		var i = 0;
		
		scoreBoard.each(function(pair) {
			arSb[i++] = {
				"participant": wave.getParticipantById(pair.key),
				"score": pair.value.score
			};
		});

		arSb.sort(function(a, b) {
			return b.score - a.score;
		});

		for(i = 0; i < arSb.size(); i++) {
			content += "<li><strong>" + parseInt(arSb[i].score) + "</strong>: <em>" + arSb[i].participant.getDisplayName() + "</em> (" + arSb[i].participant.getId() + ")</li>";
		}

		$('scorelist').innerHTML = content;

		gadgets.window.adjustHeight();
	}

	function buttonClicked() {
		playRound();
	}

	function playRound() {
		// You need to be in a coherent state
		if(!coherent) return;

		// Let's create the delta we'll send to wave
		var delta = new Object();

		// Starting to fill the delta's data
		delta['lastTime'] = Object.toJSON(getRefTimestamp());

		// You fetch the id of the viewer
		var pId = wave.getViewer().getId();

		// Getting/creating the row of the current viewer in the scoreboard
		var sb = scoreBoard.get(pId);
		if(sb != undefined) {
			// Nobody is allowed to clic twice in a quarter hour
			/*if (sb.lastPlay + 900000 > getRefTimestamp()) {
				alert("You shall not pass !\n(within the " + ((sb.lastPlay + 900000 - getRefTimestamp()) / 1000).toString() + " next second(s))");
				return;
			}*/
		} else {
			sb = new Object();
			sb.score = 0;
			sb.lastPlay = 0;
		}

		// How much does the player win ?
		var loot = (getRefTimestamp() - lastTime) / 1000;

		// Generating the line of the scoreboard
		var entry = {
			"score": sb.score + loot,
			"lastPlay": getRefTimestamp()
		};

		// Updating the scoreboard
		scoreBoard.set(pId, entry);

		// If this is not the first click
		if(lastWinner != null) {
			var lastSb = scoreBoard.get(lastWinner);
			lastSb.score = lastSb.score - loot;
			scoreBoard.set(lastWinner, lastSb);
		}

		// Switching the loot to lastWinner
		lastWinner = pId;

		// Finishing to fill the delta
		delta['lastWinner'] = lastWinner.toJSON();
		delta['scoreBoard'] = scoreBoard.toJSON();

		// Sending the delta to wave
		wave.getState().submitDelta(delta);
	}

	function stateUpdated() {
		coherent = true;

		alert("we've got an update :)");

		lastTime = getWaveKey('lastTime', getRefTimestamp());
		lastWinner = getWaveKey('lastWinner', null);
		scoreBoard = new Hash(getWaveKey('scoreBoard', new Hash()));

		displayScoreboard();
	}

	function getWaveKey(key, defaultValue) {
		var result = wave.getState().get(key);

		if(!result)
			return defaultValue;
		else
			return result.evalJSON(true);
	}

	function init() {
		if(wave && wave.isInWaveContainer()) {
			alert("setting state callback");
			wave.setStateCallback(stateUpdated);
			//wave.setStateCallback(function(){alert('update ... but we do nothing :) ')});

			alert("Init is OK");
		} else {
			alert("Not in wave ?");
		}

		updateTime();
	}

	gadgets.util.registerOnLoadHandler(init);
</script>

<div id="whole">
	<div id="button">
		<input type="button" value="DO NOT EVER PRESS THIS BUTTON" onclick="buttonClicked()" />
	</div>

	<div id="time">
		&nbsp;
	</div>

	<div id="score">
		<h3>Score !</h3>

		<ol id="scorelist">
		</ol>
	</div>
</div>
	]]></Content>

</Module>