-- require "Dialog.lua"

-- Главное Меню

comeFromStart = false
sucFromGameMenuCopy = false
needShowDialog = true
gameLayer = "MainMenu"
helpFromGame = 0
sucFromGame = false
sucFromMap = false
optionsFromGame = false
predStage = -1
newStage = -1
helpFromGame = false
countryIntro = false
countryIntroLayerName = ""
countryIntroDialogName = ""
countryIntroReturnLayer = ""
finalCredits = false
fromMap = false;

-- показывает, что игровое меню вызвано в игровом экране
menuInGame = false

lastMusicVolume = 0
lastSoundVolume = 0
lastEnvironmentVolume = 0
lastFullscreen = false
lastRelaxedMode = false
lastCustomCursor = false
lastShowHints = false
fadeScreens = 0
savedFadeScreens = 0
  -- number of fade screens.
isFadePoppingLayer = false

function SaveOptions()
    
    -- Запоминаем опции
    lastMusicVolume = gameInfo:getMusicVolume()
    lastSoundVolume = gameInfo:getSoundVolume()
    lastEnvironmentVolume = gameInfo:getEnvironmentVolume()
    lastFullscreen = gameInfo:getFullscreen()
    lastRelaxedMode = gameInfo:getRelaxedMode()
    lastCustomCursor = gameInfo:getCustomCursor()
    lastShowHints = gameInfo:getHintsEnabled()

end

function RestoreOptions()

    -- Восстанавливаем опции
    Sound:SetSoundVolume(lastSoundVolume)
    Sound:SetMusicVolume(lastMusicVolume)
    Sound:SetEnvironmentVolume(lastEnvironmentVolume)

    gameInfo:setMusicVolume(lastMusicVolume)
    gameInfo:setSoundVolume(lastSoundVolume)
    gameInfo:setEnvironmentVolume(lastEnvironmentVolume)
    gameInfo:setCustomCursor(lastCustomCursor)
    gameInfo:setHintsEnabled(lastShowHints)
    gameInfo:setFullscreen(lastFullscreen)
    gameInfo:setRelaxedMode(lastRelaxedMode)

    -- Восстанавливаем значения на слоях
    local optionsName = "Options"

    local iBoolean = "0"
    if lastFullscreen then
        iBoolean = "1"
    end
    GUI:getLayer(optionsName):getWidget("Fullscreen"):AcceptMessage(Message("SetState", iBoolean))

	iBoolean = "0"
    if lastRelaxedMode then
        iBoolean = "1"
    end
    GUI:getLayer(optionsName):getWidget("RelaxedGameMode"):AcceptMessage(Message("SetState", iBoolean))

    iBoolean = "0"
    if lastShowHints then
        iBoolean = "1"
    end
    GUI:getLayer(optionsName):getWidget("ATips"):AcceptMessage(Message("SetState", iBoolean))
    
    iBoolean = "0"
    if lastCustomCursor then
        iBoolean = "1"
    end
    GUI:getLayer(optionsName):getWidget("CustomCursor"):AcceptMessage(Message("SetState", iBoolean))

    GUI:getLayer(optionsName):getWidget("Music"):AcceptMessage(Message("SetPos", tostring(lastMusicVolume)))
    GUI:getLayer(optionsName):getWidget("Sound"):AcceptMessage(Message("SetPos", tostring(lastSoundVolume)))
    GUI:getLayer(optionsName):getWidget("SEnvironment"):AcceptMessage(Message("SetPos", tostring(lastEnvironmentVolume)))

end

function SetOptions()

    -- Устанавливаем опции (для чтения используется слой optionsLayerName)
    local state = GUI:getLayer("Options"):getWidget("Music"):QueryState(Message("GetPos"))
    local musVolume = 0+state:getData()

    state = GUI:getLayer("Options"):getWidget("Sound"):QueryState(Message("GetPos"))
    local sndVolume = 0+state:getData()

    state = GUI:getLayer("Options"):getWidget("SEnvironment"):QueryState(Message("GetPos"))
    local envVolume = 0+state:getData()

    Sound:SetSoundVolume(sndVolume)
    Sound:SetMusicVolume(musVolume)
    Sound:SetEnvironmentVolume(envVolume)
    gameInfo:setMusicVolume(musVolume)
    gameInfo:setSoundVolume(sndVolume)
    gameInfo:setEnvironmentVolume(envVolume)
    
    state = GUI:getLayer("Options"):getWidget("Fullscreen"):QueryState(Message("GetState"))
    if state:getData() == "1" and gameInfo:getFullscreen() == false then
        gameInfo:setFullscreen(true)
        SetFullscreenMode()
    elseif state:getData() == "0" and gameInfo:getFullscreen() == true then
        gameInfo:setFullscreen(false)
        SetWindowedMode()
    end

	state = GUI:getLayer("Options"):getWidget("RelaxedGameMode"):QueryState(Message("GetState"))
    if state:getData() == "1" then
        gameInfo:setRelaxedMode(true)
    elseif state:getData() == "0" then
        gameInfo:setRelaxedMode(false)
    end
    
    state = GUI:getLayer("Options"):getWidget("CustomCursor"):QueryState(Message("GetState"))
    if state:getData() == "1" then
        SetCustomCursor(true)
        gameInfo:setCustomCursor(true)
    else
        SetCustomCursor(false)
        gameInfo:setCustomCursor(false)
    end
    
    state = GUI:getLayer("Options"):getWidget("ATips"):QueryState(Message("GetState"))
    if state:getData() == "1" then
        gameInfo:setHintsEnabled(true)
    else
        gameInfo:setHintsEnabled(false)
    end


    -- Устанавливаем значения на слоях
    local optionsName = optionsLayerName

    GUI:getLayer("Options"):getWidget("Music"):AcceptMessage(Message("SetPos", tostring(musVolume)))
    GUI:getLayer("Options"):getWidget("Sound"):AcceptMessage(Message("SetPos", tostring(sndVolume)))
    GUI:getLayer("Options"):getWidget("SEnvironment"):AcceptMessage(Message("SetPos", tostring(envVolume)))

    local iBoolean = "0"
    if gameInfo:getFullscreen() then
        iBoolean = "1"
    end
    GUI:getLayer("Options"):getWidget("Fullscreen"):AcceptMessage(Message("SetState", iBoolean))

    iBoolean = "0"
    if gameInfo:getHintsEnabled() then
        iBoolean = "1"
    end
    GUI:getLayer("Options"):getWidget("ATips"):AcceptMessage(Message("SetState", iBoolean))
    
    iBoolean = "0"
    if gameInfo:getCustomCursor() then
        iBoolean = "1"
    end
    GUI:getLayer("Options"):getWidget("CustomCursor"):AcceptMessage(Message("SetState", iBoolean))

end

function StartGame()

    Sound:FadeOutAllTracks(1.0)
--	gameInfo:setLives(3)

--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("InitLevelView2") )
          
    local param = VariableSet()
    if (gameLayer == "Map") then
        param:setString("CrossHandler", "FromMapToGame")
    elseif (gameLayer == "MainMenu") then
        param:setString("CrossHandler", "FromMainMenuToGame")
    elseif (gameLayer == "Credits") then
        param:setString("CrossHandler", "FromCreditsToGame")	
    else
        param:setString("CrossHandler", "RestartMatch3")
    end		
    UpdateGameLayerName()
    param:setString("Layer1", gameLayer)
    kernel:addController(controlFactory:Create("CrossFade", param))
    
    --	if (gameInfo:getStage() == 2) and (gameInfo:getLevel() == 1) and (needShowDialog) then
--		GUI:getLayer("StageLayer_2"):getWidget("GameField"):AcceptMessage( Message("InitLevelView2") )
--		param:setString("Layer1", "StageLayer_1")
--		GUI:getLayer("StageLayer_1"):getWidget("GameField"):AcceptMessage( Message("DisableRain") )
--	else
--		GUI:getLayer("StageLayer_1"):getWidget("GameField"):AcceptMessage( Message("EnableRain") )
--		param:setString("Layer1", gameLayer)
--	end

--	param:setString("EndHandler", "InitGameField")
--	param:setString("CrossHandler", "InitGameField2")
    
--	param:setString("Layer1", gameLayer)	
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("InitGameField"))

end

function RestartMatch3()
	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("Reinit") )
	--GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("Go") )
end

function InitGameField2()
    Sound:FadeOutAllTracks(1.0)
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("HideShowLevelList") )
--	UploadResourceGroup("Game")
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("InitLevelView") )
    
    if (gameInfo:getStage() == 2) and (gameInfo:getLevel() == 1) and (needShowDialog) then
        GUI:getLayer("StageLayer_1"):getWidget("Background"):AcceptMessage( Message("SoundOn") )
    else
        GUI:getLayer(gameLayer):getWidget("Background"):AcceptMessage( Message("SoundOn") )
    
    end

    GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("Release") )
--	GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("InitBagView") )
end

function InitGameField()
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("InitLevelView") )
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("Start") )
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("SetActive", 1) )
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("RunStartAW", 1) )

--	MessageManager:putMessage(Message("ShowStartLevelDialog"))

--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("FillLevelList", 1) )

    if (needShowDialog) then
        GUI:getLayer("StageLayer_1"):getWidget("GameField"):AcceptMessage(Message("StartLevelMusicBeforeDialog"))
    else
        GUI:getLayer("StageLayer_1"):getWidget("GameField"):AcceptMessage(Message("StartLevelMusic"))
    end
end

function ViewBackgroundCross()

    local name = ""
    if (predStage == 1) then
        name = "StageLayer_1"
    elseif (predStage == 2) then
        name = "StageLayer_2"
    elseif (predStage == 3) then
        name = "StageLayer_3"
    elseif (predStage == 4) then
        name = "StageLayer_4"
    elseif (predStage == 5) then
        name = "StageLayer_5"
    elseif (predStage == 6) then
        name = "StageLayer_6"
    elseif (predStage == 7) then
        name = "StageLayer_7"
    end
    
    ReleaseResourceGroup(name)
    
    if (newStage == 1) then
        name = "StageLayer_1"
        Sound:FadeInTrack("England", 2.0, true)
    elseif (newStage == 2) then
        name = "StageLayer_2"
        Sound:FadeInTrack("France", 2.0, true)
    elseif (newStage == 3) then
        name = "StageLayer_3"
        Sound:FadeInTrack("Egypt", 2.0, true)
    elseif (newStage == 4) then
        name = "StageLayer_4"
        Sound:FadeInTrack("India", 2.0, true)
    elseif (newStage == 5) then
        name = "StageLayer_5"
        Sound:FadeInTrack("China", 2.0, true)
    elseif (newStage == 6) then
        name = "StageLayer_6"
        Sound:FadeInTrack("Japan", 2.0, true)
    elseif (newStage == 7) then
        name = "StageLayer_7"
        Sound:FadeInTrack("USA", 2.0, true)
    end
    
--	UploadResourceGroup("Game")
    UploadResourceGroup(name)
    
    predStage = newStage
end

function ViewBackground(stage)
    Sound:FadeOutAllTracks(1.0)

    newStage = stage

    local name = ""
    if (stage == 1) then
        name = "TestLayer_1"
    elseif (stage == 2) then
        name = "TestLayer_2"
    elseif (stage == 3) then
        name = "TestLayer_3"
    elseif (stage == 4) then
        name = "TestLayer_4"
    elseif (stage == 5) then
        name = "TestLayer_5"
    elseif (stage == 6) then
        name = "TestLayer_6"
    elseif (stage == 7) then
        name = "TestLayer_7"
    end
    
    GUI:getLayer(name):getWidget("1_BG"):AcceptMessage( Message("SetTimeEnabled", 1) )
    
    local param = VariableSet()
    param:setString("Layer1", name)
    param:setString("CrossHandler", "ViewBackgroundCross")

    kernel:addController(controlFactory:Create("CrossFade", param))	
end

function RunNewLevel()
    resetSucFromGame()
    Sound:FadeOutAllTracks(1.0)

    UpdateGameLayerName()
    GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("InitBagView") )
    StartGame()
end

function UploadBagRes()
    UploadResourceGroup("BagRes")
    UploadResourceGroup("SmallArts")
    GUI:getLayer(gameLayer):getWidget("Background"):AcceptMessage( Message("SoundOff") )
end

function UploadBagResAfterDialog()
    UploadResourceGroup("BagRes")
    UploadResourceGroup("SmallArts")
    GUI:getLayer(gameLayer):getWidget("Background"):AcceptMessage( Message("SoundOff") )
    GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("InitNoteView2") )
end

function RunDialog(dlg)
    Screen:pushLayer( GUI:getLayer("Dialog") )
    GUI:getLayer("Dialog"):getWidget("Dialog"):AcceptMessage( Message("Run", dlg) )
end

function AddNewAbzac()
    GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("AddAbzacAfterLevel") )
end

function StartLondonMusic()
    Sound:FadeInTrack("England2", 2.0, true)
end

function ShowHeart()
    GUI:getLayer("Dialog"):getWidget("Dialog"):AcceptMessage( Message("ShowHeart") )
end

function ShowFeerverk()
    GUI:getLayer("Dialog"):getWidget("Dialog"):AcceptMessage( Message("ShowFeerverk") )
end

function HideFeerverk()
    GUI:getLayer("Dialog"):getWidget("Dialog"):AcceptMessage( Message("HideFeerverk") )
end

function ShowTheEnd()
    GUI:getLayer("Dialog"):getWidget("Dialog"):AcceptMessage( Message("ShowTheEnd") )
end

function StartFinalCredits()
    finalCredits = true
    Screen:pushLayer( GUI:getLayer("FinalCredits") )
    GUI:getLayer("FinalCredits"):getWidget("Credits"):AcceptMessage(Message("Reset", "4.0"))
end

function StartAw()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("RunStartAW", 1) )
end

function MGFunc(message)
    GUI:getLayer("MagicGame"):getWidget("TestWidget"):AcceptMessage( message )
end

function IntroFunc(message)
    if (message:is("SetMenuLayer")) then
        Screen:Clear()
        Screen:pushLayer( GUI:getLayer("MainMenu") )
        Screen:pushLayer( GUI:getLayer("JuleBook") )

        --ReleaseResourceGroup("Intro")
        GUI:getLayer("JuleBook"):getWidget("JuleBook"):AcceptMessage( Message("Release") )
        UploadResourceGroup("MainMenu")
        GUI:getLayer("MainMenu"):getWidget("MainMenu"):AcceptMessage( Message("ResetTimer") )
--		Sound:FadeInTrack("Menu", 2.0, true)
    elseif (message:is("PopLayer")) then
        Screen:popLayer()
        if (gameInfo:getNumberOfPlayers() == 0) then
            CreateFirstPlayer()
        end
    elseif (message:is("CrossToMenu")) then
        local param = VariableSet()
        param:setString("Layer1", "MainMenu");
        param:setString("CrossHandler", "FromIntroToMenu")
        kernel:addController(controlFactory:Create("CrossFade", param))	
    end
end

function HelpFunc(message)
    if (message:is("Back", "press")) then
        FadePopLayer("Help", "Help", "ReleaseHelp");
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("Back", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Back", "press"))
    else
        GUI:getLayer("Help"):getWidget("Help"):AcceptMessage( message )
    end
end

function ReleaseHelp()
    ReleaseResourceGroup("Help");
    GUI:getLayer("Help"):getWidget("Help"):AcceptMessage( Message("Release") )
end

function UpdateGameLayerName()
    stg = gameInfo:getStage()
    if (stg == 1) then
        gameLayer = "StageLayer_1"
    elseif (stg == 2) then
        gameLayer = "StageLayer_2"
    elseif (stg == 3) then
        gameLayer = "StageLayer_3"
    elseif (stg == 4) then
        gameLayer = "StageLayer_4"
    elseif (stg == 5) then
        gameLayer = "StageLayer_5"
    elseif (stg == 6) then
        gameLayer = "StageLayer_6"
    elseif (stg == 7) then
        if (gameInfo:getLevel() < 14) then
            gameLayer = "StageLayer_7"
        else
            gameLayer = "StageLayer_1"
        end
    end
end

function StartLevelMusic()
    
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("StartLevelMusic"))

--	stg = gameInfo:getStage()
--	if (stg == 1) then
--		Sound:FadeInTrack("England", 2.0, true)
--	elseif (stg == 2) then
--		Sound:FadeInTrack("France", 2.0, true)
--	elseif (stg == 3) then
--		Sound:FadeInTrack("Egypt", 2.0, true)
--	elseif (stg == 4) then
--		Sound:FadeInTrack("India", 2.0, true)
--	elseif (stg == 5) then
--		Sound:FadeInTrack("China", 2.0, true)
--	elseif (stg == 6) then
--		Sound:FadeInTrack("Japan", 2.0, true)
--	elseif (stg == 7) then
--		Sound:FadeInTrack("USA", 2.0, true)
--	end
end

function FromAltarToMap()
    gameInfo:ClearSavedData()
    Sound:FadeInTrackContinue("Map", 2.0, true)
    GUI:getLayer("PrepareAltarEffects"):getWidget("PrepareAltarEffects"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("Altar")
    UploadResourceGroup("Map")	
    UploadResourceGroup("Fon")
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetFlag") )
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))
    
--	if (gameInfo:getStage() == 1) then
--		GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetFlag") )
--		GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))	
--	else
--		GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetMoveFlag") ) 
--		GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetFlag") )	
--		GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))
--		GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("MoveFlag") )	
--	end
    gameLayer = "Map"
end

function StoreSSOptions()
    gameInfo:setNumShowSS(gameInfo:getStage())
    gameInfo:CopySSOptionsToBuff()
end

function HiScoresFunc(message)
    if message:is("Ok", "press") then
        GUI:getLayer("HiScores"):getWidget("HiScores"):AcceptMessage( Message("Finish") )
        FadePopLayer("HiScores", "HiScores", "HiScoresClear");
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    end	
end

function HiScoresClear()
    GUI:getLayer("HiScores"):getWidget("HiScores"):AcceptMessage( Message("Clear") )
end

function ToMainMenuCross()
    Sound:FadeOutAllTracks(1.0)
    Sound:FadeInTrackContinue("MainMenu", 2.0, true)
end

function ContinueGame()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("SetActive", 1) )
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("Continue") )
end

function GameOverEndHandler()
    --GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("DestroyCountryProgress") )
    --gameInfo:setLives(3)
    --gameInfo:setScore(0)
    --gameInfo:setUID()
    --gameInfo:KillProgress()
end

function LoseLifeFunc(message)
    if message:is("LoseLife", "press") then	
		Sound:FadeOutAllTracks(1.0)
        local param = VariableSet()
        param:setString("Layer1", gameLayer);
        param:setString("CrossHandler", "RestartMatch3")
        --param:setString("EndHandler", "AfterLoseLife")
        param:setString("FadeName", "Fade")
        kernel:addController(controlFactory:Create("OldCrossFade", param))
        --gameInfo:FadeInGameTrack()
    end
end

function GameOverFunc(message)
    if message:is("Ok", "press") then
        gameInfo:KillProgress()
        Sound:FadeOutAllTracks(2.0);
        Sound:FadeInTrackContinue("Map", 3.0, true);
        local param = VariableSet()
        param:setString("Layer1", "Map");
        --param:setString("EndHandler", "MapEndHandler")
        param:setString("CrossHandler", "GameOverCrossHandler")
        kernel:addController(controlFactory:Create("CrossFade", param))
    end
end

function GameOverCrossHandler()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("Game")
    ReleaseResourceGroup("Match3")
    ReleaseResourceGroup(gameLayer)
    UploadResourceGroup("Map")
    gameInfo:setLevel(1)
    gameInfo:setNumber(1)
    gameInfo:setLives(3)
    gameInfo:setUID()
    gameInfo:setScore(0)
    gameInfo:setBonusCount(0, gameInfo:getBonusBeforeStageCount(0))
    gameInfo:setBonusCount(1, gameInfo:getBonusBeforeStageCount(1))
    gameInfo:setBonusCount(2, gameInfo:getBonusBeforeStageCount(2))
    gameInfo:setBonusCount(3, gameInfo:getBonusBeforeStageCount(3))
    gameInfo:ChangeDifficultyLevel(100)
    
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("SetFlag"))
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))
    gameInfo:SetCurrentGameType("Map")
    gameLayer = "Map"
end

function CrossLoseLife()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("Reset") )
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("InitLevel") )
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("StartLevelMusic") )
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("LoadLevel") )
end

function AfterLoseLife()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("RunStartAW") )
end

function FromMainMenuToHistory()
--	ReleaseResourceGroup("MainMenu")
--	ReleaseResourceGroup("Altar")		
--	ReleaseResourceGroup("Fon")
    UploadResourceGroup("MultCountry")
    GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage(Message("InitHistory"))
    Sound:FadeOutAllTracks(1.0)
    Sound:FadeInTrack("Map", 2.0, true)
end

function FromHistoryToMainMenu()
    GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("MultCountry")
    ReleaseResourceGroup("Mult")
    Sound:FadeOutAllTracks(1.0)
    Sound:FadeInTrackContinue("MainMenu", 2.0, true)
--	UploadResourceGroup("MainMenu")
--	UploadResourceGroup("Altar")
--	UploadResourceGroup("Fon")	
end

function FromMainMenuToMoreGames()
--	ReleaseResourceGroup("MainMenu")
--	ReleaseResourceGroup("Altar")		
--	ReleaseResourceGroup("Fon")
    UploadResourceGroup("MoreGames")
    GUI:getLayer("MoreGames"):getWidget("MoreGames"):AcceptMessage(Message("InitMoreGames"))
    Sound:FadeOutAllTracks(1.0)
    Sound:FadeInTrack("Map", 2.0, true)
end

function FromMoreGamesToMainMenu()
    GUI:getLayer("MoreGames"):getWidget("MoreGames"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("MoreGames")
    Sound:FadeOutAllTracks(1.0)
    Sound:FadeInTrackContinue("MainMenu", 2.0, true)
--	UploadResourceGroup("MainMenu")
--	UploadResourceGroup("Altar")
--	UploadResourceGroup("Fon")	
end

function FromGameToMainMenu()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("Game")
    --UploadResourceGroup("MainMenu")
    UploadResourceGroup("Altar")
    UploadResourceGroup("ISpy")
    gameInfo:WriteResultToHiScores()
    gameInfo:Save()
    gameLayer = "MainMenu"

    Sound:FadeInTrackContinue("MainMenu", 2.0, true)
end

function ExitFromGame()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("SaveGame"))
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("Game")
    ReleaseResourceGroup(gameLayer)
    ReleaseResourceGroup("Match3")
    UploadResourceGroup("MainMenu")
    UploadResourceGroup("Altar")
    gameInfo:WriteResultToHiScores()
    gameInfo:Save()
    gameLayer = "MainMenu"

    Sound:FadeInTrackContinue("MainMenu", 2.0, true)
end

function ExitFromISpy()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("Game")
    ReleaseResourceGroup("ISpy")
    UploadResourceGroup("MainMenu")
    UploadResourceGroup("Altar")
    UploadResourceGroup("Fon")
    gameInfo:WriteResultToHiScores()
    gameInfo:Save()
    gameLayer = "MainMenu"

    Sound:FadeInTrackContinue("MainMenu", 2.0, true)
end
    

function FromPrepareLevelToMainMenu()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("Game")
    ReleaseResourceGroup("ISpy")
    UploadResourceGroup("Fon")
    UploadResourceGroup("MainMenu")
    gameLayer = "MainMenu"

    Sound:FadeInTrackContinue("MainMenu", 2.0, true)
end
    

function FromISpyToMainMenu()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("Game")
    ReleaseResourceGroup("ISpy")
    --UploadResourceGroup("Fon")
    UploadResourceGroup("Altar")
    gameInfo:WriteResultToHiScores()
    gameInfo:Save()
    gameLayer = "PrepareAltarEffects"
    if (gameInfo:getStage() == 1) then
        UploadResourceGroup("Credits")
    end
    Sound:FadeInTrack("Altar", 2.0, true)
end

function FromISpyToMap()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("Game")
    ReleaseResourceGroup("ISpy")
    UploadResourceGroup("Fon")
    UploadResourceGroup("Map")
    gameInfo:WriteResultToHiScores()
    gameInfo:Save()
    gameLayer = "Map"
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetMoveFlag") ) 
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetFlag") )	
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("MoveFlag") )
    --GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("NewCycle"))	
    Sound:FadeInTrackContinue("Map", 2.0, true)
end

function GameWinFromISpy()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("Game")
    ReleaseResourceGroup("ISpy")
    UploadResourceGroup("Fon")
    UploadResourceGroup("Map")
    gameInfo:WriteResultToHiScores()
    gameInfo:Save()
    gameLayer = "Map"
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetMoveFlag") ) 
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetFlag") )	
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("MoveFlag") )
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("NewCycle"))	
    Sound:FadeInTrackContinue("Map", 2.0, true)
end

function FromMapToMainMenu()
    ReleaseResourceGroup("Map")
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("ReleaseResources"))
    UploadResourceGroup("MainMenu")
    UploadResourceGroup("Altar")
    gameLayer = "MainMenu"

    Sound:FadeInTrackContinue("MainMenu", 2.0, true)
end

function FromMapToAltar()
    ReleaseResourceGroup("Map")
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("ReleaseResources"))
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("PressAltar"))
    ReleaseResourceGroup("Fon")
    UploadResourceGroup("Altar")
    gameLayer = "PrepareAltarEffects"

    Sound:FadeInTrack("Altar", 2.0, true)
end

function FromMainMenuToAltar()
    ReleaseResourceGroup("MainMenu")
    ReleaseResourceGroup("Fon")
    UploadResourceGroup("Altar")
    gameLayer = "PrepareAltarEffects"

    Sound:FadeInTrack("Altar", 2.0, true)
end

function FromMapToGame()
    ReleaseResourceGroup("Map")
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("ReleaseResources"))
    UploadResourceGroup("Game")
    UploadResourceGroup("Match3")
    UpdateGameLayerName()
    UploadResourceGroup(gameLayer)
    InitLevel()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("LoadLevel"))
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("RunStartAW") )

    --gameInfo:FadeInGameTrack()
end

function FromMainMenuToGame()
    ReleaseResourceGroup("MainMenu")
    ReleaseResourceGroup("Altar")
    UploadResourceGroup("Game")
    UploadResourceGroup("Match3")
    UpdateGameLayerName()
    UploadResourceGroup(gameLayer)
    InitLevel()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("LoadGame"))
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("LoadLevel"))
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("RunStartAW") )

    gameInfo:FadeInGameTrack()
end

function FromCreditsToGame()
    ReleaseResourceGroup("Credits")
    ReleaseResourceGroup("StageLayer_1")
    UploadResourceGroup("Game")
    UploadResourceGroup("Match3")
    UpdateGameLayerName()
    UploadResourceGroup(gameLayer)
    InitLevel()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("LoadGame"))
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("LoadLevel"))
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("RunStartAW") )

    gameInfo:FadeInGameTrack()
end

function UploadMatch3()
    UploadResourceGroup("Match3")
    UploadResourceGroup("Fon")
    UpdateGameLayerName()
    UploadResourceGroup(gameLayer)
    InitLevel()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("LoadLevel"))
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("RunStartAW") )

--	gameInfo:FadeInGameTrack()
end

function FromMapToISpy()
    ReleaseResourceGroup("Map")
    ReleaseResourceGroup("Fon")
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("ReleaseResources"))
    
    UploadResourceGroup("Game")
    UploadResourceGroup("ISpy")
    InitLevel()

    --gameInfo:FadeInGameTrack()
end

function FromMainMenuToISpy()
    ReleaseResourceGroup("MainMenu")
    ReleaseResourceGroup("Altar")
    ReleaseResourceGroup("Fon")	
    UploadResourceGroup("Game")
    UploadResourceGroup("ISpy")
    InitLevel()

    gameInfo:FadeInGameTrack()
end

function FromMainMenuToMultCountry()
    ReleaseResourceGroup("MainMenu")	
    ReleaseResourceGroup("Altar")
    ReleaseResourceGroup("ISpy")
    ReleaseResourceGroup("Game")
    UploadResourceGroup("MultCountry")	
    GUI:getLayer("PrepareAltarEffects"):getWidget("PrepareAltarEffects"):AcceptMessage( Message("ReleaseResources") )
    if GUI:getLayer(gameLayer):IsWidgetExists("GameField") then
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
    end
    GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage( Message("InitMult") )	
    gameInfo:SetCurrentGameType("Map")
    
    Sound:FadeOutTrack("Altar", 2.0)
    --if (gameInfo:getStage() == 1) then
    --    Sound:FadeInTrack("RomeMusic", 2.0, true)
    --else	
    --    Sound:FadeInTrack("Map", 2.0, true)
    --end
	Sound:FadeInTrack("CutscenesBack", 2.0, true)
end

function FromMultCountryToMap()
    gameInfo:ClearSavedData()
    ReleaseResourceGroup("MultCountry")
    UploadResourceGroup("Map")	
    UploadResourceGroup("Fon")
    GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage( Message("ReleaseResources") )
    if (gameInfo:getStage() == 1) then
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetFlag") )
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))
    else
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetMoveFlag") ) 
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetFlag") )	
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("MoveFlag") )
    end
    gameLayer = "Map"
    
    --if (gameInfo:getStage() == 1) then
    --    Sound:FadeOutTrack("RomeMusic", 1.0)
    --    Sound:FadeInTrack("Map", 2.0, true)
    --else
    --    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("StartMusicController") )
    --end

	Sound:FadeOutTrack("CutscenesBack", 1.0)
	Sound:FadeInTrack("Map", 1.0, true)
end

function FromGameToMap()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))	
    if ((gameLayer == "ISpyFieldControl") or (gameLayer == "ISpyBonusField")) then
        ReleaseResourceGroup("ISpy")
        ReleaseResourceGroup("Game")		
    elseif (gameLayer == "PrepareAltarLevel") then
        gameInfo:setStage(1)
        ReleaseResourceGroup("Altar")
        ReleaseResourceGroup("ISpy")
        ReleaseResourceGroup("Game")		
    else
        ReleaseResourceGroup(gameLayer)
        ReleaseResourceGroup("Game")
        ReleaseResourceGroup("Match3")
    end
    UploadResourceGroup("Fon")
    UploadResourceGroup("Map")	
    gameLayer = "Map"	

    Sound:FadeInTrackContinue("Map", 2.0, true)
end

function StartIntroMult()
    UploadResourceGroup("MultCountry")	
    UploadResourceGroup("Mult")
    --Sound:FadeInTrack("Map", 2.0, true)
    GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage( Message("InitMult") )	
    GUI:getLayer("MainMenuFon"):getWidget("MainMenuFon"):AcceptMessage(Message("StartMult"))
end

function MyMainMenuFunc(message)
    if message:is("start", "press") then
        if (gameInfo:getStage() ~= 0) then		
            GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("SetFlag"))			
        end
        if (gameInfo:GetCurrentGameType() == "NewGame") then
            --GUI:getLayer("MyMainMenu"):getWidget("MyMainMenu"):AcceptMessage(Message("HideToolTip"))
            Sound:FadeOutAllTracks(1.0)
            local param = VariableSet()
            param:setString("Layer1", "MainMenuFon")
            param:setString("Layer2", "MultCountry")
            param:setString("CrossHandler", "StartIntroMult")
            kernel:addController(controlFactory:Create("CrossFade", param))
            comeFromStart = true
        else
           -- FadePushLayer("StartGamePanel", "Panel");
			Sound:FadeOutAllTracks(1.0)
			local param = VariableSet()
			if (gameInfo:getStage() == 0) then
				comeFromStart = false
				local param = VariableSet()
				gameLayer = "PrepareAltarLevel"
				param:setString("Layer1", "PrepareAltarLevel")
				param:setString("CrossHandler", "FromMultToAltar")
				kernel:addController(controlFactory:Create("CrossFade", param))
				comeFromStart = true
			elseif (gameInfo:getTypeLevel() == "TYPE_MATCH3" and gameInfo:GetCurrentGameType() == "Match3") then
				StartGame()			
			elseif (gameInfo:getTypeLevel() == "TYPE_ISPY" and gameInfo:GetCurrentGameType() == "ISpy") then
				gameLayer = "ISpyFieldControl"
				param:setString("Layer1", gameLayer);
				param:setString("CrossHandler", "FromMainMenuToISpy")
				kernel:addController(controlFactory:Create("CrossFade", param))    
			elseif (gameInfo:getTypeLevel() == "TYPE_BONUS" and gameInfo:GetCurrentGameType() == "Bonus") then 
				gameLayer = "ISpyBonusField"
				param:setString("Layer1", gameLayer);
				param:setString("CrossHandler", "FromMainMenuToISpy")
				kernel:addController(controlFactory:Create("CrossFade", param))    
			elseif (gameInfo:GetCurrentGameType() == "Map") then
				param:setString("Layer1", "Map")
	--			param:setString("CrossHandler", "SetFlag")
				param:setString("CrossHandler", "SetFlagAndStartMapMusic")
				kernel:addController(controlFactory:Create("CrossFade", param))	
				gameLayer = "Map"
			end
        end

    elseif message:is("profileButton", "press") then
        local state = GUI:getLayer("Profiles"):getWidget("Names"):AcceptMessage(Message("SetNeedHideHint", 0))
        GUI:getLayer("Profiles"):getWidget("Names"):AcceptMessage(Message("Set", gameInfo:getName()))
        FadePushLayer("Profiles", "Panel")
        
    elseif message:is("options", "press") then
        optionsLayerName = "Options"
        UploadResourceGroup("Options")
        SaveOptions()
        RestoreOptions()
        
        local optionWidget = GUI:getLayer("Options"):getWidget("Options")
        optionWidget:setPosition(Point(85, 500))
        optionWidget:setInitPosition()
        
        FadePushLayer("Options", "Options", "");
        optionsFromGame = false
    elseif message:is("history", "press") then
        local param = VariableSet()
        param:setString("Layer1", "MultCountry")
        param:setString("CrossHandler", "FromMainMenuToHistory")
        kernel:addController(controlFactory:Create("CrossFade", param))
    elseif message:is("altar", "press") then
        if (gameInfo:getStage() ~= 0) then
            Sound:PlaySample("GoToAltar");
            Sound:FadeOutTrack("MainMenu", 2.0);
            --Sound:FadeInTrack("Altar", 8.0, true);
            param = VariableSet()
            param:setString("Layer1", "MyMainMenu")
            param:setString("NeedPopLayer", "true")
            kernel:addController(controlFactory:Create("MenuPopSlider", param))
        end
    elseif message:is("hightscores", "press") then
        GUI:getLayer("HiScores"):getWidget("HiScores"):AcceptMessage( Message("Start") )
        FadePushLayer("HiScores", "HiScores");
    elseif message:is("help", "press") then
        GUI:getLayer("Help"):getWidget("Help"):AcceptMessage( Message("Init") )
        GUI:getLayer("Help"):getWidget("Help"):AcceptMessage( Message("Set1") )
        UploadResourceGroup("Help");
        --UploadResourceGroup("Match3");
        helpFromGame = false;
        FadePushLayer("Help", "Help")
    elseif message:is("screensavers", "press") then
        gameInfo:SetSSOptionsToLayer()
        FadePushLayer("SSOptions", "SSOptions", "StoreSSOptions");
    elseif message:is("exit", "press") then
        --if (gameInfo.getStage() == 1 and gameInfo.getCycle < 1) then
        if (gameInfo:isScreensaverEnabled()) then
            FadePushLayer("ExitConfirm", "Panel")
        else 
            FadePushLayer("ExitConfirmWithSS", "Panel")
        end
        --CloseApplication();
    elseif message:is("Menu_altar", "press") then
    
        Sound:FadeOutAllTracks(1.0)

        menuInGame = false
        local param = VariableSet()
        param:setString("Layer1", "PrepareAltarEffects");
        param:setString("Location", "Init");
        param:setString("CrossHandler", "FromMainMenuToAltar")
        kernel:addController(controlFactory:Create("CrossFade", param))
        gameLayer = "PrepareAltarEffects"
    elseif message:is("moreGames", "press") then
        local param = VariableSet()
        param:setString("Layer1", "MoreGames")
        param:setString("CrossHandler", "FromMainMenuToMoreGames")
        kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("baner", "press") then
		GUI:getLayer("MyMainMenu"):getWidget("MyMainMenu"):AcceptMessage(Message("BanerMainMenu"))
    end
end

function GameWinToMap()
    gameInfo:ClearSavedData()
    GUI:getLayer("PrepareAltarEffects"):getWidget("PrepareAltarEffects"):AcceptMessage(Message("ReleaseResources"))
    ReleaseResourceGroup("Altar")
    UploadResourceGroup("Map")	
    UploadResourceGroup("Fon")
    ReleaseResourceGroup("Credits")
    
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetMoveFlag") ) 
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetFlag") )	
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("MoveFlag") )
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("NewCycle"))	
    gameLayer = "Map"	
    Sound:FadeInTrackContinue("Map", 2.0, true)
end

function MainMenuFonFunc(message)
    if message:is("menu", "press") then
        Sound:PlaySample("GoFromAltar");
        Sound:FadeOutTrack("Altar", 2.0);
        --Sound:FadeInTrackContinue("MainMenu", 8.0, true);
        local param = VariableSet()
        param:setString("Layer1", "MainMenuFon")
        param:setString("NeedPopLayer", "false")
        kernel:addController(controlFactory:Create("MenuPopSlider", param))
    elseif  message:is("map", "press") then
        Sound:FadeOutAllTracks(1.0)		
        local param = VariableSet()
        
		local state = GUI:getLayer("PrepareAltarEffects"):getWidget("PrepareAltarEffects"):QueryState(Message("GetHideScroll"))
		if state:getData() == "0" then
			if (fromMap) then
				param:setString("Layer1", "Map")
				param:setString("CrossHandler", "FromAltarToMap")
				kernel:addController(controlFactory:Create("CrossFade", param))
			else
				GUI:getLayer("PrepareAltarEffects"):getWidget("PrepareAltarEffects"):AcceptMessage(Message("HideTrainWindowOnMap"))
				param:setString("Layer1", "MultCountry")
				param:setString("CrossHandler", "FromMainMenuToMultCountry")
				kernel:addController(controlFactory:Create("OldCrossFade", param))
			end
		else
			param:setString("Layer1", "Map")
			param:setString("CrossHandler", "GameWinToMap")
			kernel:addController(controlFactory:Create("OldCrossFade", param))
		end
        fromMap = false;
	elseif  message:is("skipMegaScroll", "press") or message:is("SkipMegaScroll") then
	--elseif message:is("GameWin") then
		GUI:getLayer("PrepareAltarEffects"):getWidget("PrepareAltarEffects"):AcceptMessage(Message("SkipMegaScroll"))
        --Sound:FadeOutAllTracks(1.0)		
        --local param = VariableSet()
        --param:setString("Layer1", "Map")
        --param:setString("CrossHandler", "GameWinToMap")
        --kernel:addController(controlFactory:Create("OldCrossFade", param))
        --fromMap = false;
    elseif message:is("Exit") then
        Sound:FadeOutAllTracks(1.0)		
        local param = VariableSet()
        param:setString("Layer1", "Map")
        param:setString("CrossHandler", "GameWinToMap")
        kernel:addController(controlFactory:Create("OldCrossFade", param))
        fromMap = false;
    end
end

function MoreGamesFunc(message)
	if message:is("Menu", "press") then
        GUI:getLayer("MyMainMenu"):getWidget("MyMainMenu"):AcceptMessage(Message("InitMainMenu"))
        local param = VariableSet()
        param:setString("Layer1", "MainMenuFon")
        param:setString("Layer2", "MyMainMenu")
        param:setString("CrossHandler", "FromMoreGamesToMainMenu")
        kernel:addController(controlFactory:Create("CrossFade", param))	
        gameLayer = "MainMenu"	
    elseif message:is("LeftArrow", "press") then 
		GUI:getLayer("MoreGames"):getWidget("MoreGames"):AcceptMessage(Message("LeftButtonPressed"))
		
	elseif message:is("RightArrow", "press") then
		GUI:getLayer("MoreGames"):getWidget("MoreGames"):AcceptMessage(Message("RightButtonPressed"))
	elseif message:is("TryMPG", "press") then
		GUI:getLayer("MoreGames"):getWidget("MoreGames"):AcceptMessage(Message("TryMPGButtonPressed"))
	end
end

-- Опции
function ReleaseOptions()
    ReleaseResourceGroup("Options")
end

function OptionsFunc(message)
    if message:is("OptionsCancel", "press") then
        RestoreOptions()
        FadePopLayer("Options", "Options", "ReleaseOptions");
    elseif message:is("OptionsOk", "press") then
        SetOptions()
        FadePopLayer("Options", "Options", "ReleaseOptions");
    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)
        if message:is("Sound", "up") then
            Sound:PlaySample("Hint")
        end
    elseif message:is("SEnvironment") then
        local envVolume = message:getIntegerParam()
        gameInfo:setEnvironmentVolume(envVolume)
        Sound:SetEnvironmentVolume(envVolume)
    elseif message:is("OptionsCredits", "press") then
        if (false) then
            if (gameLayer == "MainMenu") then
                local param = VariableSet()
                param:setString("Layer1", "Credits")
                param:setString("CrossHandler", "UploadCredits")
                kernel:addController(controlFactory:Create("CrossFade", param))
            else
                local param = VariableSet()
                param:setString("Layer1", "Credits")
                param:setString("CrossHandler", "UploadCredits")
                kernel:addController(controlFactory:Create("PushLayer", param))
            end
        else
            Screen:SaveLayers()
            local param = VariableSet()
            param:setString("Layer1", "Credits")
            param:setString("CrossHandler", "UploadCredits")
            kernel:addController(controlFactory:Create("CrossFade", param))
        end
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("OptionsCancel", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("OptionsOk", "press"))
    end
end

function UploadCredits()
    UploadResourceGroup("StageLayer_1")
    UploadResourceGroup("Credits")
    GUI:getLayer("Credits"):getWidget("Background"):AcceptMessage( Message("SetTime", "0.0") )
    GUI:getLayer("Credits"):getWidget("Credits"):AcceptMessage(Message("Reset"))
    if (gameLayer == "ISpyFieldControl" or gameLayer == "ISpyBonusField" or gameLayer == "PrepareAltarLevel") then
        UploadResourceGroup("Fon")
    end
--	if (gameLayer ~= MainMenu) then
--		gameInfo:Save()
--	end
end

function CreditsFunc(message)
    if (message:is("Exit")) then
        if (finalCredits) then
            finalCredits = false
            local param = VariableSet()
            param:setString("Layer1", "Map")
            param:setString("EndHandler", "MapEndHandler")
            param:setString("CrossHandler", "ExitFinalCreditsCross")
            kernel:addController(controlFactory:Create("CrossFade", param))
            gameLayer = "Map"
        else
            if (false) then
                if (gameLayer == "MainMenu") then
                    local param = VariableSet()
                    param:setString("Layer1", "MainMenuFon")
                    param:setString("Layer2", "MyMainMenu")
                    param:setString("CrossHandler", "ExitCreditsCross")
                    kernel:addController(controlFactory:Create("CrossFade", param))
                else
                    local param = VariableSet()
                    param:setString("CrossHandler", "ExitCreditsCross")
                    kernel:addController(controlFactory:Create("CrossFade", param))				
                end
            else
                local param = VariableSet()
                param:setString("CrossHandler", "ExitCreditsCross")
                kernel:addController(controlFactory:Create("CrossFade", param))	
                
            end
        end
    end
end

function ExitCreditsCross()
    Screen:RestoreLayers()
    if (gameLayer ~= "StageLayer_1") then
        ReleaseResourceGroup("StageLayer_1")
    end
    if (gameLayer == "ISpyFieldControl" or gameLayer == "ISpyBonusField" or gameLayer == "PrepareAltarLevel") then
        ReleaseResourceGroup("Fon")
    end
    ReleaseResourceGroup("Credits")
end

function ExitFinalCreditsCross()
    ReleaseResourceGroup("StageLayer_1")
    ReleaseResourceGroup("Credits")
    MapCrossHandler()
end

function FromLoadScreenStartNewPlayer()
    ReleaseResourceGroup("Game")
    UploadGameIntroNewPlayer()
end

function CreateFirstPlayer()
    GUI:getLayer("FirstProfile"):getWidget("Name"):AcceptMessage(Message("Clear"))

    FadePushLayer("FirstProfile", "Panel");
end

function ReleaseLoadScreen()
    GUI:getLayer("LoadScreen"):getWidget("LoadScreen"):AcceptMessage(Message("Release"))
end
function ShowFirstPlayerPanel()
    CreateFirstPlayer()
    GUI:getLayer("LoadScreen"):getWidget("LoadScreen"):AcceptMessage(Message("Release"))
end
function LoadScreenFunc(message)
    if message:is("Start") then
        if (gameInfo:getNumberOfPlayers() == 0) then
            local param = VariableSet()
            param:setString("Layer1", "MainMenuFon")
            param:setString("FadeName", "StartCrossCycle")
            --param:setString("Layer2", "FirstProfile")
            --param:setString("CrossHandler", "CreateFirstPlayer")
            param:setString("EndHandler", "ShowFirstPlayerPanel")
            kernel:addController(controlFactory:Create("CrossFade", param))
            gameLayer = "MainMenu"
        else
            GUI:getLayer("MyMainMenu"):getWidget("MyMainMenu"):AcceptMessage(Message("InitMainMenu"))
            local param = VariableSet()
            param:setString("Layer1", "MainMenuFon")
            param:setString("Layer2", "MyMainMenu")
            param:setString("FadeName", "StartCrossCycle")
            param:setString("EndHandler", "ReleaseLoadScreen")
            kernel:addController(controlFactory:Create("CrossFade", param))
            gameLayer = "MainMenu"
        end
    end
end

addArtefact = 0

function HintFunc(message)
    if message:is("Ok", "press") then
        GUI:getLayer("Hint"):getWidget("Hint"):AcceptMessage( Message("Hide") )
    elseif message:is("PopLayer") then
        Screen:popLayer()
    end
end

function PreviewSSExit()
    GUI:getLayer("StageLayer_1"):getWidget("GameField"):AcceptMessage( Message("SetPreviewSSMode", 0) )
    fadeScreens = 1
    gameInfo:ReleaseLastSS()
end

function GameFunc(message)

    if message:is("RunNextBackground") then
        local param = VariableSet()
        param:setString("Layer1", message:getData())
        param:setString("CrossHandler", "UploadScreensaverBG")
        kernel:addController(controlFactory:Create("OldCrossFade", param))	
        Sound:FadeOutAllTracks(1.0)
    elseif message:is("PreviewSSExit") then
        if (gameInfo:isScreensaver()) then
            CloseApplication()
        else
            local param = VariableSet()
            param:setString("Layer1", "MainMenuFon")
            param:setString("Layer2", "MyMainMenu")
            param:setString("Layer3", "Cross1")
            param:setString("Layer4", "SSOptions")
            param:setString("CrossHandler", "PreviewSSExit")
            kernel:addController(controlFactory:Create("CrossFade", param))	
            gameInfo:setPreviewSSMode(false)
            Sound:FadeOutAllTracks(1.0)
            Sound:FadeInTrackContinue("MainMenu", 2.0, true)
        end
    elseif message:is("Menu", "press") then
        menuInGame = true
        sucFromGame = true
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("Pause"))
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("SetActive", 0) )
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("SaveGame"))
        local menuWidget = GUI:getLayer("MenuInGameAQ3"):getWidget("MenuInGameAQ3")
        menuWidget:setPosition(Point(368, 444))
        menuWidget:setInitPosition()
        FadePushLayer("MenuInGameAQ3", "MenuInGameAQ3");
    elseif message:is("NextLevel") then

    elseif message:is("Load", "press") then
        needShowDialog = true
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("RunLevel"))
    elseif message:is("down", "press") then
        GUI:getLayer(gameLayer):getWidget("LevelList"):AcceptMessage(Message("ScrollUp"))
    elseif message:is("up", "press") then
        GUI:getLayer(gameLayer):getWidget("LevelList"):AcceptMessage(Message("ScrollDown"))
    elseif message:is("PushBagLayer") then
        GUI:getLayer(gameLayer):getWidget("Background"):AcceptMessage( Message("SoundOff") )
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ResetBagFlying"))
        Screen:Clear()
        ReleaseResourceGroup(gameLayer)
        ReleaseResourceGroup("Game")
        UploadResourceGroup("BagRes")
        UploadResourceGroup("SmallArts")
        GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("Upload") )
        Screen:pushLayer( GUI:getLayer("Bag") )
        GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("OpenBook") )
        GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("ShowPanel") )
        gameInfo:Save()
    elseif message:is("SetBagLayer") then
        GUI:getLayer(gameLayer):getWidget("Background"):AcceptMessage( Message("SoundOff") )
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ResetBagFlying"))
        Screen:Clear()
        ReleaseResourceGroup(gameLayer)
        UploadResourceGroup("BagRes")
        UploadResourceGroup("SmallArts")
        GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("Upload") )
        Screen:pushLayer( GUI:getLayer("Bag") )
        GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("OpenBook") )
        GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("ShowPanel") )
        gameInfo:Save()
    elseif message:is("SetMapLayer") then
        Sound:FadeOutAllTracks(1.0)
        Sound:FadeInTrack("Map", 2.0, true)
        GUI:getLayer(gameLayer):getWidget("Background"):AcceptMessage( Message("SoundOff") )
        Screen:Clear()
        UploadResourceGroup("Map")
        Screen:pushLayer( GUI:getLayer("Map") )
        GUI:getLayer("StageLayer_1"):getWidget("gameFrame"):AcceptMessage(Message("setScale", "1.0"));
        GUI:getLayer("StageLayer_2"):getWidget("gameFrame"):AcceptMessage(Message("setScale", "1.0"));
        GUI:getLayer("StageLayer_3"):getWidget("gameFrame"):AcceptMessage(Message("setScale", "1.0"));
        GUI:getLayer("StageLayer_4"):getWidget("gameFrame"):AcceptMessage(Message("setScale", "1.0"));
        GUI:getLayer("StageLayer_5"):getWidget("gameFrame"):AcceptMessage(Message("setScale", "1.0"));
        GUI:getLayer("StageLayer_6"):getWidget("gameFrame"):AcceptMessage(Message("setScale", "1.0"));
        GUI:getLayer("StageLayer_7"):getWidget("gameFrame"):AcceptMessage(Message("setScale", "1.0"));
    elseif message:is("SwitchToMapNewCountry") then
        Sound:FadeOutAllTracks(1.0)
        Sound:FadeInTrack("Map", 2.0, true)
        GUI:getLayer(gameLayer):getWidget("Background"):AcceptMessage( Message("SoundOff") )
        local param = VariableSet()
        param:setString("Layer1", "Map");
        param:setString("EndHandler", "AddMarka");
        kernel:addController(controlFactory:Create("CrossFade", param))			
        Sound:FadeOutAllTracks(1.0)
        Sound:FadeInTrackContinue("MainMenu", 2.0, true)
    elseif message:is("ShowLoseLife") then
        if (gameInfo:getLives() == 1) then
            FadePushLayer("OneLifeLost", "LoseLife")
        else
            FadePushLayer("LoseLife", "LoseLife")
        end
        
    elseif message:is("ShowGameOver") then
        needShowDialog = true
        FadePushLayer("GameOver", "GameOver")
    elseif message:is("ShowStartLevelDialog") then
        --ShowStartLevelDialog()	
    elseif message:is("CrossToBag") then
        Sound:FadeOutAllTracks(1.0)
        GUI:getLayer(gameLayer):getWidget("Background"):AcceptMessage( Message("SoundOff") )
        addArtefact = message:getIntegerParam()
        local param = VariableSet()
        param:setString("Layer1", "Bag");
        param:setString("CrossHandler", "CompleteLevelCrossBagCross");
        param:setString("EndHandler", "CompleteLevelCrossBagEnd");
        kernel:addController(controlFactory:Create("CrossFade", param))
    elseif message:is("ShowStatistics") then
        local statWidget = GUI:getLayer("Statistics"):getWidget("GameStatistics")
        statWidget:AcceptMessage(Message("Start"))
        FadePushLayer("Statistics", "GameStatistics");
    elseif message:is("RunFinalDialog") then
        Screen:pushLayer( GUI:getLayer("Dialog") )
        GUI:getLayer("Dialog"):getWidget("Dialog"):AcceptMessage( Message("Run", "Dlg_82") )
    elseif message:is("SetNextStage") then
        Screen:Clear()
        ReleaseResourceGroup(gameLayer)
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
        
        if (gameInfo:getStage() == 7) then
            gameInfo:setStage(1)
            gameInfo:setLevel(1)
            gameInfo:setNumber(1)
        else
            gameInfo:setStage(gameInfo:getStage() + 1)
        end
        
        StartGame()	
    elseif message:is("Editor") then
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("Editor"))
    
    elseif message:is("SetPrevStage") then
        Screen:Clear()
        ReleaseResourceGroup(gameLayer)
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
        if (gameInfo:getStage() == 1) then
            gameInfo:setStage(7)
        else
            if (gameInfo:getStage() == 2) then
                gameInfo:setNumber(1)
            end
            gameInfo:setStage(gameInfo:getStage() - 1)
        end
        
        StartGame()		
    elseif message:is("SetPrevLevel") then
        Screen:Clear()
        ReleaseResourceGroup(gameLayer)
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
        if (gameInfo:getNumber() == 1) then
            if (gameInfo:getStage() == 1) then
                gameInfo:setNumber(2)
            else
                gameInfo:setNumber(4)
            end
            gameInfo:setLevel(1)
        else
            gameInfo:setNumber(gameInfo:getNumber() - 1)
        end
        
        StartGame()
    elseif message:is("SetNextLevel") then
        Screen:Clear()
        ReleaseResourceGroup(gameLayer)
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
        --gameInfo:CompleteLevel()
        if (gameInfo:getStage() == 1) then
            if (gameInfo:getNumber() < 2) then
                gameInfo:setNumber(gameInfo:getNumber() + 1)
            else 
                gameInfo:setLevel(3)
                gameInfo:setNumber(1)
            end
        else
            if (gameInfo:getNumber() == 4) then
                if (gameInfo:getStage() ~= 1) then
                    gameInfo:setLevel(3)
                    gameInfo:setNumber(1)
                end
            else
                gameInfo:setNumber(gameInfo:getNumber() + 1)
            end
        end
        
        StartGame()
    elseif message:is("GoToLevel") then
        Screen:Clear()
        ReleaseResourceGroup(gameLayer)
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))

		UploadResourceGroup("Match3")
		UploadResourceGroup("Game")
		UploadResourceGroup("Fon")
		UpdateGameLayerName()
		UploadResourceGroup(gameLayer)
		
        StartGame()
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("Editor"))
    else
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( message )
    end
end

function CompleteLevelCrossBagCross()
    GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("Upload") )
    UploadResourceGroup("BagRes")
    UploadResourceGroup("SmallArts")
    GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("OpenBook") )
    GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("ShowPanel") )
    Sound:FadeInTrack("Bag", 2.0, true)

    gameInfo:Save()
end

function CompleteLevelCrossBagEnd()
    GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage( Message("AddArtefact", addArtefact) )
end

function AddMarka()
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("AddMarka"))
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("ShowPanel"))
end

function ArtCutterFunc(message)
--	GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( message )
end

function InitLevel()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("InitLevel"))
end

function SetFlag()
    ReleaseResourceGroup("MainMenu")	
    ReleaseResourceGroup("Altar")
    UploadResourceGroup("Map")
    UploadResourceGroup("Fon")
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))
end

function SetFlagAndStartMapMusic()
    ReleaseResourceGroup("MainMenu")	
    ReleaseResourceGroup("Altar")
    UploadResourceGroup("Map")
    UploadResourceGroup("Fon")
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))

    Sound:FadeInTrackContinue("Map", 2.0, true)
end

function MapFunc(message)
    if message:is("start", "press") then
        Sound:FadeOutAllTracks(1.0)
        if (gameInfo:getTypeLevel() == "TYPE_MATCH3")then
            StartGame()         
            gameInfo:SetCurrentGameType("Match3")
        elseif (gameInfo:getTypeLevel() == "TYPE_ISPY") then
            gameLayer = "ISpyFieldControl"
            local param = VariableSet()
            param:setString("Layer1", gameLayer);
            param:setString("CrossHandler", "FromMapToISpy")
            kernel:addController(controlFactory:Create("CrossFade", param))    
            gameInfo:SetCurrentGameType("ISpy")
            gameInfo:InitISpy()
        elseif (gameInfo:getTypeLevel() == "TYPE_BONUS") then 
            gameLayer = "ISpyBonusField"
            local param = VariableSet()
            param:setString("Layer1", gameLayer);
            param:setString("CrossHandler", "FromMapToISpy")
            kernel:addController(controlFactory:Create("CrossFade", param))  
            gameInfo:SetCurrentGameType("Bonus")  
            gameInfo:InitBonus()
        end
    elseif message:is("menu", "press") then
        Sound:FadeOutAllTracks(1.0)
        menuInGame = false
        GUI:getLayer("MyMainMenu"):getWidget("MyMainMenu"):AcceptMessage(Message("InitMainMenu"))
        local param = VariableSet()
        param:setString("Layer1", "MainMenuFon");
        param:setString("Location", "MainMenu");
        param:setString("Layer2", "MyMainMenu");
        param:setString("CrossHandler", "FromMapToMainMenu")		
        kernel:addController(controlFactory:Create("CrossFade", param))	
        gameLayer = "MainMenu"
    elseif message:is("altar", "press") then
        Sound:FadeOutAllTracks(1.0)
        menuInGame = false
        local param = VariableSet()
        param:setString("Layer1", "PrepareAltarEffects");
        param:setString("Location", "Init");
        param:setString("CrossHandler", "FromMapToAltar")
        kernel:addController(controlFactory:Create("CrossFade", param))
        gameLayer = "PrepareAltarEffects"
        fromMap = true;
	elseif message:is("mapScrollTop", "press") then
		GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("PressScrollTop"))
	elseif message:is("mapScrollBottom", "press") then
		GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("PressScrollBottom"))
    end
end

function CountryIntroCross()
--	UploadResourceGroup("Game")
    GUI:getLayer(countryIntroLayerName):getWidget("GameField"):AcceptMessage( Message("SetCountryIntroMode", 1) )
    GUI:getLayer(countryIntroLayerName):getWidget("Background"):AcceptMessage( Message("SoundOn") )
    GUI:getLayer(countryIntroLayerName):getWidget("Background"):AcceptMessage( Message("StoreTime") )
    GUI:getLayer(countryIntroLayerName):getWidget("Background"):AcceptMessage( Message("SetTime", "0") )
    GUI:getLayer("Dialog"):getWidget("Dialog"):AcceptMessage( Message("Run", countryIntroDialogName) )
end

function ShowMapHint()
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("ShowHint") )
end

function MapEndHandler()
    if (gameInfo:isNeedShowFinalTextOnMap()) then
        FadePushLayer("CycleCompletedLayer", "Panel")
    end
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLighting"))
end

function CycleCompletedFunc(message)
    if message:is("Ok", "press") then
        FadePopLayer("CycleCompletedLayer", "Panel", "RunNextCycleOnMap")
    end
end

function RunNextCycleOnMap()
    gameInfo:setNeedShowFinalTextOnMap(false)
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("RunNextCycle"))
end

function BonusStatEndHandler()
    GUI:getLayer("ISpyBonusField"):getWidget("GameField"):AcceptMessage(Message("Statistics finished"));
    Sound:FadeOutAllTracks(1.0)
end

function BonusCrossFade()
    Sound:FadeOutAllTracks(1.0)
    local param = VariableSet()
    if (gameInfo:getCycle() == 1 or (gameInfo:getCycle() == 2 and gameInfo:getStage() == 1)) then
        param:setString("Layer1", "PrepareAltarEffects");
        param:setString("Location", "NewArtefact");
        param:setString("CrossHandler", "FromISpyToMainMenu")
    elseif (gameInfo:getStage() == 1) then
        Sound:FadeOutAllTracks(1.0)		
        param:setString("Layer1", "Map")
        param:setString("CrossHandler", "GameWinFromISpy")
        fromMap = false;
    else 
        param:setString("Layer1", "Map");
        param:setString("CrossHandler", "FromISpyToMap")		
    end
    
    kernel:addController(controlFactory:Create("OldCrossFade", param))
end

function StatFunc(message)
    if (message:is("Ok", "press")) then
        if (gameInfo:GetCurrentGameType() == "Bonus") then
            FadePopLayer("Statistics", "GameStatistics", "BonusStatEndHandler");
        elseif (gameInfo:GetCurrentGameType() == "ISpy") then
            FadePopLayer("Statistics2", "GameStatistics2");
        else
            Sound:FadeOutAllTracks(1.0)			
            local param = VariableSet()
            param:setString("Layer1", "Map")
            param:setString("CrossHandler", "StatCrossHandler")
            kernel:addController(controlFactory:Create("OldCrossFade", param))
        end
--		GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("LoadLevel") )
--		GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("RunStartAW", 1) )
--		if (gameInfo:IsGameOver() == true) then
--			Sound:FadeOutAllTracks(1.0)
--			Sound:FadeInTrack("Menu", 3.0, true)
--			local param = VariableSet()
--			param:setString("Layer1", "Menu")
--			kernel:addController(controlFactory:Create("CrossFade", param))			
--		else
--			Sound:FadeOutAllTracks(3.0)
--			Sound:FadeInTrack("Map", 3.0, true)			
--			IncrementTip()
--			local param = VariableSet()
--			param:setString("Layer1", "Map")
--			param:setString("Layer1", "Bag")
--			param:setString("CrossHandler", "StatCrossHandler")
--			kernel:addController(controlFactory:Create("CrossFade", param))
--			Screen:popLayer()
--			Screen:popLayer()
--			GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage( Message("RunArtefactCollecting") )
--		end
    end
end

function StatCrossHandler()
    FromGameToMap()
    gameInfo:WriteResultToHiScores()
    if (gameInfo:IsGameOver() == true) then
        gameInfo:setScore(0)
        gameInfo:setUID()
    end
    gameInfo:ClearSavedData()
    gameInfo:Save()
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetMoveFlag") )
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetFlag") )
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("InitLevel") )
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("MoveFlag") )	
end

function ProfileFunc(message)
    if message:is("Names", "DoubleClick") then
        local state = GUI:getLayer("Profiles"):getWidget("Names"):AcceptMessage(Message("SetNeedHideHint", 1))
        Sound:PlaySample("ButtonClick")
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitVars"))
    end
    if message:is("Cancel", "press") then
        FadePopLayer("Profiles", "Panel")
        --optionsWidget:AddEffect("WindowShow")
    elseif message:is("Ok", "press") or message:is("Names", "DoubleClick") then
--		GUI:getLayer("Menu"):getWidget("1_MenuEffect"):AcceptMessage(Message("HideSaverTip"))
--		GUI:getLayer("Menu"):getWidget("1_MenuEffect"):AcceptMessage(Message("EndGemEffects"))
        local state = GUI:getLayer("Profiles"):getWidget("Names"):QueryState(Message("CurrentItem"))
        local playerName = state:getData()
        gameInfo:setActivePlayer(playerName)
        SetShowHints()
        GUI:getLayer("MyMainMenu"):getWidget("MyMainMenu"):AcceptMessage(Message("InitMainMenu"))
        FadePopLayer("Profiles", "Panel")
        --GUI:getLayer("MyMainMenu"):getWidget("Start"):AcceptMessage(Message("SetProfile", playerName))
        --GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitVars"))
        --optionsWidget:AddEffect("WindowShow")
    elseif message:is("0_Up", "press") then
        local namesWidget = GUI:getLayer("Profiles"):getWidget("Names")
        namesWidget:AcceptMessage(Message("ScrollDown"))
    elseif message:is("0_Down", "press") then
        local namesWidget = GUI:getLayer("Profiles"):getWidget("Names")
        namesWidget:AcceptMessage(Message("ScrollUp"))
    elseif message:is("New", "press") then
        --GUI:getLayer("NewProfile"):getWidget("InfoText"):AcceptMessage(Message("SetString", "maximum 12 characters"))
        GUI:getLayer("NewProfile"):getWidget("Name"):AcceptMessage(Message("Clear"))
		GUI:getLayer("NewProfile"):getWidget("InfoText"):AcceptMessage(Message("SetString", "#NewProfileInfoText"))
        FadePushLayer("NewProfile", "Panel")
    elseif message:is("Delete", "press") then
        if gameInfo:getNumberOfPlayers() == 1 then
            FadePushLayer("LastNoDelete", "Panel")
            needDeletePlayer = false
        else
            local playerName = GUI:getLayer("Profiles"):getWidget("Names"):QueryState(Message("CurrentItem")):getData()
            if (gameInfo:getName() == playerName) then
                FadePushLayer("ActiveNoDelete", "Panel")
            else 
                --GUI:getLayer("DeletePlayerConfirm"):getWidget("PlayerName"):AcceptMessage(Message("SetString", playerName))
                FadePushLayer("DeletePlayerConfirm", "Panel")
            end
        end
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("Cancel", "press"))
    end
end

function NewProfileFunc(message)
    if message:is("Cancel", "press") then
        FadePopLayer("NewProfile", "Panel")
    elseif message:is("Ok", "press") then
        state = GUI:getLayer("NewProfile"):getWidget("Name"):QueryState(Message("Text"))
        GUI:getLayer("MyMainMenu"):getWidget("MyMainMenu"):AcceptMessage(Message("InitMainMenu"))
        local profileName = state:getData()
        if profileName ~= "" then
            needShowDialog = true
            if gameInfo:isPlayerExist(profileName) then
                GUI:getLayer("NewProfile"):getWidget("InfoText"):AcceptMessage(Message("SetString", "#AlreadyExists"))
            else			
                GUI:getLayer("Profiles"):getWidget("Names"):AcceptMessage(Message("Add", profileName))
                gameInfo:AddNewPlayer(profileName)
                GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitVars"))
                SetShowHints()		
                FadePopLayer("NewProfile", "Panel")	
                FadePopLayerWithoutCheck("Profiles", "Panel")	
            end
        end
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("Cancel", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    end
end

function PushMainMenu()
    gameInfo:SetCurrentGameType("NewGame")
    GUI:getLayer("MyMainMenu"):getWidget("MyMainMenu"):AcceptMessage(Message("InitMainMenu"))
    local param = VariableSet()
    param:setString("Layer", "MyMainMenu")
    kernel:addController(controlFactory:Create("MenuPushSlider", param))	
end

function FirstProfileFunc(message)

    if message:is("Ok", "press") then

        state = GUI:getLayer("FirstProfile"):getWidget("Name"):QueryState(Message("Text"))
        local profileName = state:getData()

        if (profileName ~= "") then

            FadePopLayer("FirstProfile", "Panel", "PushMainMenu")
        
            GUI:getLayer("Profiles"):getWidget("Names"):AcceptMessage(Message("Add", profileName))
            gameInfo:AddNewPlayer(profileName)
            SetShowHints()
                
    --		GUI:getLayer("Bag"):getWidget("Bag"):AcceptMessage(Message("InitNoteView", profileName))
        end
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    end
end

function ActiveDeleteMessageFunc(message)
    if message:is("Ok", "press") then
        FadePopLayer("ActiveNoDelete", "Panel")
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    end
end

function LastDeleteMessageFunc(message)
    if message:is("Ok", "press") then
        FadePopLayer("LastNoDelete", "Panel")
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    end
end

function TrialTimeIsOutFunc(message)
	if message:is("Ok", "press") then
        PressOkTrialMessage();
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    end
end

function NoBackgroundsSelectedFunc(message)
    if message:is("Ok", "press") then
        FadePopLayer("NoBackgroundsSelected", "Panel");
    end
end

function DeletePlayerFunc(message)
    if message:is("No", "press") then
        FadePopLayer("DeletePlayerConfirm", "Panel")
    elseif message:is("Yes", "press") then
        local panelWidget = GUI:getLayer("DeletePlayerConfirm"):getWidget("Panel")
        local fadeWidget = GUI:getLayer("Fade3"):getWidget("BlackScreen")
        local state = GUI:getLayer("Profiles"):getWidget("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("Names"):AcceptMessage(Message("Delete", playerName))
        end
        FadePopLayer("DeletePlayerConfirm", "Panel")
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("No", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Yes", "press"))
    end
end

function ExitConfirmFunc(message)
    if message:is("No", "press") then
        FadePopLayer("ExitConfirm", "Panel");	
    elseif message:is("Yes", "press") then
        CloseApplication()
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("No", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Yes", "press"))
    end
end

function ExitConfirmWithSSFunc(message)

    if message:is("No", "press") then

        local state = GUI:getLayer("ExitConfirmWithSS"):getWidget("EnableScreensaver"):QueryState(Message("GetState"))
        if (state:getData() == "1") then
            gameInfo:EnableScreensaver()
        else
--			gameInfo:DisableScreensaver()
        end

        FadePopLayer("ExitConfirmWithSS", "Panel")

    elseif message:is("Yes", "press") then
        local state = GUI:getLayer("ExitConfirmWithSS"):getWidget("EnableScreensaver"):QueryState(Message("GetState"))
        if (state:getData() == "1") then
            gameInfo:EnableScreensaver()
        else
--			gameInfo:DisableScreensaver()
        end
        CloseApplication()
    end
end

function SSOptionsFunc(message)
    if message:is("Ok", "press") then
        gameInfo:ReadSSOptionsFromLayer()
        gameInfo:UpdateInstallSSInfo()
        FadePopLayer("SSOptions", "SSOptions");
    elseif message:is("Cancel", "press") then
        gameInfo:CopySSOptionsFromBuff()
        gameInfo:SetSSOptionsToLayer()
        FadePopLayer("SSOptions", "SSOptions");
	elseif message:is("EnableRain", "Change") then
		EnablePlaneRain();
    elseif message:is("Preview", "press") then
        gameInfo:ReadSSOptionsFromLayer()
        if (gameInfo:isAnyBackgroundSelected()) then
            GUI:getLayer("StageLayer_1"):getWidget("GameField"):AcceptMessage(Message("SetPreviewSSMode", 1))
            gameInfo:setPreviewSSMode(true)
            gameInfo:RunFirstScreensaverBG()
        else
            FadePushLayer("NoBackgroundsSelected", "Panel");
        end
    elseif message:is("RunNextBackground") then
        local param = VariableSet()
        param:setString("Layer1", message:getData())
        param:setString("CrossHandler", "UploadScreensaverBG")
        kernel:addController(controlFactory:Create("OldCrossFade", param))	
        Sound:FadeOutAllTracks(1.0)
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("Cancel", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    end
end

function UploadScreensaverBG()
    gameInfo:ResetRain()
    gameInfo:UploadScreensaverBG()
--	UploadResourceGroup("Game")
end

function ScreensaverFunc(message)
    if message:is("RunNextBackground") then
        local param = VariableSet()
        param:setString("Layer1", message:getData())
        param:setString("CrossHandler", "UploadScreensaverBG")
        kernel:addController(controlFactory:Create("OldCrossFade", param))
    elseif message:is("ShutDown") then
        CloseApplication()
    end

end


function MenuInGameAQ3Func(message)
    if message:is("Resume", "press") then
        local endHandler = ""
        if (menuInGame == true) then
            endHandler = "ContinueGame"
        end
        FadePopLayer("MenuInGameAQ3", "MenuInGameAQ3", endHandler);
    elseif message:is("Help", "press") then
        --if (gameLayer ~= "PrepareAltarLevel") then
            UploadResourceGroup("Help");
            GUI:getLayer("Help"):getWidget("Help"):AcceptMessage( Message("Init") )	
            if (gameLayer == "ISpyFieldControl") then
                GUI:getLayer("Help"):getWidget("Help"):AcceptMessage( Message("Set2") )		
            elseif (gameLayer == "ISpyBonusField") then
                GUI:getLayer("Help"):getWidget("Help"):AcceptMessage( Message("Set3") )		
            else
                GUI:getLayer("Help"):getWidget("Help"):AcceptMessage( Message("Set1") )		
            end
            FadePushLayer("Help", "Help");
        --end
    elseif message:is("Options", "press") then
        UploadResourceGroup("Options")
        SaveOptions()
        RestoreOptions()
        local param = VariableSet()
        local optionWidget = GUI:getLayer("Options"):getWidget("Options")
        if (gameLayer == "PrepareAltarLevel") then
            optionWidget:setPosition(Point(85, 500))
        else
            optionWidget:setPosition(Point(321, 500))		
        end
        optionWidget:setInitPosition(); -- ToDo: what is it?
        FadePushLayer("Options", "Options", "");
        optionsFromGame = true	
    elseif message:is("Restart", "press") then
        --Sound:FadeOutAllTracks(1.0)		
        gameInfo:ClearSavedData()
        
		local restartWidget = GUI:getLayer("RestartNoLostLife"):getWidget("Panel")
        if (gameLayer == "PrepareAltarLevel") then
            restartWidget:setPosition(Point(50, 444))
        else
            restartWidget:setPosition(Point(283, 444))		
        end
        restartWidget:setInitPosition();

        if (gameLayer == "ISpyFieldControl") then
            FadePushLayer("RestartNoLostLife", "Panel");
        elseif (gameLayer == "ISpyBonusField") then
            FadePushLayer("RestartNoLostLife", "Panel");
        elseif (gameLayer == "PrepareAltarLevel") then
            FadePushLayer("RestartNoLostLife", "Panel");
        else
			FadePushLayer("RestartNoLostLife", "Panel");	
            --if (gameInfo:NeedDecLivesOnExit()) then
            --    if (gameInfo:getLives() > 1) then
            --        FadePushLayer("RestartLostLife", "Panel");
            --    else 
            --        FadePushLayer("RestartGameOver", "Panel");
            --    end
            --else 
            --    FadePushLayer("RestartNoLostLife", "Panel");
            --end
        end
    elseif message:is("Exit", "press") then
        -- ToDo: move window
        --local center = GUI:getLayer("MenuInGameAQ3"):getWidget("MenuInGameAQ3"):GetCenterPosition();
        --GUI:getLayer("ExitGameNoLostLife"):getWidget("Panel"):SetCenterPosition(center);
        --GUI:getLayer("ExitGameNoLostLife"):getWidget("Panel"):setInitPosition();

		local exitWidget = GUI:getLayer("ExitGameNoLostLife"):getWidget("Panel")
        if (gameLayer == "PrepareAltarLevel") then
            exitWidget:setPosition(Point(50, 444))
        else
            exitWidget:setPosition(Point(283, 444))		
        end
        exitWidget:setInitPosition();

        FadePushLayer("ExitGameNoLostLife", "Panel");
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("Resume", "press"))
    end
end


function RestartLevelFunc(message)
    if message:is("Yes", "press") then
        Sound:FadeOutAllTracks(1.0)
        gameInfo:ChangeDifficultyLevel(100)
        gameInfo:ResetInfoToBeginLevel()
        StartGame()
    elseif message:is("No", "press") then
        FadePopLayer("RestartLostLife", "Panel");
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("No", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Yes", "press"))
    end
end

function RestartGameOverFunc(message)
    if message:is("Yes", "press") then
        gameInfo:KillProgress()
        Sound:FadeOutAllTracks(2.0);
        Sound:FadeInTrackContinue("Map", 3.0, true);
        local param = VariableSet()
        param:setString("Layer1", "Map");
        param:setString("CrossHandler", "GameOverCrossHandler")
        kernel:addController(controlFactory:Create("CrossFade", param))
    elseif message:is("No", "press") then
        FadePopLayer("RestartGameOver", "Panel");
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("No", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Yes", "press"))
    end
end

function RestartLevelNoLostLifeFunc(message)
    if message:is("Yes", "press") then
        Sound:FadeOutAllTracks(1.0)
		FadePopLayer("MenuInGameAQ3", "MenuInGameAQ3");
        if gameLayer == "ISpyFieldControl" or gameLayer == "ISpyBonusField" or gameLayer == "PrepareAltarLevel" then
            GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("Restart"))
            -- FadePopLayer("RestartNoLostLife", "Panel");
            local param = VariableSet()
            param:setString("Layer1", gameLayer)
            kernel:addController(controlFactory:Create("CrossFade", param))
        else 
            gameInfo:ResetInfoToBeginLevel()
            StartGame()
        end
    elseif message:is("No", "press") then
        FadePopLayer("RestartNoLostLife", "Panel");
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("No", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Yes", "press"))
    end
end

--
-- Всё что ниже нужно для уровней ISpy и бонусного
--

--
-- Реакция на нажатие кнопки меню
--
function ISpyMenuButtonPress()
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("DropArtefact"))
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("Pause"))
    menuInGame = true
    local menuWidget = GUI:getLayer("MenuInGameAQ3"):getWidget("MenuInGameAQ3")
    if (gameLayer == "PrepareAltarLevel") then
        menuWidget:setPosition(Point(138, 444))
    elseif (gameLayer == "ISpyFieldControl") then
        menuWidget:setPosition(Point(368, 444))
    elseif (gameLayer == "ISpyBonusField") then
        menuWidget:setPosition(Point(368, 444))
    end
    menuWidget:setInitPosition(); -- ToDo: what is it?
    FadePushLayer("MenuInGameAQ3", "MenuInGameAQ3");

end

--
-- Обрабатывает сообщения из ISpyFieldControl и ISpyBonusField
--
function ISpyFunc(message)
    if message:is("MenuButton", "press") then
        ISpyMenuButtonPress()
    elseif message:is("HintButton", "press") then
        GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ShowHint"))
    elseif message:is("ShowStatistics") then
        local statWidget = GUI:getLayer("Statistics"):getWidget("GameStatistics")
        statWidget:AcceptMessage(Message("Start"))
        FadePushLayer("Statistics", "GameStatistics");
    elseif message:is("KillMe") then
        Sound:FadeOutAllTracks(1.0)
        local param = VariableSet()
        gameInfo:setStage(1)
        gameInfo:setLevel(1)
        gameInfo:setNumber(1)
        gameInfo:NewSSOptions()
        param:setString("Layer1", "MultCountry")
        param:setString("CrossHandler", "FromMainMenuToMultCountry")
        kernel:addController(controlFactory:Create("OldCrossFade", param))
   end
end

function ExitGameAQ3Func(message)

   if message:is("Yes", "press") then
    Sound:FadeOutAllTracks(1.0)

      GUI:getLayer("MyMainMenu"):getWidget("MyMainMenu"):AcceptMessage(Message("InitMainMenu"))
        if (gameLayer == "PrepareAltarLevel") then
        --  sucFromGame = false
        --  creditsFromGame = false	   
        --  Sound:FadeOutAllTracks(1.0)
        --  Sound:FadeInTrack("Menu", 3.0, true)
            param = VariableSet()
            param:setString("Layer1", "MainMenuFon");
            param:setString("Layer2", "MyMainMenu");
            param:setString("CrossHandler", "FromPrepareLevelToMainMenu")
            kernel:addController(controlFactory:Create("CrossFade", param))	 			
        elseif (gameLayer == "ISpyFieldControl" or gameLayer == "ISpyBonusField") then
        --  sucFromGame = false
        --  creditsFromGame = false	   
        --  Sound:FadeOutAllTracks(1.0)
        --  Sound:FadeInTrack("Menu", 3.0, true)
            local param = VariableSet()
            param:setString("Layer1", "MainMenuFon");
            param:setString("Layer2", "MyMainMenu");
            param:setString("CrossHandler", "ExitFromISpy")
            kernel:addController(controlFactory:Create("CrossFade", param))	     
        --  SetHiscoreActive(1)	
        else
        --  sucFromGame = false
        --  creditsFromGame = false	   
        --  Sound:FadeOutAllTracks(1.0)
        --  Sound:FadeInTrack("Menu", 3.0, true)
            local param = VariableSet()
            param:setString("Layer1", "MainMenuFon");
            param:setString("Layer2", "MyMainMenu");
            param:setString("CrossHandler", "ExitFromGame")
            kernel:addController(controlFactory:Create("CrossFade", param))	      
        --  SetHiscoreActive(1)	
        end
   elseif message:is("No", "press") then
        FadePopLayer("ExitGameNoLostLife", "Panel")
   elseif message:is("Menu_ispy", "press") then
        Sound:FadeOutAllTracks(1.0)
        
      gameInfo:ClearSavedData()
      Screen:Clear()
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
      if (gameLayer == "PrepareAltarLevel") then
            ReleaseResourceGroup("Altar")
      elseif ((gameLayer ~= "ISpyFieldControl") and (gameLayer ~= "ISpyBonusField")) then
            ReleaseResourceGroup(gameLayer)
            ReleaseResourceGroup("Match3")
            ReleaseResourceGroup("Fon")
            UploadResourceGroup("ISpy")
      end
      gameLayer = "ISpyFieldControl"
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
      gameInfo:setLevel(2)
      gameInfo:setNumber(1)
      gameInfo:setStage(1)
      gameInfo:SetCurrentGameType("ISpy")
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("InitLevel"))
      Screen:pushLayer( GUI:getLayer(gameLayer) )
      
      gameInfo:FadeInGameTrack()
   elseif message:is("Menu_bonus_quest", "press") then

        Sound:FadeOutAllTracks(1.0)

      gameInfo:ClearSavedData()
      Screen:Clear()
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
       if (gameLayer == "PrepareAltarLevel") then
            ReleaseResourceGroup("Altar")
      elseif ((gameLayer ~= "ISpyFieldControl") and (gameLayer ~= "ISpyBonusField")) then
            ReleaseResourceGroup(gameLayer)
            ReleaseResourceGroup("Match3")
            ReleaseResourceGroup("Fon")
            UploadResourceGroup("ISpy")
      end
      gameLayer = "ISpyBonusField"
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
      gameInfo:setLevel(4)
      gameInfo:setNumber(1)
      gameInfo:setStage(1)
      gameInfo:SetCurrentGameType("Bonus")
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("InitLevel"))
      Screen:pushLayer( GUI:getLayer(gameLayer) )

      gameInfo:FadeInGameTrack()
   elseif message:is("Menu_altar", "press") then
        Sound:FadeOutAllTracks(1.0)

      gameInfo:ClearSavedData()
      Screen:Clear()
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
      if ((gameLayer ~= "ISpyFieldControl") and (gameLayer ~= "ISpyBonusField")) then
            ReleaseResourceGroup(gameLayer)
            ReleaseResourceGroup("Match3")
            ReleaseResourceGroup("Fon")
            UploadResourceGroup("ISpy")
            UploadResourceGroup("Altar")
      else
            UploadResourceGroup("Altar")
      end
      gameLayer = "PrepareAltarLevel"
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
      gameInfo:setLevel(1)
      gameInfo:setNumber(1)
      gameInfo:setStage(0)
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("InitLevel"))
      Screen:pushLayer( GUI:getLayer(gameLayer) )
      
      Sound:FadeInTrack("Altar", 2.0, true)
    elseif message:is("Menu_match3", "press") then
        Sound:FadeOutAllTracks(1.0)

      gameInfo:ClearSavedData()
      Screen:Clear()
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
      if ((gameLayer == "ISpyFieldControl") or (gameLayer == "ISpyBonusField")) then
            
            ReleaseResourceGroup("ISpy")			
      elseif (gameLayer == "PrepareAltarLevel") then
            ReleaseResourceGroup("Altar")
            ReleaseResourceGroup("ISpy")
      end
      gameInfo:setLevel(1)
      gameInfo:setNumber(1)    
      if (gameInfo:getStage() == 0) then
        gameInfo:setStage(1)    
      end
      gameInfo:SetCurrentGameType("Match3")
      StartGame()

      gameInfo:FadeInGameTrack()
   elseif message:is("Menu_map", "press") then
        Sound:FadeOutAllTracks(1.0)

      gameInfo:ClearSavedData()
      gameInfo:SetCurrentGameType("Map")
      Screen:Clear()
      GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ReleaseResources"))
      if (gameLayer == "PrepareAltarLevel") then
            ReleaseResourceGroup("Altar")
            ReleaseResourceGroup("ISpy")
            UploadResourceGroup("Fon")
            gameInfo:setStage(1)
            gameInfo:setLevel(1)
            gameInfo:setNumber(1)
      elseif ((gameLayer ~= "ISpyFieldControl") and (gameLayer ~= "ISpyBonusField")) then
            ReleaseResourceGroup(gameLayer)
            ReleaseResourceGroup("Match3")
            ReleaseResourceGroup("Game")
      else
            ReleaseResourceGroup("ISpy")
            ReleaseResourceGroup("Game")
            UploadResourceGroup("Fon")			
      end
      UploadResourceGroup("Map")
      GUI:getLayer("Map"):getWidget("Map"):AcceptMessage( Message("SetFlag") )
      GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("InitLevel"))
      Screen:pushLayer( GUI:getLayer("Map") )
      gameLayer = "Map"

      Sound:FadeInTrackContinue("Map", 2.0, true)
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("No", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Yes", "press"))
   end
end

--
-- Обрабатывает сообщения из тренировочного окна
--
function TrainWindowFunc(message)
   if message:is("Train-OK", "press") then
     GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
   elseif message:is("Train-Skip", "press") then
     GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
     GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("TrainSkipPressed"))
   elseif message:is("KillMe") then
     Screen:popLayer()
     GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("TrainWindowKilled"))
   elseif message:is("MenuButton", "press") then
     ISpyMenuButtonPress()
   elseif message:is("HintButton", "press") then
     GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("ShowHint"))
   end
end

function MapFirstArtFunc(message)
    if message:is("Train-OK", "press") then
        GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))		
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("HideToolTip"))
    elseif message:is("Train-Skip", "press") then
        GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
        --GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("TrainSkipPressed"))
    elseif message:is("KillMe") then
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("HideToolTip"))
        Screen:popLayer()
    elseif message:is("start", "press") then
        Sound:FadeOutAllTracks(1.0)
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("HideToolTip"))
        Screen:popLayer()
        if (gameInfo:getTypeLevel() == "TYPE_MATCH3")then
            StartGame()         
            gameInfo:SetCurrentGameType("Match3")
        elseif (gameInfo:getTypeLevel() == "TYPE_ISPY") then
            gameLayer = "ISpyFieldControl"
            local param = VariableSet()
            param:setString("Layer1", gameLayer);
            param:setString("CrossHandler", "FromMapToISpy")
            kernel:addController(controlFactory:Create("CrossFade", param))    
            gameInfo:SetCurrentGameType("ISpy")
            gameInfo:InitISpy()
        elseif (gameInfo:getTypeLevel() == "TYPE_BONUS") then 
            gameLayer = "ISpyBonusField"
            local param = VariableSet()
            param:setString("Layer1", gameLayer);
            param:setString("CrossHandler", "FromMapToISpy")
            kernel:addController(controlFactory:Create("CrossFade", param))  
            gameInfo:SetCurrentGameType("Bonus")  
            gameInfo:InitBonus()
        end
    end
end

function MapNewCycleFunc(message)
    if message:is("Train-OK", "press") then
        GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
        GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("HideNewCycle"))
    elseif message:is("Train-Skip", "press") then
        GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
    elseif message:is("KillMe") then
        Screen:popLayer()
    end
end

function FromMultToAltar()
    ReleaseResourceGroup("MultCountry")
    UploadResourceGroup("ISpy")
    UploadResourceGroup("Game")
    gameLayer = "PrepareAltarLevel"
    gameInfo:SetCurrentGameType("PrepareAltarLevel")
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("InitLevel"))
    Sound:FadeInTrack("Altar", 2.0, true)
end

function EndMult()	
    GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage(Message("EndIntro"))
    ReleaseResourceGroup("Mult")
    comeFromStart = false
end

function SkipIntroMult()
    Sound:FadeOutAllTracks(1.0)
    FromMultToAltar()
    EndMult()
end

function EndIntro()
    GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage(Message("EndIntro"))
    gameLayer = "PrepareAltarLevel"
    gameInfo:SetCurrentGameType("PrepareAltarLevel")
    GUI:getLayer(gameLayer):getWidget("GameField"):AcceptMessage(Message("InitLevel"))
    Sound:FadeInTrack("Altar", 2.0, true)
    comeFromStart = false
end

function MultGoToAltar()
    ReleaseResourceGroup("Map")
    GUI:getLayer("PrepareAltarLevel"):getWidget("GameField"):AcceptMessage(Message("StartMult"));
end

function MultGoToMap()
    UploadResourceGroup("Map")
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("StartMult"));
end

function MultGoToAltarNoHistory()
    ReleaseResourceGroup("Map")
    ReleaseResourceGroup("Fon")
    UploadResourceGroup("ISpy")
    UploadResourceGroup("Game")
    GUI:getLayer("PrepareAltarLevel"):getWidget("GameField"):AcceptMessage(Message("StartMult"));
end

function MultGoToMapNoHistory()
    UploadResourceGroup("Map")
    ReleaseResourceGroup("MainMenu")
    ReleaseResourceGroup("Mult")
    GUI:getLayer("Map"):getWidget("Map"):AcceptMessage(Message("StartMult"));
end

function MultGoToPoseidon()
    GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage(Message("ScenePoseidon"))
end

function MultCountryFunc(message)
    if message:is("Menu", "press") then
		GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage(Message("EndIntro"))
        GUI:getLayer("MyMainMenu"):getWidget("MyMainMenu"):AcceptMessage(Message("InitMainMenu"))
        local param = VariableSet()
        param:setString("Layer1", "MainMenuFon")
        param:setString("Layer2", "MyMainMenu")
        param:setString("CrossHandler", "FromHistoryToMainMenu")
        kernel:addController(controlFactory:Create("CrossFade", param))	
        gameLayer = "MainMenu"	
    elseif message:is("EndMult") then
        local param = VariableSet()
        param:setString("Layer1", "Map")
        param:setString("CrossHandler", "FromMultCountryToMap")
        kernel:addController(controlFactory:Create("OldCrossFade", param))	
        gameInfo:Save()
        gameLayer = "Map"		
    elseif message:is("SkipMult", "press") then
        if (gameInfo:GetCurrentGameType() == "NewGame") then
            comeFromStart = false
            local param = VariableSet()
            gameLayer = "PrepareAltarLevel"
            param:setString("Layer1", "PrepareAltarLevel")
            param:setString("CrossHandler", "SkipIntroMult")
            kernel:addController(controlFactory:Create("CrossFade", param))		
        else
            Sound:FadeOutAllTracks(1.0)
            local param = VariableSet()
            param:setString("Layer1", "Map")
            param:setString("CrossHandler", "FromMultCountryToMap")
            kernel:addController(controlFactory:Create("OldCrossFade", param))
            gameInfo:Save()
            gameLayer = "Map"	
        end
    elseif message:is("StartIntro") then
        Screen:Clear()
        Screen:pushLayer( GUI:getLayer("MainMenuFon"))
        Screen:pushLayer( GUI:getLayer("MultCountry"))
        UploadResourceGroup("Mult")
        GUI:getLayer("MainMenuFon"):getWidget("MainMenuFon"):AcceptMessage(Message("StartMult"))
    elseif message:is("EndIntro") then
        Screen:Clear()
        Screen:pushLayer( GUI:getLayer("MultCountry"))
        ReleaseResourceGroup("Mult")
        GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage(Message("EndIntro"))
    elseif message:is("GoToMap") then
        local param = VariableSet()
        param:setString("NumTopLayer", "2")
        param:setString("Layer1", "Map")
        param:setString("Layer2", "MultCountry")
        param:setString("CrossHandler", "MultGoToMap")
        kernel:addController(controlFactory:Create("MyCrossFade", param))
        gameLayer = "Map"
    elseif message:is("GoToAltar") then
        local param = VariableSet()
        param:setString("NumTopLayer", "2")
        param:setString("Layer1", "PrepareAltarLevel")
        param:setString("Layer2", "MultCountry")
        param:setString("CrossHandler", "MultGoToAltar")
        kernel:addController(controlFactory:Create("MyCrossFade", param))
    elseif message:is("GoToMapNoHistory") then
        local param = VariableSet()
        param:setString("NumTopLayer", "2")
        param:setString("Layer1", "Map")
        param:setString("Layer2", "MultCountry")
        param:setString("CrossHandler", "MultGoToMapNoHistory")
        kernel:addController(controlFactory:Create("MyCrossFade", param))
        gameLayer = "Map"
    elseif message:is("GoToAltarNoHistory") then
        local param = VariableSet()
        param:setString("NumTopLayer", "2")
        param:setString("Layer1", "PrepareAltarLevel")
        param:setString("Layer2", "MultCountry")
        param:setString("CrossHandler", "MultGoToAltarNoHistory")
        kernel:addController(controlFactory:Create("MyCrossFade", param))
    elseif message:is("GoToPoseidon") then
        local param = VariableSet()
        param:setString("NumTopLayer", "2")
        param:setString("Layer2", "MultCountry")
        param:setString("CrossHandler", "MultGoToPoseidon")
        kernel:addController(controlFactory:Create("MyCrossFade", param))	
    elseif message:is("GoFromPoseidon") then
        Screen:Clear()
        Screen:pushLayer( GUI:getLayer("MainMenuFon"))
        Screen:pushLayer( GUI:getLayer("MultCountry"))
        GUI:getLayer("MultCountry"):getWidget("MultCountry"):AcceptMessage(Message("SceneSityStorm"))
    elseif message:is("EndIntroMult") then
        --FromMultToAltar()
        EndIntro()
        Screen:popLayer()
    end	
end

function StartGamePanelFunc(message)
    if message:is("Ok", "press") then
        Sound:FadeOutAllTracks(1.0)
        local param = VariableSet()
        if (gameInfo:getStage() == 0) then
            comeFromStart = false
            local param = VariableSet()
            gameLayer = "PrepareAltarLevel"
            param:setString("Layer1", "PrepareAltarLevel")
            param:setString("CrossHandler", "FromMultToAltar")
            kernel:addController(controlFactory:Create("CrossFade", param))
            comeFromStart = true
        elseif (gameInfo:getTypeLevel() == "TYPE_MATCH3" and gameInfo:GetCurrentGameType() == "Match3") then
            StartGame()			
        elseif (gameInfo:getTypeLevel() == "TYPE_ISPY" and gameInfo:GetCurrentGameType() == "ISpy") then
            gameLayer = "ISpyFieldControl"
            param:setString("Layer1", gameLayer);
            param:setString("CrossHandler", "FromMainMenuToISpy")
            kernel:addController(controlFactory:Create("CrossFade", param))    
        elseif (gameInfo:getTypeLevel() == "TYPE_BONUS" and gameInfo:GetCurrentGameType() == "Bonus") then 
            gameLayer = "ISpyBonusField"
            param:setString("Layer1", gameLayer);
            param:setString("CrossHandler", "FromMainMenuToISpy")
            kernel:addController(controlFactory:Create("CrossFade", param))    
        elseif (gameInfo:GetCurrentGameType() == "Map") then
            param:setString("Layer1", "Map")
--			param:setString("CrossHandler", "SetFlag")
            param:setString("CrossHandler", "SetFlagAndStartMapMusic")
            kernel:addController(controlFactory:Create("CrossFade", param))	
            gameLayer = "Map"
        end
    elseif message:is("StartNewGame", "press") then	
        FadePushLayer("StartNewGamePanel", "Panel")
        local panelWidget = GUI:getLayer("StartNewGamePanel"):getWidget("Panel")
        panelWidget:setColor(Color(255, 255, 255, 0))
    elseif message:is("Cancel", "press") then
        FadePopLayer("StartGamePanel", "Panel");
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("Cancel", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Ok", "press"))
    end	
end

function StartNewGamePanelFunc(message)
    if message:is("Yes", "press") then
        Sound:FadeOutAllTracks(1.0)
        gameInfo:StartNewGame()
        local param = VariableSet()
        param:setString("Layer1", "MainMenuFon")
        param:setString("Layer2", "MultCountry")
        param:setString("CrossHandler", "StartIntroMult")
        kernel:addController(controlFactory:Create("CrossFade", param))
        comeFromStart = true
        
        gameInfo:ClearSavedData()
        comeFromStart = true
        gameInfo:SetCurrentGameType("NewGame")
    elseif message:is("No", "press") then
        FadePopLayer("StartNewGamePanel", "Panel")
    elseif message:is("StartIntro") then
        Screen:Clear()
        Screen:pushLayer( GUI:getLayer("MainMenuFon"))
        Screen:pushLayer( GUI:getLayer("MultCountry"))
        UploadResourceGroup("Mult")
        GUI:getLayer("MainMenuFon"):getWidget("MainMenuFon"):AcceptMessage(Message("StartMult"))
    elseif message:is("EscapePressed") then
        MessageManager:putMessage(Message("No", "press"))
    elseif message:is("EnterPressed") then
        MessageManager:putMessage(Message("Yes", "press"))
    end
end

function getCurrentLayer()
    return gameLayer
end

function AdventureContinueFunc(message)
    if message:is("Train-OK", "press") then
        GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
    elseif message:is("KillMe") then
        GUI:getLayer("PrepareAltarEffects"):getWidget("PrepareAltarEffects"):AcceptMessage(Message("HideTrainWindow"))
        --Sound:FadeOutAllTracks(1.0)
        Screen:popLayer()		
        --local param = VariableSet()
        --param:setString("Layer1", "MultCountry")
        --param:setString("CrossHandler", "FromMainMenuToMultCountry")
        --kernel:addController(controlFactory:Create("CrossFade", param))
    else 
        MainMenuFonFunc(message)
    end
end

function AltarMapButtonFunc(message)
    if message:is("Train-OK", "press") then
        GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
    elseif message:is("KillMe") then
        GUI:getLayer("PrepareAltarEffects"):getWidget("PrepareAltarEffects"):AcceptMessage(Message("HideTrainWindowOnMap"))
        Screen:popLayer()
    elseif (message:is("map", "press")) then
        GUI:getLayer("PrepareAltarEffects"):getWidget("PrepareAltarEffects"):AcceptMessage(Message("HideTrainWindowOnMap"))
        Sound:FadeOutAllTracks(1.0)
        local param = VariableSet()
        param:setString("Layer1", "MultCountry")
        param:setString("CrossHandler", "FromMainMenuToMultCountry")
        kernel:addController(controlFactory:Create("CrossFade", param))
    end
end

function FadePushLayer(layerName, widgetName, endHandler)

    fadeScreens = fadeScreens+1
    local fadeLayer = GetFadeLayerName()
    GUI:getLayer(layerName):getWidget(widgetName):ResetPosition();
    GUI:getLayer(layerName):UpdateRotateCenter(widgetName);
    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))
    local param = VariableSet()
    param:setWidget("Widget", fadeWidget)
    param:setColor("To", Color(0, 0, 0, 150))
    param:setString("FaderType", "Scaled")
    if endHandler ~= "" and endHandler ~= nil then
        param:setString("EndHandler", endHandler)
    end
    kernel:addController(controlFactory:Create("Fader", param))

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


function EndPopLayer()
    isFadePoppingLayer = false;
end

function FadePopLayerWithoutCheck(layerName, widgetName, endHandler) 
    isFadePoppingLayer = true;
    local fadeLayer = GetFadeLayerName()
    fadeScreens = fadeScreens-1
    GUI:getLayer(layerName):UpdateRotateCenter(widgetName)

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

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

    local param = VariableSet()
    param:setWidget("Widget", fadeWidget)
    param:setColor("To", Color(0, 0, 0, 0))
    param:setBool("PopLayer", true)
    param:setString("Layer", fadeLayer)
    param:setString("FaderType", "Scaled")
    if endHandler ~= "" and endHandler ~= nil then
        param:setString("EndHandler", endHandler)
    end
    kernel:addController(controlFactory:Create("Fader", param))
end

function FadePopLayer(layerName, widgetName, endHandler)
    if not isFadePoppingLayer then
        FadePopLayerWithoutCheck(layerName, widgetName, endHandler)
    end
end

function GetFadeLayerName()
    if fadeScreens == 1 then
        return "Cross1";
    elseif fadeScreens == 2 then
        return "Cross2";
    elseif fadeScreens == 3 then
        return "Cross3";
    elseif fadeScreens == 0 then
        return "WidgetNotExists.0";
    else
        return "WidgetNotExists";
    end
end

function ResetFadeScreens()
    fadeScreens = 0;
end

function GetFadeScreensNumber()
    return fadeScreens;
end

function SetFadeScreensNumber(fadeScreens_)
    fadeScreens = fadeScreens_;
end

function ReleaseFon()
    Sound:FadeOutAllTracks(1.0) 
    Screen:Clear()
    ReleaseResourceGroup(gameLayer) 
end

function InitFon()
    if (gameLayer == "StageLayer_1") then
        GUI:getLayer("Rome"):getWidget("Rome"):AcceptMessage(Message("SoundOn", "1"))
        UploadResourceGroup("StageLayer_1");
        UploadResourceGroup("Fon");
    elseif (gameLayer == "StageLayer_2") then
        GUI:getLayer("Greece"):getWidget("Greece"):AcceptMessage(Message("SoundOn", "2"))
        UploadResourceGroup("StageLayer_2");
        UploadResourceGroup("Fon");
    elseif (gameLayer == "StageLayer_3") then
        GUI:getLayer("Troy"):getWidget("Troy"):AcceptMessage(Message("SoundOn", "3"))
        UploadResourceGroup("StageLayer_3");
        UploadResourceGroup("Fon");
    elseif (gameLayer == "StageLayer_4") then
        GUI:getLayer("Phoenicia"):getWidget("Phoenicia"):AcceptMessage(Message("SoundOn", "4"))
        UploadResourceGroup("StageLayer_4");
        UploadResourceGroup("Fon");
    elseif (gameLayer == "StageLayer_5") then
        GUI:getLayer("Babylon"):getWidget("Babylon"):AcceptMessage(Message("SoundOn", "5"))
        UploadResourceGroup("StageLayer_5");
        UploadResourceGroup("Fon");
    elseif (gameLayer == "StageLayer_6") then
        GUI:getLayer("EgyptNew"):getWidget("EgyptNew"):AcceptMessage(Message("SoundOn", "6"))
        UploadResourceGroup("StageLayer_6");
        UploadResourceGroup("Fon");
    elseif (gameLayer == "StageLayer_7") then
        GUI:getLayer("Karfagen"):getWidget("Karfagen"):AcceptMessage(Message("SoundOn", "7"))
        UploadResourceGroup("StageLayer_7");
        UploadResourceGroup("Fon");
    elseif (gameLayer == "MainMenu") then
        Sound:FadeInTrackContinue("MainMenu", 2.0, true)		
        UploadResourceGroup("MainMenu");
        UploadResourceGroup("Altar");
        UploadResourceGroup("Fon");
    end
end
