function SimpleFadePushLayer(layerName, widgetName)

	fadeScreens = fadeScreens+1
	
	local fadeLayer = ""
	if (fadeScreens == 1) then
		fadeLayer = "Cross1"
	elseif (fadeScreens == 2) then
		fadeLayer = "Cross2"
	else
		fadeLayer = "Cross3"
	end
	
	local panelWidget = GUI:getLayer(layerName):getWidget(widgetName)
	if panelWidget ~= nil then
		panelWidget:setColor(Color(255, 255, 255, 0))
	end

	local fadeWidget = GUI:getLayer(fadeLayer):getWidget("BlackScreen")
	fadeWidget:setColor(Color(0, 0, 0, 0))

	local param = VariableSet()
	param:setWidget("Widget", panelWidget)
	param:setColor("To", Color(255, 255, 255, 255))
	kernel:addController(controlFactory:Create("Fader", param))

	param = VariableSet()
	param:setWidget("Widget", fadeWidget)
	param:setColor("To", Color(0, 0, 0, 150))
	kernel:addController(controlFactory:Create("Fader", param))

	Screen:pushLayer(GUI:getLayer(fadeLayer))
	Screen:pushLayer(GUI:getLayer(layerName) )
end

function SimpleFadePopLayer(layerName, widgetName)

	local fadeLayer = ""
	if (fadeScreens == 1) then
		fadeLayer = "Cross1"
	elseif (fadeScreens == 2) then
		fadeLayer = "Cross2"
	else
		fadeLayer = "Cross3"
	end

	fadeScreens = fadeScreens - 1

	local panelWidget = GUI:getLayer(layerName):getWidget(widgetName)
	local fadeWidget = GUI:getLayer(fadeLayer):getWidget("BlackScreen")

	param = VariableSet()
	param:setWidget("Widget", panelWidget)
	param:setColor("To", Color(255, 255, 255, 0))
	param:setBool("PopLayer", true)
	kernel:addController(controlFactory:Create("Fader", param))

	param = VariableSet()
	param:setWidget("Widget", fadeWidget)
	param:setColor("To", Color(0, 0, 0, 0))
	param:setBool("PopLayer", true)
	kernel:addController(controlFactory:Create("Fader", param))
end

function VideosFadePushLayer(layerName, widgetName)

	fadeScreens = fadeScreens+1
	
	local fadeLayer = ""
	if (fadeScreens == 1) then
		fadeLayer = "Cross1"
	elseif (fadeScreens == 2) then
		fadeLayer = "Cross2"
	else
		fadeLayer = "Cross3"
	end
	
	local panelWidget = GUI:getLayer(layerName):getWidget(widgetName)
	if panelWidget ~= nil then
		panelWidget:setColor(Color(255, 255, 255, 0))
	end

	local fadeWidget = GUI:getLayer(fadeLayer):getWidget("BlackScreen")
	fadeWidget:setColor(Color(0, 0, 0, 0))

	local param = VariableSet()
	param:setWidget("Widget", panelWidget)
	param:setColor("To", Color(255, 255, 255, 255))
	param:setString("EndHandler", "StartVideo")
	kernel:addController(controlFactory:Create("Fader", param))

	param = VariableSet()
	param:setWidget("Widget", fadeWidget)
	param:setColor("To", Color(0, 0, 0, 190))
	kernel:addController(controlFactory:Create("Fader", param))

	Screen:pushLayer(GUI:getLayer(fadeLayer))
	Screen:pushLayer(GUI:getLayer(layerName) )
end

fadeScreens = 0
fadeScreens2 = 0

function ResetFadeScreens()
	fadeScreens = 0
end

function SaveFadeScreens()
	fadeScreens2 = fadeScreens
end

function RestoreFadeScreens()
	fadeScreens = fadeScreens2
end

function RestoreFadeScreens2()
	fadeScreens = fadeScreens2
	GUI:getLayer("CGuide"):getWidget("ACGuide"):AcceptMessage(Message("Release"))
end

function GetFadeScreensNumber()
    return fadeScreens;
end

function SetFadeScreensNumber(fadeScreens_)
	fadeScreens = fadeScreens_;
end

-----------------------------------------------------------
-- Утилиты
-----------------------------------------------------------
function FadePushLayer(layerName, widgetName, faderType)
	fadeScreens = fadeScreens+1
	
	local fadeLayer = ""
	if (fadeScreens == 1) then
		fadeLayer = "Cross1"
	elseif (fadeScreens == 2) then
		fadeLayer = "Cross2"
	else
		fadeLayer = "Cross3"
	end
	
	local panelWidget = GUI:getLayer(layerName):getWidget(widgetName)
	panelWidget:setColor(Color(255, 255, 255, 0))

	local fadeWidget = GUI:getLayer(fadeLayer):getWidget("BlackScreen")
	fadeWidget:setColor(Color(0, 0, 0, 0))

	local param = VariableSet()
	param:setWidget("Widget", panelWidget)
	param:setColor("To", Color(255, 255, 255, 255))
	kernel:addController(controlFactory:Create("Fader", param))

	param = VariableSet()
	param:setWidget("Widget", fadeWidget)
	param:setColor("To", Color(0, 0, 0, 150))
	if (faderType) then
		param:setString("FaderType", faderType)
	else
		param:setString("FaderType", "Scaled")
	end
	kernel:addController(controlFactory:Create("Fader", param))

	Screen:pushLayer(GUI:getLayer(fadeLayer))
	Screen:pushLayer(GUI:getLayer(layerName) )
end

function FlyPushLayer(layerName, widgetName, Mode, handler)
	if (Mode == 0) then
		fadeScreens = fadeScreens+1
	end
	
	local fadeLayer = ""
	if (fadeScreens == 1) then
		fadeLayer = "Cross1"
	elseif (fadeScreens == 2) then
		fadeLayer = "Cross2"
	else
		fadeLayer = "Cross3"
	end

	if (Mode == 1) then
		fadeScreens = fadeScreens-1
	end
	
	local panelWidget = GUI:getLayer(layerName):getWidget(widgetName)
	local fadeWidget = GUI:getLayer(fadeLayer):getWidget("BlackScreen")
	fadeWidget:setColor(Color(0, 0, 0, 150*Mode))
	local param = VariableSet()
	param:setWidget("Widget", panelWidget)
	param:setString("Layer", layerName);
	param:setColor("To", Color(255, 255, 255, 255))
	param:setBool("PopLayer", Mode == 1)
	param:setFloat("timeScale", 2.5)
	if (handler) then
		param:setString("EndHandler", handler)
	end
	kernel:addController(controlFactory:Create("Flyer", param))

	param = VariableSet()
	param:setWidget("Widget", fadeWidget)
	param:setColor("To", Color(0, 0, 0, 150*(1-Mode)))
	param:setBool("PopLayer", Mode == 1)
	param:setFloat("timeScale", 3.2)
	--param:setString("FaderType", "Scaled")
	kernel:addController(controlFactory:Create("Fader", param))
	if (Mode == 0) then
		GUI:getLayer(layerName):getWidget("Seal"):AcceptMessage(Message("SetSwing", 20))
		Screen:pushLayer(GUI:getLayer(fadeLayer))
		Screen:pushLayer(GUI:getLayer(layerName))
	end
end

function ExitConfirmFlyPushLayer(Mode, handler)
	local panelWidget = GUI:getLayer("ExitConfirm"):getWidget("ExitConfirm")
	local fadeWidget = GUI:getLayer("ExitConfirmCross"):getWidget("BlackScreen")
	fadeWidget:setColor(Color(0, 0, 0, 150*Mode))
	local param = VariableSet()
	param:setWidget("Widget", panelWidget)
	param:setString("Layer", "ExitConfirm");
	param:setColor("To", Color(255, 255, 255, 255))
	param:setBool("PopLayer", Mode == 1)
	param:setFloat("timeScale", 2.5)
	if (handler) then
		param:setString("EndHandler", handler)
	end
	kernel:addController(controlFactory:Create("Flyer", param))

	param = VariableSet()
	param:setWidget("Widget", fadeWidget)
	param:setColor("To", Color(0, 0, 0, 150*(1-Mode)))
	param:setBool("PopLayer", Mode == 1)
	param:setFloat("timeScale", 3.2)
	kernel:addController(controlFactory:Create("Fader", param))
	if (Mode == 0) then
		GUI:getLayer("ExitConfirm"):getWidget("Seal"):AcceptMessage(Message("SetSwing", 20))
		Screen:pushLayer(GUI:getLayer("ExitConfirmCross"))
		Screen:pushLayer(GUI:getLayer("ExitConfirm"))
	end
end

function FadePushLayerWithEndHandler(layerName, widgetName, endHandler)

	fadeScreens = fadeScreens+1
	
	local fadeLayer = ""
	if (fadeScreens == 1) then
		fadeLayer = "Cross1"
	elseif (fadeScreens == 2) then
		fadeLayer = "Cross2"
	else
		fadeLayer = "Cross3"
	end
	
	local panelWidget = GUI:getLayer(layerName):getWidget(widgetName)
	panelWidget:setColor(Color(255, 255, 255, 0))

	local fadeWidget = GUI:getLayer(fadeLayer):getWidget("BlackScreen")
	fadeWidget:setColor(Color(0, 0, 0, 0))

	local param = VariableSet()
	param:setWidget("Widget", panelWidget)
	param:setColor("To", Color(255, 255, 255, 255))
	kernel:addController(controlFactory:Create("Fader", param))

	param = VariableSet()
	param:setWidget("Widget", fadeWidget)
	param:setColor("To", Color(0, 0, 0, 150))
	param:setString("EndHandler", endHandler)
	param:setString("FaderType", "Scaled")
	kernel:addController(controlFactory:Create("Fader", param))

	Screen:pushLayer(GUI:getLayer(fadeLayer))
	Screen:pushLayer(GUI:getLayer(layerName) )

end

function FadePopLayerWithEndHandler(layerName, widgetName, endHandler)
	
	local fadeLayer = ""
	if (fadeScreens == 1) then
		fadeLayer = "Cross1"
	elseif (fadeScreens == 2) then
		fadeLayer = "Cross2"
	else
		fadeLayer = "Cross3"
	end

	fadeScreens = fadeScreens-1

	local panelWidget = GUI:getLayer(layerName):getWidget(widgetName)
	local fadeWidget = GUI:getLayer(fadeLayer):getWidget("BlackScreen")

	param = VariableSet()
	param:setWidget("Widget", panelWidget)
	param:setColor("To", Color(255, 255, 255, 0))
	param:setBool("PopLayer", true)
	kernel:addController(controlFactory:Create("Fader", param))

	param = VariableSet()
	param:setWidget("Widget", fadeWidget)
	param:setColor("To", Color(0, 0, 0, 0))
	param:setBool("PopLayer", true)
	param:setString("EndHandler", endHandler)
	param:setString("FaderType", "Scaled")
	kernel:addController(controlFactory:Create("Fader", param))
end

function FadePopLayer(layerName, widgetName, faderType)

	local fadeLayer = ""
	if (fadeScreens == 1) then
		fadeLayer = "Cross1"
	elseif (fadeScreens == 2) then
		fadeLayer = "Cross2"
	else
		fadeLayer = "Cross3"
	end

	fadeScreens = fadeScreens-1

	local panelWidget = GUI:getLayer(layerName):getWidget(widgetName)
	local fadeWidget = GUI:getLayer(fadeLayer):getWidget("BlackScreen")

	param = VariableSet()
	param:setWidget("Widget", panelWidget)
	param:setColor("To", Color(255, 255, 255, 0))
	param:setBool("PopLayer", true)
	kernel:addController(controlFactory:Create("Fader", param))

	param = VariableSet()
	param:setWidget("Widget", fadeWidget)
	param:setColor("To", Color(0, 0, 0, 0))
	param:setBool("PopLayer", true)
	if (faderType) then
		param:setString("FaderType", faderType)
	else
		param:setString("FaderType", "Scaled")
	end
	kernel:addController(controlFactory:Create("Fader", param))
end

-----------------------------------------------------------
-- Стратегия
-----------------------------------------------------------

introFromMainMenu = false
fromIntroToMainMenu = false
multFromCinemas = 0
trophyRoomFrom = 0
minimizeFrom = 0
minimizeFrom2 = 0
extrasFrom = 0
optionsVersion = "Options"
bonusLevelsFromMainMenu = false
allResolutions = true

function GameMapWinLevelInitFunc(message)
	PrintDebug("GameMapWinLevelInitFunc\n")
	local startTrack = true
	if gameInfo:getBool("DoNotStartTrackInMap") == true then
		startTrack = false
		PrintDebug("DoNotStartTrackInMap is true, so startTrack = false\n")
	end

	if startTrack then
		PrintDebug("StartTrack\n")
		StartMusicInMap()
	end
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("WinLevel"))

	gameInfo:setBool("DoNotStartTrackInMap", false)
end

function GameMapWinLevelInitWOMusicFunc(message)
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("WinLevel"))	
end

function GameMapLoseLevelInitFunc(message)
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("LoseLevel"))
end

function PlyPushBonusRestartConfirm()
	FlyPushLayer("BonusRestartConfirm", "BonusRestartConfirm", 0)
end

function GameMenuPress()
	if (not gameInfo:getActiveBetaStat():findName("Game Menu Pressed")) then
		gameInfo:getActiveBetaStat():setInt("Game Menu Pressed", 0)
	end
	gameInfo:getActiveBetaStat():setInt("Game Menu Pressed", gameInfo:getActiveBetaStat():getInt("Game Menu Pressed", 0) + 1)
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("HideAllHints"))
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("Pause"))
	FlyPushLayer("GameMenu", "GameMenu", 0)
end

function GameExtrasPress()
	extrasFrom = 1
	Screen:StoreSnapShot()
	GUI:getLayer("Game"):SetAllowDeinit(false)
	local param = VariableSet()
	param:setString("Layer1", "CGuide")
	param:setBool("ResourceManagement", false)
	param:setString("CrossHandler", "PrepareCGFunc2")
	param:setBool("NoFadeTracks", true)
	Sound:SetPause(true, false)
	SaveFadeScreens()
	kernel:addController(controlFactory:Create("CrossFade", param))
end

function GameBonusLevelFail()
	if (not gameInfo:getActiveBetaStat():findName("Bonus Level Fail")) then
		gameInfo:getActiveBetaStat():setInt("Bonus Level Fail", 0)
	end
	gameInfo:getActiveBetaStat():setInt("Bonus Level Fail", gameInfo:getActiveBetaStat():getInt("Bonus Level Fail", 0) + 1)
end

function GameFunc(message)
	if (message:is("zzzzzMenu", "press")) then
		GameMenuPress()
	elseif message:is("zzzzzExtras", "press") then
		GameExtrasPress()
	elseif message:is("BonusLevelFail") then
		GameBonusLevelFail()
	elseif message:is("WinLevel") then
		if message:getVariables():findName("bonus") then
			local param = VariableSet()
			param:setString("Layer1", "Bonus")
			param:setString("CrossHandler", "WinBonusFunc")
			param:setBool("ResourceManagement", false)
			kernel:addController(controlFactory:Create("CrossFade", param))		
		elseif message:getVariables():findName("trophy") then
			trophyRoomFrom = 2
			local param = VariableSet()
			param:setString("Layer1", "Trophy")
			param:setString("CrossHandler", "InitTrophy")
			param:setBool("ResourceManagement", false)
			kernel:addController(controlFactory:Create("CrossFade", param))
		else
			local param = VariableSet()
			--param:setString("Layer1", "GameMap")
			param:setString("Layer1", "GameMapNew")
			param:setString("CrossHandler", "GameMapWinLevelInitFunc")
			param:setBool("ResourceManagement", false)
			param:setBool("NoFadeTracks", true)
			kernel:addController(controlFactory:Create("CrossFade", param))
		end
	elseif (message:is("LoseLevel")) then
		local param = VariableSet()
		--param:setString("Layer1", "GameMap")
		param:setString("Layer1", "GameMapNew")
		param:setString("CrossHandler", "GameMapLoseLevelInitFunc")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("Layer", "Init") then
		GUI:getLayer("Game"):BroadcastMessage(Message("Screen", "activate", 1))
	elseif message:is("Layer", "Deinit") then
		GUI:getLayer("Game"):BroadcastMessage(Message("Screen", "activate", 0))
	else
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(message)
	end
end

function EditorFunc(message)
	GUI:getLayer("Editor"):getWidget("zEditor"):AcceptMessage(message)
end

function EditorLevelListFunc(message)
	if (message:is("Return", "press")) then
		GUI:getLayer("EditorLevelList"):getWidget("EditorFileList"):AcceptMessage(Message("Return"))
	elseif (message:is("Load", "press")) then
		GUI:getLayer("EditorLevelList"):getWidget("EditorFileList"):AcceptMessage(Message("Load"))
	elseif (message:is("Save", "press")) then
		GUI:getLayer("EditorLevelList"):getWidget("EditorFileList"):AcceptMessage(Message("Save"))
	elseif (message:is("Delete", "press")) then
		GUI:getLayer("EditorLevelList"):getWidget("EditorFileList"):AcceptMessage(Message("Delete"))
	end
end

function EditorLevelList2Func(message)
	if (message:is("Return", "press")) then
		GUI:getLayer("EditorLevelList2"):getWidget("EditorFileList"):AcceptMessage(Message("Return"))
	elseif (message:is("Load", "press")) then
		GUI:getLayer("EditorLevelList2"):getWidget("EditorFileList"):AcceptMessage(Message("Load"))
	elseif (message:is("Save", "press")) then
		GUI:getLayer("EditorLevelList2"):getWidget("EditorFileList"):AcceptMessage(Message("Save"))
	elseif (message:is("Delete", "press")) then
		GUI:getLayer("EditorLevelList2"):getWidget("EditorFileList"):AcceptMessage(Message("Delete"))
	end
end


function EditorSelectListFunc(message)
	if (message:is("Return", "press")) then
		--GUI:getLayer("EditorSelectList"):getWidget("EditorFileList"):AcceptMessage(Message("Return"))
		GUI:getLayer("Editor"):getWidget("zEditor"):AcceptMessage(Message("BackFromEditorFileList"))
	end
	--else
	--if (message:is("Load", "press")) then
		--GUI:getLayer("EditorSelectList"):getWidget("EditorFileList"):AcceptMessage(Message("Load"))
	--end
end

function ParametersEditorFunc(message)
	if (message:is("Return", "press")) then
		GUI:getLayer("ParametersEditor"):getWidget("ParametersEditor"):AcceptMessage(Message("BackFromParametersEditor"))
	else
		GUI:getLayer("ParametersEditor"):getWidget("ParametersEditor"):AcceptMessage(message)
	end
end

function TasksEditorFunc(message)
	local namesWidget = GUI:getLayer("TasksEditor"):getWidget("SelectTask")
	if message:is("TaskUp", "down") then
		namesWidget:AcceptMessage(Message("ScrollUp"))
	elseif message:is("TaskDown", "down") then
		namesWidget:AcceptMessage(Message("ScrollDown"))
	else
		GUI:getLayer("TasksEditor"):getWidget("TasksEditor"):AcceptMessage(message)
	end
end

function DecorationsEditorFunc(message)
	GUI:getLayer("DecorationsEditor"):getWidget("DecorationsEditor"):AcceptMessage(message)
end


----------------------------------------------------------------
-- Меню
----------------------------------------------------------------
continueSavedOnScreen = false
function StartSavedGameFunc()
	continueSavedOnScreen = false
	param = VariableSet()
	param:setString("Layer1", "Game")
	-- В коде сделана жесткая привязка к имени функции StartInLevelSavedGame. Меняешь сдесь, поменяй и в LayerLoadScree.cpp\struct GameLevelLoader
	param:setString("AfterPushHandler", "StartInLevelSavedGame")
	param:setString("LoadLayerEndHandler", "AfterFadeFunc")
	param:setBool("ResourceManagement", false)
	kernel:addController(controlFactory:Create("ProgressCrossFade", param))	
end
function ContinueSavedFunc(message)
	if message:is("FlyerActive") then
		continueSavedOnScreen = true
		GUI:getLayer("ContinueSaved"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		continueSavedOnScreen = false
		GUI:getLayer("ContinueSaved"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif continueSavedOnScreen and message:is("Yes", "press") then
		StartSavedGameFunc()
	elseif continueSavedOnScreen and message:is("No", "press") then
		continueSavedOnScreen = false
		gameInfo:CancelContinue()
		FlyPushLayer("ContinueSaved", "ContinueSaved", 1)
	else
		GUI:getLayer("ContinueSaved"):getWidget("KeyToMessage"):AcceptMessage(message)
	end	
end

function ResetButtonsInMainMenu()
	local mmLayer = GUI:getLayer("MainMenu")
	mmLayer:getWidget("Start"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("2_Options"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("3_Extras"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("3_Credits"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("4_Achievements4"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("5_Achievements5"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("5_Challenges"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("1_Exit"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("3_Intro3"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("4_Intro4"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("MoreGames"):AcceptMessage(Message("HardReset"))
	mmLayer:getWidget("zPencil"):AcceptMessage(Message("Reset"))
end

function SoftResetButtonsInMainMenu()
	local mmLayer = GUI:getLayer("MainMenu")
	mmLayer:getWidget("Start"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("2_Options"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("3_Extras"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("3_Credits"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("4_Achievements4"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("5_Achievements5"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("5_Challenges"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("1_Exit"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("3_Intro3"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("4_Intro4"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("MoreGames"):AcceptMessage(Message("Reset"))
	mmLayer:getWidget("zPencil"):AcceptMessage(Message("Reset"))
end

-- Send MainMenu InitMainMenu message
function MainMenuInitFunc()
	GUI:getLayer("MainMenu"):getWidget("1_Menu"):AcceptMessage(Message("InitMainMenu"))
	ResetButtonsInMainMenu()
end

-- Подтверждение выхода из игры
-- Из обычных уровней выходим в карту
-- Из бонусных - в список бонусных уровней
exitFromGameConfirmOnScreen = false
function ExitFromGameConfirmFunc(message)
	if message:is("FlyerActive") then
		exitFromGameConfirmOnScreen = true
		GUI:getLayer("ExitFromGameConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		exitFromGameConfirmOnScreen = false
		GUI:getLayer("ExitFromGameConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif exitFromGameConfirmOnScreen and message:is("Yes", "press") then
		exitFromGameConfirmOnScreen = false
		-- Подчищаем за собой
		EffectObserverContinueEffects()
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("SetStartLevelJinggleToFalse"))
		gameInfo:SaveState()

		-- Если текущий уровень - бонусный - выходим в экран бонусных уровней
		if gameInfo:game():IsCurrentLevelBonusLevel() then
			local param = VariableSet()
			param:setString("Layer1", "Bonus")
			param:setString("CrossHandler", "PrepareBonusFunc")
			param:setString("AfterFadeHandler", "StartMusicInMainMenu")
			param:setBool("ResourceManagement", false)
			kernel:addController(controlFactory:Create("CrossFade", param))
		else
			if ShouldLoadFirstLevel() then
				StartMusicInMap()
				GameMapFunc(Message("MainMenu", "press"))
			else
				-- В противном случае - выходим в карту
				gameInfo:restoreLevel()

				-- Выйграли уровень, но в статистике нажали переиграть, а затем вышли, не завершая уровень
				-- это нужно для того, чтобы сработал туториал в карте
				if gameInfo:GetLastPlayedLevelRating() ~= 0 and gameInfo:WasTutInMapForLastPlayedLevel() == false and gameInfo:HasMapTutorialForLastPlayedLevel() == true then
					GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StatisticsOk"))
				else
					param = VariableSet()
					--param:setString("Layer1", "GameMap")
					param:setString("Layer1", "GameMapNew")
					param:setString("AfterFadeHandler", "GameMapUpdateStarsCount")
					param:setString("CrossHandler", "PrepareMapFunc")
					param:setBool("ResourceManagement", false)
					kernel:addController(controlFactory:Create("CrossFade", param))
					gameInfo:ContinueSavedGame()
				end		
			end
		end
	elseif exitFromGameConfirmOnScreen and message:is("No", "press") then
		exitFromGameConfirmOnScreen = false
		FlyPushLayer("ExitFromGameConfirm", "ExitFromGameConfirm", 1)
	elseif message:is("WinLevel") then
		GameFunc(message)
	else
		GUI:getLayer("ExitFromGameConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

function DoRestartGameThroughtCrossFade()
	gameInfo:IncLevelRestartsCount()
	GUI:getLayer("Game"):SetAllowDeinit(false)
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("MarkLevelAsRestarting"))
	local param = VariableSet()
	param:setString("Layer1", "Game")
	param:setString("AfterPushHandler", "RestartGameFunc")
	param:setBool("ResourceManagement", false)
	param:setBool("ShowLoading", false)
	kernel:addController(controlFactory:Create("CrossFade", param))
end

restartLevelConfirmOnScreen = false
function RestartLevelConfirmFunc(message)
	if message:is("FlyerActive") then
		restartLevelConfirmOnScreen = true
		GUI:getLayer("RestartLevelConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		restartLevelConfirmOnScreen = false
		GUI:getLayer("RestartLevelConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif restartLevelConfirmOnScreen and message:is("Yes", "press") then
		restartLevelConfirmOnScreen = false
		gameInfo:WriteStatistics(false)
		DoRestartGameThroughtCrossFade()
	elseif restartLevelConfirmOnScreen and message:is("No", "press") then
		restartLevelConfirmOnScreen = false
		FlyPushLayer("RestartLevelConfirm", "RestartLevelConfirm", 1)
	else
		GUI:getLayer("RestartLevelConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

bonusRestartConfirmOnScreen = false
function BonusRestartConfirmFunc(message)
	if message:is("FlyerActive") then
		bonusRestartConfirmOnScreen = true
		GUI:getLayer("BonusRestartConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		bonusRestartConfirmOnScreen = false
		GUI:getLayer("BonusRestartConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif bonusRestartConfirmOnScreen and message:is("Yes", "press") then
		bonusRestartConfirmOnScreen = false
		gameInfo:WriteStatistics(false)
		DoRestartGameThroughtCrossFade()
	elseif bonusRestartConfirmOnScreen and message:is("No", "press") then
		bonusRestartConfirmOnScreen = false
		--FlyPushLayer("BonusRestartConfirm", "BonusRestartConfirm", 1)
		StartTempleLevel(1)
	elseif message:is("Skip", "press") then
		StartTempleLevel(1)
	else
		GUI:getLayer("BonusRestartConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	end	
end

function FromGameMenuToGame(message)
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("Continue"))
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("ContinueTutorial"))
end

-- Меню в игре, которое вызывается по кнопке "Меню"
gameMenuOnScreen = false
function GameMenuFunc(message)
	if message:is("FlyerActive") then
		gameMenuOnScreen = true
		GUI:getLayer("GameMenu"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		gameMenuOnScreen = false
		GUI:getLayer("GameMenu"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif gameMenuOnScreen and message:is("Resume", "press") then
		gameMenuOnScreen = false
		if (not gameInfo:getActiveBetaStat():findName("Game Menu Resume")) then
			gameInfo:getActiveBetaStat():setInt("Game Menu Resume", 0)
		end
		gameInfo:getActiveBetaStat():setInt("Game Menu Resume", gameInfo:getActiveBetaStat():getInt("Game Menu Resume", 0) + 1)
		FlyPushLayer("GameMenu", "GameMenu", 1, "FromGameMenuToGame")
	elseif gameMenuOnScreen and message:is("Exit", "press") then
		if (not gameInfo:getActiveBetaStat():findName("Game Menu Exit")) then
			gameInfo:getActiveBetaStat():setInt("Game Menu Exit", 0)
		end
		gameInfo:getActiveBetaStat():setInt("Game Menu Exit", gameInfo:getActiveBetaStat():getInt("Game Menu Exit", 0) + 1)
		FlyPushLayer("ExitFromGameConfirm", "ExitFromGameConfirm", 0)
	elseif gameMenuOnScreen and message:is("Restart", "press") then
		if (not gameInfo:getActiveBetaStat():findName("Game Menu Restart")) then
			gameInfo:getActiveBetaStat():setInt("Game Menu Restart", 0)
		end
		gameInfo:getActiveBetaStat():setInt("Game Menu Restart", gameInfo:getActiveBetaStat():getInt("Game Menu Restart", 0) + 1)
		FlyPushLayer("RestartLevelConfirm", "RestartLevelConfirm", 0)
	elseif gameMenuOnScreen and message:is("Options", "press") then
		if (not gameInfo:getActiveBetaStat():findName("Game Menu Options")) then
			gameInfo:getActiveBetaStat():setInt("Game Menu Options", 0)
		end
		gameInfo:getActiveBetaStat():setInt("Game Menu Options", gameInfo:getActiveBetaStat():getInt("Game Menu Options", 0) + 1)
		SaveOptions()
		RestoreOptions()
		FlyPushLayer(optionsVersion, "Options", 0)
	else
		GUI:getLayer("GameMenu"):getWidget("KeyToMessage"):AcceptMessage(message)
	end	
end

-- Устанавливает положение кнопок ok и cancel в зависимости от того, есть ли на панели кнопка credits
function OptionsSetOkAndCancelPositions(hasCredits)
	if hasCredits == true then
		GUI:getLayer("Options"):getWidget("Ok"):setPosition(IPoint(103, 44))
		GUI:getLayer("Options"):getWidget("Cancel"):setPosition(IPoint(270, 44))
	else
		GUI:getLayer("Options"):getWidget("Ok"):setPosition(IPoint(103, 64))
		GUI:getLayer("Options"):getWidget("Cancel"):setPosition(IPoint(270, 64))
	end
end

-- Uploads resources for MainMenu group, sets visibility for widgets
function StartFromMainMenu()
	-- hide all
	local mmLayer = GUI:getLayer("MainMenu")
	mmLayer:getWidget("MoreGames"):setVisible(false)
	mmLayer:getWidget("Start"):setVisible(false)
	mmLayer:getWidget("2_Options"):setVisible(false)
	mmLayer:getWidget("3_Extras"):setVisible(false)
	mmLayer:getWidget("3_Credits"):setVisible(false)
	mmLayer:getWidget("4_Achievements4"):setVisible(false)
	mmLayer:getWidget("5_Achievements5"):setVisible(false)
	mmLayer:getWidget("5_Challenges"):setVisible(false)
	mmLayer:getWidget("1_Exit"):setVisible(false)
	mmLayer:getWidget("3_Intro3"):setVisible(false)
	mmLayer:getWidget("4_Intro4"):setVisible(false)
	mmLayer:getWidget("Profile"):setVisible(false)
	mmLayer:getWidget("zzWelcomeBack"):setVisible(false)

	GUI:getLayer("MainMenu"):getWidget("ScrPartnerLogo"):setVisible(true)
	GUI:getLayer("MainMenu"):getWidget("ScrPlayrixLogo"):setVisible(true)
	GUI:getLayer("MainMenu"):getWidget("CELabels"):setVisible(false)
		
	-- game
	if not gameInfo:IsScreenSaverMode() then
		-- common buttons
		GUI:getLayer("MainMenu"):getWidget("Profile"):setVisible(true)
		GUI:getLayer("MainMenu"):getWidget("zzWelcomeBack"):setVisible(true)
		GUI:getLayer("MainMenu"):getWidget("Start"):setVisible(true)
		GUI:getLayer("MainMenu"):getWidget("1_Exit"):setVisible(true)
		GUI:getLayer("MainMenu"):getWidget("2_Options"):setVisible(true)
		GUI:getLayer("MainMenu"):getWidget("ScrPartnerLogo"):setVisible(false)
		GUI:getLayer("MainMenu"):getWidget("ScrPlayrixLogo"):setVisible(false)
		
		-- standard
		if gameInfo:getString("main_menu_type") == "standard" then
			GUI:getLayer("MainMenu"):getWidget("5_Achievements5"):setVisible(true)
			GUI:getLayer("MainMenu"):getWidget("4_Intro4"):setVisible(true)
			GUI:getLayer("MainMenu"):getWidget("3_Credits"):setVisible(true)
			GUI:getLayer("Options"):getWidget("Credits"):setVisible(false)
			OptionsSetOkAndCancelPositions(false)
		-- extended
		elseif gameInfo:getString("main_menu_type") == "extended" then
			GUI:getLayer("MainMenu"):getWidget("5_Challenges"):setVisible(true)
			GUI:getLayer("MainMenu"):getWidget("4_Achievements4"):setVisible(true)
			GUI:getLayer("MainMenu"):getWidget("3_Intro3"):setVisible(true)
			GUI:getLayer("Options"):getWidget("Credits"):setVisible(true)
			OptionsSetOkAndCancelPositions(true)
		-- collectors
		elseif gameInfo:getString("main_menu_type") == "collectors" then
			GUI:getLayer("MainMenu"):getWidget("5_Challenges"):setVisible(true)
			GUI:getLayer("MainMenu"):getWidget("4_Achievements4"):setVisible(true)
			GUI:getLayer("MainMenu"):getWidget("3_Extras"):setVisible(true)
			GUI:getLayer("Options"):getWidget("Credits"):setVisible(true)
			GUI:getLayer("MainMenu"):getWidget("CELabels"):setVisible(true)
			OptionsSetOkAndCancelPositions(true)
		end
	end
end

gameInfoWasCorruptedOnScreen = false
function GameInfoWasCorruptedFunc(message)
	if message:is("FlyerActive") then
		gameInfoWasCorruptedOnScreen = true
		GUI:getLayer("GameInfoWasCorrupted"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		gameInfoWasCorruptedOnScreen = false
		GUI:getLayer("GameInfoWasCorrupted"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif gameInfoWasCorruptedOnScreen and message:is("Ok", "press") then
		gameInfoWasCorruptedOnScreen = false
		FlyPushLayer("GameInfoWasCorrupted", "GameInfoWasCorrupted", 1)
	else
		GUI:getLayer("GameInfoWasCorrupted"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

function FirstStartCheck(message)
	if gameInfo:NoPlayers() then
		local username = gameInfo:getUserName()
		if Utf8_StringLength(username) > 10 then
			username = ""
		end
		FlyPushLayer("NewProfileFirstTime", "NewProfile", 0)
		
		if gameInfo:getBool("gameInfoCorrupted") then
			FlyPushLayer("GameInfoWasCorrupted", "GameInfoWasCorrupted", 0)
		end 
	end
end

-- Reload MainMenu in ScreenSaver mode when it's time to change the scene without resource management
function ReloadMainMenu()
	LoadMainMenu(false)
end

-- Load MainMenu layer with/without resource management
function LoadMainMenu(resManagement)
	if resManagement == true then
		GUI:getLayer("MainMenu"):SetAllowDeinit(true)
	else
		GUI:getLayer("MainMenu"):SetAllowDeinit(false)
	end
	GUI:getLayer("MainMenu"):getWidget("1_Menu"):AcceptMessage(Message("IncMainMenuInitCounts"))
	local param = VariableSet()
	param:setString("Layer1", "MainMenu")
	param:setString("CrossHandler", "StartFromMainMenu")
	param:setString("AfterPushHandler", "MainMenuInitFunc")
	param:setString("EndHandler", "FirstStartCheck")
	param:setBool("NoFadeTracks", true)
	param:setBool("ShowLoading", false)
	-- Загрузка текстур или не нужна (когда все грузится в самом начале)
	-- или происходит во время pushLayer'a, когда слою прописана его группа
	param:setBool("ResourceManagement", false)
	if resManagement == false then
		param:setBool("ResourceManagement", false)
	end
	kernel:addController(controlFactory:Create("CrossFade", param))
end

function LoadScreenFunc(message)
	if message:is("Start") then
		SetMaxFps(1500)
		LoadMainMenu(true)
	end
end

function StartIntro()
	GUI:getLayer("Intro"):getWidget("IntroVideo"):AcceptMessage(Message("Play"))
	GUI:getLayer("Intro"):getWidget("IntroSkip"):setVisible(true)
end

function StartIntroSkipOnClick()
	GUI:getLayer("Intro"):getWidget("IntroVideo"):AcceptMessage(Message("Play"))
	GUI:getLayer("Intro"):getWidget("IntroVideo"):AcceptMessage(Message("SkipOnClick", 1))
	GUI:getLayer("Intro"):getWidget("IntroSkip"):setVisible(true)
end

function StartIntroNoSkipOnClick()
	GUI:getLayer("Intro"):getWidget("IntroVideo"):AcceptMessage(Message("Play"))
	GUI:getLayer("Intro"):getWidget("IntroVideo"):AcceptMessage(Message("SkipOnClick", 0))
	GUI:getLayer("Intro"):getWidget("IntroSkip"):setVisible(true)
end

-- Cleans theora stuff
function IntroMovieCleanEverything()
	GUI:getLayer("Intro"):getWidget("IntroVideo"):AcceptMessage(Message("CleanEverything"))
end

function FromIntroToGameMap()
	IntroMovieCleanEverything()
	--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("InitGLevel"))
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("InitGLevel"))
	GameMapWinLevelInitFunc()
end

function FromIntroToBonus()
	IntroMovieCleanEverything()
	PrepareBonusFunc()
end

function FromIntroToPremium()
	IntroMovieCleanEverything()
	PremiumVersionCross()
end

-- Вызывается, когда прячется курсор у видео
function IntroOnHideCursor()
	GUI:getLayer("Intro"):getWidget("IntroSkip"):AcceptMessage(Message("Disappear"))
end

-- Вызывается, когда появляется курсор у видео
function IntroOnShowCursor()
	GUI:getLayer("Intro"):getWidget("IntroSkip"):AcceptMessage(Message("Appear"))
end

function IntroFunc(message)
	if message:is("SimpleVideoWidgetStopped") then
		if introFromMainMenu == true then
			if fromIntroToMainMenu == true then
				local param = VariableSet()
				param:setString("Layer1", "MainMenu")
				param:setString("CrossHandler", "IntroMovieCleanEverything")
				param:setString("AfterPushHandler", "MainMenuInitFunc")
				param:setString("EndHandler", "StartMusicInMainMenu")
				param:setBool("ResourceManagement", false)
				kernel:addController(controlFactory:Create("CrossFade", param))
			else
				--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("UpdateStarsCount"))
				GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("UpdateStarsCount"))
				
				local param = VariableSet()
				--param:setString("Layer1", "GameMap")
				param:setString("Layer1", "GameMapNew")
				param:setString("CrossHandler", "FromIntroToGameMap")	
				param:setString("EndHandler", "ShowMapFunc")
				param:setBool("ResourceManagement", false)
				kernel:addController(controlFactory:Create("CrossFade", param))
			end
		else
			--[[
			local param = VariableSet()
			param:setBool("NoFadeTracks", true)
			param:setString("Layer1", "PremiumVersion")
			param:setString("CrossHandler", "FromIntroToPremium")
			param:setString("EndHandler", "StartMusicInMainMenu")
			param:setBool("ResourceManagement", false)
			kernel:addController(controlFactory:Create("CrossFade", param))				
			]]
			local param = VariableSet()
			param:setBool("NoFadeTracks", true)
			param:setString("Layer1", "Videos")
			param:setString("CrossHandler", "FromIntroToPremium")
			param:setString("EndHandler", "StartMusicInMainMenu")
			param:setBool("ResourceManagement", false)
			kernel:addController(controlFactory:Create("CrossFade", param))
		end
	elseif message:is("IntroSkip", "press") then
		GUI:getLayer("Intro"):getWidget("IntroVideo"):AcceptMessage(Message("Pause"))
		IntroFunc(Message("SimpleVideoWidgetStopped"))
	end
end

function NewProfileSetLimitText()
	GUI:getLayer("NewProfile"):getWidget("InfoText"):AcceptMessage(Message("SetText", "NewProfileInfoText"))
end

newProfileOnScreen = false
function NewProfileFunc(message)
	if message:is("FlyerActive") then
		newProfileOnScreen = true
		GUI:getLayer("NewProfile"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		newProfileOnScreen = false
		GUI:getLayer("NewProfile"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif newProfileOnScreen and message:is("Cancel", "press") then
		newProfileOnScreen = false
		FlyPushLayer("NewProfile", "NewProfile", 1, "NewProfileSetLimitText")
	elseif newProfileOnScreen and message:is("Ok", "press") then
		state = GUI:getLayer("NewProfile"):getWidget("Name"):QueryState(Message("Text"))
		local profileName = state:getData()
		if not (profileName == "") then
			if gameInfo:isPlayerExist(profileName) then
              	GUI:getLayer("NewProfile"):getWidget("InfoText"):AcceptMessage(Message("SetText", "NewProfilePlayerAlreadyExists"))
			else
				newProfileOnScreen = false
				local namesWidget = GUI:getLayer("Profiles"):getWidget("A_ListBoxPanel"):getChild("Names")
				namesWidget:AcceptMessage(Message("Add", profileName))
				namesWidget:AcceptMessage(Message("Set", profileName))
				gameInfo:AddNewPlayer(profileName)
				introFromMainMenu = true
				fromIntroToMainMenu = false
				FlyPushLayer("NewProfile", "NewProfile", 1, "NewProfileSetLimitText")
				FlyPushLayer("Profiles", "Profiles", 1)
				gameInfo:Save()
			end
		end
	else
		GUI:getLayer("NewProfile"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

function NewProfileFirstTimeFunc(message)
	if message:is("Ok", "press") then
		state = GUI:getLayer("NewProfileFirstTime"):getWidget("Name"):QueryState(Message("Text"))
		local profileName = state:getData()
		if not (profileName == "") then
			local username = gameInfo:getUserName()
			local namesWidget = GUI:getLayer("Profiles"):getWidget("A_ListBoxPanel"):getChild("Names")
			namesWidget:AcceptMessage(Message("Add", profileName))
			namesWidget:AcceptMessage(Message("Set", profileName))
			gameInfo:AddNewPlayer(profileName)
			if (username ~= profileName) then
				gameInfo:getActiveBetaStat():setBool("DefaultSystemNameChanged", true)
			end
			if Utf8_StringLength(username) > 10 then
				gameInfo:getActiveBetaStat():setBool("DefaultSystemNameFailed", true)
			end
			if fadeScreens > 0 then
				FlyPushLayer("NewProfileFirstTime", "NewProfile", 1)
			end
		end
	end
end

lastNoDeleteOnScreen = false
function LastNoDeleteFunc(message)
	if message:is("FlyerActive") then
		lastNoDeleteOnScreen = true
		GUI:getLayer("LastNoDelete"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		lastNoDeleteOnScreen = false
		GUI:getLayer("LastNoDelete"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif lastNoDeleteOnScreen and message:is("Ok", "press") then
		lastNoDeleteOnScreen = false
		FlyPushLayer("LastNoDelete", "LastNoDelete", 1)
	else
		GUI:getLayer("LastNoDelete"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

tooManyPlayersOnScreen = false
function TooManyPlayersFunc(message)
	if message:is("FlyerActive") then
		tooManyPlayersOnScreen = true
		GUI:getLayer("TooManyPlayers"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		tooManyPlayersOnScreen = false
		GUI:getLayer("TooManyPlayers"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif tooManyPlayersOnScreen and message:is("Ok", "press") then
		tooManyPlayersOnScreen = false
		FlyPushLayer("TooManyPlayers", "TooManyPlayers", 1)
	else
		GUI:getLayer("TooManyPlayers"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

activeNoDeleteOnScreen = false
function ActiveNoDeleteFunc(message)
	if message:is("FlyerActive") then
		activeNoDeleteOnScreen = true
		GUI:getLayer("ActiveNoDelete"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		activeNoDeleteOnScreen = false
		GUI:getLayer("ActiveNoDelete"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif activeNoDeleteOnScreen and message:is("Ok", "press") then
		activeNoDeleteOnScreen = false
		FlyPushLayer("ActiveNoDelete", "ActiveNoDelete", 1)
	else
		GUI:getLayer("ActiveNoDelete"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

deletePlayerConfirmOnScreen = false
function DeletePlayerConfirmFunc(message)
	if message:is("FlyerActive") then
		deletePlayerConfirmOnScreen = true
		GUI:getLayer("DeletePlayerConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		deletePlayerConfirmOnScreen = false
		GUI:getLayer("DeletePlayerConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif deletePlayerConfirmOnScreen and message:is("No", "press") then
		deletePlayerConfirmOnScreen = false
		FlyPushLayer("DeletePlayerConfirm", "DeletePlayerConfirm", 1)
	elseif deletePlayerConfirmOnScreen and message:is("Yes", "press") then
		deletePlayerConfirmOnScreen = false
		local state = GUI:getLayer("Profiles"):getWidget("A_ListBoxPanel"):getChild("Names"):QueryState(Message("CurrentItem"))
		local playerName = state:getData()
		if ( not(gameInfo:getName() == playerName) and not(gameInfo:getNumberOfPlayers() == 1)  ) then
			gameInfo:DeletePlayer(playerName)
			GUI:getLayer("Profiles"):getWidget("A_ListBoxPanel"):getChild("Names"):AcceptMessage(Message("Delete", playerName))
		end
		FlyPushLayer("DeletePlayerConfirm", "DeletePlayerConfirm", 1)
	else
		GUI:getLayer("DeletePlayerConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

profilesOnScreen = false
function ProfilesFunc(message)
	if message:is("FlyerActive") then
		profilesOnScreen = true
		GUI:getLayer("Profiles"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		profilesOnScreen = false
		GUI:getLayer("Profiles"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("New", "press") then
		if gameInfo:getNumberOfPlayers() == 15 then
			FlyPushLayer("TooManyPlayers", "TooManyPlayers", 0)
		else
			GUI:getLayer("NewProfile"):getWidget("Name"):AcceptMessage(Message("Clear"))
			FlyPushLayer("NewProfile", "NewProfile", 0)
		end
	elseif message:is("Select", "press") or message:is("Names", "DoubleClick") then
		local state = GUI:getLayer("Profiles"):getWidget("A_ListBoxPanel"):getChild("Names"):QueryState(Message("CurrentItem"))
		local playerName = state:getData()
		gameInfo:setActivePlayer(playerName)
		FlyPushLayer("Profiles", "Profiles", 1)
	elseif message:is("B_Up", "down") then
		local namesWidget = GUI:getLayer("Profiles"):getWidget("A_ListBoxPanel"):getChild("Names")
		namesWidget:AcceptMessage(Message("ScrollUp"))
	elseif message:is("B_Down", "down") then
		local namesWidget = GUI:getLayer("Profiles"):getWidget("A_ListBoxPanel"):getChild("Names")
		namesWidget:AcceptMessage(Message("ScrollDown"))
	elseif profilesOnScreen and message:is("Cancel", "press") then
		profilesOnScreen = false
		FlyPushLayer("Profiles", "Profiles", 1)
	elseif message:is("Delete", "press") then
		local state = GUI:getLayer("Profiles"):getWidget("A_ListBoxPanel"):getChild("Names"):QueryState(Message("CurrentItem"))
		local playerName = state:getData()
		if gameInfo:getNumberOfPlayers() == 1 then
			FlyPushLayer("LastNoDelete", "LastNoDelete", 0)
		elseif gameInfo:getName() == playerName then
			FlyPushLayer("ActiveNoDelete", "ActiveNoDelete", 0)
		else
			SetTextProperty("DeletePlayerConfirmPlayerName", "PlayerName", playerName)
			TextTrueUpdate("DeletePlayerConfirmPlayerName")
			FlyPushLayer("DeletePlayerConfirm", "DeletePlayerConfirm", 0)
		end
	else
		GUI:getLayer("Profiles"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

exitConfirmOnScreen = false
function ExitConfirmFunc(message)
	if message:is("FlyerActive") then
		exitConfirmOnScreen = true
		GUI:getLayer("ExitConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		exitConfirmOnScreen = false
		GUI:getLayer("ExitConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif exitConfirmOnScreen and message:is("No", "press") then
		exitConfirmOnScreen = false
		ExitConfirmFlyPushLayer(1)
		SoftResetButtonsInMainMenu()
		if (Screen:isLayerOnScreen("Game")) and not (Screen:isLayerOnScreen("GameMenu")) then
			GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("Continue"))
		end
	elseif exitConfirmOnScreen and message:is("Yes", "press") then
		exitConfirmOnScreen = false
		--[[
		local state = GUI:getLayer("ExitConfirm"):getWidget("ScreenSaver"):QueryState(Message("GetState"))
		local visible = GUI:getLayer("ExitConfirm"):getWidget("ScreenSaver"):isVisible()
		-- При выходе устанавливаем скринсейвер если только галочка видна. Если не видна - не устанавливаем
		if visible == true then
			if state:getData() == "1" then 
				gameInfo:setEnableSS(true)
			else
				gameInfo:setEnableSS(false)
			end	
		end
		]]--
		CloseApplicationVideo()
	else
		GUI:getLayer("ExitConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

function ExitCreditsCross()
	GUI:getLayer("MainMenu"):SetAllowDeinit(true)
	GUI:getLayer("Game"):SetAllowDeinit(true)
	Screen:LoadSnapShot()
end

function CreditsFunc(message)
	if (message:is("Exit")) then
		local param = VariableSet()
		param:setBool("NoFadeTracks", true)
		param:setString("CrossHandler", "ExitCreditsCross")
		kernel:addController(controlFactory:Create("CrossFade", param))
	end
end

function TrophyFunc(message)
	if (message:is("ReturnToMap", "press")) or (message:is("ReturnToMenu", "press")) then
		param = VariableSet()
		if trophyRoomFrom == 0 or trophyRoomFrom == 3 then
			--param:setString("Layer1", "GameMap")
			param:setString("Layer1", "GameMapNew")
			param:setString("CrossHandler", "PrepareMapWOMusicFunc")
			param:setBool("NoFadeTracks", true)
			param:setBool("ResourceManagement", false)
			kernel:addController(controlFactory:Create("CrossFade", param))
		elseif trophyRoomFrom == 1 then
			param:setString("Layer1", "MainMenu")
			param:setBool("NoFadeTracks", true)			
			param:setString("AfterPushHandler", "MainMenuInitFunc")
			param:setBool("ResourceManagement", false)
			kernel:addController(controlFactory:Create("CrossFade", param))
		elseif trophyRoomFrom == 2 then
			--param:setString("Layer1", "GameMap")
			param:setString("Layer1", "GameMapNew")
			param:setString("CrossHandler", "PrepareMapWOMusicFunc")
			param:setString("EndHandler", "GameMapWinLevelInitWOMusicFunc")
			param:setBool("ResourceManagement", false)
			param:setBool("NoFadeTracks", true)
			kernel:addController(controlFactory:Create("CrossFade", param))			
		end
	elseif message:is("Continue", "press") then
		GUI:getLayer("Trophy"):getWidget("Trophy"):AcceptMessage(Message("Continue"))
	elseif message:is("Init") then
		GUI:getLayer("Trophy"):getWidget("Trophy"):AcceptMessage(Message("Init"))		
	elseif message:is("StartMMTrack") then
		GUI:getLayer("LoadScreen"):getWidget("LoadScreen"):AcceptMessage(Message("StartMMTrack"))
	elseif message:is("Layer", "Init") then
		GUI:getLayer("Trophy"):BroadcastMessage(Message("Screen", "activate", 1))
	elseif message:is("Layer", "Deinit") then
		GUI:getLayer("Trophy"):BroadcastMessage(Message("Screen", "activate", 0))
	end		
end

function VideoFunc(message)
	if message:is("SimpleVideoWidgetStopped") then
		GUI:getLayer("VideoLayer"):getWidget("LastVideo"):AcceptMessage(Message("Pause"))
		CloseApplication()
	end		
end

lastMusicVolume = 0
lastSoundVolume = 0
lastFullscreen = false
lastCustomCursor = false
lastShowHints = false
lastEnableSS = false

function SaveOptions(message)
	
	lastMusicVolume = gameInfo:getMusicVolume()
	lastSoundVolume = gameInfo:getSoundVolume()
	lastFullscreen = RE2IsActualFullScreenMode()--gameInfo:isFullScreen()
	lastCustomCursor = gameInfo:isCustomCursor()
	lastShowHints = gameInfo:isHintsEnabled(true)
	--lastEnableSS = gameInfo:enableScreenSaver()
end

function RestoreOptions(message)
	Sound:SetSoundVolume(lastSoundVolume)
	Sound:SetMusicVolume(lastMusicVolume)
	gameInfo:setMusicVolume(lastMusicVolume)
	gameInfo:setSoundVolume(lastSoundVolume)
	gameInfo:setCustomCursor(lastCustomCursor)
	gameInfo:setHintsEnabled(lastShowHints)
	gameInfo:setFullScreen(lastFullscreen)
	gameInfo:setEnableSS(lastEnableSS)
	-- FullScreen
	local iBoolean = "0"
	if lastFullscreen then
		iBoolean = "1"
	end
	GUI:getLayer(optionsVersion):getWidget("Fullscreen"):AcceptMessage(Message("SetState", iBoolean))
	-- Hints
	iBoolean = "0"
	if lastShowHints then
		iBoolean = "1"
	end
	GUI:getLayer(optionsVersion):getWidget("ATips"):AcceptMessage(Message("SetState", iBoolean))
	-- CustomCursor
	iBoolean = "0"
	if lastCustomCursor then
		iBoolean = "1"
	end
	GUI:getLayer(optionsVersion):getWidget("CustomCursor"):AcceptMessage(Message("SetState", iBoolean))
	if iBoolean == "1" then
		SetCustomCursor(true)
		gameInfo:setCustomCursor(true)
	else
		SetCustomCursor(false)
		gameInfo:setCustomCursor(false)
	end		
	
	-- ScreenSaver
	--[[
	iBoolean = "0"
	if lastEnableSS then
		iBoolean = "1"
	end
	GUI:getLayer(optionsVersion):getWidget("ScreenSaver"):AcceptMessage(Message("SetState", iBoolean))
	]]

	GUI:getLayer(optionsVersion):getWidget("Music"):AcceptMessage(Message("SetPos", tostring(lastMusicVolume)))
	GUI:getLayer(optionsVersion):getWidget("Sound"):AcceptMessage(Message("SetPos", tostring(lastSoundVolume)))
end

function SetOptions(message)
	local state = GUI:getLayer(optionsVersion):getWidget("Music"):QueryState(Message("GetPos"))
	local musVolume = 0+state:getData()
	state = GUI:getLayer(optionsVersion):getWidget("Sound"):QueryState(Message("GetPos"))
	local sndVolume = 0+state:getData()
	state = GUI:getLayer(optionsVersion):getWidget("Fullscreen"):QueryState(Message("GetState"))
	Sound:SetMusicVolume(musVolume)
	Sound:SetSoundVolume(sndVolume)
	gameInfo:setMusicVolume(musVolume)
	gameInfo:setSoundVolume(sndVolume)
	if state:getData() == "1" and gameInfo:isFullScreen() == false then
		gameInfo:setFullScreen(true)
		SetFullscreenMode()
	end
	if state:getData() == "0" and gameInfo:isFullScreen() == true then
		gameInfo:setFullScreen(false)
		SetWindowedMode()
	end
	-- CustomCursor
	state = GUI:getLayer(optionsVersion):getWidget("CustomCursor"):QueryState(Message("GetState"))
	if state:getData() == "1" then
		SetCustomCursor(true)
		gameInfo:setCustomCursor(true)
	else
		SetCustomCursor(false)
		gameInfo:setCustomCursor(false)
	end
	-- ScreenSaver
	--[[
	state = GUI:getLayer(optionsVersion):getWidget("ScreenSaver"):QueryState(Message("GetState"))
	if state:getData() == "1" then
		gameInfo:setEnableSS(true)
	else
		gameInfo:setEnableSS(false)
	end
	]]
	-- ATips
	state = GUI:getLayer(optionsVersion):getWidget("ATips"):QueryState(Message("GetState"))
	if state:getData() == "1" then
		gameInfo:setHintsEnabled(true)
	else
		gameInfo:setHintsEnabled(false)
		if lastShowHints == true then
			tutorial:eventUpdate(Message("TutorialPass", "press"))
		end
	end
	GUI:getLayer(optionsVersion):getWidget("Music"):AcceptMessage(Message("SetPos", tostring(musVolume)))
	GUI:getLayer(optionsVersion):getWidget("Sound"):AcceptMessage(Message("SetPos", tostring(sndVolume)))
	-- FullScreen
	local iBoolean = "0"
	if gameInfo:isFullScreen() then
		iBoolean = "1"
	end
	GUI:getLayer(optionsVersion):getWidget("Fullscreen"):AcceptMessage(Message("SetState", iBoolean))
	-- Hints
	iBoolean = "0"
	if gameInfo:isHintsEnabled(true) then
		iBoolean = "1"
	end
	GUI:getLayer(optionsVersion):getWidget("ATips"):AcceptMessage(Message("SetState", iBoolean))
	-- CustomCursor
	iBoolean = "0"
	if gameInfo:isCustomCursor() then
		iBoolean = "1"
	end
	GUI:getLayer(optionsVersion):getWidget("CustomCursor"):AcceptMessage(Message("SetState", iBoolean))
end

optionsOnScreen = false
function OptionsFunc(message)
	if message:is("FlyerActive") then
		optionsOnScreen = true
		GUI:getLayer(optionsVersion):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		optionsOnScreen = false
		GUI:getLayer(optionsVersion):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif optionsOnScreen and message:is("Ok", "press") then
		if (lastMusicVolume ~= gameInfo:getMusicVolume()) then
			gameInfo:getActiveBetaStat():setBool("MusicVolumeChanged", true)
			if (not gameInfo:getActiveBetaStat():findName("MusicVolumeChangeTime")) then
				gameInfo:getActiveBetaStat():setFloat("MusicVolumeChangeTime", gameInfo:getActiveTotalTimeInMinutes())
				gameInfo:getActiveBetaStat():setInt("FirstMusicVolume", gameInfo:getMusicVolume())
			end
			gameInfo:getActiveBetaStat():setInt("MusicVolume", gameInfo:getMusicVolume())
		end
		if (lastSoundVolume ~= gameInfo:getSoundVolume()) then
			gameInfo:getActiveBetaStat():setBool("SoundVolumeChanged", true)
			if (not gameInfo:getActiveBetaStat():findName("SoundVolumeChangeTime")) then
				gameInfo:getActiveBetaStat():setFloat("SoundVolumeChangeTime", gameInfo:getActiveTotalTimeInMinutes())
				gameInfo:getActiveBetaStat():setInt("FirstSoundVolume", gameInfo:getSoundVolume())
			end
			gameInfo:getActiveBetaStat():setInt("SoundVolume", gameInfo:getSoundVolume())
		end
		if (lastFullscreen ~= (GUI:getLayer(optionsVersion):getWidget("Fullscreen"):QueryState(Message("GetState")):getData() == "1")) then
			gameInfo:getActiveBetaStat():setBool("FullscreenChanged", true)
			if (not gameInfo:getActiveBetaStat():findName("FullscreenChangeTime")) then
				gameInfo:getActiveBetaStat():setFloat("FullscreenChangeTime", gameInfo:getActiveTotalTimeInMinutes())
				gameInfo:getActiveBetaStat():setBool("FirstFullscreen", GUI:getLayer(optionsVersion):getWidget("Fullscreen"):QueryState(Message("GetState")):getData() == "1")
			end
			gameInfo:getActiveBetaStat():setBool("Fullscreen", GUI:getLayer(optionsVersion):getWidget("Fullscreen"):QueryState(Message("GetState")):getData() == "1")
		end
		if (lastCustomCursor ~= (GUI:getLayer(optionsVersion):getWidget("CustomCursor"):QueryState(Message("GetState")):getData() == "1")) then
			gameInfo:getActiveBetaStat():setBool("CustomCursorChanged", true)
			if (not gameInfo:getActiveBetaStat():findName("CustomCursorChangeTime")) then
				gameInfo:getActiveBetaStat():setFloat("CustomCursorChangeTime", gameInfo:getActiveTotalTimeInMinutes())
				gameInfo:getActiveBetaStat():setBool("FirstCursomCursor", GUI:getLayer(optionsVersion):getWidget("CustomCursor"):QueryState(Message("GetState")):getData() == "1")
			end
			gameInfo:getActiveBetaStat():setBool("CursomCursor", GUI:getLayer(optionsVersion):getWidget("CustomCursor"):QueryState(Message("GetState")):getData() == "1")
		end
		if (lastShowHints ~= (GUI:getLayer(optionsVersion):getWidget("ATips"):QueryState(Message("GetState")):getData() == "1")) then
			gameInfo:getActiveBetaStat():setBool("HintsEnabledChanged", true)
			if (not gameInfo:getActiveBetaStat():findName("HintsEnabledChangeTime")) then
				gameInfo:getActiveBetaStat():setFloat("HintsEnabledChangeTime", gameInfo:getActiveTotalTimeInMinutes())
				gameInfo:getActiveBetaStat():setBool("FirstHintsEnabled", GUI:getLayer(optionsVersion):getWidget("ATips"):QueryState(Message("GetState")):getData() == "1")
			end
			gameInfo:getActiveBetaStat():setBool("HintsEnabled", GUI:getLayer(optionsVersion):getWidget("ATips"):QueryState(Message("GetState")):getData() == "1")
		end
		--[[
		if (lastEnableSS ~= (GUI:getLayer(optionsVersion):getWidget("ScreenSaver"):QueryState(Message("GetState")):getData() == "1")) then
			gameInfo:getActiveBetaStat():setBool("ScreenSaverChanged", true)
			if (not gameInfo:getActiveBetaStat():findName("ScreenSaverChangeTime")) then
				gameInfo:getActiveBetaStat():setFloat("ScreenSaverTime", gameInfo:getActiveTotalTimeInMinutes())
				gameInfo:getActiveBetaStat():setBool("FirstScreenSaver", GUI:getLayer(optionsVersion):getWidget("ScreenSaver"):QueryState(Message("GetState")):getData() == "1")
			end
			gameInfo:getActiveBetaStat():setBool("ScreenSaver", GUI:getLayer(optionsVersion):getWidget("ScreenSaver"):QueryState(Message("GetState")):getData() == "1")
		end
		]]
		optionsOnScreen = false
		SetOptions()
		SoftResetButtonsInMainMenu()
		FlyPushLayer(optionsVersion, "Options", 1)
	elseif optionsOnScreen and message:is("Cancel", "press") then
		optionsOnScreen = false
		SoftResetButtonsInMainMenu()
		FlyPushLayer(optionsVersion, "Options", 1, "RestoreOptions")
	elseif message:is("Music") then
		local musicVolume = message:getIntegerParam()
		gameInfo:setMusicVolume(musicVolume)
		Sound:SetMusicVolume(musicVolume)
	elseif message:is("Sound") then
		local soundVolume = message:getIntegerParam()
		gameInfo:setSoundVolume(soundVolume)
		Sound:SetSoundVolume(soundVolume)
	elseif message:is("Credits", "press") then
		GUI:getLayer("MainMenu"):SetAllowDeinit(false)
		GUI:getLayer("Game"):SetAllowDeinit(false)
		Screen:StoreSnapShot()
		local param = VariableSet()
		param:setString("Layer1", "Credits")
		param:setString("CrossHandler", "CreditsReset")
		param:setString("NoFadeTracks", "true")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("CustomCursor", "Change") then
		local state = GUI:getLayer(optionsVersion):getWidget("CustomCursor"):QueryState(Message("GetState"))
		if state:getData() == "1" then
			SetCustomCursor(true)
			gameInfo:setCustomCursor(true)
		else
			SetCustomCursor(false)
			gameInfo:setCustomCursor(false)
		end		
	else
		GUI:getLayer(optionsVersion):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

function CreditsReset(message)
	GUI:getLayer("Credits"):getWidget("Credits"):AcceptMessage(Message("Reset"))
end

function CreditsReset2(message)
	GUI:getLayer("Credits"):getWidget("Credits"):AcceptMessage(Message("Reset2"))
	Sound:FadeInTrack("MainMenuAndMap", 1.0, true)
end

function ShowMapFunc(message)
	--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("Show"))
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("Show"))
end

function PrepareMapFunc(message)
	StartMusicInMap()
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("Prepare"))
end

function PrepareMapWOMusicFunc(message)
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("Prepare"))
end

-- Вызывается, если попадает в карту после последнего мульта
function PrepareMapFunc2(message)
	StartMusicInMap()
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("Prepare2"))
end

function PrepareMapWOMusicFunc2(message)
	StartMusicInMap()
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("Prepare2"))
end

function PrepareBonusFunc(message)
	GUI:getLayer("Bonus"):getWidget("Bonus"):AcceptMessage(Message("Prepare"))
end

function PrepareCGFunc(message)
	GUI:getLayer("CGuide"):getWidget("ACGuide"):AcceptMessage(Message("Prepare"))
end

function PrepareCGFunc2(message)
	GUI:getLayer("CGuide"):getWidget("ACGuide"):AcceptMessage(Message("Prepare2"))
end

function PrepareCGFunc3(message)
	GUI:getLayer("CGuide"):getWidget("ACGuide"):AcceptMessage(Message("Prepare3"))
end

function PrepareCGWalk(message)
	GUI:getLayer("CGuide"):getWidget("ACGuide"):AcceptMessage(Message("PrepareWalk"))
end

function WinBonusFunc(message)
	StartMusicInMainMenu()
	GUI:getLayer("Bonus"):getWidget("Bonus"):AcceptMessage(Message("WinLevel"))
end

function PortalMapFunc(message)
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("PortalIn"))	
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("Prepare"))
end

function PortalShowMapFunc(message)
	if gameInfo:GetSavedState() == 1 then
		StartInMapSavedGame()
	else
		ShowMapFunc()
	end
end

function StartGameFunc(message)
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StartLevel"))
end

function RestartGameFunc(message)
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("UnmarkLevelAsRestarting"))
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("RestartLevel"))
	tutorial:eventUpdate(Message("LayerPushed"))
end

-- Функция слоя LayerLoadFade
function LayerLoadFadeFunc(message)
	GUI:getLayer("LayerLoadFade"):getWidget("LayerLoadFade"):AcceptMessage(message)
end

function EndLoadLayer()
	param:setString("Layer1", "Game")
	param:setString("AfterPushHandler", "StartGameFunc")
	param:setBool("ResourceManagement", false)
	kernel:addController(controlFactory:Create("CrossFade", param))
end

-- Функция вызывается при загрузке слоя LayerLoadFade и говорит ему, чтобы тот начал грузить уровень
function AfterFadeFunc()
	GUI:getLayer("LayerLoadFade"):getWidget("LayerLoadFade"):AcceptMessage(Message("LoadGameLevel"))
end

-- Вызывается при переходе через кросс-фейд на экран загрузки уровней
function LayerLoadFadeCrossHandler()
	-- Пушим слой игры. Он будет лежать ПОД экраном загрузки уровней
	Screen:pushLayer(GUI:getLayer("Game"))
	-- Запрещаем игре обновляться и рисоваться
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("LevelLoadPause"))
end

--[[
При проигрывании лава-мультов нужно убрать заглуши для широкоформатных мониторов и поставить черные полосы
]]--
function HideGameWidePanels()
	GUI:getLayer("Game"):getWidget("zzzzWPLeft"):setVisible(false)
	GUI:getLayer("Game"):getWidget("zzzzWPRight"):setVisible(false)
	
	GUI:getLayer("Game"):getWidget("zzzzzWPRightUp"):setVisible(false)
	GUI:getLayer("Game"):getWidget("zzzzzWPRightDown"):setVisible(false)
	GUI:getLayer("Game"):getWidget("zzzzzWPLeftUp"):setVisible(false)
	GUI:getLayer("Game"):getWidget("zzzzzWPLeftDown"):setVisible(false)
	GUI:getLayer("Game"):getWidget("zzzzzzTopBlackSolidRect"):setVisible(true)
	GUI:getLayer("Game"):getWidget("zzzzzzBottomBlackSolidRect"):setVisible(true)
end

--[[
Возвращаем обычные заглушки для широкоформатных мониторов
]]--
function ShowGameWidePanels()
	GUI:getLayer("Game"):getWidget("zzzzWPLeft"):setVisible(true)
	GUI:getLayer("Game"):getWidget("zzzzWPRight"):setVisible(true)
	
	GUI:getLayer("Game"):getWidget("zzzzzWPRightUp"):setVisible(true)
	GUI:getLayer("Game"):getWidget("zzzzzWPRightDown"):setVisible(true)
	GUI:getLayer("Game"):getWidget("zzzzzWPLeftUp"):setVisible(true)
	GUI:getLayer("Game"):getWidget("zzzzzWPLeftDown"):setVisible(true)
	GUI:getLayer("Game"):getWidget("zzzzzzTopBlackSolidRect"):setVisible(false)
	GUI:getLayer("Game"):getWidget("zzzzzzBottomBlackSolidRect"):setVisible(false)
	
	gameInfo:game():SetScriptScene(false)
end

-- Возвращается на карту псоле мульта с лавой
function ReturnToMapAfterLavaMult()
	--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("LastMovieStartedToFalse"))
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("LastMovieStartedToFalse"))
	local param = VariableSet()
	--param:setString("Layer1", "GameMap")
	param:setString("Layer1", "GameMapNew")
	param:setString("CrossHandler", "PrepareMapFunc2")
	param:setString("AfterPushHandler", "ShowGameWidePanels")
	param:setBool("ResourceManagement", false)
	kernel:addController(controlFactory:Create("CrossFade", param))
end

-- Посылает сообщение Game, чтобы тот начал грузить очередной лава-уровень
function StartLavaLevelHelper()
	gameInfo:game():SetScriptScene(false)
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StartLavaLevel"))
	HideGameWidePanels()
end

-- Стартует игру и запускает очередной лава-уровень
function StartLavaLevel()
	local param = VariableSet()
	param:setString("Layer1", "Game")
	param:setString("AfterPushHandler", "StartLavaLevelHelper")
	param:setBool("ResourceManagement", false)
	kernel:addController(controlFactory:Create("CrossFade", param))
end

function StartLavaLevelHelperDebug()
	--gameInfo:game():SetScriptScene(false)
	--gameInfo:game():SetScriptSceneDebug(true)
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StartLavaLevel"))
	HideGameWidePanels()
end

function StartLavaLevelDebug()
	local param = VariableSet()
	param:setString("Layer1", "Game")
	param:setString("AfterPushHandler", "StartLavaLevelHelperDebug")
	param:setBool("ResourceManagement", false)
	kernel:addController(controlFactory:Create("CrossFade", param))
end

function GameMapUpdateStarsCount()
	--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("UpdateStarsCount"))
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("UpdateStarsCount"))
end

function GameMapFunc(message)
	if message:is("StartGame1") then
		local param = VariableSet()
		param:setString("Layer1", "Game")
		-- В коде сделана жесткая привязка к имени функции StartGameFunc. Меняешь сдесь, поменяй и в LayerLoadScreen.cpp\struct GameLevelLoader
		param:setString("AfterPushHandler", "StartGameFunc")
		param:setString("LoadLayerEndHandler", "AfterFadeFunc")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("ProgressCrossFade", param))
	elseif message:is("StartGame2") then
		multFromCinemas = 2
		gameInfo:setMult(2)
		local param = VariableSet()
		param:setString("Layer1", "Mult")
		param:setString("CrossHandler", "PlayMult2")
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("StartGame3") then
		multFromCinemas = 3
		gameInfo:setMult(3)
		local param = VariableSet()
		param:setString("Layer1", "Mult")
		param:setString("CrossHandler", "PlayMult3")
		--param:setInt("ResourcesAmount", gameInfo:getMultResourcesCount("video3"))
		param:setString("EndHandler", "ShowMapFunc")
		--kernel:addController(controlFactory:Create("LoadCrossFade", param))
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("StartGame", "press") then
		--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("Start"))
		GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("Start"))
	elseif message:is("StartPirate") then
		--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("Show"))
		GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("Show"))
	elseif message:is("EndPirate") then
		--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("StopShipSound"))
		GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("StopShipSound"))
		multFromCinemas = 4
		gameInfo:setMult(4)
		local param = VariableSet()
		param:setString("Layer1", "Mult")
		param:setString("CrossHandler", "PlayMult4")
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("End7") then		
		--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("StopShipSound"))
		GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("StopShipSound"))
		multFromCinemas = 6
		gameInfo:setMult(6)
		local param = VariableSet()
		param:setString("Layer1", "Mult")
		param:setString("CrossHandler", "PlayMult6")
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("End9") then		
		multFromCinemas = 7
		gameInfo:setMult(7)
		local param = VariableSet()
		param:setString("Layer1", "Credits")								
		param:setString("Layer2", "Mult")
		param:setString("CrossHandler", "PlayMultCredits")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("HiddenLevel") then		
		--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("StopShipSound"))	
		GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("StopShipSound"))	
		multFromCinemas = 5
		gameInfo:setMult(5)
		local param = VariableSet()
		param:setString("Layer1", "Mult")
		param:setString("CrossHandler", "PlayMult5")
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("MainMenu", "press") then
		local param = VariableSet()
		param:setString("Layer1", "MainMenu")
		param:setString("AfterFadeHandler", "GameMapUpdateStarsCount")
		--param:setString("CrossHandler", "StartMusicInMainMenu")
		param:setBool("ResourceManagement", false)
		param:setBool("NoFadeTracks", true)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("Trophy", "press") then
		trophyRoomFrom = 0;
		local param = VariableSet()
		param:setString("Layer1", "Trophy")
		param:setString("AfterFadeHandler", "GameMapUpdateStarsCount")
		param:setString("CrossHandler", "InitTrophy")
		param:setBool("NoFadeTracks", true)
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("Portal", "press") then
		local param = VariableSet()
		--param:setString("Layer1", "GameMap")
		param:setString("Layer1", "GameMapNew")
		param:setBool("NoFadeTracks", true)
		param:setString("CrossHandler", "PortalMapFunc")
		param:setString("EndHandler", "PortalShowMapFunc")
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("EndLava") then
		-- Обнуляем текущий лава-уровень
		gameInfo:game():setCurrentLavaLevel(0)
		StartLavaLevel()
	elseif message:is("EndLavaDebug") then
		-- Обнуляем текущий лава-уровень
		gameInfo:game():setCurrentLavaLevel(0)
		StartLavaLevelDebug()
	elseif message:is("ContinueSavedOrLevels") then
		FlyPushLayer("ContinueSaved", "ContinueSaved", 0)
		-- IslandName
		-- Идиотизм, но после "улучшения" работы с текстами без этого никуда
		SetTextProperty("ContinueSavedIslandName", "ContinueSavedIslandName", gameInfo:getLevelIslandName(gameInfo:getLevel()))
		UpdateTextProperties("ContinueSavedIslandName")
		-- LevelNum
		SetTextProperty("ContinueSavedLevelNum", "LevelNum", gameInfo:getLevelAsString())
		UpdateTextProperties("ContinueSavedLevelNum")
	elseif message:is("SkipTutorial", "press") then
		GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(message)	
	elseif message:is("Layer", "Init") then
		GUI:getLayer("GameMapNew"):BroadcastMessage(Message("Screen", "activate", 1))
	elseif message:is("Layer", "Deinit") then
		GUI:getLayer("GameMapNew"):BroadcastMessage(Message("Screen", "activate", 0))
	end
end

function InitTrophy()
	GUI:getLayer("Trophy"):getWidget("Trophy"):AcceptMessage(Message("Init"))
	if trophyRoomFrom == 1 then
		GUI:getLayer("Trophy"):getWidget("ReturnToMenu"):setVisible(true)
		GUI:getLayer("Trophy"):getWidget("ReturnToMap"):setVisible(false)
	elseif trophyRoomFrom == 0 then
		GUI:getLayer("Trophy"):getWidget("ReturnToMenu"):setVisible(false)
		GUI:getLayer("Trophy"):getWidget("ReturnToMap"):setVisible(true)
	end	
end

function StartInLevelSavedGame()
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StartSavedGame"))
	-- Раньше тут еще было tutorial:eventUpdate(Message("LayerPushed")), теперь этот код вызывается в TutorialLayerPushed
end

function TutorialLayerPushed()
	--[[
	Извещаем туториал, что слой Game запушен (он запушен раньше, но туториалу об этом знать не положено)
	Раньше этот код был в AfterPushHandler'e crossfade'a перехода с экрана загрузки в экран игры
	Порядок вызова функции по отношению к AcceptMessage(Message("LevelLoadContinue")) важен, т.к. нужно соблюсти очередность сообщений
	]]--
	tutorial:eventUpdate(Message("LayerPushed"))
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("LevelLoadContinue"))
end

function StartInGameLayer()
	tutorial:eventUpdate(Message("LayerPushed"))
end

function StartInMapSavedGame()
	--GUI:getLayer("GameMap"):getWidget("GameMap"):AcceptMessage(Message("StartSavedGame"))
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("StartSavedGame"))
	GUI:getLayer("MainMenu"):getWidget("1_Menu"):AcceptMessage(Message("ResetParrot"))
end

function StartInMapNewSavedGame()
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("StartSavedGame"))
	GUI:getLayer("MainMenu"):getWidget("1_Menu"):AcceptMessage(Message("ResetParrot"))
end

function StartInBonusSavedGame()
	GUI:getLayer("Bonus"):getWidget("Bonus"):AcceptMessage(Message("StartSavedGame"))
end

function StartIntroMovie()
	local param = VariableSet()
	param:setString("Layer1", "Intro")
	param:setString("AfterPushHandler", "StartIntro")
	kernel:addController(controlFactory:Create("CrossFade", param))
end

function StartIntroMovieSkipOnClick()
	local param = VariableSet()
	param:setString("Layer1", "Intro")
	param:setString("AfterPushHandler", "StartIntroSkipOnClick")
	kernel:addController(controlFactory:Create("CrossFade", param))
end

function StartIntroMovieNoSkipOnClick()
	local param = VariableSet()
	param:setString("Layer1", "Intro")
	param:setString("AfterPushHandler", "StartIntroNoSkipOnClick")
	kernel:addController(controlFactory:Create("CrossFade", param))
end

function PrepareGameMapNewFunc(message)
	StartMusicInMap()
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("Prepare"))
end

function ShouldLoadFirstLevel()
	if gameInfo:getLevel() == 0 and gameInfo:GetLastPlayedLevelRating() == 0 then
		return true
	else
		return false
	end
end

function MainMenuFunc(message)
	if (message:is("ScreenPushLayer")) then
		GUI:getLayer("MainMenu"):getWidget("1_Menu"):AcceptMessage(message)
	elseif message:is("Layer", "Init") then
		gameInfo:setBool("InMainMenu", true)
	elseif message:is("Layer", "Deinit") then
		ResetButtonsInMainMenu()
	elseif (message:is("Start", "press")) then
		gameInfo:setBool("InMainMenu", false)
		gameInfo:restoreLevel()
		if gameInfo:NoSavedStates() then
			introFromMainMenu = true
			fromIntroToMainMenu = false
			StartIntroMovie()
		elseif gameInfo:GetSavedState() == 3 and not gameInfo:HasSavedLevel() then -- Сохранились в статистике
			gameInfo:setBool("DoNotStartTrackInMap", true)
			PrintDebug("DoNotStartTrackInMap is set to true\n")
			GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("SetCurrentRating"))
			GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("CalcStarsCount"))
			GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("PrepareStat"))
			GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StatisticsOk"))
		else
			if ShouldLoadFirstLevel() then
				if gameInfo:HasSavedLevel() then
					StartSavedGameFunc()
				else
					GameMapFunc(Message("StartGame1"))
				end
			else
				param = VariableSet()
				param:setString("Layer1", "GameMapNew")
				param:setString("AfterFadeHandler", "GameMapUpdateStarsCount")
				-- Начали смотреть последний мульт, но не досмотрели
				if gameInfo:getBoolData("LastMovieStarted") == true then
					param:setString("CrossHandler", "PrepareMapWOMusicFunc2")
				else
					param:setString("CrossHandler", "PrepareMapWOMusicFunc")
				end
				param:setString("EndHandler", "StartInMapSavedGame")
				param:setBool("ResourceManagement", false)
				param:setBool("NoFadeTracks", true)
				kernel:addController(controlFactory:Create("CrossFade", param))
				gameInfo:ContinueSavedGame()
			end
		end
	elseif message:is("2_Options", "press") then
		SaveOptions()
		RestoreOptions()
		FlyPushLayer(optionsVersion, "Options", 0)
	elseif message:is("Profile", "press") then
		FlyPushLayer("Profiles", "Profiles", 0)
	elseif message:is("1_Exit", "press") then
		CloseApplicationConfirm()
	elseif message:is("MoreGames", "press") then
		local param = VariableSet()
		param:setString("Layer1", "MoreGames")
		param:setString("CrossHandler", "MoreGamesCross")
		param:setString("EndHandler", "MoreGamesEndHandler")
		param:setBool("NoFadeTracks", true)
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))		
	elseif message:is("3_Intro3", "press") or message:is("4_Intro4", "press") then
		introFromMainMenu = true
		fromIntroToMainMenu = true
		StartIntroMovieSkipOnClick()
	elseif message:is("4_Achievements4", "press") or message:is("5_Achievements5", "press") then
		trophyRoomFrom = 1;
		local param = VariableSet()
		param:setString("Layer1", "Trophy")
		param:setString("CrossHandler", "InitTrophy")
		param:setBool("NoFadeTracks", true)
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("3_Credits", "press") then
		GUI:getLayer("MainMenu"):SetAllowDeinit(false)
		GUI:getLayer("Game"):SetAllowDeinit(false)
		Screen:StoreSnapShot()
		local param = VariableSet()
		param:setString("Layer1", "Credits")
		param:setString("CrossHandler", "CreditsReset")
		param:setString("NoFadeTracks", "true")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))	
	elseif message:is("3_Extras", "press") then
		local param = VariableSet()
		param:setBool("NoFadeTracks", true)
		param:setString("Layer1", "PremiumVersion")
		param:setString("CrossHandler", "PremiumVersionCross")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("5_Challenges", "press") then
		bonusLevelsFromMainMenu = true
		local param = VariableSet()
		param:setBool("NoFadeTracks", true)
		param:setString("Layer1", "Bonus")
		param:setString("CrossHandler", "PrepareBonusFunc")
		param:setString("EndHandler", "StartInBonusSavedGame")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("StartInLevelSavedGame") then
		param = VariableSet()
		param:setString("Layer1", "Game")
		param:setString("CrossHandler", "StartInLevelSavedGame")
		param:setString("AfterPushHandler", "StartInGameLayer")
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("StartInMapSavedGame") then
		param = VariableSet()
		--param:setString("Layer1", "GameMap")
		param:setString("Layer1", "GameMapNew")
		param:setString("CrossHandler", "StartInMapSavedGame")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("WinLevel")  then
		GameFunc(message)
	elseif message:is("Run morphing editor") then
		Screen:Clear()
		GUI:getLayer("MorphingEditorLayer"):getWidget("MorphingEditor"):AcceptMessage(Message("Init"))
		Screen:pushLayer(GUI:getLayer("MorphingEditorLayer"))
	elseif message:is("Intro3", "press") or message:is("Intro4", "press") then
		introFromMainMenu = true
		fromIntroToMainMenu = true
		StartIntroMovieSkipOnClick()
	elseif message:is("GameMapNew", "press") then
		gameInfo:restoreLevel()
		if gameInfo:NoSavedStates() then
			introFromMainMenu = true
			fromIntroToMainMenu = false
			StartIntroMovie()
		elseif gameInfo:GetSavedState() == 3 and not gameInfo:HasSavedLevel() then -- Сохранились в статистике
			GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("SetCurrentRating"))
			GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("CalcStarsCount"))
			GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("PrepareStat"))
			GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StatisticsOk"))
		else
			param = VariableSet()
			param:setString("Layer1", "GameMapNew")
			param:setString("AfterFadeHandler", "GameMapUpdateStarsCount")
			param:setString("CrossHandler", "PrepareMapFunc")
			param:setString("EndHandler", "StartInMapNewSavedGame")
			param:setBool("ResourceManagement", false)
			kernel:addController(controlFactory:Create("CrossFade", param))
			gameInfo:ContinueSavedGame()
		end

	elseif message:is("StartMMTrack") then
		--GUI:getLayer("LoadScreen"):getWidget("LoadScreen"):AcceptMessage(Message("StartMMTrack"))
		
	else
		GUI:getLayer("MainMenu"):getWidget("1_Menu"):AcceptMessage(message)
	end
end

-- Функция слоя Mult
function MultFunc(message)
end	


-- Функция туториала
function TutorialFunc(message)
	if (not message:is("Layer", "Deinit")) then
		GameFunc(message)
	end
	tutorial:eventUpdate(message)
end

-- Функция статистики
function StatisticsFunc(message)
	if (message:is("StartOffset")) then
		GUI:getLayer("Statistics"):getWidget("zzStatistics"):AcceptMessage(message)
	elseif (message:is("Continue", "press")) then
		GUI:getLayer("Statistics"):getWidget("zzStatistics"):AcceptMessage(Message("ForbidAchievementsUpdate"))
		GUI:getLayer("StatisticsLong"):getWidget("zzStatistics"):AcceptMessage(Message("ForbidAchievementsUpdate"))
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StatisticsOk"))
	elseif (message:is("Restart", "press")) then
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StatisticsRestart"))
	elseif (message:is("OnScreen")) then
		GUI:getLayer("Statistics"):getWidget("zzStatistics"):AcceptMessage(message)
	elseif (message:is("KeyPress")) then
		GUI:getLayer("Statistics"):getWidget("zzStatistics"):AcceptMessage(message)
	elseif (message:is("TipNext", "press") or message:is("TipPrev", "press")) then
		GUI:getLayer("Statistics"):getWidget("zzStatistics"):AcceptMessage(message)
	elseif (message:is("RestartStatistics")) then
		Screen:popLayer()
		Screen:popLayer()
		Screen:popLayer()
		messageManager:putMessage(Message("PushStatistics"))
	else
		GameFunc(message)
	end
end

function StatisticsLongFunc(message)
	if (message:is("StartOffset")) then
		GUI:getLayer("StatisticsLong"):getWidget("zzStatistics"):AcceptMessage(message)
	elseif (message:is("Continue", "press")) then
		GUI:getLayer("StatisticsLong"):getWidget("zzStatistics"):AcceptMessage(Message("ForbidAchievementsUpdate"))
		GUI:getLayer("Statistics"):getWidget("zzStatistics"):AcceptMessage(Message("ForbidAchievementsUpdate"))
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StatisticsOk"))
	elseif (message:is("Restart", "press")) then
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StatisticsRestart"))
	elseif (message:is("OnScreen")) then
		GUI:getLayer("StatisticsLong"):getWidget("zzStatistics"):AcceptMessage(message)
	elseif (message:is("KeyPress")) then
		GUI:getLayer("StatisticsLong"):getWidget("zzStatistics"):AcceptMessage(message)
	elseif (message:is("TipNext", "press") or message:is("TipPrev", "press")) then
		GUI:getLayer("StatisticsLong"):getWidget("zzStatistics"):AcceptMessage(message)
	elseif (message:is("RestartStatistics")) then
		Screen:popLayer()
		Screen:popLayer()
		Screen:popLayer()
		messageManager:putMessage(Message("PushStatistics"))
	else
		GameFunc(message)
	end
end


function StatisticsWideFunc(message)
	if gameInfo:getBool("StatisticsLong") then
		StatisticsLongFunc(message)
	else
		StatisticsFunc(message)
	end
end

-- Функции включения/отключения звуков

function StartMusicInMainMenu()
	Sound:Fade(1.0, 0.0)
	Sound:FadeInTrack("MainMenuAndMap", 2.0, true)
end

function StartMusicInMoreGames()
	Sound:Fade(1.0, 0.0)
	Sound:FadeInTrack("MainMenuAndMap", 2.0, true)
end
function StartMusicInMap()
	Sound:Fade(1.0, 0.0)
	Sound:FadeInTrack("MainMenuAndMap", 2.0, true)
	GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(Message("StartShipSound"))	
end
function StartMusicInGame()
	Sound:Fade(1.0, 0.0)
	local trackName = gameInfo:getCurrentGameTrack()
	gameInfo:setCurrentGameTrackName(trackName)
	Sound:FadeInTrack(trackName, 2.0, true)
end

function ActualStartMusicInGame()
	local trackName = gameInfo:getCurrentGameTrack()
	gameInfo:setCurrentGameTrackName(trackName)
	Sound:FadeInTrack(trackName, 1.0, true)
end

function StartMusicInTrophy()
	Sound:Fade(1.0, 0.0)
	Sound:FadeInTrack("MainMenuAndMap", 2.0, true)
end

function CloseApplicationConfirm()
	if (Screen:isLayerOnScreen("ExitConfirmCross") or Screen:isLayerOnScreen("LoadFade") or Screen:getMainLayerName() == "Cross" 
		or Screen:getMainLayerName() == "Cross1" or Screen:getMainLayerName() == "Cross2" or Screen:getMainLayerName() == "Cross3"
		or Screen:isLayerOnScreen("Splashes")) -- or kernel:isControllerFinish("Fader varset") == false 
		then
		return
	end
	--[[
	if gameInfo:enableScreenSaver() then
		GUI:getLayer("ExitConfirm"):getWidget("ScreenSaver"):AcceptMessage(Message("Show"))
		GUI:getLayer("ExitConfirm"):getWidget("ScreenSaver"):AcceptMessage(Message("SwitchOn"))
	else
		GUI:getLayer("ExitConfirm"):getWidget("ScreenSaver"):AcceptMessage(Message("Show"))
		GUI:getLayer("ExitConfirm"):getWidget("ScreenSaver"):AcceptMessage(Message("SwitchOff"))
	end
	]]
	GUI:getLayer("ExitConfirm"):getWidget("InfoSubText"):AcceptMessage(Message("SetVisible", 0))
	local layer = GUI:getLayer(Screen:getMainLayerName())
	ExitConfirmFlyPushLayer(0)
	
	if Screen:isLayerOnScreen("Game") then
		GUI:getLayer("ExitConfirm"):getWidget("InfoSubText"):AcceptMessage(Message("SetVisible", 1))
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("HideAllHints"))
	end
end

function SetOptionsCheckboxForFullScreenMode()
	if Screen:isLayerOnScreen(optionsVersion) then
		if gameInfo:isFullScreen() then
			GUI:getLayer(optionsVersion):getWidget("Fullscreen"):AcceptMessage(Message("SwitchOn"))
		else
			GUI:getLayer(optionsVersion):getWidget("Fullscreen"):AcceptMessage(Message("SwitchOff"))
		end
	end
end

function AltEnterHandler()
	if gameInfo:isFullScreen() then
		SetWindowedMode()
		gameInfo:setFullScreen(false)
	else
		SetFullscreenMode()
		gameInfo:setFullScreen(true)
	end
	
	--SetOptionsCheckboxForFullScreenMode()
	if Screen:isLayerOnScreen("VideoLayer") then	
		GUI:getLayer("VideoLayer"):getWidget("LastVideo"):AcceptMessage(Message("SetPosition", GetLastVideoPosition()))
	end	

	if Screen:isLayerOnScreen("Intro") then
		GUI:getLayer("Intro"):getWidget("IntroVideo"):AcceptMessage(Message("WindowModeChange"))
	end
end

function setOptionsVersion(version)
	optionsVersion = version
end

function RunLastVideo(message)
	GUI:getLayer("VideoLayer"):getWidget("LastVideo"):AcceptMessage(Message("SetFileName", gameInfo:getString("videoPath")))
	GUI:getLayer("VideoLayer"):getWidget("LastVideoInputHandler"):AcceptMessage(Message("SetActive"))
	local param = VariableSet()
	param:setString("Layer1", "VideoLayer")
	param:setString("CrossHandler", "playVideo")
	kernel:addController(controlFactory:Create("CrossFade", param))
end

function playVideo()
	GUI:getLayer("VideoLayer"):getWidget("LastVideo"):AcceptMessage(Message("SetPosition", GetLastVideoPosition()))
	GUI:getLayer("VideoLayer"):getWidget("LastVideo"):AcceptMessage(Message("Play"))
end

function MoreGamesCross(message)
	GUI:getLayer("MoreGames"):getWidget("MoreGames"):AcceptMessage(Message("Init"))
end

function MoreGamesEndHandler(message)
	GUI:getLayer("MoreGames"):getWidget("MoreGames"):AcceptMessage(Message("ResetTimers"))
end

function MoreGamesCrossEnd(message)
	GUI:getLayer("MoreGames"):getWidget("MoreGames"):AcceptMessage(Message("Release"))
end

function MoreGamesFunc(message)
	if (message:is("Return", "press")) then
		local param = VariableSet()
		param:setString("Layer1", "MainMenu")
		param:setString("AfterPushHandler", "MainMenuInitFunc")
		param:setString("CrossHandler", "MoreGamesCrossEnd")			
		param:setBool("NoFadeTracks", true)
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("Layer", "Init") then
		GUI:getLayer("MoreGames"):BroadcastMessage(Message("Screen", "activate", 1))
	elseif message:is("Layer", "Deinit") then
		GUI:getLayer("MoreGames"):BroadcastMessage(Message("Screen", "activate", 0))
	else
		GUI:getLayer("MoreGames"):getWidget("MoreGames"):AcceptMessage(message)
	end
end

function PremiumVersionCross(message)
	GUI:getLayer("PremiumVersion"):getWidget("OAWheel"):AcceptMessage(Message("StartWheel"))
	--GUI:getLayer("PremiumVersion"):getWidget("Bonus"):AcceptMessage(Message("SetBlinkTime", "8.0"))
end

function CGuideEnd(message)
end

function PremiumVersionFunc(message)
	if message:is("Return", "press") then
		local param = VariableSet()
		param:setString("Layer1", "MainMenu")
		param:setString("AfterPushHandler", "MainMenuInitFunc")
		param:setBool("ResourceManagement", false)
		param:setBool("NoFadeTracks", true)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("Bonus", "press") then
		bonusLevelsFromMainMenu = false
		local param = VariableSet()
		param:setString("Layer1", "Bonus")
		param:setBool("NoFadeTracks", true)
		param:setString("CrossHandler", "PrepareBonusFunc")
		param:setString("EndHandler", "StartInBonusSavedGame")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	--[[
	elseif message:is("CG", "press") then
		extrasFrom = 0
		local param = VariableSet()
		param:setString("Layer1", "CGuide")
		param:setBool("NoFadeTracks", true)
		param:setString("CrossHandler", "PrepareCGWalk")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("MO", "press") then
		extrasFrom = 0
		local param = VariableSet()
		param:setString("Layer1", "CGuide")
		param:setBool("NoFadeTracks", true)
		param:setString("CrossHandler", "PrepareCGFunc3")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
		]]
	elseif message:is("Wallpapers", "press") then
		local param = VariableSet()
		param:setBool("NoFadeTracks", true)
		param:setString("Layer1", "Wallpapers")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("IM", "press") then
		local param = VariableSet()
		param:setBool("NoFadeTracks", true)
		param:setString("Layer1", "Videos")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("OST", "press") then
		local param = VariableSet()
		param:setString("Layer1", "OST")
		param:setBool("ResourceManagement", false)
		param:setString("CrossHandler", "OSTInit")
		kernel:addController(controlFactory:Create("CrossFade", param))
		--[[
	elseif message:is("IM", "press") then
		introFromMainMenu = false
		fromIntroToMainMenu = false
		StartIntroMovieSkipOnClick()
	]]
	elseif message:is("StartMMTrack") then
		GUI:getLayer("LoadScreen"):getWidget("LoadScreen"):AcceptMessage(Message("StartMMTrack"))
	elseif message:is("Layer", "Init") then
		GUI:getLayer("PremiumVersion"):BroadcastMessage(Message("Screen", "activate", 1))
	elseif message:is("Layer", "Deinit") then
		GUI:getLayer("PremiumVersion"):BroadcastMessage(Message("Screen", "activate", 0))
	else	
		GUI:getLayer("PremiumVersion"):getWidget("Premium"):AcceptMessage(message)
	end
end

function HideWallpapersStuff()
	local param = VariableSet()
	param:setColor("To", Color(0, 0, 0, 0))
	param:setString("Layer", "Wallpapers")
	param:setString("WidgetName", "ClickToPreview")
	kernel:addController(controlFactory:Create("WidgetFader", param))
	
	param = VariableSet()
	param:setColor("To", Color(0, 0, 0, 0))
	param:setString("Layer", "Wallpapers")
	param:setString("WidgetName", "BlackFrame")
	kernel:addController(controlFactory:Create("WidgetFader", param))
end

function ShowWallpapersStuff()
	local param = VariableSet()
	param:setColor("To", Color(255, 255, 255, 255))
	param:setString("Layer", "Wallpapers")
	param:setString("WidgetName", "ClickToPreview")
	kernel:addController(controlFactory:Create("WidgetFader", param))
	
	param = VariableSet()
	param:setColor("To", Color(0, 0, 0, 128))
	param:setString("Layer", "Wallpapers")
	param:setString("WidgetName", "BlackFrame")
	kernel:addController(controlFactory:Create("WidgetFader", param))
end


function HideVideosStuff()
	local param = VariableSet()
	param:setColor("To", Color(0, 0, 0, 0))
	param:setString("Layer", "Videos")
	param:setString("WidgetName", "ClickToPreview")
	kernel:addController(controlFactory:Create("WidgetFader", param))
	
	param = VariableSet()
	param:setColor("To", Color(0, 0, 0, 0))
	param:setString("Layer", "Videos")
	param:setString("WidgetName", "BlackFrame")
	kernel:addController(controlFactory:Create("WidgetFader", param))
end

function ShowVideosStuff()
	local param = VariableSet()
	param:setColor("To", Color(255, 255, 255, 255))
	param:setString("Layer", "Videos")
	param:setString("WidgetName", "ClickToPreview")
	kernel:addController(controlFactory:Create("WidgetFader", param))
	
	param = VariableSet()
	param:setColor("To", Color(0, 0, 0, 128))
	param:setString("Layer", "Videos")
	param:setString("WidgetName", "BlackFrame")
	kernel:addController(controlFactory:Create("WidgetFader", param))
end

function StartVideo()
	GUI:getLayer("VideosPreview"):getWidget("VideoPreview"):AcceptMessage(Message("Play"))
end

function VideosFunc(message)
	if message:is("Return", "press") then
		local param = VariableSet()
		param:setBool("NoFadeTracks", true)
		param:setString("Layer1", "PremiumVersion")
		param:setString("CrossHandler", "PremiumVersionCross")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))

		GUI:getLayer("Videos"):getWidget("Videos"):AcceptMessage(Message("SaveScrollPosition"))
	elseif message:is("Layer", "Init") then
		GUI:getLayer("Videos"):BroadcastMessage(Message("Screen", "activate", 1))
		GUI:getLayer("Videos"):getWidget("Videos"):AcceptMessage(Message("ScrollToSavedPosition"))
		GUI:getLayer("Videos"):getWidget("Videos"):AcceptMessage(Message("Init"))

	elseif message:is("Layer", "Deinit") then
		GUI:getLayer("Videos"):BroadcastMessage(Message("Screen", "activate", 0))
	
	elseif message:is("Intro") then
		introFromMainMenu = false
		fromIntroToMainMenu = false
		StartIntroMovieNoSkipOnClick()
	elseif message:is("LeftArrow", "down") then
		GUI:getLayer("Videos"):getWidget("Videos"):AcceptMessage(Message("ScrollLeft"))
	elseif message:is("RightArrow", "down") then
		GUI:getLayer("Videos"):getWidget("Videos"):AcceptMessage(Message("ScrollRight"))
	else
		-- Video1..N
		local publisher = message:getPublisher()
		local substring = string.sub(publisher, 1, 5)
		if substring == "Video" then
			local videos = {
				Video1 = "video/GameMapNew/tv1.ogg",
				Video2 = "video/GameMapNew/tv2.ogg",
				Video3 = "video/GameMapNew/tv3.ogg",
				Video4 = "video/GameMapNew/tv4.ogg",
				Video5 = "video/GameMapNew/tv5.ogg",
				Video6 = "video/GameMapNew/tv6.ogg",
				Video7 = "video/GameMapNew/tv7.ogg",
				Video8 = "video/GameMapNew/tv8.ogg",
				Video9 = "video/GameMapNew/tv9.ogg",
				Video10 = "video/GameMapNew/tv10.ogg",
				Video11 = "video/GameMapNew/tv11.ogg",
				Video12 = "video/GameMapNew/tv12.ogg",
				Video13 = "video/GameMapNew/tv13.ogg",
				Video14 = "video/GameMapNew/tv14.ogg",
				Video15 = "video/GameMapNew/tv15.ogg",
				Video16 = "video/GameMapNew/tv16.ogg",
				Video17 = "video/GameMapNew/tv17.ogg",
				Video18 = "video/GameMapNew/tv18.ogg",
				Video19 = "video/GameMapNew/tv19.ogg",
				Video20 = "video/GameMapNew/tv20.ogg",
			}

			HideVideosStuff()
			GUI:getLayer("VideosPreview"):getWidget("VideoPreview"):AcceptMessage(Message("SetFileName", videos[publisher]))
			GUI:getLayer("Videos"):getWidget("Videos"):AcceptMessage(Message("Reset"))

			GUI:getLayer("VideosPreview"):getWidget("VideosSubtitles"):AcceptMessage(Message("Reset"))
			GUI:getLayer("VideosPreview"):getWidget("VideosSubtitles"):AcceptMessage(Message("SetVideo", publisher))

			GUI:getLayer("VideosPreview"):getWidget("PreviewCaption"):AcceptMessage(Message("SetText", publisher.."TitleLarge"))
			Sound:Fade(1.0, 0.0)
			VideosFadePushLayer("VideosPreview", "PreviewFrame")
		end
	end
end

function VideosPreviewFunc(message)
	if message:is("Return", "press") then
		VideosPreviewFunc(Message("VideoWidgetStopped"))
	elseif message:is("VideoWidgetStopped") then
		GUI:getLayer("VideosPreview"):getWidget("VideoPreview"):AcceptMessage(Message("Pause"))
		GUI:getLayer("VideosPreview"):getWidget("VideoPreview"):AcceptMessage(Message("Clear"))
		ShowVideosStuff()
		StartMusicInMainMenu()
		SimpleFadePopLayer("VideosPreview", "PreviewFrame")
	end
end

function WallpapersFunc(message)
	if message:is("Return", "press") then
		local param = VariableSet()
		param:setBool("NoFadeTracks", true)
		param:setString("Layer1", "PremiumVersion")
		param:setString("CrossHandler", "PremiumVersionCross")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
		
	elseif message:is("Wallpaper1", "press") then
		HideWallpapersStuff()
		
		GUI:getLayer("WallpapersPreview"):getWidget("Preview"):AcceptMessage(Message("SetTexture", "#WallpaperPreview01"))
		WallpapersPreviewFunc(Message("InitResolutionButtons", "true"))
		SimpleFadePushLayer("WallpapersPreview", "PreviewFrame")
	elseif message:is("Wallpaper2", "press") then
		HideWallpapersStuff()
		
		GUI:getLayer("WallpapersPreview"):getWidget("Preview"):AcceptMessage(Message("SetTexture", "#WallpaperPreview02"))
		WallpapersPreviewFunc(Message("InitResolutionButtons", "true"))
		SimpleFadePushLayer("WallpapersPreview", "PreviewFrame")
	elseif message:is("Wallpaper3", "press") then
		HideWallpapersStuff()

		GUI:getLayer("WallpapersPreview"):getWidget("Preview"):AcceptMessage(Message("SetTexture", "#WallpaperPreview03"))
		WallpapersPreviewFunc(Message("InitResolutionButtons", "true"))
		SimpleFadePushLayer("WallpapersPreview", "PreviewFrame")
	elseif message:is("Wallpaper4", "press") then
		HideWallpapersStuff()

		GUI:getLayer("WallpapersPreview"):getWidget("Preview"):AcceptMessage(Message("SetTexture", "#WallpaperPreview04"))
		WallpapersPreviewFunc(Message("InitResolutionButtons", "true"))
		SimpleFadePushLayer("WallpapersPreview", "PreviewFrame")
	elseif message:is("Wallpaper5", "press") then
		HideWallpapersStuff()

		GUI:getLayer("WallpapersPreview"):getWidget("Preview"):AcceptMessage(Message("SetTexture", "#WallpaperPreview05"))
		WallpapersPreviewFunc(Message("InitResolutionButtons", "true"))
		SimpleFadePushLayer("WallpapersPreview", "PreviewFrame")
	elseif message:is("Wallpaper6", "press") then
		HideWallpapersStuff()

		GUI:getLayer("WallpapersPreview"):getWidget("Preview"):AcceptMessage(Message("SetTexture", "#WallpaperPreview06"))
		WallpapersPreviewFunc(Message("InitResolutionButtons", "true"))
		SimpleFadePushLayer("WallpapersPreview", "PreviewFrame")
	elseif message:is("Wallpaper7", "press") then
		HideWallpapersStuff()

		GUI:getLayer("WallpapersPreview"):getWidget("Preview"):AcceptMessage(Message("SetTexture", "#WallpaperPreview07"))
		WallpapersPreviewFunc(Message("InitResolutionButtons", "true"))
		SimpleFadePushLayer("WallpapersPreview", "PreviewFrame")
	elseif message:is("Wallpaper8", "press") then
		HideWallpapersStuff()

		GUI:getLayer("WallpapersPreview"):getWidget("Preview"):AcceptMessage(Message("SetTexture", "#WallpaperPreview08"))
		WallpapersPreviewFunc(Message("InitResolutionButtons", "false"))
		SimpleFadePushLayer("WallpapersPreview", "PreviewFrame")
	elseif message:is("Layer", "Init") then
		GUI:getLayer("Wallpapers"):BroadcastMessage(Message("Screen", "activate", 1))
	elseif message:is("Layer", "Deinit") then
		GUI:getLayer("Wallpapers"):BroadcastMessage(Message("Screen", "activate", 0))
	end
end

function CheckAlreadySavedWallpapers()
	local textureId = GUI:getLayer("WallpapersPreview"):getWidget("Preview"):QueryState(Message("GetTexture")):getPublisher()
	
	local resolution = "1024x768"
	if HasSavedWallpaper(resolution, textureId) then
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(false)
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(true)
	else
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(true)
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(false)
	end
		
	if allResolutions then
		resolution = "1280x800"
		if HasSavedWallpaper(resolution, textureId) then
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(false)
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(true)
		else
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(true)
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(false)
		end		
	end
	
	resolution = "1280x960"
	if HasSavedWallpaper(resolution, textureId) then
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(false)
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(true)
	else
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(true)
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(false)
	end		

	if allResolutions then
		resolution = "1440x900"
		if HasSavedWallpaper(resolution, textureId) then
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(false)
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(true)
		else
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(true)
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(false)
		end		
	end
	
	resolution = "1600x1200"
	if HasSavedWallpaper(resolution, textureId) then
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(false)
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(true)
	else
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(true)
		GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(false)
	end		

	if allResolutions then
		resolution = "1920x1200"
		if HasSavedWallpaper(resolution, textureId) then
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(false)
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(true)
		else
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution):setVisible(true)
			GUI:getLayer("WallpapersPreview"):getWidget("W"..resolution.."Done"):setVisible(false)
		end
	end
	
	if not allResolutions then
		GUI:getLayer("WallpapersPreview"):getWidget("W1280x800Done"):setVisible(false)
		GUI:getLayer("WallpapersPreview"):getWidget("W1440x900Done"):setVisible(false)
		GUI:getLayer("WallpapersPreview"):getWidget("W1920x1200Done"):setVisible(false)
		
		GUI:getLayer("WallpapersPreview"):getWidget("W1024x768Done"):setPosition(IPoint(301, 103))
		GUI:getLayer("WallpapersPreview"):getWidget("W1280x960Done"):setPosition(IPoint(443, 103))
		GUI:getLayer("WallpapersPreview"):getWidget("W1600x1200Done"):setPosition(IPoint(585, 103))
	else
		GUI:getLayer("WallpapersPreview"):getWidget("W1024x768Done"):setPosition(IPoint(94, 103))
		GUI:getLayer("WallpapersPreview"):getWidget("W1280x960Done"):setPosition(IPoint(378, 103))
		GUI:getLayer("WallpapersPreview"):getWidget("W1600x1200Done"):setPosition(IPoint(662, 103))
	end
end

function WallpapersPreviewFunc(message)
	local textureId = ""
	local resolution = ""
	if message:is("Return", "press") then
		ShowWallpapersStuff()
		SimpleFadePopLayer("WallpapersPreview", "PreviewFrame")
		
		return
	elseif message:is("OpenFolder", "press") then
		if RE2IsActualFullScreenMode() and not gameInfo:isDataSet("minimizeWallpapers") then
			PushMinimizeConfirm2(1)
		else
			OpenMyDocumentsWallpapers()
		end
		return
	elseif message:is("InitResolutionButtons") then
		allResolutions = message:getData() == "true"
		if not allResolutions then
			GUI:getLayer("WallpapersPreview"):getWidget("W1280x800"):setVisible(false)
			GUI:getLayer("WallpapersPreview"):getWidget("W1440x900"):setVisible(false)
			GUI:getLayer("WallpapersPreview"):getWidget("W1920x1200"):setVisible(false)
			
			GUI:getLayer("WallpapersPreview"):getWidget("W1024x768"):setPosition(IPoint(301, 103))
			GUI:getLayer("WallpapersPreview"):getWidget("W1280x960"):setPosition(IPoint(443, 103))
			GUI:getLayer("WallpapersPreview"):getWidget("W1600x1200"):setPosition(IPoint(585, 103))
		else
			GUI:getLayer("WallpapersPreview"):getWidget("W1280x800"):setVisible(true)
			GUI:getLayer("WallpapersPreview"):getWidget("W1440x900"):setVisible(true)
			GUI:getLayer("WallpapersPreview"):getWidget("W1920x1200"):setVisible(true)

			GUI:getLayer("WallpapersPreview"):getWidget("W1024x768"):setPosition(IPoint(94, 103))
			GUI:getLayer("WallpapersPreview"):getWidget("W1280x960"):setPosition(IPoint(378, 103))
			GUI:getLayer("WallpapersPreview"):getWidget("W1600x1200"):setPosition(IPoint(662, 103))
		end
		CheckAlreadySavedWallpapers()
		return
	elseif message:is("W1024x768", "press") then
		resolution = "1024x768"
	elseif message:is("W1280x800", "press") then
		resolution = "1280x800"
	elseif message:is("W1280x960", "press") then
		resolution = "1280x960"
	elseif message:is("W1440x900", "press") then
		resolution = "1440x900"
	elseif message:is("W1600x1200", "press") then
		resolution = "1600x1200"
	elseif message:is("W1920x1200", "press") then
		resolution = "1920x1200"
	end

	if resolution ~= "" then
		textureId = GUI:getLayer("WallpapersPreview"):getWidget("Preview"):QueryState(Message("GetTexture")):getPublisher()
		PrintDebug("Resolution: " ..resolution.."; textureId = "..textureId.."\n")
		CopyWallpaperToMyDocuments(resolution, textureId)
		CheckAlreadySavedWallpapers()
	end
end

function OSTInit()
	GUI:getLayer("OST"):getWidget("SoundTrackList"):AcceptMessage(Message("Init"))
end

function OSTFunc(message)
	if message:is("Return", "press") then
		local param = VariableSet()
		param:setBool("NoFadeTracks", false)
		param:setString("Layer1", "PremiumVersion")
		param:setString("CrossHandler", "PremiumVersionCross")
		param:setString("AfterFadeHandler", "StartMusicInMainMenu")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("OpenFolder", "press") then
		if RE2IsActualFullScreenMode() and not gameInfo:isDataSet("minimizeOST") then
			PushMinimizeConfirm2(2)
		else
			OpenMyDocumentsOST()
		end
	elseif message:is("Layer", "Init") then
		GUI:getLayer("OST"):BroadcastMessage(Message("Screen", "activate", 1))
	elseif message:is("Layer", "Deinit") then
		GUI:getLayer("OST"):BroadcastMessage(Message("Screen", "activate", 0))
	else
		GUI:getLayer("OST"):getWidget("SoundTrackList"):AcceptMessage(message)
	end
end

function IsExtendedVersion()
	if gameInfo:getString("main_menu_type") == "collectors" or gameInfo:getString("main_menu_type") == "extended" then
		return true
	else
		return false
	end
end

function BonusFunc(message)
	if message:is("Return", "press") then
		GUI:getLayer("Bonus"):getWidget("Bonus"):AcceptMessage(Message("SaveScrollPosition"))
		local param = VariableSet()
		param:setBool("NoFadeTracks", true)
		if bonusLevelsFromMainMenu == true then
			param:setString("Layer1", "MainMenu")
			param:setString("AfterPushHandler", "MainMenuInitFunc")
			param:setBool("ResourceManagement", false)
		else
			param:setString("Layer1", "PremiumVersion")
			param:setString("CrossHandler", "PremiumVersionCross")
			param:setBool("ResourceManagement", false)
		end
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("StartGame") then
		GUI:getLayer("Bonus"):getWidget("Bonus"):AcceptMessage(Message("SaveScrollPosition"))
		local param = VariableSet()
		param:setString("Layer1", "Game")
		-- В коде сделана жесткая привязка к имени функции StartGameFunc. Меняешь сдесь, поменяй и в LayerLoadScree.cpp\struct GameLevelLoader
		param:setString("AfterPushHandler", "StartGameFunc")
		param:setString("LoadLayerEndHandler", "AfterFadeFunc")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("ProgressCrossFade", param))
	elseif message:is("ContinueSavedOrLevels") then
		FlyPushLayer("ContinueSaved", "ContinueSaved", 0)
		
		-- IslandName
		SetTextProperty("ContinueSavedIslandName", "ContinueSavedIslandName", gameInfo:getLevelIslandName(gameInfo:getLevel()))
		UpdateTextProperties("ContinueSavedIslandName")
		-- LevelNum
		SetTextProperty("ContinueSavedLevelNum", "LevelNum", gameInfo:getLevelAsString())
		UpdateTextProperties("ContinueSavedLevelNum")
	elseif message:is("StartMMTrack") then
		GUI:getLayer("LoadScreen"):getWidget("LoadScreen"):AcceptMessage(Message("StartMMTrack"))
	elseif message:is("Layer", "Init") then
		GUI:getLayer("Bonus"):BroadcastMessage(Message("Screen", "activate", 1))
		GUI:getLayer("Bonus"):getWidget("Bonus"):AcceptMessage(Message("ScrollToSavedPosition"))
	elseif message:is("Layer", "Deinit") then
		GUI:getLayer("Bonus"):BroadcastMessage(Message("Screen", "activate", 0))
	elseif message:is("LeftArrow", "down") then
		GUI:getLayer("Bonus"):getWidget("Bonus"):AcceptMessage(Message("ScrollLeft"))
	elseif message:is("RightArrow", "down") then
		GUI:getLayer("Bonus"):getWidget("Bonus"):AcceptMessage(Message("ScrollRight"))
	else
		GUI:getLayer("Bonus"):getWidget("Bonus"):AcceptMessage(message)
	end
end

function ExitCGuideCross()
	Screen:LoadSnapShot()
	Sound:SetPause(false, false)
	--GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("Continue"))
	GUI:getLayer("Game"):SetAllowDeinit(true)
end

function CGuideFunc(message)
	if message:is("Return", "press") and extrasFrom == 0 then
		local param = VariableSet()
		param:setString("Layer1", "PremiumVersion")
		param:setBool("NoFadeTracks", true)
		param:setString("CrossHandler", "PremiumVersionCross")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("Exit") then
		local param = VariableSet()
		param:setBool("NoFadeTracks", true)
		param:setString("CrossHandler", "ExitCGuideCross")
		kernel:addController(controlFactory:Create("CrossFade", param))
		
	elseif message:is("Layer", "Init") then
		GUI:getLayer("CGuide"):BroadcastMessage(Message("Screen", "activate", 1))
	elseif message:is("Layer", "Deinit") then
		GUI:getLayer("CGuide"):BroadcastMessage(Message("Screen", "activate", 0))
	else
		GUI:getLayer("CGuide"):getWidget("ACGuide"):AcceptMessage(message)
	end
end

function PushMinimizeConfirm(minimize)
	minimizeFrom = minimize
	FlyPushLayer("MinimizeConfirm", "MinimizeConfirm", 0)
end

minimizeConfirmOnScreen = false
function MinimizeConfirmFunc(message)
	if message:is("FlyerActive") then
		minimizeConfirmOnScreen = true
		GUI:getLayer("MinimizeConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		minimizeConfirmOnScreen = false
		GUI:getLayer("MinimizeConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif minimizeConfirmOnScreen and message:is("Yes", "press") then
		minimizeConfirmOnScreen = false
		if minimizeFrom == 1 then
			GUI:getLayer("MoreGames"):getWidget("MoreGames"):AcceptMessage(Message("Minimize"))
		elseif minimizeFrom == 3 then
			GUI:getLayer("PremiumVersion"):getWidget("Premium"):AcceptMessage(Message("Minimize"))			
		end
		FlyPushLayer("MinimizeConfirm", "MinimizeConfirm", 1)
	elseif minimizeConfirmOnScreen and message:is("No", "press") then
		minimizeConfirmOnScreen = false
		FlyPushLayer("MinimizeConfirm", "MinimizeConfirm", 1)
	else
		GUI:getLayer("MinimizeConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

function PushMinimizeConfirm2(minimize)
	minimizeFrom2 = minimize
	FlyPushLayer("MinimizeConfirm2", "MinimizeConfirm2", 0)
end

minimizeConfirm2OnScreen = false
function MinimizeConfirm2Func(message)
	if message:is("FlyerActive") then
		minimizeConfirm2OnScreen = true
		GUI:getLayer("MinimizeConfirm2"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		minimizeConfirm2OnScreen = false
		GUI:getLayer("MinimizeConfirm2"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif minimizeConfirm2OnScreen and message:is("Yes", "press") then
		minimizeConfirm2OnScreen = false
		-- Wallpapers
		if minimizeFrom2 == 1 then
			gameInfo:setBoolData("minimizeWallpapers", true)
			OpenMyDocumentsWallpapers()
		-- OST
		elseif minimizeFrom2 == 2 then
			gameInfo:setBoolData("minimizeOST", true)
			OpenMyDocumentsOST()
		end
		FlyPushLayer("MinimizeConfirm2", "MinimizeConfirm2", 1)
	elseif minimizeConfirm2OnScreen and message:is("No", "press") then
		minimizeConfirm2OnScreen = false
		FlyPushLayer("MinimizeConfirm2", "MinimizeConfirm2", 1)
	else
		GUI:getLayer("MinimizeConfirm2"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

function DemoConfirmAppear(message)
	FlyPushLayer("DemoConfirm", "DemoConfirm", 0)
end

demoConfirmOnScreen = false
function DemoConfirmFunc(message)
	if message:is("FlyerActive") then
		demoConfirmOnScreen = true
		GUI:getLayer("DemoConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		demoConfirmOnScreen = false
		GUI:getLayer("DemoConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif demoConfirmOnScreen and message:is("Yes", "press") then
		demoConfirmOnScreen = false
		CloseApplicationVideo()
	else
		GUI:getLayer("DemoConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

function BonusAllowConfirmAppear(message)
	FlyPushLayer("BonusAllowConfirm", "BonusAllowConfirm", 0)
end

bonusAllowConfirmOnScreen = false
function BonusAllowConfirmFunc(message)
	if message:is("FlyerActive") then
		bonusAllowConfirmOnScreen = true
		GUI:getLayer("BonusAllowConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		bonusAllowConfirmOnScreen = false
		GUI:getLayer("BonusAllowConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif bonusAllowConfirmOnScreen and message:is("Yes", "press") then
		bonusAllowConfirmOnScreen = false
		local param = VariableSet()
		param:setBool("NoFadeTracks", true)
		if IsExtendedVersion() then
			param:setString("Layer1", "MainMenu")
			param:setString("AfterPushHandler", "MainMenuInitFunc")
			--param:setString("CrossHandler", "StartMusicInMainMenu")
			param:setBool("ResourceManagement", false)
		else
			param:setString("Layer1", "PremiumVersion")
			param:setString("CrossHandler", "PremiumVersionCross")
			param:setBool("ResourceManagement", false)
		end
		kernel:addController(controlFactory:Create("CrossFade", param))
	else
		GUI:getLayer("BonusAllowConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	end
end

function StartTempleBonusLevelFunc(message)
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("StartLevel", "RE2_08_07_b"))
	tutorial:eventUpdate(Message("LayerPushed"))
end

-- Функция запуска бонусного уровня для Храма богов
function StartTempleBonusLevel()
	GUI:getLayer("Game"):SetAllowDeinit(false)
	local param = VariableSet()
	param:setString("Layer1", "Game")
	param:setString("CrossHandler", "StartTempleBonusLevelFunc")
	param:setBool("NoFadeTracks", true)
	param:setBool("ResourceManagement", false)
	kernel:addController(controlFactory:Create("CrossFade", param))
end

function StartTempleLevelFunc(message)
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("LoadSavedLevel", "TempleLevel"))
	tutorial:eventUpdate(Message("LayerPushed"))
end

function StartTempleLevelFunc2(message)
	local mes = Message("LoadSavedLevel", "TempleLevel")
	mes:getVariables():setBool("mode", true)
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(mes)
	tutorial:eventUpdate(Message("LayerPushed"))
end

-- Функция запуска уровня Храма богов после сбора всех рун
function StartTempleLevel(mode)
	GUI:getLayer("Game"):SetAllowDeinit(false)
	local param = VariableSet()
	param:setString("Layer1", "Game")
	param:setBool("NoFadeTracks", true)	
	if (mode) then
		param:setString("CrossHandler", "StartTempleLevelFunc2")
	else
		param:setString("CrossHandler", "StartTempleLevelFunc")
	end
	param:setBool("ResourceManagement", false)
	kernel:addController(controlFactory:Create("CrossFade", param))
end

function SplineEditorFunc(message)
	if (message:is("Return", "press")) then
		Screen:popLayer()
		messageManager:putMessage(Message("SaveKeys"))
	else
		GUI:getLayer("SplineEditor"):getWidget("SplineEditor"):AcceptMessage(message)
	end
end

-- Пропуск снежного боя
function PlyPushSkipSnowfightConfirm()
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("Pause"))
	FlyPushLayer("SkipSnowfightConfirm", "SkipSnowfightConfirm", 0)
end

skipSnowfightConfirmOnScreen = false
function SkipSnowfightConfirmFunc(message)
	if message:is("FlyerActive") then
		skipSnowfightConfirmOnScreen = true
		GUI:getLayer("SkipSnowfightConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		skipSnowfightConfirmOnScreen = false
		GUI:getLayer("SkipSnowfightConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif skipSnowfightConfirmOnScreen and message:is("Yes", "press") then
		skipSnowfightConfirmOnScreen = false
		FlyPushLayer("SkipSnowfightConfirm", "SkipSnowfightConfirm", 1)
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("Continue"))
		SkipSnowbattleFunc()
	elseif skipSnowfightConfirmOnScreen and message:is("No", "press") then
		skipSnowfightConfirmOnScreen = false
		FlyPushLayer("SkipSnowfightConfirm", "SkipSnowfightConfirm", 1)
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("Continue"))
	else
		GUI:getLayer("SkipSnowfightConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	end	
end

function SkipSnowbattleFunc()
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("SkipSnowbattle"))
end

function GMNotSkipFirstSnowbattle()
	if gameInfo:IsSnowbattleSkipped() then
		return false
	else
		return true
	end
end

-- Пропуск уровня с рунами
function PlyPushSkipBonusLevelConfirm()
	GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("Pause"))
	FlyPushLayer("SkipBonusLevelConfirm", "SkipBonusLevelConfirm", 0)
end

skipBonusLevelConfirmOnScreen = false
function SkipBonusLevelConfirmFunc(message)
	if message:is("FlyerActive") then
		skipBonusLevelConfirmOnScreen = true
		GUI:getLayer("SkipBonusLevelConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif message:is("FlyerDeactive") then
		skipBonusLevelConfirmOnScreen = false
		GUI:getLayer("SkipBonusLevelConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	elseif skipBonusLevelConfirmOnScreen and message:is("Yes", "press") then
		skipBonusLevelConfirmOnScreen = false
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("Continue"))
		StartTempleLevel(1)
	elseif skipBonusLevelConfirmOnScreen and message:is("No", "press") then
		skipBonusLevelConfirmOnScreen = false
		FlyPushLayer("SkipBonusLevelConfirm", "SkipBonusLevelConfirm", 1)
		GUI:getLayer("Game"):getWidget("Game"):AcceptMessage(Message("Continue"))
	else
		GUI:getLayer("SkipBonusLevelConfirm"):getWidget("KeyToMessage"):AcceptMessage(message)
	end	
end

function CheckLocaleForExtras()
	if gameInfo:getString("muiPrefix") == "en" then
		return true
	else
		return false
	end
end

function GameMapNewFunc(message)
	if (message:is("Return", "press")) then
		local param = VariableSet()
		param:setString("Layer1", "MainMenu")
		param:setString("AfterPushHandler", "MainMenuInitFunc")
		param:setString("CrossHandler", "StartMusicInMainMenu")
		param:setBool("ResourceManagement", false)
		kernel:addController(controlFactory:Create("CrossFade", param))
	else
		GUI:getLayer("GameMapNew"):getWidget("GameMapNew"):AcceptMessage(message)
	end
end