function CreatePlayerMoney()
	PermanentStorage.SetLocalInt("Money", 200)
end


function SetClickMessage(screen, receiver, message)
	SendMessage(screen, "template TopMessageTemplate")
    SendMessage(screen, "defineText [receiver] "..receiver)
    SendMessage(screen, "defineText [message] "..message)
	SendMessage(screen, "create top instance")
end

function UnsetClickMessage(screen)
	assert(SendMessageReply(screen, "name of top") == "TopMessageTemplate")
	SendMessage(screen, "erase top child")
end

function TrimBlanks(stroka)
	while string.len(stroka) > 0 and string.find(stroka, "%s") == 1 do 
		stroka = string.sub(stroka, 2);
	end
	while string.len(stroka) > 0 and string.sub(stroka, - 1) == " " do 
		stroka = string.sub(stroka, 1, string.len(stroka) - 1);
	end
	return stroka
end

function GameFunc(message)
	if message == "XML loaded" then
		if PermanentStorage.GetGlobalBool("temp:ScreensaverMode") then
			SendMessage("GameScreen", "clear children list")
			SendMessage("GameScreen", "template TankOnlyTemplate")
			SendMessage("GameScreen", "defineText [exitMessageReceiver] post:lua:GameFunc")
			SendMessage("GameScreen", "defineText [exitMessage] Screen saver done")
			SendMessage("GameScreen", "create top instance")
			SendMessage("post:Aquarium bottom", "Load Screensaver Content")
			local tankId = PermanentStorage.GetLocalStringOrDef("Screensaver Tank", "1")
			if tonumber(tankId) > 3 then
				tankId = PermanentStorage.GetLocalString(tankId.." Tank Type")
			end
			Sound:FadeInTrack("Menu"..tankId, 3, true)
		else
		    if PermanentStorage.GetGlobalBool("Ask player name") then
				SendMessage("GameScreen", "template GUI")
				SendMessage("GameScreen", "create instance before 0")
				Instantiate("Screen", "MainMenuTemplate")
				SendMessage("EffectGameScreen", "template FirstTimeIntro")
 				SendMessage("EffectGameScreen", "create bottom instance")
				Instantiate("EnterTank container", "IntroEnterEffectTemplate")
			end
			SendMessage("Startup progress mover", "report arrival to lua:GameFunc")
			SendMessage("Startup progress mover", "set arrival message Startup progress bar out")
			SendMessage("Startup progress mover", "move to out")
			SendMessage("Logo", "idle")
		end
	elseif message == "Screen saver done" then
		CloseApplication()
	elseif message == "Startup progress bar out" then
		SendMessage("Startup click to start mover", "move to in")
		UnlockScreen() --убираем слой, блокирующий ввод пользователя
		SetClickMessage("LoadScreen", "post:lua:GameFunc", "Start game")
	elseif message == "Start game" then
		UnsetClickMessage("LoadScreen")
		LockScreen()
		--if PermanentStorage.GetGlobalBoolOrDef("temp:dev", false) then
		if PermanentStorage.GetGlobalBool("Ask player name") then
			-- запускаем интро, если стартуем первый раз
			SendMessage("Logo mover", "move to out")
			SendMessage("Logo", "hide premium 0.2")
			SendMessage("Startup click to start mover", "move to out")
			SendMessage("TimedSMS", "Intro click to skip mover, move to in, 0.2")
			SendMessage("TimedSMS", "lua:GameFunc, start Intro, 0.4")
			SendMessage("LoadingScreen alpha changer", "change alpha to 0.0")
		else
			SendMessage("GameScreen", "template DarkeningTemplateLoadScreen")
			SendMessage("GameScreen", "defineText [receiver] post:lua:GameFunc")
			SendMessage("GameScreen", "defineText [message] Click to start main menu")
			SendMessage("GameScreen", "create top instance")
			PermanentStorage.SetLocalBool("temp:black screen", true)
		end
		Application.StartGame()
		
	elseif message == "start Intro" then
	    SendMessage("blank alpha changer", "change alpha to 0.0")
  		SendMessage("Intro", "play");
		SendMessage("TimedSMS", "lua:GameFunc, start Intro continue, 0.4")
		local currentTank = PermanentStorage.GetLocalString("Current Tank")
		if tonumber(currentTank) > 3 then
			Sound:FadeOutTrack("Menu"..PermanentStorage.GetLocalString(currentTank.." Tank Type"), 0.5)
		else
			Sound:FadeOutTrack("Menu"..currentTank, 0.5)
		end
		Sound:FadeInTrack("IntroTrack", 0.5, true)
	    
	elseif message == "start Intro continue" then
		if PermanentStorage.GetGlobalBool("Ask player name") then
			UnlockScreen() --убираем слой, блокирующий ввод пользователя
			SendMessage("EffectGameScreen", "erase child at 1")
		end
		SendMessage("TimedSMS", "lua:GameFunc, finish Intro, 38.6")

	elseif message == "finish Intro" then
		SendMessage("TimedSMS", "clear")
		SendMessage("Intro click to skip mover", "move to out")
		SendMessage("Intro self alpha changer", "change alpha to 0.0") -- прячем мульт, под ним уже лежит аквариум
		SendMessage("Finished intro text alpha", "move to in")         -- показываем последнюю надпись
		SendMessage("Intro click to continue", "move to in")
		LockScreen()
		SendMessage("TimedSMS", "post:lua:GameFunc, set click last intro effect, 0.5")
		SendMessage("TimedSMS", "post:lua:GameFunc, switch track, 3.0")
	elseif message == "switch track" then
		Sound:FadeOutTrack("IntroTrack", 1.0)
		Sound:FadeInTrack("Menu1", 1.0, true)
	elseif message == "set click last intro effect" then
		UnlockScreen()
		SetClickMessage("EffectGameScreen", "post:lua:GameFunc", "exit Intro")
		--[[if PermanentStorage.GetGlobalBool("Ask player name") then
			SetClickMessage("EffectGameScreen", "post:lua:GameFunc", "exit Intro")
		else 
			SetClickMessage("GameScreen", "post:lua:GameFunc", "exit Intro")
		end]]
	elseif message == "exit Intro" then
		UnsetClickMessage("EffectGameScreen")
		--[[if PermanentStorage.GetGlobalBool("Ask player name") then
			SetClickMessage("EffectGameScreen", "post:lua:GameFunc", "exit Intro")
		else 
			UnsetClickMessage("GameScreen")
		end]]
		SendMessage("End Intro", "play effect")
		SendMessage("Finished intro text alpha", "move to out")
		SendMessage("Intro click to continue", "move to out")
		SendMessage("Finished intro text zoom", "change zoom to end")
		SendMessage("TimedSMS", "Finished intro background alpha changer, change alpha to 0.0, 0.2")
		LockScreen()
		
	elseif message == "enter MainMenu" then
        if PermanentStorage.GetGlobalBool("Ask player name") then
			SendMessage("GameScreen", "erase top child")
			SendMessage("GameScreen", "erase top child")
			--SendMessage("EffectGameScreen", "clear children list")
			SendMessage("First name modal dialog", "instantiate FirstPlayerNameEditTemplate")
			SendMessage("EditBoxDialogMover", "move to in")
			Instantiate("Current tank content", "MainMenuTankTemplate")
		else
			GameFunc("Click to start main menu")
		end
		
	elseif message == "ok first player name" then
		local newName = SendMessageReply("Player name edit", "get value")
		newName = TrimBlanks(newName)
		if newName ~= "" then
			PermanentStorage.RenamePlayer(PermanentStorage.GetActivePlayerName(), newName)
			PermanentStorage.SetGlobalBool("Ask player name", false)
			SendMessage("EditBoxDialogMover", "move to out")
			SendMessage("First name modal dialog", "hide")
			SendMessage("TimedSMS", "lua:GameFunc, Show panels first time, 0.2")
			SendMessage("TimedSMS", "lua:GameFunc, Show logo first time, 0.5")
			LockScreen()
			CreatePlayerMoney()
		end
	elseif message == "Show panels first time" then
		MoveMainMenuPanels("in", "null", "null")
	elseif message == "Show logo first time" then
		UnlockScreen()
		Instantiate("Current tank content", "GameLogoTemplate")
		SendMessage("Swinging 2", "run")
	elseif message == "Start intro key pressed" then
		SendMessage("Intro", "play")
		--SendMessage("IntroTextControlReceiver", "start")--запускаем тексты
	elseif message == "new player create" then
		newPlayerName = SendMessageReply("Player name edit", "get value") --глобальная переменная в луа
		newPlayerName = TrimBlanks(newPlayerName)
		SendMessage("EditBoxDialogMover", "move to out");
		SendMessage("Main menu modal dialog", "hide")
		SendMessage("GameScreen", "template DarkeningTemplate") --кладем затемняюдий слой
		SendMessage("GameScreen", "defineText [receiver] post:lua:GameFunc")
		SendMessage("GameScreen", "defineText [message] new player create continue")
		SendMessage("GameScreen", "create top instance")
		LockScreen()
		MoveMainMenuPanels("out")

  	elseif message== "new player create continue" then
		SendMessage("GameScreen", "erase top child") -- ~UnlockScreen
		SendMessage("GameScreen", "erase top child")
    	SendMessage("Current tank content", "clear children list")
		--выключаем музыку
		local currentTank = PermanentStorage.GetLocalString("Current Tank");
		if (tonumber(currentTank) > 3) then
			currentTank = PermanentStorage.GetLocalString(currentTank.." Tank Type")
		end
		Sound:FadeOutTrack("Menu"..currentTank, 1.0)
		PermanentStorage.CreatePlayer(newPlayerName)
		CreatePlayerMoney()
		newPlayerName = nil
		Sound:FadeInTrack("Menu1", 1.0, true)
		
    	--EnterMainMenu("intro")                                --кладем меню и переход в аквариум

		Instantiate("GameScreen", "IntroEnterEffectMainTemplate")

		SendMessage("EffectGameScreen", "template FirstTimeIntro")
		SendMessage("EffectGameScreen", "create bottom instance")
		Instantiate("EffectGameScreen", "LoadingLogoTemplate")
		Instantiate("EnterTank container", "IntroEnterEffectTemplate")
		SendMessage("End Intro", "run")

		GameFunc("start Intro")

		SendMessage("TimedSMS", "Intro click to skip mover, move to in, 0.2")

		SendMessage("Logo mover", "move to out")
		SendMessage("Logo", "idle")
		SendMessage("Logo", "hide premium 0.0")
		SendMessage("GameScreen", "template BrighteningTemplate")   --кладем выцветающий слой
		SendMessage("GameScreen", "create top instance")

	elseif message == "Click to start main menu" then
		SendMessage("GameScreen", "clear children list")
		Instantiate("GameScreen", "GUI")
		MainMenuFunc("Enter main menu")
		if PermanentStorage.GetLocalBoolOrDef("temp:black screen", false) then
			SendMessage("Screen", "template BrighteningTemplate")
			SendMessage("Screen", "create top instance")
		end
	else
		assert(false, "Unknown message "..message)
	end
end

function BetaFunc(message)
	if message == "Game field to main screen" 
		or message == "Game field to shop" 
		or message == "Main menu to main screen"
		or message == "Main screen to shop"
		or message == "Main screen to game field"
		or message == "Shop to main screen" then
			--SendMessage("post:lua:BetaFunc", "Duplicate player if hour")
	elseif message == "Duplicate player if hour" then
		if PermanentStorage.GetGlobalBoolOrDef("betaLog", false) then
			local totalTime = PermanentStorage.GetLocalFloatOrDef("Total time", 0)
			local backuped = PermanentStorage.GetLocalBoolOrDef("Was one hour backup", false)
			if totalTime > 3600 and not backuped then
				PermanentStorage.SetLocalBool("Was one hour backup", true)
				PermanentStorage.BackupActivePlayer("  (1h)")
				WriteToLogColor("One hour checkpoint!", "Red")
			end
		end
	elseif message == "Duplicate player won cup" then
		if PermanentStorage.GetGlobalBoolOrDef("betaLog", false) then
			local tankId = PermanentStorage.GetLocalString("Current Tank")
			local cup = PermanentStorage.GetLocalString(tankId.." Cup")
			if cup == "Bronze" then
				PermanentStorage.BackupActivePlayer(tankId.." B")
			elseif cup == "Silver" then
				PermanentStorage.BackupActivePlayer(tankId..".S")
			elseif cup == "Gold" then
				PermanentStorage.BackupActivePlayer(tankId..":G")
			else
				assert(false)
			end
		end
	elseif message == "Clear cup time" then
		if PermanentStorage.GetGlobalBoolOrDef("betaLog", false) then
			PermanentStorage.SetLocalFloat("Cup time", 0)
			WriteToLog("Cup time reset")
		end
	elseif message == "Commit" then
		if PermanentStorage.GetGlobalBoolOrDef("betaLog", false) then
			WriteToLog("autosave...")
		end
		PermanentStorage.Commit()
	else
		assert(false, "Unknown message "..message)
	end
end