// Handles Main Menu Operations.
// Worthless Bums 2012.


function chooseNewGameDifficulty ()
{//echo("chooseNewGameDifficulty()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	Canvas.pushDialog(DifficultyDialog);
}
function difficultyGuiEasy ()
{//echo("difficultyGuiEasy()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	Canvas.popDialog(DifficultyDialog);
	$difficultyLevel = 0;
	initializeSquadCreationGui();
}
function difficultyGuiNormal ()
{//echo("difficultyGuiNormal()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	Canvas.popDialog(DifficultyDialog);
	$difficultyLevel = 1;
	initializeSquadCreationGui();
}
function difficultyGuiHard ()
{//echo("difficultyGuiHard()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	Canvas.popDialog(DifficultyDialog);
	$difficultyLevel = 2;
	initializeSquadCreationGui();
}
function difficultyGuiBrutal ()
{//echo("difficultyGuiBrutal()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	Canvas.popDialog(DifficultyDialog);
	$difficultyLevel = 3;
	initializeSquadCreationGui();
}
function newGameButton (%loadFromSave)
{//echo("newGameButton()");//echo("%loadFromSave =" SPC %loadFromSave);
	// Destroy all objects!

	clearRankHighlights();
	
	// Create the fog of war class and object instance!
	if (isObject($fogOfWar))
	{
		$fogOfWar.destroy();
		//$fogOfWar.safeDelete();
		deleteVariables("$fogOfWar");
	}
	$fogOfWar = new ScriptObject("FogOfWar")
	{
		class = "fogOfWarClass";
		tiles[32, 32] = 0;
	};
	
	startGameTimer();
	updateGuiElementPositioning();
	resetSquadPowerCooldowns();
	clearTalentBarIcons();
	clearSquadInventory();
	initializeGlobals();
	setupInputs();
	// NOTE: Not in function initializeGlobals() because it will screw up
	//		 the New Game Plus run counter!
	if (!%loadFromSave)
	{
		$NewGamePlus = 0;
	}
	if (%loadFromSave)
	{
		loadSaveDataFromFile();
	}
	clearLog();
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	$timescale = 1;
	popMainMenu();
	Canvas.hideCursor();
	startGame($Game::DefaultScene);
	$fogOfWar.init();
	// Only generate new level data if we're not loading from file!
	if ($NewGameStart)	// For loading a fresh New Game Plus save file!
	{//echo("$NewGameStart =" SPC $NewGameStart);
		generateRandomLevel();
		spawnTreasureChests();
		createSquadInventory();
		spawnItems();
		createNewSquad(levelSceneGraph);
		moveSquadToFreeArea();
		spawnTraps();
	}
	else if (!%loadFromSave	||
			 $generateNewLevel)
	{//echo("$generateNewLevel =" SPC $generateNewLevel);
		generateRandomLevel();
		spawnTreasureChests();
		createSquadInventory();
		spawnItems();
		createNewSquad(levelSceneGraph);
		spawnTraps();
	}
	else if ($NewLevelObjectSpawning)	// Flag for elevator progression.
	{//echo("level generation from elevator progression!");		// New + progress memory leak!
		generateLoadLevel();
		spawnTreasureChests();
		spawnItems();
		spawnTraps();
		createNewSquad(levelSceneGraph);
	}
	else	// This code gets called on load game and on elevator progression!
	{//echo("generating load level from save file!");
		generateLoadLevel();				// Leaking ~12kb of memory per level load!
		createNewSquad(levelSceneGraph);	// Leaking ~388kb of memory per level load!
	}
	$NewLevelObjectSpawning = false;
	if ($loadFromSave)
	{//echo("$loadFromSave =" SPC $loadFromSave);
		schedule(1000, 0, "updateSquadMemberFloatingText");
		schedule(1000, 0, "updateMonsterFloatingText");
	}
	setPortraits();
	updateSquadInfoGui();
	Canvas.pushDialog(exploreGui);
	setupInputs();
	handleActiveCharacterIndicator();
	updateEventText("Press " @ $whiteColor @ "[" @ $ToggleTutorialBind @ "] " @ $defaultColor @ "for keybinds!");
	// Don't bother doing this here if we're loading from save.
	if (!%loadFromSave	||
		$generateNewLevel)
	{
		mountSquadWeapons();
		if (!$generateNewLevel)
		{
			moveSquadToFreeArea();
		}
		correctStairs();
		setDefaultSquadFacing();
		$fogOfWar.initFogOfWar();
		handleHealthIndicators();
		resetSquadGuardModes();
	}
	updatePortraits();
	switch ($scaleLevel)
	{
		case 1:	setZoom1x();
		case 2:	setZoom2x();
		case 3:	setZoom3x();
	}
	updateCameraPosition();
	orientSquadMemberWeaponAttachments();
	if (!%loadFromSave	||
		$generateNewLevel)
	{
		%numberOfMonsters = getDungeonLevelSpawnCount();
		spawnMonsters(%numberOfMonsters);
	}
	attachAllUnitShadows();
	updateSquadMemberFloatingText();
	updateMonsterFloatingText();
	initializeMissionObjectives();
	updateControlPanelTooltips();
	updateMoneyCounter();
	showHud();
	updateScrollingEventLogPosition();
	schedule(50, 0, "updateScrollingEventLogPosition");
	schedule(50, 0, "updateDeckStats");
	enforceMonsterPositions();
	enforceGameState();
	// Brand new game!
	if (!%loadFromSave)
	{
		executeNewGameDialogue();
		schedule(1700, 0, "pushDeckStatsText");
		if ($difficultyLevel >= 3)	// Difficulty is at least Brutal.
		{
			giveItem(0);	// Medkit.
			giveItem(0);	// Medkit.
			giveItem(5);	// Adrenal Shot.
			giveItem(5);	// Adrenal Shot.
			giveItem(10);	// Grenade.
			giveItem(10);	// Grenade.
			giveItem(17);	// Lasershot.
			giveItem(17);	// Lasershot.
			giveItem(3);	// Sentry Case.
			giveItem(3);	// Sentry Case.
			giveItem(21);	// Lasershot.
			giveItem(25);	// MedStim.
			// Set squad weapons to plasma!
			setSquadMemberLaserWeapon(0);
			setSquadMemberLaserWeapon(1);
			setSquadMemberLaserWeapon(2);
			setSquadMemberLaserWeapon(3);
			setSquadMemberPlasmaWeapon(0);
			setSquadMemberPlasmaWeapon(1);
			setSquadMemberPlasmaWeapon(2);
			setSquadMemberPlasmaWeapon(3);
		}
	}
	//runGirderParallax();			// Disabled for now!
	$generateNewLevel = false;
	executeRandomWeatherEvent();	// Randomize? Level specific? Actual effect?
	$LastWindowPoint = sceneWindow2D.getWindowPoint(sceneWindow2D.getMousePosition());
	// Strip sprite physics!
	// Lock in original squad member sizes to account for rapid growing/shrinking!
	if ($leaderPersist)
	{
		$playerSquad[0].CollisionPhysicsReceieve = "0";
		$playerSquad[0].CollisionPhysicsSend = "0";
		$playerSquad[0].originalSize = $playerSquad[0].size;
	}
	if ($scoutPersist)
	{
		$playerSquad[1].CollisionPhysicsReceieve = "0";
		$playerSquad[1].CollisionPhysicsSend = "0";
		$playerSquad[1].originalSize = $playerSquad[1].size;
	}
	if ($grenadierPersist)
	{
		$playerSquad[2].CollisionPhysicsReceieve = "0";
		$playerSquad[2].CollisionPhysicsSend = "0";
		$playerSquad[2].originalSize = $playerSquad[2].size;
	}
	if ($supportPersist)
	{
		$playerSquad[3].CollisionPhysicsReceieve = "0";
		$playerSquad[3].CollisionPhysicsSend = "0";
		$playerSquad[3].originalSize = $playerSquad[3].size;
	}
	// Fade mouse after a set amount of time if inactive!
	$LastTimeSinceMouseEvent = getScriptTimer();
	checkMouseEvents();
	checkMousePosition();
	// Update Firearm UI.
	updateFirearmReloadReadout();
	// Set indices (primarily to set lifted tile marker animations!)
	schedule(500, 0, "enforceMonsterIndices");
	
	// Handle active character indicator for new tutorial level!
	handleActiveCharacterIndicator();
}
// This is called from MainMenuGui to show the options dialog.
function optionsButton ()
{//echo("optionsButton()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	Canvas.pushDialog(optionsDlg);
}
// This is called from MainMenuGui to load a game.
function loadGameButton ()
{//echo("loadGameButton()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	%path = $UserDirectory @ "/Worthless Bums/Steam Marines";
	loadGameGuiDirectoryFileListCtrl.setPath(%path, "*.sav");					// No trailing slash in the directory path!
	Canvas.pushDialog(OpenFileGui);
}
// Called from OpenFileGui when the cancel button is clicked.
function cancelLoadGame ()
{//echo("cancelLoadGame()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	MessageCallback(OpenFileGui, OpenFileGui.cancelCallback);
}
// Gets called from OpenFileGui.gui when a file is selected and the delete button is clicked.
function deleteSelectedFile ()
{//echo("loadSelectedFile()");
	%selectedFile = loadGameGuiDirectoryFileListCtrl.getSelectedFile();
	if (%selectedFile !$= "")
	{
		playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
		messageBoxOKCancel("Delete Save Game!", "Are you sure you wish to delete " @ %selectedFile @ "?", "deleteSelectedSaveGame();", "doNotdeleteSaveGame();");
	}
	else
	{
		playAudio("Audio:cancelButton", EffectsAudioVolume.value);
	}
}
// Called when the player chooses to not delete the selected save game.
function doNotdeleteSaveGame ()
{//echo("doNotdeleteSaveGame()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
}
// The user has really elected to delete the selected save file!
function deleteSelectedSaveGame ()
{//echo("deleteSelectedSaveGame()");
	%filePath = loadGameGuiDirectoryFileListCtrl.getSelectedFile();
	%filePath = $UserDirectory @ "/Worthless Bums/Steam Marines/" @ %filePath;
	fileDelete(%filePath);
}
// Gets called from OpenFileGui.gui when a file is selected and the load button is clicked.
function loadSelectedFile ()
{//echo("loadSelectedFile()");
	%file = loadGameGuiDirectoryFileListCtrl.getSelectedFile();
	if (%file $= "")
	{
		playAudio("Audio:cancelButton", EffectsAudioVolume.value);
	}
	else
	{
		playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
		Canvas.popDialog(OpenFileGui);
		%filePath = $UserDirectory @ "/Worthless Bums/Steam Marines/" @ %file;
		LoadSaveGameData(%filePath);
	}
}
// Gets called from OpenFileGui.gui when a file is selected and the load button is clicked.
function loadSaveGameFromPlayerName (%playerName)
{//echo("loadSaveGameFromPlayerName()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	%filePath = %playerName @ ".sav";
	%filePath = $UserDirectory @ "/Worthless Bums/Steam Marines/" @ %filePath;
	LoadSaveGameData(%filePath);
}
// This is called from MainMenuGui to show the about box.
function aboutButton ()
{//echo("aboutButton()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	Canvas.pushDialog(aboutGui);
}
// This is called from the about box to close the gui.
function leaveAboutBox ()
{//echo("leaveAboutBox()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	Canvas.popDialog(aboutBoxGui);
}
// This is called from the main menu gui to quit the game.
function quitGameButton ()
{//echo("quitGameButton()");
quitMessageBoxCurrentGame();
return;
	// Dispatch based on if there is a current game in progress or not.
	if ($gameInProgress)
	{
		quitMessageBoxCurrentGame();
	}
	else
	{
		playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
		messageBoxOKCancel("Quit Game.", "Are you sure you\nwish to quit the game?", "quitGame();", "doNotQuit();");
	}
}
// This is called from the main menu gui to quit the game (when there is a game in progress!).
function quitMessageBoxCurrentGame ()
{//echo("quitMessageBoxCurrentGame()");
quitGameInProgress();
return;	// Remove prompt!
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	messageBoxOKCancel("Quit Game.", "Really quit the game?\nAll progress will be saved.", "quitGameInProgress();", "doNotQuit();");
}
// Called when the player chooses not to quit the game.
function doNotQuit ()
{//echo("doNotQuit()");
	disableGuiInProgress();
	playAudio("Audio:cancelButton", EffectsAudioVolume.value);
}
// Called when the player chooses to quit the game.
function quitGame ()
{//echo("quitGame()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	quit();
}
// Called when the player chooses to quit the game in progress.
function quitGameInProgress ()
{//echo("quitGameInProgress()");
	playAudio("Audio:mainMenuButton", EffectsAudioVolume.value);
	if (!$NewGameStart)
	{
		saveCurrentGame();
	}
	quit();
}