
require "LP_Logic.lua"

fadeScreens = 0
lastMusicVolume = 0
lastSoundVolume = 0
lastEnvVolume = 0
lastFullscreen = false
lastCustomCursor = false
lastShowHints = false
lastRelaxMode = false
optionsLayerName = "Options"
fromGameMenu = false
cycleRepeatMode2 = 4
showTrain = false;
showPrevWindow = false;
skipWithoutButton = false;
prevTrainWindow = ""
startRain = false

nameLevel = ""
DoneCollectorResponse = false

function MaxLevelMoney(numLevel)
	return 1500;
end;

function GetStartTextId()
	return "CollectorChildroom20";
end

function PrepareLetterInfo()
end;
	
function StartPersonAction()
end;

function GetI(Iter)
	local i = {"Bench", "Wall", "Pond", "Kennel"}
	if Iter == 1 then 
		i[1] = "Bench";
		i[2] = "Wall";
		i[3] = "Pond";
		i[4] = "Kennel";
	elseif Iter == 2 then 
		i[1] = "Gazone";
		i[2] = "Sculpture1";
		i[3] = "Lantern";
		i[4] = "Sculpture2";
	elseif Iter == 3 then 
		i[1] = "Cage";
		i[2] = "Road";
		i[3] = "Fountain";
		i[4] = "Sculpture3";
	elseif Iter == 4 then 
		i[1] = "Golf";
		i[2] = "Porch";
		i[3] = "Swing";
		i[4] = "Bridge";
	else
		i[1] = "Pergola";
		i[2] = "Front";
		i[3] = "SummerHouse";
		i[4] = "Trees";
	end
	return i;
end	

function UploadGardenResource()
    local iter = gameInfo:getGardenIter()	
    if (iter == 5) then
		UploadResourceGroup("Garden5Iter")
		UploadResourceGroup("Garden4Iter")
		UploadResourceGroup("Garden3Iter")
		UploadResourceGroup("Garden2Iter")
		UploadResourceGroup("Garden1Iter")
	elseif (iter == 4) then
		UploadResourceGroup("Garden4Iter")
		UploadResourceGroup("Garden3Iter")
		UploadResourceGroup("Garden2Iter")
		UploadResourceGroup("Garden1Iter")
	elseif (iter == 3) then
		UploadResourceGroup("Garden3Iter")
		UploadResourceGroup("Garden2Iter")
		UploadResourceGroup("Garden1Iter")
	elseif (iter == 2) then
		UploadResourceGroup("Garden2Iter")
		UploadResourceGroup("Garden1Iter")
	else 
		UploadResourceGroup("Garden1Iter")
    end    
    
end

function ReleaseGardenResource()
	GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage (Message("ReleaseResources"))
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage (Message("ReleaseResources"))
	local iter = gameInfo:getGardenIter()	
    if (iter == 5) then
		ReleaseResourceGroup("Garden5Iter")
		ReleaseResourceGroup("Garden4Iter")
		ReleaseResourceGroup("Garden3Iter")
		ReleaseResourceGroup("Garden2Iter")
		ReleaseResourceGroup("Garden1Iter")
	elseif (iter == 4) then
		ReleaseResourceGroup("Garden4Iter")
		ReleaseResourceGroup("Garden3Iter")
		ReleaseResourceGroup("Garden2Iter")
		ReleaseResourceGroup("Garden1Iter")
	elseif (iter == 3) then
		ReleaseResourceGroup("Garden3Iter")
		ReleaseResourceGroup("Garden2Iter")
		ReleaseResourceGroup("Garden1Iter")
	elseif (iter == 2) then
		ReleaseResourceGroup("Garden2Iter")
		ReleaseResourceGroup("Garden1Iter")
	else 
		ReleaseResourceGroup("Garden1Iter")
    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))
    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 FadePopLayer(layerName, widgetName, endHandler)

    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")

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

    param = VariableSet()
    param:setWidget("Widget", fadeWidget)
    param:setColor("To", Color(0, 0, 0, 0))
    param:setBool("PopLayer", true)
    param:setString("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 MyFadePushLayer(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, 150))

    local param = VariableSet()
    param:setWidget("Widget", panelWidget)
    param:setColor("To", Color(255, 255, 255, 255))
    kernel:addController(controlFactory:Create("Fader", param))
    param = VariableSet()
    param:setWidget("Widget", fadeWidget)
    param:setColor("To", Color(0, 0, 0, 150))
    param:setString("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 MyFadePopLayer(layerName, widgetName, endHandler)

    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")

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

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

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

function FadeHelpPopLayer(layerName, widgetName, endHandler)
	
    local fadeLayer = GetFadeLayerName()
	fadeScreens = fadeScreens-1
    local panelWidget = GUI:getLayer(layerName):getWidget(widgetName)
    local fadeWidget = GUI:getLayer(fadeLayer):getWidget("BlackScreen")

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

    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("FaderHelp", param))
end



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


function GetFadeScreensNumber()
    return fadeScreens;
end

function SetFadeScreensNumber(fadeScreens_)
	fadeScreens = fadeScreens_;
end

--------------

--опции
function SaveOptions(message)
	
	-- Запоминаем опции
	lastMusicVolume = gameInfo:getMusicVolume()
	lastSoundVolume = gameInfo:getSoundVolume()
	lastEnvVolume = gameInfo:getEnvVolume()
	lastFullscreen = gameInfo:isFullScreen()
	lastCustomCursor = gameInfo:isCustomCursor()
	lastShowHints = gameInfo:isHintsEnabled()
	lastRelaxMode = gameInfo:isRelaxMode()

end

function RestoreOptions(message)

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

	gameInfo:setMusicVolume(lastMusicVolume)
	gameInfo:setSoundVolume(lastSoundVolume)
	gameInfo:setEnvVolume(lastEnvVolume)
	gameInfo:setCustomCursor(lastCustomCursor)
	gameInfo:setRelaxMode(lastRelaxMode)
	gameInfo:setHintsEnabled(lastShowHints)
	gameInfo:setFullScreen(lastFullscreen)
	local optionsName = "Options"

	local iBoolean = "0"
	if lastFullscreen then
		iBoolean = "1"
	end
	GUI:getLayer(optionsName):getWidget("Fullscreen"):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))
	
	iBoolean = "0"
	if (lastRelaxMode) then
		iBoolean = "1"
	end
	GUI:getLayer(optionsName):getWidget("RelaxMode"):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("Environment"):AcceptMessage(Message("SetPos", tostring(lastEnvVolume)))

end


function SetOptions(message)

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

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

	state = GUI:getLayer(optionsLayerName):getWidget("Fullscreen"):QueryState(Message("GetState"))

	Sound:SetMusicVolume(musVolume)
	Sound:SetSoundVolume(sndVolume)
	Sound:SetEnvVolume(envVolume)
	gameInfo:setMusicVolume(musVolume)
	gameInfo:setSoundVolume(sndVolume)
	gameInfo:setEnvVolume(envVolume)
	
	if state:getData() == "1" and gameInfo:isFullScreen() == false then
		gameInfo:setFullScreen(true)
		SetFullscreenMode()
	end

	if state:getData() == "0" and gameInfo:isFullScreen() == true then
		gameInfo:setFullScreen(false)
		SetWindowedMode()
	end
	
	state = GUI:getLayer(optionsLayerName):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(optionsLayerName):getWidget("ATips"):QueryState(Message("GetState"))
	if state:getData() == "1" then
		gameInfo:setHintsEnabled(true)
	else
		gameInfo:setHintsEnabled(false)
	end
	
	state = GUI:getLayer(optionsLayerName):getWidget("RelaxMode"):QueryState(Message("GetState"))
	if state:getData() == "1" then
		gameInfo:setRelaxMode(true)
	else
		gameInfo:setRelaxMode(false)
	end

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

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

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

	iBoolean = "0"
	if gameInfo:isHintsEnabled() then
		iBoolean = "1"
	end
	GUI:getLayer(optionsName):getWidget("ATips"):AcceptMessage(Message("SetState", iBoolean))
	
	iBoolean = "0"
	if gameInfo:isCustomCursor() then
		iBoolean = "1"
	end
	GUI:getLayer(optionsName):getWidget("CustomCursor"):AcceptMessage(Message("SetState", iBoolean))
	
	iBoolean = "0"
	if gameInfo:isRelaxMode() then
		iBoolean = "1"
	end
	GUI:getLayer(optionsName):getWidget("RelaxMode"):AcceptMessage(Message("SetState", iBoolean))
	SaveOptions()
end

--обработка сообщений виджета LoadScreen
function LoadScreenFunc(message)
	if message:is("AddFirstPlayer") then
	    --FadePushLayer("FirstNewProfile", "FirstNewProfile", "")
	elseif message:is("StartISpy") then
		local param = VariableSet()
	    param:setString("Layer1", "ISpyField")
	    param:setString("CrossHandler", "FromLoadScreenToISpyCross")
		param:setString("EndHandler" , "ReleaseLoadScreen")
	    kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("CrossToGarden") then
		local param = VariableSet()
		param:setString("Layer1", "Garden")
		param:setString("Layer2", "Shop")
		param:setString("CrossHandler", "FromLoadScreenToGardenCross")
		param:setString("EndHandler", "StartMainMenuPanel")
		kernel:addController(controlFactory:Create("CrossFade", param))		
	elseif message:is("PopSelf") then
		Screen:popLayer()
	end
end

--обработка сообщений виджета MoviePlayerWidget
function MoviePlayerFunc(message)
	if message:is("Stopped") then
	    local nameMovie = message:getData()
		if (nameMovie == "start") then
			
	        local param = VariableSet()
		    param:setString("Layer1", "Garden")
		    param:setString("Layer2", "Shop")
		    param:setString("CrossHandler", "FromMovieToGardenCross")
			param:setString("EndHandler", "EndMult")
		    kernel:addController(controlFactory:Create("MultCrossFade", param))
		elseif nameMovie=="...." then
		    -- ....
		end
	elseif message:is("NoMovie") then
		local param = VariableSet()
		param:setString("Layer1", "Garden")
		param:setString("Layer2", "Shop")
		param:setString("FromMult", "true")
		param:setString("CrossHandler", "FromMovieToGardenCross")
		param:setString("EndHandler", "EndMult")
		kernel:addController(controlFactory:Create("GardenCrossFade", param))
	end
end

function EndMult()
	Sound:FadeOutAllTracks(1.0)
	gameInfo:StartGardenMusic()
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("StartEnterYourName"))
	GUI:getLayer("MoviePlayer"):getWidget("MoviePlayerWidget"):AcceptMessage(Message("ReleaseResource"))
end

function GardenEnterName()
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("StartEnterYourName"))
end

function StartMainMenuPanel()
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("StartMainMenuPanel"))
end

function FromMovieToGardenCross()
	Sound:FadeOutAllTracks(1.0)
	gameInfo:StartGardenMusic()
	gameInfo:AddNewPlayer("test153~123")
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("NoButterfly"))
	InitShopAndGarden()
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("InitMainMenu"))
	SetRainInMainMenu()
	
	LP_SetPosition(Point(132, 277));
	LP_PlayAnim("HandUp1", 0.6, 100, true, false);
	RunIdle(1000, 1, false);
--	gameInfo:StartGardenMusic()
	ReleaseLoadScreen()
end

function FromLoadScreenToGardenCross()
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("InitMainMenu"))
	InitShopAndGarden()
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("InitMainMenu"))
	SetRainInMainMenu()
--	gameInfo:StartGardenMusic()
	ReleaseLoadScreen()
end

function FromLoadScreenToISpyCross()
	GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("UploadLevelResource"))
	GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("RestartLevel"))
	ReleaseLoadScreen()
end

function ReleaseLoadScreen()
	GUI:getLayer("LoadScreen"):getWidget("LoadScreen"):AcceptMessage(Message("Release"));
end

function MenuInGameFunc(message)

	if message:is("Resume", "press") then
		FadePopLayer("MenuInGame", "MenuInGame", "MenuInGameFuncDeactive")
	elseif message:is("Options", "press") then
		SaveOptions()
		FadePushLayer("Options", "Options", "")
		RestoreOptions()
	elseif message:is("MainMenu","press") then
		if (fromGameMenu == false) then
			GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("FromShopToMainMenu"))
			FadePopLayer("MenuInGame", "MenuInGame", "")
			--FadePushLayer("ExitLevel","ExitLevel","")
		else
			FadePushLayer("ExitLevel","ExitLevel","")
			--FadePopLayer("MenuInGame", "MenuInGame", "")
		end
	elseif message:is("Escape") then
		FadePopLayer("MenuInGame", "MenuInGame", "MenuInGameFuncDeactive")
	end
end

function MenuInGameFuncDeactive()
    GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("MenuDeactive"))
end

function ResetPauseTutorial()
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("ResetPauseTutorial"))
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("StartMainMenuPanel"))
end

function ExitLevelFunc(message)
	if message:is("Cancel","press") then
		FadePopLayer("ExitLevel","ExitLevel","")		
	end
	if   message:is("Ok","press") then
		
		local param = VariableSet()
	    param:setString("Layer1", "Garden")
	    param:setString("Layer2", "Shop")
		param:setString("StartHandler", "StopFonSound")
	    param:setString("CrossHandler", "FromISpyToGardenCross")
		param:setString("EndHandler", "ResetPauseTutorial")
	    kernel:addController(controlFactory:Create("GardenCrossFade", param))

		fromGameMenu  = false		
	end
end

function StopFonSound()
	GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("StopFonSound"))
end


function OptionsFunc(message)
	if message:is("Ok", "press") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
		SetOptions()
		FadePopLayer("Options", "Options")
	elseif message:is("Cancel", "press") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
		FadePopLayer("Options", "Options")
		RestoreOptions()	
	elseif message:is("Music") then
		local musicVolume = message:getIntegerParam()
		gameInfo:setMusicVolume(musicVolume)
		Sound:SetMusicVolume(musicVolume)
	elseif message:is("Credits", "press") then
		Screen:SaveLayers()
		local param = VariableSet()
	    param:setString("Layer1", "Credits")
	    param:setString("CrossHandler", "UploadCredits")
	    kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is("Sound") then
		local soundVolume = message:getIntegerParam()
		gameInfo:setSoundVolume(soundVolume)
		Sound:SetSoundVolume(soundVolume)
	elseif message:is("Environment") then
		local envVolume = message:getIntegerParam()
		gameInfo:setEnvVolume(envVolume)
		Sound:SetEnvVolume(envVolume)
	end
end

--запустить требуемый мультик (либо снять с паузы)
function MoviePlayerPlay(name_movie)
	Sound:FadeOutAllTracks(1.0)
	Sound:FadeInTrack("MultFon", 1, false);
	if not name_movie then
	    name_movie = ""
	end
    GUI:getLayer("MoviePlayer"):getWidget("MoviePlayerWidget"):AcceptMessage(Message("Play", name_movie))
end

function LoadEntranceMovie()
	ReleaseGardenResource()
    MoviePlayerPlay("start")
--	GUI:getLayer("MoviePlayer"):getWidget("MoviePlayerWidget"):AcceptMessage(Message("Pause"))
end


function FirstNewProfileFunc(message)
    if message:is("Ok", "press") then
		local profileName = GUI:getLayer("FirstNewProfile"):getWidget("Name"):QueryState(Message("Text")):getData()
		if not (profileName == "") then
			if gameInfo:isPlayerExist(profileName) then
              	GUI:getLayer("FirstNewProfile"):getWidget("InfoText"):AcceptMessage(Message("SetText", "ExistPlayer"))
			else 
				local namesWidget = GUI:getLayer("Profiles"):getWidget("Names")
				namesWidget:AcceptMessage(Message("Add", profileName))
				namesWidget:AcceptMessage(Message("Set", profileName))
				gameInfo:AddNewPlayer(profileName)
				gameInfo:DeletePlayer("test153~123")
				MyFadePopLayer("FirstNewProfile", "FirstNewProfile", "StartChooseMode")
			end
		end
    end
end

function StartChooseMode()
	MyFadePushLayer("ChooseMode", "ChooseMode")
end

function EndChooseMode()
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("StartInitShop"));
	
	StartMainMenuPanel();
	FadePopLayer("ChooseMode", "ChooseMode")
	GUI:getLayer("LoadScreen"):getWidget("LoadScreen"):AcceptMessage(Message("Continue"))
				
	LP_FastFinishCurrentBehav()
	LP_PlayAnim("Tutorial2", 0.7, 1, true, true);
	AddTalkWindowToLastAction(0.5, "HelloNewPlayer", 6.0); 
	
	GreetingAction();
end

function ChooseModeFunc(message)
	if (message:is("Relax", "press")) then
		GUI:getLayer("Options"):getWidget("RelaxMode"):AcceptMessage(Message("SetState", "1"))
		gameInfo:setRelaxMode(true)
		EndChooseMode()
	elseif (message:is("Timed", "press")) then
		GUI:getLayer("Options"):getWidget("RelaxMode"):AcceptMessage(Message("SetState", "0"))
		gameInfo:setRelaxMode(false)
		EndChooseMode()
	end
end;

function DogNameFunc(message)
    if message:is("Ok", "press") then
		local dogName = GUI:getLayer("DogName"):getWidget("Name"):QueryState(Message("Text")):getData()
		if not (dogName == "") then
			Dog_SetName(dogName);
			FadePopLayer("DogName", "DogName")
			GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("EndTutorial"))
            GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
			LP_StartScriptAction();
			LP_PlayAnim("Tutorial4", 1.0, 1, true, false);
			AddTalkWindowToLastAction(0.5, "AboutDogName", 7.0); 
			LP_PlayAnim("Stay1", 0.3, 100, true, false);
			local mes = Message("StayWithDog");
			mes:getVariables():setPoint("posDog1", Point(186, 286));
			mes:getVariables():setPoint("posDog2", Point(186, 286));			
			LP_AddMessageToLastAction(mes, 1.5);
		end
    end
end


function ChangeDogNameFunc(message)
    if message:is("Ok", "press") then
		local dogName = GUI:getLayer("ChangeDogName"):getWidget("Name"):QueryState(Message("Text")):getData()
		if not (dogName == "") then
			Dog_SetName(dogName);
			FadePopLayer("ChangeDogName", "ChangeDogName")
            GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
		end
	elseif message:is("Cancel", "press") then
		FadePopLayer("ChangeDogName", "ChangeDogName")
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
    end
	OstinAboutChangeDogName();
end

function NewProfileFunc(message)
	if message:is ("Ok", "press") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage (Message("StopMusic"))
		GUI:getLayer("FirstNewProfile"):getWidget("Name"):AcceptMessage(Message("Clear"))
		GUI:getLayer("FirstNewProfile"):getWidget("InfoText"):AcceptMessage(Message("SetText", "MaxProfileSize" ))
		local param = VariableSet()
	   	param:setString("Layer1", "MoviePlayer")
      	param:setString("CrossHandler", "LoadEntranceMovie")
	    kernel:addController(controlFactory:Create("CrossFade", param))
	elseif message:is ("Cancel", "press") then
		FadePopLayer("NewProfile", "NewProfile")
	end
end

function ProfilesFunc(message)
	if message:is("New", "press") then
		FadePushLayer("NewProfile", "NewProfile")
	elseif message:is("Select", "press") or message:is("Names", "DoubleClick") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("SaveGarden"))
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
		local state = GUI:getLayer("Profiles"):getWidget("Names"):QueryState(Message("CurrentItem"))
		local playerName = state:getData()
		gameInfo:setActivePlayer(playerName)
		gameInfo:ContinueSavedGame()
		UploadGardenResource();
		FadePopLayer("Profiles", "Profiles")

	elseif message:is("B_Up", "press") then
		local namesWidget = GUI:getLayer("Profiles"):getWidget("Names")
		namesWidget:AcceptMessage(Message("ScrollUp"))

	elseif message:is("B_Down", "press") then
		local namesWidget = GUI:getLayer("Profiles"):getWidget("Names")
		namesWidget:AcceptMessage(Message("ScrollDown"))

	elseif message:is("Cancel", "press") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
		FadePopLayer("Profiles", "Profiles")

	elseif message:is("Delete", "press") then
		local state = GUI:getLayer("Profiles"):getWidget("Names"):QueryState(Message("CurrentItem"))
		local playerName = state:getData()
		if gameInfo:getName() == playerName then
			FadePushLayer("ActiveNoDelete", "ActiveNoDelete")
		else
			FadePushLayer("DeletePlayerConfirm","DeletePlayerConfirm")
		end
	end
end

function LastNoDeleteFunc(message)
	if message:is("Ok", "press") then
		local panelWidget = GUI:getLayer("LastNoDelete"):getWidget("LastNoDelete")
		local fadeWidget = GUI:getLayer("LastNoDeleteFade"):getWidget("BlackScreen")

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

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

	end
end

function ActiveNoDeleteFunc(message)
	if message:is("Ok", "press") then
	
		FadePopLayer("ActiveNoDelete","ActiveNoDelete")

	end
end

function DeletePlayerConfirmFunc(message)

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

		FadePopLayer("DeletePlayerConfirm", "DeletePlayerConfirm")

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

		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", "DeletePlayerConfirm")
	end
end

function ExitGameWithSSFunc(message)

	if message:is("Cancel", "press") then
		FadePopLayer("ExitGameWithSS", "ExitGameWithSS","")
	elseif message:is("Ok", "press") then
		state = GUI:getLayer("ExitGameWithSS"):getWidget("EnableScreensaver"):QueryState(Message("GetState"))
		if state:getData() == "1" then 
			gameInfo:setEnableSS(true)
		else
			gameInfo:setLocalInt("SetSS", 0);
			gameInfo:setEnableSS(false)
		end	
		CloseApplication()
	end
end

function ExitGameFunc(message)
	if message:is("Cancel", "press") then
		FadePopLayer("ExitGame", "ExitGame","")
	elseif message:is("Ok", "press") then
		CloseApplication()
	end
end

function ResetFadeScreens()
	fadeScreens = 0
end

function FromMarketToISpy()
	Sound:FadeOutAllTracks(1.0)
	ReleaseGardenResource()
	StartRainInISpy();
	GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage (Message("CreateScreenShot"))
	GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("UploadLevelResource"))
	GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("RestartLevel"))
	
	Log_WriteMessage("StartISpy, "..GetFileLevel(gameInfo:getLocalIntOrDef("GardenLevelNumber", 0), true));
end

function UpdateMarketCash()
	GUI:getLayer("Market"):getWidget("Market"):AcceptMessage(Message("UpdateCash"))
end

function InitShopAndGarden()
	UploadGardenResource()

	GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage (Message("InitGarden"))
	GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage (Message("InitShop"))
	SetRainInGarden()
	--StartPersonAction()
end

function SetRainInMainMenu()
	SetEnableRain(false);
end

function SetRainInGarden()
	local level = gameInfo:getLocalIntOrDef("GardenLevelNumber", 0);
	local prevStrenght = gameInfo:getLocalFloatOrDef("GardenRain", 0);		
	local firstStrangeRain = gameInfo:getLocalIntOrDef("firstStrangeRain", 1);
	local FirstRain = gameInfo:getLocalBoolOrDef("FirstRain", true);
	
	if (prevStrenght > 0.5) then 
		LP_SetPosition(Point(266, 514))
		RunIdle(3, -1, false);
	end;
	
	if (not gameInfo:HintWasShowed("GardenPressDesignTutorial")) then
		SetEnableRain(false);
	elseif startRain and ((FirstRain) or (Random("RainRandom", 1, 8)<4)) then 
		gameInfo:setLocalBool("FirstRain", false);
		SetEnableRain(true);
		local now 
		if math.random(0, 1) == 0 then now = false else now = true; end;
		StartRain(now, 20*math.random(1, 10), math.random(1, 9)/10, 0.2, 1)
	elseif (startRain == false) then
		if (prevStrenght > 0) then 
			SetEnableRain(true);
			StartRain(true, 15, 0.95, prevStrenght, prevStrenght)
		else
			SetEnableRain(false);
		end;
	else
		SetEnableRain(false);
	end;

end

function StartRainInISpy()
	local firstStrangeRainInIspy = gameInfo:getLocalIntOrDef("firstStrangeRainInIspy", 1);
	local level = gameInfo:getLocalIntOrDef("GardenLevelNumber",0)
	local prevStrenght = gameInfo:getLocalFloatOrDef("GardenRain", 0);		
	if (prevStrenght > 0) then 
		gameInfo:setLocalBool("EnableRain", true);
		gameInfo:setLocalFloat("MaxRainStrength", 3);
		gameInfo:setLocalFloat("PauseBefor", 0);
		gameInfo:setLocalFloat("ISpyRainTime", 1000);
	else
		gameInfo:setLocalBool("EnableRain", false);
	end;
end

function ISpyFieldFunc(message)
	if message:is("LevelComplete") then
--	        local param = VariableSet()
--	        param:setString("Layer1", "ISpyField")
--	        param:setString("CrossHandler", "FromMarkeyToISpy")
--	        kernel:addController(controlFactory:Create("CrossFade", param))

	        local param = VariableSet()
	        param:setString("Layer1", "Garden")
	        param:setString("Layer2", "Shop")
			param:setString("StartHandler", "StopFonSound")
	        param:setString("CrossHandler", "FromISpyToGardenCross")
			param:setString("EndHandler", "ResetPauseTutorial")
	        kernel:addController(controlFactory:Create("GardenCrossFade", param))
	elseif message:is("HINT_BUTTON","press") then
		GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("ShowHint"))	
	elseif message:is("ISpyHint","press") then	
		local numLevel = gameInfo:getLocalIntOrDef("GardenLevelNumber",0)		
		local mode = 1;
		if (gameInfo:getBool("OldLevelSystem")) then
			mode = GetISpyMode(numLevel)				
		else	
			mode = GetISpyMode(numLevel)
		end
		if (gameInfo:isRelaxMode()) then
			if (mode == 1) then
				GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("HelpMode"));
				GUI:getLayer("HelpFadeISpyRelax"):getWidget("HelpFade"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyRelax"):getWidget("HelpFade2"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyRelax"):getWidget("HelpFade3"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyRelax"):getWidget("HelpFade4"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyRelax"):getWidget("HelpFade5"):AcceptMessage(Message("Init"))
				FadeHelpPushLayer("HelpFadeISpyRelax","HelpFade")		
			else			
				GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("HelpMode"));
				GUI:getLayer("HelpFadeISpyRelaxCollector"):getWidget("HelpFade"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyRelaxCollector"):getWidget("HelpFade2"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyRelaxCollector"):getWidget("HelpFade3"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyRelaxCollector"):getWidget("HelpFade4"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyRelaxCollector"):getWidget("HelpFade5"):AcceptMessage(Message("Init"))
				FadeHelpPushLayer("HelpFadeISpyRelaxCollector","HelpFade")		
			end
		else 
			if (mode == 1) then
				GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("HelpMode"));
				GUI:getLayer("HelpFadeISpy"):getWidget("HelpFade"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpy"):getWidget("HelpFade1"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpy"):getWidget("HelpFade2"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpy"):getWidget("HelpFade3"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpy"):getWidget("HelpFade4"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpy"):getWidget("HelpFade5"):AcceptMessage(Message("Init"))
				FadeHelpPushLayer("HelpFadeISpy","HelpFade")		
			else 
				GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("HelpMode"));
				GUI:getLayer("HelpFadeISpyCollector"):getWidget("HelpFade"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyCollector"):getWidget("HelpFade1"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyCollector"):getWidget("HelpFade2"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyCollector"):getWidget("HelpFade3"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyCollector"):getWidget("HelpFade4"):AcceptMessage(Message("Init"))
				GUI:getLayer("HelpFadeISpyCollector"):getWidget("HelpFade5"):AcceptMessage(Message("Init"))
				FadeHelpPushLayer("HelpFadeISpyCollector","HelpFade")		
			end
		end
		if (mode == 1) then
		-- скрыть те слои хелпа которые не нужны
		end
	
	elseif message:is("StatOk", "press") then
		GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("EndStat"))		
	elseif message:is("ISpyGameMenu","press") then
		fromGameMenu = true
		FadePushLayer("MenuInGame","MenuInGame","")
		GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("MenuActive"))
	end
end

function FromISpyToGardenCross()
	Sound:FadeOutAllTracks(1.0)
	GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("ReleaseLevelResource"))
	InitShopAndGarden()
	gameInfo:StartGardenMusic()
	gameInfo:Save()
	Log_WriteMessage("StartGarden, level "..gameInfo:getLocalIntOrDef("GardenLevelNumber", 0));
end

function FromISpyToCreditsCross()
	Sound:FadeOutAllTracks(1.0)
	GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("ReleaseLevelResource"))
	Sound:FadeInTrack("Garden3", 2.0, true);
end

function UploadCredits()
	UploadResourceGroup("Credits");
	Sound:FadeOutAllTracks(1.0)
	GUI:getLayer("Credits"):getWidget("Credits"):AcceptMessage(Message("Reset"))
	Sound:FadeInTrackContinue("Garden3", 2.0, true)
end

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

function ExitCreditsCross()
	Sound:FadeOutAllTracks(1.0)
	ReleaseResourceGroup("Credits");
	GUI:getLayer("Credits"):getWidget("Credits"):AcceptMessage(Message("Restore"))
	Screen:RestoreLayers()
	if (fromGameMenu) then
		gameInfo:StartISpyMusic()
	else
		gameInfo:StartGardenMusic()
	end
end

--
function ISpyLevelBegin()
	Sound:PlaySample("level_begin")
end

function ShowProfiles()
	GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("HelpMode"))
	FadePushLayer("Profiles","Profiles","")			
end


function ShopFunc (message)
	if message:is("Start", "press") then 
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage (Message("StopMusic"))
		Sound:FadeOutNoMusic(1.0);
		LP_SetNotShowPhraseTime(1.0)
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("StartFade"))
		local param = VariableSet()
		param:setString("Layer1", "ISpyField")
		param:setString("CrossHandler", "FromMarketToISpy")
		param:setString("EndHandler","ISpyLevelBegin")
		kernel:addController(controlFactory:Create("HouseCrossFade", param))
	elseif message:is("SkipMult", "press") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage (Message("LP_EndMultMode"))
	elseif message:is("Eye", "press") then 
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage (Message("StartEyeMode"))
	elseif message:is("Menu", "press") then
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("FromShopToMainMenu"))
--		FadePushLayer("MenuInGame", "MenuInGame", "");
	elseif message:is("Design", "press") then 
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage (Message("StartDesignMode"))
	elseif message:is("DesignClose", "press") then
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage (Message("EndDesignMode"))
	elseif message:is("DesignLeft", "press") then
	elseif message:is("DesignRight", "press") then
	elseif message:is("MainMenuStart", "press") then
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("FromMainMenuToShop"))
	elseif message:is("MainMenuOptions", "press") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("HelpMode"))
		fromGameMenu = false;
		SaveOptions()
		FadePushLayer("Options", "Options", "")
		RestoreOptions()
	elseif message:is("Exit","press") then
		if gameInfo:enableScreenSaver() then
			FadePushLayer("ExitGame", "ExitGame")
		else 
			local ssMode = gameInfo:getLocalIntOrDef("SetSS", 1);
			GUI:getLayer("ExitGameWithSS"):getWidget("EnableScreensaver"):AcceptMessage(Message("SetState", ""..ssMode))
			FadePushLayer("ExitGameWithSS", "ExitGameWithSS")
		end
	elseif message:is("MainMenuScreensavers","press") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("HelpMode"))
		FadePushLayer("ScreenSaverOptions","ScreenSaverOptions","")
	elseif message:is("StartTrainWindow") then
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("StartTrainWindow"))
	elseif message:is("Skip", "press") then
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("SkipPhrase"))
    elseif message:is("Train-Skip", "press") then
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("SkipDialog"))
	elseif message:is("Back", "press") then
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("HideBackPanel"))
	elseif message:is("AddNewPlayer") then
	    --GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
	--	FadePushLayer("NewProfile", "NewProfile")
        --GUI:getLayer("NewProfile"):getWidget("Cancel"):AcceptMessage(Message("Activ", "0"))
	elseif message:is("AddFirstPlayer") then
		FadePushLayer("FirstNewProfile", "FirstNewProfile", "")
	elseif message:is("LetterClose","press") then
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("CloseLetter"))
	elseif message:is("Hint","press") then
		local mesFromShop = GUI:getLayer("Shop"):getWidget("Shop"):QueryState(Message("GetState"))
		if mesFromShop:getIntegerParam() == 1 then --мы в режиме магазина
			GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("HelpMode"));	
			GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("HelpMode"));
			--GUI:getLayer("HelpFadeShop"):getWidget("Cancel"):AcceptMessage(Message("GOINDOWN"))
			GUI:getLayer("HelpFadeShop"):getWidget("HelpFade"):AcceptMessage(Message("Init"))
			GUI:getLayer("HelpFadeShop"):getWidget("HelpFade1"):AcceptMessage(Message("Init"))
			GUI:getLayer("HelpFadeShop"):getWidget("HelpFade2"):AcceptMessage(Message("Init"))
			GUI:getLayer("HelpFadeShop"):getWidget("HelpFade3"):AcceptMessage(Message("Init"))
			GUI:getLayer("HelpFadeShop"):getWidget("HelpFade4"):AcceptMessage(Message("Init"))
			FadeHelpPushLayer("HelpFadeShop","HelpFade")
		end
		if mesFromShop:getIntegerParam() == 2 then --мы в режиме дизайна
			--GUI:getLayer("HelpFadeDesign"):getWidget("Cancel"):AcceptMessage(Message("GOINDOWN"))
			GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("HelpMode"));	
			GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("HelpMode"));
			--GUI:getLayer("HelpFadeDesign"):getWidget("HelpFade"):AcceptMessage(Message("Init"))
			GUI:getLayer("HelpFadeDesign"):getWidget("HelpFade"):AcceptMessage(Message("Init"))
			GUI:getLayer("HelpFadeDesign"):getWidget("HelpFade1"):AcceptMessage(Message("Init"))
			GUI:getLayer("HelpFadeDesign"):getWidget("HelpFade2"):AcceptMessage(Message("Init"))
			GUI:getLayer("HelpFadeDesign"):getWidget("HelpFade3"):AcceptMessage(Message("Init"))
			GUI:getLayer("HelpFadeDesign"):getWidget("HelpFade4"):AcceptMessage(Message("Init"))
			FadeHelpPushLayer("HelpFadeDesign","HelpFade")
		end
	elseif message:is("PushDogName") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("HelpMode"))
		GUI:getLayer("DogName"):getWidget("Name"):AcceptMessage(Message("Clear"))
		FadePushLayer("DogName", "DogName")		
	elseif message:is("DesignDog", "press") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("HelpMode"))
		GUI:getLayer("ChangeDogName"):getWidget("Name"):AcceptMessage(Message("Clear"))
		FadePushLayer("ChangeDogName", "ChangeDogName")	
	elseif message:is("ExitScreenSaverPreview") then
		local param = VariableSet()
		param:setString("Layer1", "Garden")
		param:setString("Layer2", "Shop")
		param:setString("CrossHandler", "EndScreenSaverMode")
		param:setString("EndHandler", "AddScreenSaverPanelOnScreen")
		kernel:addController(controlFactory:Create("CrossFade", param))		
	end
end

function AddScreenSaverPanelOnScreen()
	FadePushLayer("ScreenSaverOptions","ScreenSaverOptions","");
end

pressMainMenu = false

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
      showTrain = true
      showPrevWindow = false
      prevTrainWindow = Screen:getMainLayerName()
      GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("TrainSkipPressed"))
   elseif message:is("SkipTrainYes", "press") then
      showTrain = false
      showPrevWindow = false
      GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("TrainSkip"))
   elseif message:is("SkipTrainNo", "press") then
      showTrain = false
      showPrevWindow = true
      GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("TrainNoSkip"))
   elseif message:is("KillMe") then
      local nameWidget = GetWidgetNameUnderTrain();
      Screen:popLayer()
      if (showTrain) then
		  ShowTrainWindow("Train-Skip")
		  showTrain = false
		  showPrevWindow = true
	  elseif (showPrevWindow) then
		  showPrevWindow = false
		  ShowTrainWindow(prevTrainWindow)
	  elseif (skipWithoutButton) then
		  showPrevWindow = false
		  GUI:getLayer(Screen:getMainLayerName()):getWidget(nameWidget):AcceptMessage(Message("SkipWithoutButton"))
		  if (pressMainMenu) then
		    ISpyFieldFunc(Message("ISpyGameMenu","press"))
		  end;
	  else 
		  showPrevWindow = false
		  GUI:getLayer(Screen:getMainLayerName()):getWidget(nameWidget):AcceptMessage(Message("KillTrainWindow"))
      end
      pressMainMenu = false;
      skipWithoutButton = false;
   elseif message:is("TrainYes", "press") then
      GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
   elseif message:is("TrainNo", "press") then
      showTrain = true
      showPrevWindow = false
      prevTrainWindow = Screen:getMainLayerName()
      GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("TrainSkipPressed"))
   elseif message:is("SkipWithoutButton") then
	  skipWithoutButton = true;
	  GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
   elseif message:is("Start", "press") then 
	  Sound:FadeOutNoMusic(1.0);
	  GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage (Message("StopMusic"))
      GUI:getLayer(Screen:getMainLayerName()):getWidget("TrainWindow"):AcceptMessage(Message("Hide"))
      GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("ToLittlePeople_EndTutorial"))
      LP_SetNotShowPhraseTime(1.0)
      local param = VariableSet()
      param:setString("Layer1", "ISpyField")
      param:setString("CrossHandler", "FromMarketToISpy")
      param:setString("EndHandler","ISpyLevelBegin")
      kernel:addController(controlFactory:Create("HouseCrossFade", param))
   elseif message:is("Design", "press") then 
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage (Message("StartDesignMode"))
	elseif message:is("ISpyGameMenu","press") then
		--перенаправим действие туда, куда оно должно было идти
		if (skipWithoutButton) then
		    pressMainMenu = true;
		else
		    ISpyFieldFunc(message)
		end;
	elseif message:is("AddNewPlayer") then
		FadePushLayer("FirstNewProfile", "FirstNewProfile")
	elseif message:is("PushDogName") then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("HelpMode"))
		GUI:getLayer("DogName"):getWidget("Name"):AcceptMessage(Message("Clear"))
		FadePushLayer("DogName", "DogName")		
	elseif message:is("HINT_BUTTON","press") then
		GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("ShowHint"))	
	elseif message:is("DesignClose", "press") then
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage (Message("EndDesignMode"))
	end
end

function DialogWindowFunc(message)
   if message:is("Skip", "press") then
      GUI:getLayer(Screen:getMainLayerName()):getWidget("Garden"):AcceptMessage(Message("SkipPhrase"))
   elseif message:is("Train-Skip", "press") then
   elseif message:is("KillMe") then
      Screen:popLayer()
   end
end

-- Какую сумму денег получает игрок, при быстром нахождении предмета
-- count - который раз подряд игрок находит предмет
function sequenceRapidlyFinding(count)
	if count > 0 then
		return 5+5*count
	end
	return 0
end

function GetCustomerAtLevel(level)
	local N = 0
	if (level == 0) then N = 10 
	elseif (gameInfo:getGardenIter() == 1) then N = 15
	else N = 20
	end;
	if gameInfo:getLocalIntOrDef("Store", 0) == 1 then 
		if N == 15 then N = 10 else N = 15 end;
	end;
	return N
end

function GetISpyMode(level)
	if (gameInfo:getBool("OldLevelSystem")) then
		if (math.mod(level, cycleRepeatMode2) == 0 and (level > 1)) then
			return 2
		else
			return 1
		end
	else
		return gameInfo:getLocalIntOrDef("ISpyMode", 1);
	end
end

function GetCustomerAtScreen(level)
	if (true) then
		return 5;
	end
	if (level < 4) then
	    return 3
	elseif (level < 7) then
	    return 4
	else
	    return 5
	end;
end;


function GetISpyLevelName(level, mode)

--	return gameInfo:getISpyLevelName(level, mode);

	levelMapMode1 = {	
		"bar.xml",
		"bar(2).xml",
		"blue_hall.xml",
		"blue_hall(2).xml",
		"bathroom2.xml",
		"bathroom2(2).xml",
		"garage2.xml",
		"garage2(2).xml",
		"hall2.xml",
		"hall2(2).xml",
		"bedroom2.xml",
		"bedroom2(2).xml",
		"child room.xml",
		"child room(2).xml",
		"china2.xml",
		"china2(2).xml",
		"drawing room.xml",
		"drawing room(2).xml",
		"garret2.xml",
		"garret2(2).xml",
		"kitchen.xml",
		"kitchen(2).xml",
		"kladovaya.xml",
		"kladovaya(2).xml",
		"office.xml",
		"office(2).xml",
		"veranda.xml",
		"veranda(2).xml",
		"veranda2.xml",
		"veranda2(2).xml"
		}
		
	levelMapMode2 = {
	--	"Bar20",
		"Hall20",
		"Bedroom20",
		"Childroom20",
		"China20",
		"Garret20",
		"Office20",
--		"Kitchen20",
--		"Drawingroom20",
--		"Kladovaya20"
--		"Blue_hall20"
--		 "Bathroom20"
--		"Garage20",
--		"Veranda20",
		"Veranda2_20"

	    
	}
	countMode1 = 1
	while levelMapMode1[countMode1] do countMode1 = countMode1+1 end countMode1 = countMode1-1
	countMode2 = 1
	while levelMapMode2[countMode2] do countMode2 = countMode2+1 end countMode2 = countMode2-1
	
	if mode == 1 then
        return levelMapMode1[math.mod(level - math.floor(level/cycleRepeatMode2), countMode1)+1]
	elseif mode == 2 then
	    if countMode2 > 1 then
			-- надо еще правильлно подобрать функцию подстановки, чтобы второй режим правильно повторялся
			return levelMapMode2[math.mod(level, countMode2)+1]
		else
		    return levelMapMode2[1]
		end
	end
	return ""

end



function GetISpyLevelMap(level, mode)

--	return gameInfo:getISpyLevelName(level, mode);

	levelMapMode1 = {	
		"levels/bar.xml",
		"levels/bar(2).xml",
		"levels/blue_hall.xml",
		"levels/blue_hall(2).xml",
		"levels/bathroom2.xml",
		"levels/bathroom2(2).xml",
		"levels/garage2.xml",
		"levels/garage2(2).xml",
		"levels/hall2.xml",
		"levels/hall2(2).xml",
		"levels/bedroom2.xml",
		"levels/bedroom2(2).xml",
		"levels/child room.xml",
		"levels/child room(2).xml",
		"levels/china2.xml",
		"levels/china2(2).xml",
		"levels/drawing room.xml",
		"levels/drawing room(2).xml",
		"levels/garret2.xml",
		"levels/garret2(2).xml",
		
		"levels/kitchen.xml",
		"levels/kitchen(2).xml",	

		"levels/kladovaya.xml",
		"levels/kladovaya(2).xml",
		"levels/office.xml",
		"levels/office(2).xml",
		"levels/veranda.xml",
		"levels/veranda(2).xml",
		"levels/veranda2.xml",
		"levels/veranda2(2).xml"
		}
		
	levelMapMode2 = {
--			"levels/bar20.xml",
			"levels/blue_hall20.xml",
			"levels/hall220.xml",
			"levels/bedroom2_20.xml",
--			"levels/child room20.xml",
--			"levels/china2_20.xml",
--			"levels/garret20.xml",
--			"levels/office20.xml",
--			"levels/kitchen20.xml",
--			"levels/drawing room20.xml",
			"levels/kladovaya20.xml",
			"levels/blue_hall20.xml",
			"levels/bathroom2_20.xml",
--			"levels/garage2_20.xml",
			"levels/veranda20.xml",
			"levels/veranda220.xml",
	    "levels/veranda220.xml"	    
	}
	countMode1 = 1
	while levelMapMode1[countMode1] do countMode1 = countMode1+1 end countMode1 = countMode1-1
	countMode2 = 1
	while levelMapMode2[countMode2] do countMode2 = countMode2+1 end countMode2 = countMode2-1
	
	if mode == 1 then
        return levelMapMode1[math.mod(level - math.floor(level/cycleRepeatMode2), countMode1)+1]
	elseif (mode == 2) then
	    if countMode2 > 1 then
			-- надо еще правильлно подобрать функцию подстановки, чтобы второй режим правильно повторялся
			return levelMapMode2[math.mod(level, countMode2)+1]
		else
		    return levelMapMode2[1]
		end
	end
	return ""

end


--возращает сколько должно быть пукупателей, которые запросят не предмет, а категорию предметов (например: игрушку)
function GetCategoricalCustomer(level)
	return 7
end

--возварщает количество подсказок на уровне
function GetPhotoHint(level)

	if (level >= gameInfo:getFeatureIntParam("PhotoHint", "fromLevel")) then
		if (level == 3) then
			return 2;
		elseif (level >= 4) and (level <= 7) then 
			return 1
		elseif (level > 7) and (level <= 15) then
			return 2
		elseif (level > 15) then
			return math.random(0, 2)
		else
			return 0
		end;
	else
		return 0;
	end
end

function GetTermoHint(level)

	if (level >= gameInfo:getFeatureIntParam("TermoHint", "fromLevel")) then
		if (level == 5) then 
			return 2;
		elseif (level >= 6) and (level <= 10) then 
			return 1
		elseif (level > 10) and (level <= 20) then
			return 2
		elseif (level > 20) then
			return math.random(0, 2)
		else
			return 0
		end;
	else
		return 0;
	end
end

----------------------------------------------------------------------------------------
-- получить имя файла или имя уровня (в зависимости от name)
function GetFileLevel(level, file)
	if (gameInfo:getLocalIntOrDef("ISpyMode", 1) == 2) then
		return gameInfo:GetColNameLevel(file)
	else
		return gameInfo:GetNameLevel(level, file);
	end
end

function GetLevelComplex(level, RelaxMode)
	local min = 1.0
	local max = 1.0
	local LevelTime = gameInfo:getLocalIntOrDef("LevelTime", 500) -- время установленное на уровень
	local passTime = gameInfo:getLocalIntOrDef("passTime", 100) -- сколько потратили на уровень
	local remainingTime = LevelTime - passTime;
	local remainingCustomers = gameInfo:getLocalIntOrDef("remainingCustomers", 0)
	
	local TotalISpyTime = gameInfo:getLocalIntOrDef("TotalISpyTime", 0)	
	
	local d = gameInfo:getLocalIntOrDef("Difficulty", 0);
	
	if (remainingTime > 0.25*LevelTime and remainingCustomers < 5 and not RelaxMode) then 
		if TotalISpyTime < 600 then
			d = Div(math.sqrt(level*0.0085)*100, 10)*10
		elseif TotalISpyTime < 2000 then
			d = Div(math.sqrt(level*0.015)*100, 10)*10
		else
			d = Div(math.sqrt(level*0.035)*100, 10)*10
		end;
		if d > 100 then d = 100; end;
		gameInfo:setLocalInt("Difficulty", d)
	elseif RelaxMode then 
		if TotalISpyTime < 600 then
			d = Div(math.sqrt(level*0.0085)*100, 10)*10
		elseif TotalISpyTime < 2000 then
			d = Div(math.sqrt(level*0.015)*100, 10)*10
		else
			d = Div(math.sqrt(level*0.035)*100, 10)*10
		end;
		if d > 100 then d = 100; end;
		gameInfo:setLocalInt("Difficulty", d)
	else
		gameInfo:setLocalInt("Difficulty", 0)
	end;
	
	
	if d < 15 then 
		min = 0.8; max = 1; 
	elseif d < 30 then 
		min = 0.5; max = 1; 
	elseif d < 50 then 
		min = 0.25; max = 0.75
	elseif d < 75 then 
		min = 0.5; max = 1;
	else 
		min = 0; max = 1; 
	end;
	
	varset = VariableSet();
	varset:setFloat("complexMin", min);
	varset:setFloat("complexMax", max);
	return varset;
end

function getBasePrice(d)
	local p
	if d <= 30 then 
		p = 5;
	elseif d <= 50 then 
		p = 7;
	elseif d <= 70 then 
		p = 10 
	else
		p = 15
	end;
	return p
end;

--возвращает все параметры зависящие от номера уровня
function GetISpyParameters(level)

	local result = VariableSet()
	local fileLevel = ""
	local mode = 1
	local RelaxMode = gameInfo:isRelaxMode();
	
	if (gameInfo:getBool("OldLevelSystem")) then
		mode = GetISpyMode(level)
		fileLevel = GetISpyLevelMap(level, mode)
		nameLevel = GetISpyLevelName(level, mode)	
	else
		fileLevel = GetFileLevel(level, true)
		nameLevel = GetFileLevel(level, false)
		mode = GetISpyMode(level)
	end

	result:setInt("mode", mode)

	--количество покупателей на уровне и на экране
 	local customerAtScreen = 1
	local customerAtLevel  = 1
	if mode == 1 then
	    customerAtLevel  = GetCustomerAtLevel(level)
	    customerAtScreen = GetCustomerAtScreen(level)
	end;

	result:setInt("customerAtScreen", customerAtScreen)
	result:setInt("customerAtLevel", customerAtLevel)
	result:setString("levelMap", fileLevel)
	result:setString("levelName", nameLevel)

	--сколько должно быть "различных" покупателей
	local cat = 0;
	local gro = 0;
	local cat_gro = 0;

	if (level <=3) then
		cat = 0;
		gro = 0;
		cat_gro = 0;
	elseif ((level > 3) and (level < 7)) then
		if (math.mod(level, 2) == 0) then
			cat = math.random(0, 1);
			gro = math.random(0, 1);
			cat_gro = 0;
		end
	elseif (level <= 12) then
		cat = math.random(0, 1);
		gro = math.random(0, 1);
		cat_gro = math.random(0, 1);
	else 
		cat = math.random(1, 2);
		gro = math.random(1, 2);
		cat_gro = math.random(1, 2);
	end;

	result:setInt("categoricalCustomer", cat )
	result:setInt("groupCustomer", gro )
	result:setInt("groupCategoricalCustomer", cat_gro )

	--сложность прохождения
	local complex = GetLevelComplex(level, RelaxMode);
	result:setFloat("complexMin", complex:getFloat("complexMin"))
	result:setFloat("complexMax", complex:getFloat("complexMax"))
	
	--количество подсказок в уровне
	result:setInt("countPhotoHint", mode==1 and GetPhotoHint(level) or 0 )  --C++ аналог: "mode==1 ? GetPhotoHint(level) : 0"
	result:setInt("countTermoHint", mode==1 and GetTermoHint(level) or 0 )
	
	--количество монеток в уровне
	local coins = 0;
	if (level >= 2) then
		coins = math.random(5, 7);
		--coins = 10;
	end
	result:setInt("countCoins", coins )
	-- значение времени в уровне. В секундах
	local passTime = gameInfo:getLocalIntOrDef("passTime", 100) -- сколько потратили на уровень
	local timeOnPrevLevel = gameInfo:getLocalIntOrDef("OldLevelTime", 500) -- сколько времени было отведено на предыдущий уровень
	local remainingTime = timeOnPrevLevel - passTime;
	local t = 0
	local h = 0
	if not RelaxMode then 
		-- значение времени в уровне. В секундах
		if remainingTime < 0.05*timeOnPrevLevel then 
			t = 20
			h = 10
		elseif remainingTime < 0.1*timeOnPrevLevel then 
			t = 15
			h = 7
		elseif remainingTime < 0.15*timeOnPrevLevel then
			t = 10
			h = 5
		elseif remainingTime < 0.2*timeOnPrevLevel then 
			t = 5
			h = 3
		elseif remainingTime > 0.65*timeOnPrevLevel then 
			t = -20; 
			h = -10;
		end;
		local LevelTime = timeOnPrevLevel + t;
		if LevelTime < 150 then
			LevelTime = 150
		end
	
		if Level == 0 then LevelTime = 250; end;
	
		gameInfo:setLocalInt("LevelTime", LevelTime);
		result:setFloat("Level_Time_Limit", LevelTime);

	else -- от if RelaxMode
		result:setFloat("Level_Time_Limit", 2000);
	end;
	
	local d = gameInfo:getLocalIntOrDef("Difficulty", 0);
	local p = getBasePrice(d);
	local q = 100;
	
	result:setInt("Money_Base", p);						-- базовая ставка для предмета
	result:setInt("Money_Base_Excess", 15);				--  Если искали группу, увеличение, если нашли больше чем один предмет
	result:setInt("Money_3_Heart", 5);					-- бонус за сердечко
	result:setInt("Money_2_Heart", 5);					-- бонус за сердечко
	result:setInt("Money_1_Heart", 5);					-- бонус за сердечко
	result:setInt("Money_Field_Coin", 25);				-- сколько стоят монетки найденные на поле
	result:setInt("Money_Base_Mode_2", 40);				-- базовая ставка предмета в коллекционере
	result:setInt("Money_Max_Time_Bonus", 200);			-- максимально возможный тайм бонус (как если бы игра закончилась в самом начале)
	result:setInt("Money_Quantum_Time_Bonus", 1);		-- квант, изменения тайм бонуса
	if not RelaxMode then 
		if d <= 30 then 
			p = 150;
			q = 300;
		elseif d <= 50 then 
			p = 120;
			q = 250;
		elseif d <= 70 then 
			p = 100 
			q = 200;
		else
			p = 75
			q = 125;
		end;
		result:setFloat("Time_3_Heart", 40+math.random(2,7));				-- Время до взрыва сердечка
		result:setFloat("Time_2_Heart", p + h);					-- Время до взрыва сердечка
		result:setFloat("Time_1_Heart", q + h);					-- Время до взрыва сердечка
	else
		result:setFloat("Time_3_Heart", 300);				-- Время до взрыва сердечка
		result:setFloat("Time_2_Heart", 600);					-- Время до взрыва сердечка
		result:setFloat("Time_1_Heart", 900);					-- Время до взрыва сердечка
	end	

	
	result:setString("greetingsText", gameInfo:getLocalStringOrDef("TalkHistoryISpyText", ""));
	return result;
end


function SaveScreensaverOptionsFunc()

	--Запомнили громкость музыки
	local state = GUI:getLayer("ScreenSaverOptions"):getWidget("ScreenSaverMusic"):QueryState(Message("GetPos"))
	local musVolume = 0+state:getData()
	gameInfo:setMusicVolumeInScreenSaver(musVolume)

	--Запомнили громкость звуков
	state = GUI:getLayer("ScreenSaverOptions"):getWidget("ScreenSaverSound"):QueryState(Message("GetPos"))
	local sndVolume = 0+state:getData()
	gameInfo:setSoundVolumeInScreenSaver(sndVolume)
	
	state = GUI:getLayer("ScreenSaverOptions"):getWidget("ScreenSaverEnv"):QueryState(Message("GetPos"))
	local envVolume = 0+state:getData()
	gameInfo:setEnvVolumeInScreenSaver(envVolume)
	
	--запомнилм силу дождя
	state = GUI:getLayer("ScreenSaverOptions"):getWidget("RainStrenghtSlider"):QueryState(Message("GetPos"))
	local strenghtVal = 0+state:getData()
	gameInfo:setRainStrenghtSS(strenghtVal)
	
	local iBoolean = "0"
	state = GUI:getLayer("ScreenSaverOptions"):getWidget("EnableScreensaver"):QueryState(Message("GetState"))
	if state:getData() == "1" then 
		gameInfo:setEnableSS(true)
	else
		gameInfo:setEnableSS(false)
	end
	
	iBoolean = "0"
	state = GUI:getLayer("ScreenSaverOptions"):getWidget("IsRainSS"):QueryState(Message("GetState"))
	if state:getData() == "1" then 
		gameInfo:setRainSS(true)
	else
		gameInfo:setRainSS(false)
	end
	
end

function RestoreScreensaverOptionsFunc()
	
	local iBoolean = "0"
	if gameInfo:enableScreenSaver() then
		iBoolean = "1"
	end
	GUI:getLayer("ScreenSaverOptions"):getWidget("EnableScreensaver"):AcceptMessage(Message("SetState", iBoolean))
	
	iBoolean = "0"
	if gameInfo:isRainInScreenSaver() then
		iBoolean = "1"
	end
	GUI:getLayer("ScreenSaverOptions"):getWidget("IsRainSS"):AcceptMessage(Message("SetState", iBoolean))
	
	GUI:getLayer("ScreenSaverOptions"):getWidget("ScreenSaverMusic"):AcceptMessage(Message("SetPos", tostring(gameInfo:getMusicVolumeInScreenSaver())))
	GUI:getLayer("ScreenSaverOptions"):getWidget("ScreenSaverSound"):AcceptMessage(Message("SetPos", tostring(gameInfo:getSoundVolumeInScreenSaver())))
	GUI:getLayer("ScreenSaverOptions"):getWidget("ScreenSaverEnv"):AcceptMessage(Message("SetPos", tostring(gameInfo:getEnvVolumeInScreenSaver())))
	GUI:getLayer("ScreenSaverOptions"):getWidget("RainStrenghtSlider"):AcceptMessage(Message("SetPos", tostring(gameInfo:getRainStrenghtSS())))
	
end

function StartScreenSaverMode()
	gameInfo:setBool("ScreensaverFromGame", true);
	gameInfo:SetScreenSaverMode(true);

	local soundVolume = gameInfo:getSoundVolumeInScreenSaver();
	local musicVolume = gameInfo:getMusicVolumeInScreenSaver();
	local envVolume = gameInfo:getEnvVolumeInScreenSaver();

	Sound:SetSoundVolume(soundVolume)
	Sound:SetMusicVolume(musicVolume)
	Sound:SetEnvVolume(envVolume)

	if (gameInfo:isRainInScreenSaver()) then
		SetEnableRain(true);
		StartRain(false, math.random(150, 200), math.random(30, 70)/100, 2*gameInfo:getRainStrenghtSS()/3, gameInfo:getRainStrenghtSS()) -- (дождь идёт сразу, как долго идёт дождь, время дождя, минимальная сила, максимальная сила
	else 
		SetEnableRain(false);
	end
	LP_FastFinishCurrentBehav();
end

function EndScreenSaverMode()
	gameInfo:setBool("ScreensaverFromGame", false);
	gameInfo:SetScreenSaverMode(false);

	local soundVolume = gameInfo:getSoundVolume();
	local musicVolume = gameInfo:getMusicVolume();
	local envVolume = gameInfo:getEnvVolume();

	Sound:SetSoundVolume(soundVolume)
	Sound:SetMusicVolume(musicVolume)
	Sound:SetEnvVolume(envVolume)

	SetRainInGarden();
	LP_FastFinishCurrentBehav();
end

--обработка панели скринсейвера
function ScreenSaverOptionsFunc(message)
	if (message:is("Ok", "press")) then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
		SaveScreensaverOptionsFunc()
		FadePopLayer("ScreenSaverOptions","ScreenSaverOptions","")
	elseif (message:is("Cancel", "press")) then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
		RestoreScreensaverOptionsFunc()
		FadePopLayer("ScreenSaverOptions","ScreenSaverOptions","")	
	elseif (message:is("Preview", "press")) then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"))
		SaveScreensaverOptionsFunc()
		LP_FastFinishCurrentBehav();
		local param = VariableSet()
		param:setString("Layer1", "Garden")
		param:setString("Layer2", "Shop")
		param:setString("CrossHandler", "StartScreenSaverMode")
		kernel:addController(controlFactory:Create("CrossFade", param))		
	end
end



function HelpFunc(message)
	if (message:is("Cancel","press")) then
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"));
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("EndHelpMode"));				
		--GUI:getLayer("HelpFadeShop"):getWidget("Cancel"):AcceptMessage(Message("GOINGUP"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade1"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade2"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade3"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade4"):AcceptMessage(Message("Hide"))
		FadeHelpPopLayer("HelpFadeShop","HelpFade")
	end
end

function HelpFuncDesign(message)
	if (message:is("Cancel","press")) then
		--GUI:getLayer("HelpFadeDesign"):getWidget("Cancel"):AcceptMessage(Message("GOINGUP"))
		GUI:getLayer("Garden"):getWidget("Garden"):AcceptMessage(Message("EndHelpMode"));
		GUI:getLayer("Shop"):getWidget("Shop"):AcceptMessage(Message("EndHelpMode"));				
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade1"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade2"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade3"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade4"):AcceptMessage(Message("Hide"))
		FadeHelpPopLayer("HelpFadeDesign","HelpFade")
	end
end

function HelpFuncISpy(message)
	if (message:is("Cancel","press")) then
		--GUI:getLayer("HelpFadeISpy"):getWidget("Cancel"):AcceptMessage(Message("GOINGUP"))
		GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("EndHelpMode"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade"):AcceptMessage(Message("Hide"))
		if (gameInfo:isRelaxMode()) then
		else
			GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade1"):AcceptMessage(Message("Hide"))
		end
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade2"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade3"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade4"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade5"):AcceptMessage(Message("Hide"))
		FadeHelpPopLayer("HelpFadeISpy","HelpFade")
	end
end

function HelpFuncISpyCollector(message)
	if (message:is("Cancel","press")) then
		--GUI:getLayer("HelpFadeISpy"):getWidget("Cancel"):AcceptMessage(Message("GOINGUP"))
		GUI:getLayer("ISpyField"):getWidget("ISpyField"):AcceptMessage(Message("EndHelpMode"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade"):AcceptMessage(Message("Hide"))
		if (gameInfo:isRelaxMode()) then
		else
			GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade1"):AcceptMessage(Message("Hide"))
		end
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade2"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade3"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade4"):AcceptMessage(Message("Hide"))
		GUI:getLayer(Screen:getMainLayerName()):getWidget("HelpFade5"):AcceptMessage(Message("Hide"))
		FadeHelpPopLayer("HelpFadeISpyCollector","HelpFade")
	end
end
