<?xml version="1.0" encoding="UTF-8" ?>
<Module>
  <ModulePrefs title="Wave Word Jumble" height="120">
    <Require feature="wave-preview"/>
	<Require feature="dynamic-height" />
  </ModulePrefs>
  <Content type="html">
    <![CDATA[
    <script type="text/javascript">
		var word_list = new Array();
		var current_word;
		var shuffled_word;
		var players = new Array();
		
		// retrieves wave participants
		function loadPlayers() {
			var player_list = document.getElementById("player_list");			
			players = wave.getParticipants();			
			
			var s = "<tr>" +
					"	<th colspan='3'>Players</th>" +
					"</tr>" +
					"<tr>" +
					"	<td style='width:80px;text-decoration:underline;'>Name</td>" +
					"	<td colspan='2' style='text-decoration:underline;'>Score</td>" +
					"</tr>";
					
			for(var i = 0; i < players.length; i++) {
				s += "<tr>" +
					 "	<td style='font-weight:bold;'>" + players[i].getDisplayName() + "</td>" +
					 "	<td id='score" + i +"' style='width:50px;font-weight:bold;'>0</td>" + 
					 "	<td id='vote" + i +"' style='width:33px;color:#FFFFFF;font-weight:bold;text-align:center;'></td>" + 
					 "</tr>";					 
			}
			
			player_list.innerHTML = s;
			
			gadgets.window.adjustHeight();
		}
		
		// retrieves words from dictionary
		function loadWords() {			
			makeRequest();						
		}
		
		// requests for a file
		function makeRequest() {  		
			var params = {};
			params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.TEXT;
			var url = "http://cs291miniproject.zymichost.com/dictionary.txt";
			gadgets.io.makeRequest(url, response, params);
		}
		
		// callback function that loads file contents into an array
		function response(obj) {
			word_list = obj.text.toUpperCase().split("\n");
			for(var i = 0; i < word_list.length; i++) {
				word_list[i] = word_list[i].trim();
			}							
		}
		
		// response to state updates
		function gameUpdated() {						
			//initial shuffled word
			if(!wave.getState().get("shuffled_word")) {
				generateShuffledWord();
			} else {			
				shuffled_word = wave.getState().get("shuffled_word");				
				document.getElementById("shuffled_word").innerHTML = shuffled_word;			
			}
			
			var voted = 0;
			for(var i = 0; i < players.length; i++) {
				if (wave.getState().get("score"+i)) {
					document.getElementById("score"+i).innerHTML = wave.getState().get("score"+i);
				}
				if ((wave.getState().get("vote"+i)) && (wave.getState().get("vote"+i) == "1")) {
					document.getElementById("vote"+i).innerHTML = "Voted";
				} else {
					document.getElementById("vote"+i).innerHTML = "";
				}
				if (wave.getState().get("vote"+i)) {
					voted += parseInt(wave.getState().get("vote"+i));
				}
			}						
			if (voted > players.length * 0.5) {
				generateShuffledWord();
			}
			
			document.getElementById("word_input").value = "";
		}
		
		// converts strings to arrays
		function strToArray(str) {
			var buffer = new Array(str.length);
			for(var i = 0; i < str.length; i++) {
				buffer[i] = str[i];			
			}
			
			return buffer;
		}
				
		// jumbles a word
		function shuffleWord(word) {		
			var buffer = strToArray(word);
			
			for(var i = 0; i < buffer.length; i++) {
				var index1 = Math.floor(Math.random() * buffer.length);
				var index2 = Math.floor(Math.random() * buffer.length);
				
				var temp = buffer[index1];
				buffer[index1] = buffer[index2];
				buffer[index2] = temp;			 		
			}
			
			return buffer.join("");				
		}
		
		// generates a jumbled word of length >= 3
		function generateShuffledWord() {								
			loadWords();
			
			for(var i = 0; i < players.length; i++) {
				wave.getState().submitValue("vote"+i,"0");
			}
						
			current_word = "";
			while(current_word.length <= 2) {
				current_word = word_list[Math.floor(Math.random() * word_list.length)];				
			}
			shuffled_word = shuffleWord(current_word);
			wave.getState().submitValue("shuffled_word", shuffled_word);			
			document.getElementById("shuffled_word").innerHTML = shuffled_word;
		}	
		
		// converts a participant's id into a unique number
		function convertPlayerId(playerId) {
			for(var i = 0; i < players.length; i++) {
				if (players[i].getId() == playerId) {
					return i;
				}
			}
		}
		
		// adjusts a player's score
		function scorePlayer(id, word_length) {  
			var score;
			
			if(!wave.getState().get("score"+id)) {
				score = 0;
			} else {
				score = parseInt(wave.getState().get("score"+id));
			}
			score += word_length;
			
			wave.getState().submitValue("score"+id, score);
		}
		
		// checks if an answer is correct
		function checkInput() {									
			loadWords();
			
			var input = document.getElementById("word_input").value.toUpperCase();
			var correct = false;						
			
			// brute force!!!
			if (strToArray(input).sort().join("") == strToArray(shuffled_word).sort().join("")) {
				for(var i = 0; i < word_list.length; i++) {
					if (input == word_list[i]) {
						correct = true;
					}
				}
			}
			
			if (correct) {
				scorePlayer(convertPlayerId(wave.getViewer().getId()), shuffled_word.length);
				generateShuffledWord();				
			}						
			
			document.getElementById("word_input").value = "";
		}

		// registers player votes
		function vote() {
			wave.getState().submitValue("vote"+convertPlayerId(wave.getViewer().getId()), "1");
		}			
		
		// launches a popup window
		function popUp(url, title, height, width) {
			window.open(url, title, "toolbar=0, scrollbars=1, location=0, statusbar=0, menubar=0, height="+ height +", width=" + width +", resizable=0");
		}
		
		// initialize gadget
		function init() {
			if (wave && wave.isInWaveContainer()) {								
				wave.setParticipantCallback(loadPlayers);				
				wave.setStateCallback(gameUpdated);
			}						
		}
		
		gadgets.util.registerOnLoadHandler(init);
	</script>
	
	<div style="padding-top:5px;padding-bottom:20px;margin:0 auto;width:100%;border:2px solid #336699;background:url('http://cs291miniproject.zymichost.com/bg.png') top left repeat #CCCCCC;font-size:12px;font-family:Helvetica,Arial,Sans-serif;">
		<div style="margin-bottom:5px;font-size:11px;text-align:center;">
			<a href="javascript:popUp('http://cs291miniproject.zymichost.com/instructions.html','',500,500);" style="color:#336699;">How to play</a> | <a href="javascript:popUp('http://cs291miniproject.zymichost.com/about.html','',50,300);" style="color:#336699;">About</a>
		</div>
		<div style="margin-bottom:15px;height:20px;font-size:18px;font-weight:bold;color:#444466;text-align:center;">Wave Word Jumble</div>	
		<div id="shuffled_word" style="margin-bottom:2px;height:20px;font-size:14px;font-weight:bold;text-align:center;color:#FFFF00;"></div>
		<div style="margin-bottom:2px;text-align:center;">
			<input id="word_input" type="text" style="width:300px;border:1px solid #336699;vertical-align:bottom;" />
		</div>	
		<div style="margin-bottom:20px;text-align:center;">
			<input type="button" value="Answer" onclick="checkInput()" />
			<input type="button" value="Vote to Skip" onclick="vote();" />
		</div>
		<table id="player_list" style="margin:0 auto;width:300px;border:1px solid #000000;font-size:12px;">
		</table>
	</div>
    ]]>	
  </Content>
</Module>
