 ////////////////////////////////////////////////////////////////////////////
//
// Base code for Zero Hour
// - contains all functions used pre-game and in the screener game
//
////////////////////////////////////////////////////////////////////////////

//***************************************************
// Global Variables
//***************************************************

	var myName = null;
	var mySession = null;
	var myGameName = null;
	var inGame = false;
	var myChallenge = null;

//******************************************************************************************************
//******************************************************************************************************
// Pre Login
//******************************************************************************************************
//******************************************************************************************************


	
//******************************************************************************************************
//******************************************************************************************************
// Logging in
//******************************************************************************************************
//******************************************************************************************************

	function Login(loginName, loginPw)
	{
		//alert("login attempted " + loginName + " " + loginPw);
		myName = loginName;
		GameFunctions.Login(loginName, loginPw, "", Login_Callback);
	}

	function Login_Callback(response)
	{
		//alert("login returned " + response.value);
		if(response.error) 
		{
			//alert(response.error);	
			flash.LoginCallback(false, "Error: Unable to log in. Game Server may be down.");
		}
		else
		{
		    var dictionary = CreateDictionaryWrap(response.value);
		    var succeeded = GetValue(dictionary, 'Success');
		    if(succeeded == "True")
		    {
		    		//alert("Logged in");
			    mySession = GetValue(dictionary, 'Session');
			    flash.LoginCallback(true, "");
		    }
		    else
		    {
		        var reason = GetValue(dictionary, 'Reason');
		        flash.LoginCallback(false, reason);
		    }
		}
	}

//******************************************************************************************************
//******************************************************************************************************
// Finding a Game
//******************************************************************************************************
//******************************************************************************************************

	//****************
	// FindGames
	//****************
	function FindGames()
	{
		//alert("findgames attempted");
		GameFunctions.Find(FindGames_Callback)
	}
	
	function FindGames_Callback(response)
	{
		//alert("findgames returned " + response.value);
		if(response.error)
			flash.ShowError(response.error);
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);			
			var numGames = parseInt(GetValue(dictionary, 'NumGame'));
			
			flash.ClearGameList();
			for(var i = 1; i < numGames + 1; i++)
			{
				newGameName = GetValue(dictionary, 'GameName' + i);
				if(newGameName)
				{
					flash.AddGameToList(newGameName);
				}
			}
		}
	}

	//****************
	// GetGameInfo
	//****************	
	function GetGameInfo(gameName)
	{
		//alert("getgameinfo attempted " + gameName);
		GameFunctions.GetGameInfo(gameName, GetGameInfo_Callback);
	}
	
	function GetGameInfo_Callback(response)
	{
		//alert("getgameinfo returned " + response.value);
		if(response.error)
			flash.ShowError(response.error);
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
		
			var theInfo = "";
			theInfo += "Game Name: " + GetValue(dictionary, 'GameName') + "\n ";
			theInfo += "Players: \n ";
			for(var i = 1; i < parseInt(GetValue(dictionary, 'NumPlayers')); i++)
				theInfo += " - " + GetValue(dictionary, 'Player' + i) + "\n ";
			theInfo += " - " + GetValue(dictionary, 'Player' + i);
			
			flash.DisplayGameInfo(theInfo);
		}
	}
		
	//****************
	// JoinGame
	//****************
	function JoinGame(gameName)
	{
		//alert("joingame attempted " + gameName);
		GameFunctions.Join(gameName, mySession, JoinGame_Callback);
	}
	
	function JoinGame_Callback(response)
	{
		//alert("joingame returned " + response.value);
		if(response.error)
			flash.ShowError("Join Game Error: " + response.error);
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, "Success");
			if(succeeded == "False")
			{
				var reason = GetValue(dictionary, "Reason");
				flash.ShowError('Join Game Failed: ' + reason);
			}
			else
			{
				myGameName = GetValue(dictionary, "GameName");
				flash.SetScene("WaitingRoom");
			}
		}
	}

//******************************************************************************************************
//******************************************************************************************************
// Creating a Game
//******************************************************************************************************
//******************************************************************************************************

	function CreateNewGame(gameName, gameParams)
	{
	    //alert("createnewgame attempted " + gameName + " " + gameParams);
		//GameFunctions.Create(gameName, "pw", mySession, CreateNewGame_Callback);

        var dictionary = CreateDictionaryWrap(gameParams);
	    var isMultiplayer = GetValue(dictionary, "isMultiplayer");
		if(isMultiplayer == "True")
		    GameFunctions.Create(gameName, "pw", mySession, CreateNewMPGame_Callback);
	    else
	        GameFunctions.Create(gameName, "pw", mySession, CreateNewSPGame_Callback);	    
	}
	
	function CreateNewMPGame_Callback(response)
	{
		//alert("createnewMPgame returned " + response.value);
		if(response.error)
			flash.ShowError(response.error);
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, "Success");
			var reason = GetValue(dictionary, "Reason");
			if(succeeded == "True")
			{
			    myGameName = GetValue(dictionary, 'GameName');
			    flash.MoveToWaitingRoom();
		    }
		    else
		        flash.ShowError("Could not create game: " + reason);
		}
	}
	
	function CreateNewSPGame_Callback(response)
	{
		//alert("createnewSPgame returned " + response.value);
		if(response.error)
			flash.ShowError(response.error);//flash.ShowError(response.error);
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, "Success");
			var reason = GetValue(dictionary, "Reason");
			if(succeeded == "True")
			{
			    myGameName = GetValue(dictionary, 'GameName');
			    flash.AttemptRoleSelection();
		    }
		    else
		        flash.AttemptCreateSPGame(reason);
		}
	}

//******************************************************************************************************
//******************************************************************************************************
// Waiting Room
//******************************************************************************************************
//******************************************************************************************************
	
	//****************
	// GetGameInfoDetailed
	//****************
	function GetGameInfoDetailed()
	{
		//	alert("getgameinfodetailed attempted");
		GameFunctions.GetGameInfoDetailed(myGameName, GetGameInfoDetailed_Callback);
	}
	
	function GetGameInfoDetailed_Callback(response)
	{
	    //alert("ggid returned: " + response.value);
		if(response.error)
			flash.ShowError(response.error);	
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
		
			var theGameName = GetValue(dictionary, 'GameName');
			var theGameScenario = GetValue(dictionary, 'GameScenario');
			//!!!!!!!!!!!!!!!!!!!!!!! HACK !!!!!!!!!!!!!!!!!!!!!!!!!
			theGameScenario = "Anthrax Attack - Chicago";
			//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
			flash.DisplayDetailedGameInfo(theGameName, theGameScenario);
			
			// Here will be code to display the other players in the game, their pictures, and the seats they have
			flash.ClearPlayersList();
			var numPlayers = parseInt(GetValue(dictionary, 'NumPlayers'));
			for(var k = 1; k < numPlayers; k++)
				flash.DisplayDetailedGamePlayer(GetValue(dictionary, 'Player' + k) + ", ", "", "");
			flash.DisplayDetailedGamePlayer(GetValue(dictionary, 'Player' + k), "", ""); //no comma for the last one
		}	
	}
	
	//****************
	// GetChatMessages
	//****************	
	function GetChatMessages()
	{
		//alert("GetChatMessages attempted");
		GameFunctions.GetChatMessages(myGameName, mySession, GetChatMessages_Callback);
	}
	
	function GetChatMessages_Callback(response)
	{
	    //alert("GCM " + response.value);
		if(response.error)
		    return; //flash.ShowError('Chat Error: ' + response.error);
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, 'Success');
		    if(succeeded != "False")
		    {		
			    var numMessages = parseInt(GetValue(dictionary, 'ChatMessages'));
			    for(j = 1; j < numMessages + 1; j++)
			    {
				    var sender = GetValue(dictionary, 'MessageSender' + j);
				    var message = GetValue(dictionary, 'Message' + j);
				    //flash.ShowError(sender + ":" + message);
				    if(inGame == false) //Must be in waiting room
					    flash.AddChatMessage(sender, message);
				    else
					    flash.ReceiveMessage(sender, message);
			    }
			}   
		}
	}
	
	//****************
	// SendChatMessage
	//****************
	function SendChatMessage(target, messageText, command)
	{
	    if(messageText == null || messageText == "null")
	        messageText = "";
	    if(command == null || command == "null")
	        command = "";
		//flash.ShowError("sendchatmessage attempted to " +target + ": " + messageText + command);
		GameFunctions.SendChatMessage(myGameName, mySession, target, messageText + command, "emotion", SendChatMessage_Callback);
	}
	
	function SendChatMessage_Callback(response)
	{
		//alert("sendchatmessage returned " + response.value);
		if(response.error)
			flash.ShowError('Message not sent: ' + response.error);
	}
	
	//****************
	// ChooseRole
	//****************
	function ChooseRole(roleId, isMultiplayer)
	{	
		//alert("ChooseRole attempted");
		if(isMultiplayer == false)
		    GameFunctions.ChooseRole(myGameName, mySession, roleId, ChooseRoleSP_Callback);
		else
		    GameFunctions.ChooseRole(myGameName, mySession, roleId, ChooseRoleMP_Callback);
	}

	function ChooseRoleSP_Callback(response)
	{
		//alert("ChooseRole returned " + response.value);
		if(response.error)
			flash.ShowError('ChooseRole error: ' + response.error);	
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, 'Success');
			var reason = GetValue(dictionary, 'Reason');
			var multi = GetValue(dictionary, 'Multiplier');
		
			if(succeeded == "True")
				flash.RoleSelectionResult(true, "", multi);
			else
				flash.RoleSelectionResult(false, reason, multi);
		}
	}
	
	function ChooseRoleMP_Callback(response)
	{
		//alert("ChooseRole returned " + response.value);
		if(response.error)
			flash.ShowError('ChooseRole error: ' + response.error);	
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, 'Success');
			var reason = GetValue(dictionary, 'Reason');
		
			if(succeeded == "True")
				flash.SitDown();
			else
				flash.ShowError("This seat is not available: " + reason);
		}
	}
	
	//****************
	// StartGame
	//****************
	function StartGame(isMultiplayer)
	{
	    if(isMultiplayer == false)
	        GameFunctions.StartGame(myGameName, mySession, StartGameSP_Callback);
	    else
		    GameFunctions.StartGame(myGameName, mySession, StartGameMP_Callback);
	}

	function StartGameSP_Callback(response)
	{
	    //alert("StartGame Callback: " + response.value);
		if(response.error)
			flash.ShowError('StartGame error: ' + response.error);
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, 'Success');
			var reason = GetValue(dictionary, 'Reason');
			if(succeeded == "True")
			{
				flash.StartGameResult(true, "", response.value);
				inGame = true;
			}
			else
				flash.StartGameResult(false, reason, response.value);
		}
	}

	function StartGameMP_Callback(response)
	{
	    //alert("StartGame Callback: " + response.value);
		if(response.error)
			flash.ShowError('StartGame error: ' + response.error);
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, 'Success');
			var reason = GetValue(dictionary, 'Reason');
		    
			if(succeeded == "True")
			{
				flash.GoToGame(response.value);
				inGame = true;
			}
			else
				flash.ShowError("Game could not be started: " + reason);
		}
	}

	//****************
	// SetStartDateNow
	//****************
	function SetStartDateNow()
	{
	    //alert("set startedate got called");
	    GameFunctions.SetStartDateNow(myGameName, mySession, SetStartDateNow_Callback);
	}
	
	function SetStartDateNow_Callback(response)
	{
	    //alert(response.value);
	}
	
	//****************
	// ExitGame
	//****************
	function ExitGame()
	{
		//alert("Exiting Game");
		GameFunctions.ExitGame(myGameName, mySession, ExitGame_Callback);
	}
	
	function ExitGame_Callback(response)
	{
		//alert("Exit Game " + response.value);
		if(response.error)
			flash.ShowError('ExitGame error: ' + response.error);
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, 'Success');
		
			if(succeeded == "true")
			{
				inGame = false;
			}
			else
				flash.ShowError("Exit Error. Please close your browser.");
		}
	}

//******************************************************************************************************
//******************************************************************************************************
// The Game
//******************************************************************************************************
//******************************************************************************************************
	
	//****************
	// GetChallenge
	//****************
	function GetChallenge()
	{
		//alert("GetChallenge call");
		GameFunctions.GetChallenge(myGameName, mySession, GetChallenge_Callback);
	}
	
	function GetChallenge_Callback(response)
	{
	    //alert("GetChallenge returned " + response.value);
		if(response.error)
			flash.ShowError('GetChallenge Error: ' + response.error);
		else
		{
            var dictionary = CreateDictionaryWrap(response.value);
			myChallenge = GetValue(dictionary, 'Challenge');
			flash.AllowChallengeButtonClick();
			flash.ReceiveChallenge(response.value);
			flash.UpdateSupplies(response.value);
		}
	}
	
	//****************
	// GetResultForAction
	//****************
	function GetResultForAction(action, challengeId)
	{
		//alert("GetResultForAction call (A,CI): " + action + "," + challengeId);
		if(challengeId) // if challengeId is given, action may apply to another challenge which has been set aside
		{
			GameFunctions.GetResultForAction(myGameName, mySession, challengeId, action, GetResultForAction_Callback);
		}
		else
		{
		    //alert(myGameName + " " + mySession + " " + myChallenge + " " + action);
			GameFunctions.GetResultForAction(myGameName, mySession, myChallenge, action, GetResultForAction_Callback);
	    }
	}
	
	function GetResultForAction_Callback(response)
	{
		//alert("GetResultForAction returned " + response.value);
		if(response.error)
			flash.ShowError('GetResultFA Error: ' + response.error);
		else
		{	
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, 'Success');
			if(succeeded != "True")
			{
			    flash.AllowChallengeButtonClick();
			    flash.ShowError("Action not accepted.  Please try again.");
			}
			else
			{
			    if(GetValue(dictionary, 'Status') == "Complete") // Case is over
			    {
				    myChallenge = null;
				    var actionScore = parseInt(GetValue(dictionary, 'ActionScore'));
				    var evalText = GetValue(dictionary, 'Brief');
				    flash.ShowChallengeEvaluation(evalText, actionScore);
				    flash.EndChallenge();
			    }
			    else
			    {
				    flash.AllowChallengeButtonClick();
				    var theResponse = GetValue(dictionary, 'Response');
				    if(theResponse != "none") // There is another part of this case
				    {
				        myChallenge = GetValue(dictionary, 'Challenge');
    				
					    // Show Evaluation
					    var actionScore = parseInt(GetValue(dictionary, 'ActionScore'));
					    var evalText = GetValue(dictionary, 'Brief');
					    flash.ShowChallengeEvaluation(evalText, actionScore);
    					
					    // Show next part of case
					    flash.ReceiveChallenge(response.value);	
				    }	
				    else // No response video, just give some evaluation
				    {
					    var actionScore = parseInt(GetValue(dictionary, 'ActionScore'));
					    var evalText = GetValue(dictionary, 'Brief');
					    flash.ShowChallengeEvaluation(evalText, actionScore);
				    }
			    }
			    flash.UpdateSupplies(response.value);
			}
		}
	}	
	
	//****************
	// GetQuiz
	//****************
	function GetQuiz()
	{
		//alert("GetQuiz call");
		GameFunctions.GetQuiz(myGameName, mySession, GetQuiz_Callback);
	}
	
	function GetQuiz_Callback(response)
	{
		//alert("GetQuiz returned " + response.value);
		if(response.error)
			flash.ShowError('GetQuiz Error: ' + response.error);
		else
		{
			flash.AllowQuizButtonClick();
			var dictionary = CreateDictionaryWrap(response.value);
			var succeeded = GetValue(dictionary, 'Success');
	   		var reason = GetValue(dictionary, 'Reason');
			if(succeeded == "True")
			{
				var theText = GetValue(dictionary, 'Question');
				if(theText != null && theText.length >= 2)
					flash.ShowQuiz(response.value);
			}
			else
			    flash.CheckIfGameIsDone();
		}
	}	
	
	//****************
	// GetResultForChoice
	//****************
	function GetResultForChoice(choice)
	{
		//alert("GetResultForChoice call");
		GameFunctions.GetResultForChoice(myGameName, mySession, "someQuiz", choice, GetResultForChoice_Callback);
	}
	
	function GetResultForChoice_Callback(response)
	{
		//alert("GetResultForChoice returned " + response.value);
		if(response.error)
			flash.ShowError('GetResultFC Error: ' + response.error);
		else
		{
			var dictionary = CreateDictionaryWrap(response.value);
			var actionScore = parseInt(GetValue(dictionary, 'Score'));
			var evalText = GetValue(dictionary, 'EvalText');
			flash.ShowQuizEvaluation(evalText, actionScore, null);
		}
	}
	
//******************************************************************************************************
//******************************************************************************************************
// The After Action Report
//******************************************************************************************************
//******************************************************************************************************

	//****************
	// SaveReport
	//****************
	function SaveReport()
	{
		//alert("SaveReport call");
		GameFunctions.SaveReport(myGameName, mySession, SaveReport_Callback);
	}
	
	function SaveReport_Callback(response)
	{
		//alert("SaveReport returned " + response.value);
		if(response.error)
			flash.ShowError('SaveReport Error: ' + response.error);
		else
		{
			flash.GetGameResults();
		}
	}

	//****************
	// GetQuizHistory
	//****************
	function GetQuizHistory()
	{
		//alert("GetQuizHistory call");
		GameFunctions.GetQuizHistory(myGameName, mySession, GetQuizHistory_Callback);
	}
	
	function GetQuizHistory_Callback(response)
	{
		//alert("GetQuizHistory returned " + response.value);
		if(response.error)
			flash.ShowError('GetQuizHistory Error: ' + response.error);
		else
		{
			flash.DisplayQuizHistory(response.value);
		}
	}
	
	//****************
	// GetChallengeHistory
	//****************
	function GetChallengeHistory()
	{
		//alert("GetChallengeHistory call");
		GameFunctions.GetChallengeHistory(myGameName, mySession, GetChallengeHistory_Callback);
	}
	
	function GetChallengeHistory_Callback(response)
	{
		//alert("GetChallengeHistory returned " + response.value);
		if(response.error)
			flash.ShowError('GetChallengeHistory Error: ' + response.error);
		else
		{
			flash.DisplayChallengeHistory(response.value);
		}
	}
	
	//****************
	// GetIndividualResults
	//****************
	function GetIndividualResults()
	{
		//alert("GetIndividualResults call");
		GameFunctions.GetIndividualResults(myGameName, mySession, GetIndividualResults_Callback);
	}
	
	function GetIndividualResults_Callback(response)
	{
		//alert("GetIndividualResults returned " + response.value);
		if(response.error)
			flash.ShowError('GetIndividualResults Error: ' + response.error);
		else
		{
			flash.DisplayIndividualResults(response.value);
		}
	}
		
	//****************
	// GetIndividualResults
	//****************
	function GetIndividualRecords()
	{
		//alert("GetIndividualRecords call");
		GameFunctions.GetIndividualRecords(myGameName, mySession, GetIndividualRecords_Callback);
	}
	
	function GetIndividualRecords_Callback(response)
	{
		alert("GetIndividualRecords returned " + response.value);
		if(response.error)
			flash.ShowError('GetIndividualRecords Error: ' + response.error);
		else
		{
			flash.DisplayIndividualRecords(response.value);
		}
	}
	
	//****************
	// GetTeamResults
	//****************
	function GetTeamResults()
	{
		//alert("GetTeamResults call");
		GameFunctions.GetTeamResults(myGameName, mySession, GetTeamResults_Callback);
	}
	
	function GetTeamResults_Callback(response)
	{
		//alert("GetTeamResults returned " + response.value);
		if(response.error)
			flash.ShowError('GetTeamResults Error: ' + response.error);
		else
		{
			flash.DisplayTeamResults(response.value);
		}
	}
	
	//****************
	// GetTeamResults
	//****************
	function GetGraphData()
	{
		//alert("GetTeamResults call");
		GameFunctions.GetGraphData(myGameName, mySession, GetGraphData_Callback);
	}
	
	function GetGraphData_Callback(response)
	{
		//alert("GetGraphData returned " + response.value);
		if(response.error)
			flash.ShowError('GetGraphData Error: ' + response.error);
		else
		{
			flash.DisplayGraphs(response.value);
		}
	}

//******************************************************************************************************
//******************************************************************************************************
