//---------------------------------------------------------------------------------------------
// Torque Game Builder
// Copyright (C) GarageGames.com, Inc.
//---------------------------------------------------------------------------------------------
$Game::CommonVersion = 114;

//---------------------------------------------------------------------------------------------
// initializeCommon
// Initializes common game functionality.
//---------------------------------------------------------------------------------------------
function initializeCommon()
{

	// Common keybindings.
	// GlobalActionMap doesn't get preference anymore so need special sequence to toggle console.
	// This also allows ~ to be used in the console now ;p	
	GlobalActionMap.bind(keyboard, $Game::ScreenshotBind, doScreenShot);
	GlobalActionMap.bindcmd(keyboard, $Game::FullscreenBind, "toggleFullScreen();","");
	
	GlobalActionMap.bindCmd(keyboard, "escape", "$quitDialog.OpenDialog(false);","");
	GlobalActionMap.bindCmd(keyboard, "s", "skipEffectQueue();","");
	GlobalActionMap.bindCmd(keyboard, "c", "Cheats::KeyPress(\"c\");","");
	GlobalActionMap.bindCmd(keyboard, "h", "Cheats::KeyPress(\"h\");","");
	GlobalActionMap.bindCmd(keyboard, "e", "Cheats::KeyPress(\"e\");","");
	GlobalActionMap.bindCmd(keyboard, "a", "Cheats::KeyPress(\"a\");","");
	GlobalActionMap.bindCmd(keyboard, "t", "Cheats::KeyPress(\"t\");","");
	// GlobalActionMap.bindCmd(keyboard, "[", "TextDebug::ViewIndex($TextDebug::Index-1);","");
	// GlobalActionMap.bindCmd(keyboard, "]", "TextDebug::ViewIndex($TextDebug::Index+1);","");
	// exec("~/gui/textDebug.gui");	
	
	// Very basic functions used by everyone.
	exec("./audio.cs"); 
	exec("./canvas.cs");
	exec("./cursor.cs");

   // Seed the random number generator.
   setRandomSeed();
   
   // Set up networking.
   if( $Game::UsesNetwork )
      setNetPort(0);
      
   // Load user preferences
   exec("common/preferences/GeneralSettings.cs");
   	$pref::Video::fullScreen = GeneralSettings::LoadFullscreen();
	// echo("We gots the fullscreen equal to: "@ $pref::Video::fullScreen);
   // Force videomode based on file presence, for debugging
	exec("common/preferences/videoPrefs.cs"); 
	//set up resolution change failure message
	if($Error::DisplayChange::Title $= "")
	{
		$Error::DisplayChange::Title = "Display Change Failed";
		$Error::DisplayChange::Body  = "The game couldn't switch your monitor to fullscreen automatically.  You may want to try quitting the game, and setting your monitor resolution to 800x600 to enable fullscreen.";
	}
   // Initialize the canvas.
   initializeCanvas( $Game::ProductName );
   
   // Start up the audio system.
   if( $Game::UsesAudio )
   {
      initializeOpenAL();
      // kw: for now, don't use CADI
      //if(isFunction("cadiInitialize"))
      	//cadiInitialize();
   }
   
   // Content.
   exec("~/gui/profiles.cs");
   exec("~/gui/cursors.cs");

   // Common Guis.
   $leanAndMean = (!isFile("common/skDebug"));
   if(!$leanAndMean)
   {
		exec("~/gui/messageBoxOk.gui");
		exec("~/gui/messageBoxYesNo.gui");
		exec("~/gui/messageBoxYesNoCancel.gui");
		exec("~/gui/messageBoxOKCancel.gui");
		exec("~/gui/messageBoxOKCancelDetailsDlg.gui");
		exec("~/gui/messagePopup.gui");
   		exec("~/gui/console.gui");
		exec("~/gui/remap.gui");
		exec("~/gui/NetworkMenu.gui");
		exec("~/gui/startServer.gui");
		exec("~/gui/joinServer.gui");
		exec("~/gui/waitingForServer.gui");
		exec("~/gui/helpDlg.gui");
   }
   exec("~/gui/options.gui");
   
   // Gui Helper Scripts.
   exec("~/gui/messageBox.cs");
   exec("~/gui/help.cs");

   // Chat gui
   if(!$leanAndMean)
   	exec("~/gui/chatGui.gui");

   // Random Scripts.
   exec("./screenshot.cs");
   exec("./metrics.cs");
   exec("./scriptDoc.cs");
   exec("./keybindings.cs");
   exec("./options.cs");
   exec("./levelManagement.cs");
   exec("./projectManagement.cs");
   exec("./projectResources.cs");
   exec("./align.cs");

   // Load client and server scripts.
   if( $Game::UsesNetwork )
   {
      initBaseClient();
      initBaseServer();
   }
   // Set a default cursor.
   Canvas.setCursor(DefaultCursor);
   
   // Clean the screen
   exec("common/gui/skCleanScreen.gui");
   Canvas.setContent(skCleanScreen);
   // Go fullscreen or adjust canvas accordingly
   %goodres = $Game::Resolution;
   // If desktop is 800x600 then downsize window
   //if ($Video::WindowedDesktopSize !$= "" && getWord($Video::WindowedDesktopSize,0) <= GetWord( %goodres,1)) {
      //echo("Desktop too small, so sticking into fullscreen at desktop size");
      //%goodres = "800 600 32";
      //$Game::Resolution = "800 600 32";
      //$pref::Video::fullscreen = "1";
   //}
   
   // kw: for Flux check desktop, if 1024x768 or less then go fullscreen all the time
   %tDesktop = $Game::DesktopResolution;
   if (getWord(%tDesktop,0) <= getWord($Game::Resolution,0))
   {
      $pref::Video::fullScreen = true;
      $Game::FullscreenRequired = true;
   }
   
   if ($pref::Video::fullScreen || $pref::Video::fullScreen $= "true") {
	   if ($Game::EnterWindowed != 1)
	   {
	      %res = setScreenMode( GetWord( %goodres, 0), GetWord( %goodres,1), GetWord( %goodres,2), true );
	      if(!%res)
	      {
	      	$pref::Video::fullScreen = false;
	      	setScreenMode( GetWord( %goodres, 0), GetWord( %goodres,1), GetWord( %goodres,2), false );
	      }
	   }
		$pref::Video::fullScreen = 1;
		// kw: for Flux, trying commenting restoreWindow() out in case it's causing the flickery-flicker
		//     jan 12, 2009. didn't cause problems for me but look out for it. Maybe a bad idea.
	   //restoreWindow();
	} else {
		setScreenMode( GetWord( %goodres, 0), GetWord( %goodres,1), GetWord( %goodres,2), false );
   }
   
   loadKeybindings();

   $commonInitialized = true;

}


//---------------------------------------------------------------------------------------------
// _shutdownCommon
// Shuts down common game functionality.
//---------------------------------------------------------------------------------------------
function _shutdownCommon()
{
   if(isFunction("shutdownProject"))
      shutdownProject();
   
   // kw: for now don't use CADI
   //if(isFunction("cadiShutdown"))
   	//cadiShutdown();   
   shutdownOpenAL();
}

//---------------------------------------------------------------------------------------------
// dumpKeybindings
// Saves of all keybindings.
//---------------------------------------------------------------------------------------------
function dumpKeybindings()
{
   // Loop through all the binds.
   for (%i = 0; %i < $keybindCount; %i++)
   {
      // If we haven't dealt with this map yet...
      if (isObject($keybindMap[%i]))
      {
         // Save and delete.
         $keybindMap[%i].save("~/prefs/bind.cs", %i == 0 ? false : true);
         $keybindMap[%i].delete();
      }
   }
}

//---------------------------------------------------------------------------------------------
// initBaseClient
// Initializes necessary client functionality.
//---------------------------------------------------------------------------------------------
function initBaseClient()
{
   // Base client scripts.
   exec("./client/client.cs");
   exec("./client/message.cs");
   exec("./client/serverConnection.cs");
   exec("./client/chatClient.cs");
}

//---------------------------------------------------------------------------------------------
// initBaseServer
// Initializes necessary server functionality.
//---------------------------------------------------------------------------------------------
function initBaseServer()
{
   // Base server scripts.
   exec("./server/server.cs");
   exec("./server/message.cs");
   exec("./server/clientConnection.cs");
   exec("./server/kickban.cs");
   exec("./server/chatServer.cs");
}

//--------------------------------------------------------------------------
// Load a Mod Directory.
//--------------------------------------------------------------------------
function loadDir( %dir )
{
   // Set Mod Paths.
   setModPaths( getModPaths() @ ";" @ %dir );
   
   // Execute Boot-strap file.
   exec( %dir @ "/main.cs" );
}


//--------------------------------------------------------------------------
// Rounds a number
//--------------------------------------------------------------------------
function mRound(%num)
{
   if((%num-mFloor(%num)) >= 0.5)
   {
      %value = mCeil(%num);
   }
   else
   {
      %value = mFloor(%num);
   }    

   return %value;
}
