local zone_lock
local key_nclicks
local rotate_small_key = false

function add_fibrillation_effector_light(obj, delay)
	local duration = 7.20

	eff= CreateAnimationEffector()
	eff:AttachTo(obj)
	eff:SetMode(_ANIM_LOOP)

    local o = obj:GetOpacity()
    local dopacity = -0.15

	eff:SetKey(_TRACK_O, 0.0 + delay, o * 1.0 + dopacity)
	eff:SetKey(_TRACK_O, duration *1.0/4.0 + delay, o * 0.75 + dopacity)
	eff:SetKey(_TRACK_O, duration *2.0/4.0 + delay, o * 1.0 + dopacity)
	eff:SetKey(_TRACK_O, duration *3.0/4.0 + delay, o * 0.59 + dopacity)
	eff:SetKey(_TRACK_O, duration *4.0/4.0 + delay, o * 1.0 + dopacity)
	eff:Play()
end

function OnSceneLoad(screen)
    LoadData(screen)
    DefaultOnSceneLoad('data/Scenes/12_Theatre_Gate_Main.lua', 'quest')

	RegisterQuestObjects('area_zoom_lock', 'area_lock', 'area_openeddoor', 'zoom_Big_key2')

    LinkScene('area_back', 'CursorDoorDown', 'data/Scenes/09_Museum_Street_Main.lua', false)

	if HasGameState('ToolFound', '11_key') then
		game_state.ignore_on_highlight['area_back'] = true
	end

	play_field:GetObject('area_zoom_lock'):SetMaxOpacity(0.001)

    zone_lock = CreateZoomZone('area_lock',
                               'CloseZoneBox',
                               'zoom_BG_Key', true,
                               'zoom_Big_key2', false,
							   'area_zoom_lock', true)
    zone_lock.on_open = function()
        --if not HasGameState('TaskComplete', '12_rotate_key_three_times') then
        if not HasGameState('ToolApplied', '11_key') then
            --ShowMonolog('12_HaveGateKey', 'C_12_HAVE_GATE_KEY')
            RegisterActiveObject('area_zoom_lock',
                     function()
                         ShowMonolog('12_HaveGateKey', 'C_12_HAVE_GATE_KEY')
                     end,
                     nil,
                     true,
                     'CursorGlass')
        end
    end

    local pf = play_field

    local on_garguel_click = function(obj_name)
        if not play_field:GetObject(obj_name):GetAnimation():IsPlaying() then
            play_field:GetObject(obj_name):GetAnimation():Play()
            if not play_field.garguelSound
            then
                play_field.garguelSound = MakeSoundEntity("Garguel_wing");
            end
            play_field.garguelSound:StopSound();
            play_field.garguelSound:Play(false);
        end

        ShowGarguelleComment();
    end
    RegisterActiveObject('garguel2', on_garguel_click, nil, true, 'CursorGlass')
    RegisterActiveObject('garguel3', on_garguel_click, nil, true, 'CursorGlass')

    game_state.ignore_on_highlight['garguel2'] = true
    game_state.ignore_on_highlight['garguel3'] = true

    play_field:GetObject('Layer_Key_Small'):SetOpacity(0.)

    local on_key_apply = function(tool_name, object_name)
        zone_lock.SetObjectVisible('zoom_Big_key2', true)
        play_field:GetObject('Layer_Key_Small'):SetOpacity(1.)
        pf:GetObject('zoom_Big_key2'):ChangeOpacity(0., 1., 0.3)
        UnregisterActiveObject('area_zoom_lock')
		game_state.ignore_on_highlight['area_zoom_lock'] = true
    end
    local on_load_when_key_applied = function(tool_name)
        play_field:GetObject('Layer_Key_Small'):SetOpacity(1.)
        zone_lock.SetObjectVisible('zoom_Big_key2', true)
		game_state.ignore_on_highlight['area_zoom_lock'] = true
    end
    RegisterToolApplyInfo('11_key', 'area_zoom_lock', nil, nil, on_key_apply, on_load_when_key_applied)

    if not HasGameState('TaskComplete', '12_rotate_key_three_times') then
		if not HasGameState('12_key_rotates') then
			AddGameState('12_key_rotates', '0')
		end
        play_field:GetObject('area_openeddoor'):SetVisible(false)
        key_nclicks = tonumber(GetGameState('12_key_rotates'):Get(0))

        local on_key_click = function(obj_name)
            if key_nclicks < 3 then

                PlaySound("Lock");

                pf:GetObject(obj_name):Rotate(M_PI, 0.5)
                key_nclicks = key_nclicks + 1
				SetGameState('12_key_rotates', tostring(key_nclicks))
                game_state.locked_objects['zoom_Big_key2'] = true
                TimerDoString("game_state.locked_objects['zoom_Big_key2'] = false", 0.5, pf:GetTimer())
                if key_nclicks == 3 then
                    AddGameState('TaskComplete', '12_rotate_key_three_times')
                    play_field:GetObject('area_closeddoor'):SetVisible(false)
                    TimerDoString("StartMech()", 0.5, pf:GetTimer())
					game_state.ignore_on_highlight['area_back'] = true
                end
            end
        end
        RegisterActiveObject('zoom_Big_key2', on_key_click, nil, true)
    end

    pf:GetObject('meh'):GetAnimation():Stop()
    pf:GetObject('meh_doll'):GetAnimation():Stop()
    pf:GetObject('garguel2'):GetAnimation():Stop()
    pf:GetObject('garguel2'):GetAnimation():SetMode(HGEANIM_NOLOOP)
    pf:GetObject('garguel3'):GetAnimation():Stop()
    pf:GetObject('garguel3'):GetAnimation():SetMode(HGEANIM_NOLOOP)
    pf:GetObject('door'):GetAnimation():Stop()
    pf:GetObject('door'):GetAnimation():SetMode(HGEANIM_NOLOOP)

    pf:GetObject('gate_light'):SetOpacity(0.)

    if HasGameState('TaskComplete', '12_rotate_key_three_times') then
        pf:GetObject('area_lock'):SetOpacity(0.)
        pf:GetObject('door'):GetAnimation():SetFrame(pf:GetObject('door'):GetAnimation():GetFrames() - 1)
        --pf:GetObject('door'):SetOpacity(0.)
        play_field:GetObject('gate_light'):SetOpacity(1.)
        AnimateDoorLighting()
		game_state.ignore_on_highlight['area_back'] = true
    else
        game_state.custom_cursors['area_lock'] = 'CursorGlass'
    end

    if not HasGameState('TaskComplete', '12_rotate_key_three_times') then
        RegisterMonologObject('area_closeddoor', 'C_12_NO_GATE_KEY', true)
    else
        play_field:GetObject('area_closeddoor'):SetVisible(false)
        play_field:GetObject('area_openeddoor'):SetVisible(true)
        LinkScene('area_openeddoor', 'CursorDoorUp', 'data/Scenes/13_Theatre_Fountain_Main.lua', false)
    end

	if HasGameState('SceneVisited', 'data/Scenes/08_Library_Main.lua') then
		play_field:GetObject('Doll_Alive'):SetOpacity(0.)
		AddSpiderMan(screen)
    end
end

function StartMech()
    zone_lock.SetVisible(false)
    play_field:GetObject('area_lock'):SetOpacity(0.)

    play_field:GetObject('door'):GetAnimation():Play()
    play_field:GetObject('meh'):GetAnimation():Play()
    play_field:GetObject('meh_doll'):GetAnimation():Play()

    rotate_small_key = true

    TimerDoString("OpenDoor()", GetAnimationLength(play_field:GetObject('door'):GetAnimation()), play_field:GetTimer())

    PlaySound("Gates_opening");
end

function OpenDoor()
    rotate_small_key = false

    --play_field:GetObject('door'):ChangeOpacity(1., 0., 0.3)
    play_field:GetObject('gate_light'):ChangeOpacity(0., 1., 0.3)
    TimerDoString("StopMech()", 0.3, play_field:GetTimer())

    play_field:GetObject('area_openeddoor'):SetVisible(true)
    LinkScene('area_openeddoor', 'CursorDoorUp', 'data/Scenes/13_Theatre_Fountain_Main.lua', false)

    --StopMech()
end

function AnimateDoorLighting()
    add_fibrillation_effector_light(play_field:GetObject('gate_light'), 0.)
end

function StopMech()
    AnimateDoorLighting()
    play_field:GetObject('door'):GetAnimation():Stop()
    play_field:GetObject('meh'):GetAnimation():Stop()
    play_field:GetObject('meh_doll'):GetAnimation():Stop()
end

function ShowGarguelleComment()

    ShowMonolog('12_garguelle_click',
                SelectRandom('C_12_GARGUELLE_1',
                             'C_12_GARGUELLE_2',
                             'C_12_GARGUELLE_3'),
                nil, true);

end

function RegisterRippedPuppetObject()

    RegisterActiveObject(
        'area_ripped_puppet',
        function()
			ShowMonolog('12_ripped_puppet',
                        SelectRandom('C_12_RIPPED_PUPPET_1',
                                     'C_12_RIPPED_PUPPET_2',
                                     'C_12_RIPPED_PUPPET_3'))
			game_state.ignore_on_highlight['area_ripped_puppet'] = true
        end,
        function()
			game_state.ignore_on_highlight['area_ripped_puppet'] = true
        end,
		true,
		'CursorGlass')
end

function OnSceneFree(screen)
    DefaultOnSceneFree()
    FreeData(screen)
end

function OnUpdate(dt)
    DefaultOnUpdate(dt)

    if rotate_small_key then
        local key = play_field:GetObject('Layer_Key_Small')
        key:SetAngle(key:GetAngle() - 5. * dt)
    end
end

function OnAllItemsFound()
    DefaultOnAllItemsFound()
end

function OnLose()
    DefaultOnLose()
end

function OnExit()
    DefaultOnExit()
end

function OnClose()
    DefaultOnClose()
end

function OnObjectMouseEnter(object)
    DefaultOnObjectMouseEnter(object)
end

function OnObjectMouseLeave(object)
    DefaultOnObjectMouseLeave(object)
end

function OnObjectMouseDown(object)
    local is_wrong_click = not DefaultOnObjectMouseDown(object)
    local obj_name = object:GetName()
    local pf = play_field

    if obj_name == 'area_lock' then
        is_wrong_click = false
        if HasGameState('ToolFound', '11_key') then
            if not HasGameState('ToolApplied', '11_key') then
                zone_lock.SetVisible(true)
            end
        else
            --ShowMonolog('12_NoGateKey', 'C_12_NO_GATE_KEY')
        end
    end

    DefaultOnObjectMouseDownProcessed(is_wrong_click);
end

function OnObjectMouseUp(object)
    DefaultOnObjectMouseUp(object)
end

function OnObjectFound(object)
    DefaultOnObjectFound(object)
end

function OnToolFound(tool)
    DefaultOnToolFound(tool)
end

function OnToolApply(tool, object)
    DefaultOnToolApply(tool, object)
end

function OnObjectReachPanel(object)
    DefaultOnObjectReachPanel(object)
end

function OnButtonPress(title)
    DefaultOnButtonPress(title)
end

function OnMouseMove(previous_pos, current_pos)
    DefaultOnMouseMove(previous_pos, current_pos)
end

function OnSetTool(tool)
    DefaultOnSetTool(tool)
end

--------------------------------------------------------------------------------
function LevelLoaded(level)

    local screen = level;

    local anim = screen:CreateAnimation('data/Texture/Scenes/Common/Sky.jpg')
	anim:SetPosXY(512, 150);
	anim:SetPosZ(41);

	local anim = screen:CreateAnimation('data/Texture/Scenes/Common/Moon.png')
	anim:SetHotSpot(170, 160);
	anim:SetPosXY(580, 115);
	anim:SetPosZ(42);

	-- clouds 1
	local anim = screen:CreateAnimation('data/Texture/Scenes/Common/Clouds.png');
	anim:SetPosXY(1024, 150);
	anim:SetOpacity(0);
	anim:SetScaleXY(1, 1);
	anim:SetPosZ(43);

	local effector = CreateTextureEffector();
	effector:AttachToAnimation(anim);
	effector:SetSpeed(-16);
	effector:Play();

	local effector = CreateAnimationEffector();
	effector:AttachTo(anim);
	effector:SetKey(_TRACK_O, 0, 0.0);
	effector:SetKey(_TRACK_O, 1.5, 0.45);
	effector:Play();

	-- clouds 2
	local anim = screen:CreateAnimation('data/Texture/Scenes/Common/Clouds.png');
	anim:SetPosXY(0, 150);
	anim:SetOpacity(0);
	anim:SetScaleXY(1, 1);
	anim:SetPosZ(44);

	local effector = CreateTextureEffector();
	effector:AttachToAnimation(anim);
	effector:SetSpeed(-4);
	effector:Play();

	local effector = CreateAnimationEffector();
	effector:AttachTo(anim);
	effector:SetKey(_TRACK_O, 0, 0.0);
	effector:SetKey(_TRACK_O, 1.5, 0.75);
	effector:Play();

	--

	local anim = screen:CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Layers/Layer_Top_clean.PNG')
	anim:SetHotSpot(512, 175);
	anim:SetPosXY(512, 175);
	anim:SetPosZ(45);

end

--------------------------------------------------------------------------------
function AddSpiderMan(scene)

    local state = GetGameManager():GetCurrPlayer().m_gameState;
    if (state:HasState('SpiderManVanished') and state:GetState('SpiderManVanished'):HasValue('12'))
    then
        RegisterRippedPuppetObject();
    else
        state:AddState('SpiderManVanished', '12');
        PlaySpiderManFleeingAnimation(scene);
        
        local snd = MakeSoundEntity('12_spider'); snd:Play(false);
        
        TimerDoString('RegisterRippedPuppetObject()', 4, play_field:GetTimer());
    end
end

--------------------------------------------------------------------------------
function PlaySpiderManFleeingAnimation(scene)

    local zOffset = 120;

    --TimerDoString("PlaySound('06_spider')", timeOffset, play_field:GetTimer())

    --------
    local anim = nil;
    local object = nil;
    local effector = nil;

    -- Layer Spider_man_fleeing_2
    anim = CreateAnimation("data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Animations/SpiderMan/Spider_Man_Fleeing_2.png",
                            0, 0, 95, 84, 24, 20);
    anim:SetHotSpot(47.5, 42);
    object = scene:CreateObject('SpiderManFleeing2', anim, 462.5, 249.5, zOffset + 3, 0, 1, 1);
    object:SetVisible(false);

    effector = CreateAnimationEffector();
    effector:SetLifeTime(3.0333333, 4.2333333);
    effector:SetAnimationTime(5);
    effector:AttachTo(object);
    effector:Play();


    -- Layer Spider_man_fleeing_1
    anim = CreateAnimation("data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Animations/SpiderMan/Spider_Man_Fleeing_1.png",
                           0, 0, 217, 483, 17, 15);
    anim:SetHotSpot(108.5, 241.5);
    object = scene:CreateObject('SpiderManFleeing1', anim, 377, 462, zOffset + 2, 0, 1, 1);
    object:SetVisible(false);

    effector = CreateAnimationEffector();
    effector:SetLifeTime(1.9, 3.0333333);
    effector:SetAnimationTime(4);
    effector:AttachTo(object);
    effector:Play();


    -- Layer Spider_man_scavenging
    anim = CreateAnimation("data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Animations/SpiderMan/Spider_Man_Scavenging.png",
                           0, 0, 188, 134, 38, 20);
    anim:SetHotSpot(94, 67);
    object = scene:CreateObject('SpiderManScavenging', anim, 263, 671, zOffset + 1, 0, 1, 1);

    effector = CreateAnimationEffector();
    effector:SetLifeTime(0, 1.9);
    effector:SetAnimationTime(3);
    effector:AttachTo(object);
    effector:Play();

end

function OnSceneDestroy(playfield)
    DefaultOnSceneDestroy(playfield)
end

--------------------------------------------------------------------------------
-- CLEAR_ON_SAVE_BEGIN
-- Do not edit code listed below (generated by the editor on each save)
function LoadData(screen)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Animations/meh_doll.png',0,0,119,225,8,8)
	anim:SetHotSpot(59,112)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('meh_doll',anim,754,522,110,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Animations/garguel3.png',0,0,129,203,16,16)
	anim:SetHotSpot(0,0)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('garguel3',anim,192,70,100,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Animations/meh.png',0,0,92,244,3,3)
	anim:SetHotSpot(0,0)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('meh',anim,723,385,90,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Animations/doll_helix.png',0,0,40,58,8,8)
	anim:SetHotSpot(0,0)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('doll_helix',anim,230,612,100,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Animations/garguel2.png',0,0,208,231,16,16)
	anim:SetHotSpot(0,0)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('garguel2',anim,667,14,100,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Layers/BG_Theatre_Gate.JPG',0,0,1024,768,1,0)
	anim:SetHotSpot(512,384)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('BG_Theatre_Gate',anim,512,384,40,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Animations/door.png',0,0,184,414,3,1)
	anim:SetHotSpot(94,0)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('door',anim,579,305,116,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Layers/front.png',0,0,1024,768,1,0)
	anim:SetHotSpot(512,384)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('front',anim,790,482,100,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Layers/Theatre_Gate_svet.png',0,0,546,454,1,0)
	anim:SetHotSpot(273,227)
	anim:SetBlendMode(0)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('gate_light',anim,371,541,115,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Zoom_Key/zoom_BG_Key.jpg',0,0,640,480,1,0)
	anim:SetHotSpot(320,240)
	anim:SetBlendMode(2)
	anim:SetColor('0x00FFFFFF')
	screen:CreateObject('zoom_BG_Key',anim,512,384,150,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Zoom_Key/zoom_Big_key2.png',0,0,288,83,1,0)
	anim:SetHotSpot(144,41)
	anim:SetBlendMode(2)
	anim:SetColor('0x00FFFFFF')
	screen:CreateObject('zoom_Big_key2',anim,518,346,155,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/Common/area.png',0,0,8,8,1,0)
	anim:SetHotSpot(6,5)
	anim:SetBlendMode(2)
	anim:SetColor('0x01FFFFFF')
	screen:CreateObject('area_lock',anim,799,544,120,0,17,37)
	local anim = CreateAnimation('data/Texture/Scenes/Common/area.png',0,0,8,8,1,0)
	anim:SetHotSpot(4,4)
	anim:SetBlendMode(2)
	anim:SetColor('0x01FFFFFF')
	screen:CreateObject('area_back',anim,600,726,120,0,100,12)
	local anim = CreateAnimation('data/Texture/Scenes/Common/area.png',0,0,8,8,1,0)
	anim:SetHotSpot(4,4)
	anim:SetBlendMode(2)
	anim:SetColor('0x01FFFFFF')
	screen:CreateObject('area_fountain',anim,503,497,95,0,2,48)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Layers/Layer_Key_Small.png',0,0,77,42,1,0)
	anim:SetHotSpot(38,21)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_Key_Small',anim,800,559,110,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Layers/Layer_Tumba_L.png',0,0,258,60,1,0)
	anim:SetHotSpot(129,30)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('left_column_top',anim,283,290,101,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Layers/Layer_Tumba_R.png',0,0,231,77,1,0)
	anim:SetHotSpot(115,38)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('right_column_top',anim,749,258,101,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/Common/area.png',0,0,8,8,1,0)
	anim:SetHotSpot(4,4)
	anim:SetBlendMode(2)
	anim:SetColor('0x01FFFFFF')
	screen:CreateObject('area_closeddoor',anim,506,463,130,0,40,45)
	local anim = CreateAnimation('data/Texture/Scenes/Common/area.png',0,0,8,8,1,0)
	anim:SetHotSpot(4,4)
	anim:SetBlendMode(2)
	anim:SetColor('0x01FFFFFF')
	screen:CreateObject('area_openeddoor',anim,506,463,131,0,40,45)
	local anim = CreateAnimation('data/Texture/Scenes/Common/area.png',0,0,8,8,1,0)
	anim:SetHotSpot(4,4)
	anim:SetBlendMode(2)
	anim:SetColor('0x01FFFFFF')
	screen:CreateObject('area_ripped_puppet',anim,218,689,130,0,26,14)
	local anim = CreateAnimation('data/Texture/Scenes/Common/area.png',0,0,8,8,1,0)
	anim:SetHotSpot(4,4)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('area_zoom_lock',anim,522,332,151,0,15,20)
	local anim = CreateAnimation('data/Texture/Scenes/12_Theatre_Gate/Zone_Main/Layers/Doll_Alive.JPG',0,0,267,331,1,0)
	anim:SetHotSpot(133,165)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Doll_Alive',anim,228,585,102,0,1,1)
end

function FreeData(screen)
end
-- CLEAR_ON_SAVE_END
