local zone_mech

function add_fibrillation_effector_door_light(obj)
    local delay = 0.
    local duration = 4.0

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

    local dopacity = -0.

    eff:SetKey(_TRACK_O, 0.0 + delay, 1.0 + dopacity)
    eff:SetKey(_TRACK_O, duration * 1.0/4.0 + delay, 0.3 + dopacity)
    eff:SetKey(_TRACK_O, duration * 2.0/4.0 + delay, 0.8 + dopacity)
    eff:SetKey(_TRACK_O, duration * 3.0/4.0 + delay, 0.5 + dopacity)
    eff:SetKey(_TRACK_O, duration * 4.0/4.0 + delay, 1.0 + dopacity)
    eff:Play()
end

function add_fibrillation_effector_lamp(obj, delay)
	local duration = 1.20

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

    local dopacity = -0.55

	eff:SetKey(_TRACK_O, 0.0 + delay, obj:GetOpacity() * 1.0 + dopacity)
	eff:SetKey(_TRACK_O, duration *1.0/4.0 + delay, obj:GetOpacity() * 0.90 + dopacity)
	eff:SetKey(_TRACK_O, duration *2.0/4.0 + delay, obj:GetOpacity() * 1.0 + dopacity)
	eff:SetKey(_TRACK_O, duration *3.0/4.0 + delay, obj:GetOpacity() * 0.80 + dopacity)
	eff:SetKey(_TRACK_O, duration *4.0/4.0 + delay, obj:GetOpacity() * 1.0 + dopacity)
	eff:Play()
end

function MarkScrew(obj)
	local scaler = CreateAnimationEffector()
	scaler:AttachTo(obj)
	scaler:SetKey(_TRACK_A, 0.0, 0.)
	scaler:SetKey(_TRACK_A, 1.1, -M_TWO_PI * 3)
	scaler:SetKey(_TRACK_O, 1.1, 1.)
	scaler:SetKey(_TRACK_O, 1.3, 0.)
	scaler:Play()
end

function PinonShow(obj)
	local scaler = CreateAnimationEffector()
	scaler:AttachTo(obj)
	scaler:SetKey(_TRACK_S, 0., 1.)
	scaler:SetKey(_TRACK_S, 0.3, 1.2)
	scaler:SetKey(_TRACK_S, 0.6, 1.)
	scaler:SetKey(_TRACK_S, 0.9, 1.2)
	scaler:SetKey(_TRACK_S, 1.1, 1.)
	scaler:Play()
end

function RegisterGearsInstallActiveZone()
    RegisterActiveObject('area',
                         function()
                             ShowMonolog('10_LOckLidOpen', 'C_10_LOCK_LID_OPEN')
                         end,
                         nil,
                         true,
                         'CursorGlass')
end

function RegisterMechStartActiveZone()
    RegisterActiveObject('area',
                         function()
                             ShowMonolog('10_LockOpen', 'C_10_LOCK_OPEN')
                         end,
                         nil,
                         true,
                         'CursorGlass')
end

function OnSceneLoad(screen)
    LoadData(screen)
    DefaultOnSceneLoad('data/Scenes/10_Museum_Hall_1_Main.lua', 'quest')

	RegisterQuestObjects('area',
						 'Layer_cover',
						 'Layer_vintik1',
						 'Layer_vintik2',
						 'Layer_vintik3',
						 'Layer_vintik4',
						 'area_ho',
						 'area_museum_hall_2',
						 'area_zoom')

	LevelScreen = screen;

	LinkScene('area_museum_street', 'CursorDoorLeft', 'data/Scenes/09_Museum_Street_Main.lua', false)
    LinkScene('area_ho', 'CursorGlass', 'data/Scenes/10_Museum_Hall_1_HO.lua', true)

	add_fibrillation_effector_lamp(screen:GetObject("radial_glow"), 0.0);
	add_fibrillation_effector_lamp(screen:GetObject("radial_glow_2"), 0.0);
	
	screen:GetObject("radial_glow"):SetVisible(false);
	screen:GetObject("radial_glow_2"):SetVisible(false);
	
    local hall2_condition = function()
        return HasGameState('MiniGameCompleted', 'Pinions')
    end
    local hall2_fail = function()
        ShowMonolog('10_DoorClose', 'C_10_DOOR_CLOSE')
		game_state.ignore_on_highlight['area_museum_hall_2'] = true
		AddGameState('IgnoreOnHighlight', 'area_museum_hall_2')
    end
	LinkScene('area_museum_hall_2', 'CursorDoorUp', 'data/Scenes/11_Museum_Hall_2_Main.lua', false, hall2_condition, hall2_fail)

	play_field:GetObject('area'):SetVisible(false)

    play_field:GetObject('area'):SetMaxOpacity(0.001)
    zone_mech = CreateZoomZone('area_zoom',
                               'CloseZoneMech',
                               'BG_Minigame', true,
                               'Layer_cover', true,
                               'Layer_vintik1', true,
                               'Layer_vintik2', true,
                               'Layer_vintik3', true,
                               'Layer_vintik4', true,
								'Layer_Lever_1', true,
								'Layer_Lever_2', true,
								'sh1', true,
								'sh2', true,
								'sh3', true,
								'sh4', true,
								'sh5', true,
								'sh6', true,
								'sh7', true,
								'Layer_Button_on', true,
								'Layer_Button_off', true,
								'Layer_Left', true,
								'Layer_Right', true,
                                'area', true)
    zone_mech.on_open = function()
        play_field:GetObject('area'):SetVisible(true)
        if HasGameState('MiniGameCompleted', 'Pinions') then
            ShowMonolog('10_LockOpen', 'C_10_LOCK_OPEN')
        else
            if HasGameState('ToolApplied', '05_screwdriver') then
                if HasGameState('TaskCompleted', '10_AllGearsInstalled') then
                    --TimerDoString("ShowMonolog('10_LockOpen', 'C_10_LOCK_OPEN')", 0.3, play_field:GetTimer())
                    RegisterMechStartActiveZone()
                else
                    --TimerDoString("ShowMonolog('10_LOckLidOpen', 'C_10_LOCK_LID_OPEN')", 0.3, play_field:GetTimer())
                    RegisterGearsInstallActiveZone()
                end
            else
                RegisterMonologObject('Layer_cover', 'C_10_LOCK_LID_CLOSE')
				RegisterMonologObject('Layer_vintik1', 'C_10_LOCK_LID_CLOSE')
				RegisterMonologObject('Layer_vintik2', 'C_10_LOCK_LID_CLOSE')
				RegisterMonologObject('Layer_vintik3', 'C_10_LOCK_LID_CLOSE')
				RegisterMonologObject('Layer_vintik4', 'C_10_LOCK_LID_CLOSE')
                --TimerDoString("ShowMonolog('10_LockLidClose', 'C_10_LOCK_LID_CLOSE')", 0.3, play_field:GetTimer())
            end
        end
        if HasGameState('ToolApplied', '02_gears') then
            play_field:GetLevelScreen():GetPanel():SetMode(PM_MINIGAME)
			play_field:GetLevelScreen():GetPanel():SetDelayTimer(GetStartMiniGameTimer())
        end

        if IsRotated
        then
            PlaySoundCyclic("Gears_working_loop");
        end
    end
    zone_mech.on_close = function()
		if game_state.comics then
			game_state.comics.SetVisible(false)
			game_state.comics = nil
		end

        play_field:GetLevelScreen():GetPanel():SetMode(PM_QUEST)
        play_field:GetObject('area'):SetVisible(false)
        StopSound("Gears_working_loop");
        
        play_field:GetObject('Layer_vintik1'):DestroyChildren();
        play_field:GetObject('Layer_vintik2'):DestroyChildren();
        play_field:GetObject('Layer_vintik3'):DestroyChildren();
        play_field:GetObject('Layer_vintik4'):DestroyChildren();
    end
    
    --play_field:IgnoreOnTestPoint('Layer_vintik1')
    --play_field:IgnoreOnTestPoint('Layer_vintik2')
    --play_field:IgnoreOnTestPoint('Layer_vintik3')
    --play_field:IgnoreOnTestPoint('Layer_vintik4')

	play_field:GetObject('Layer_Button_on'):SetVisible(false);
	play_field:GetObject('Layer_Lever_2'):SetVisible(false);
	MiniGameActive = false;
    local on_screwdriver_get = function(tool_name)
        local inv = play_field:GetLevelScreen():GetInventory()
        local info = inv:GetToolInfo(tool_name)
        info.m_tool:GetAnimation():SetHotSpot(50., 10.)
    end
    local on_screwdriver_drop = function(tool_name)
        local inv = play_field:GetLevelScreen():GetInventory()
        local info = inv:GetToolInfo(tool_name)
        info.m_tool:GetAnimation():SetHotSpot(info.m_tool:GetAnimation():GetWidth() / 2.,
                                              info.m_tool:GetAnimation():GetHeight() / 2.)
    end
    local on_screwdriver_apply = function(tool_name, object_name)   
        if object_name == 'Layer_vintik1' then
            zone_mech.SetObjectVisible('Layer_vintik1', false)
            MarkScrew(play_field:GetObject('Layer_vintik1'))
            PlayScrewSound();
        end
        if object_name == 'Layer_vintik2' then
            zone_mech.SetObjectVisible('Layer_vintik2', false)
            MarkScrew(play_field:GetObject('Layer_vintik2'))
            PlayScrewSound();
        end
        if object_name == 'Layer_vintik3' then
            zone_mech.SetObjectVisible('Layer_vintik3', false)
            MarkScrew(play_field:GetObject('Layer_vintik3'))
            PlayScrewSound();
        end
        if object_name == 'Layer_vintik4' then
            zone_mech.SetObjectVisible('Layer_vintik4', false)
            MarkScrew(play_field:GetObject('Layer_vintik4'))
            PlayScrewSound();
        end
        local nmarked_screws = 0
        if HasGameState('ToolTargetUsed', 'Layer_vintik1') then
            nmarked_screws = nmarked_screws + 1
        end
        if HasGameState('ToolTargetUsed', 'Layer_vintik2') then
            nmarked_screws = nmarked_screws + 1
        end
        if HasGameState('ToolTargetUsed', 'Layer_vintik3') then
            nmarked_screws = nmarked_screws + 1
        end
        if HasGameState('ToolTargetUsed', 'Layer_vintik4') then
            nmarked_screws = nmarked_screws + 1
        end
        if nmarked_screws == 3 then
            --play_field:GetObject('area'):GetAnimation():SetColor("0x01FFFFFF");
            --zone_mech.SetObjectVisible('Layer_cover', false)
            TimerDoString("HideZoomObj()", 1.6, LevelScreen:GetTimer())
            TimerDoString("HideBox()", 1.3, LevelScreen:GetTimer())
            --TimerDoString("ShowMonolog('10_LOckLidOpen', 'C_10_LOCK_LID_OPEN')", 1.5, play_field:GetTimer())
            MiniGameActive = true;
			game_state.custom_cursors['Layer_Button_on'] = 'CursorActive'
			game_state.custom_cursors['Layer_Button_off'] = 'CursorActive'
            RegisterGearsInstallActiveZone()
			RegisterQuestObjects('Layer_Button_off')
        end
    end
    local on_load_when_screwdriver_applied = function(tool_name, object_name)
        if object_name == 'Layer_vintik1' then
            zone_mech.SetObjectVisible('Layer_vintik1', false)
            play_field:GetObject('Layer_vintik1'):SetOpacity(0.0)
        end
        if object_name == 'Layer_vintik2' then
            zone_mech.SetObjectVisible('Layer_vintik2', false)
            play_field:GetObject('Layer_vintik2'):SetOpacity(0.0)
        end
        if object_name == 'Layer_vintik3' then
            zone_mech.SetObjectVisible('Layer_vintik3', false)
            play_field:GetObject('Layer_vintik3'):SetOpacity(0.0)
        end
        if object_name == 'Layer_vintik4' then
            zone_mech.SetObjectVisible('Layer_vintik4', false)
            play_field:GetObject('Layer_vintik4'):SetOpacity(0.0)
        end
        if not object_name then
            zone_mech.SetObjectVisible('Layer_vintik1', false)
            play_field:GetObject('Layer_vintik1'):SetOpacity(0.0)
            zone_mech.SetObjectVisible('Layer_vintik2', false)
            play_field:GetObject('Layer_vintik2'):SetOpacity(0.0)
            zone_mech.SetObjectVisible('Layer_vintik3', false)
            play_field:GetObject('Layer_vintik3'):SetOpacity(0.0)
            zone_mech.SetObjectVisible('Layer_vintik4', false)
            play_field:GetObject('Layer_vintik4'):SetOpacity(0.0)
            zone_mech.SetObjectVisible('Layer_cover', false)
            --play_field:GetObject('area'):GetAnimation():SetColor("0x01FFFFFF");
            play_field:GetObject('Layer_cover'):SetOpacity(0.0)
            MiniGameActive = true;
			game_state.custom_cursors['Layer_Button_on'] = 'CursorActive'
			game_state.custom_cursors['Layer_Button_off'] = 'CursorActive'
			RegisterQuestObjects('Layer_Button_off')
        end
    end
    --RegisterToolApplyInfo('05_screwdriver', 'Layer_cover', nil, nil, on_screwdriver_apply, on_load_when_screwdriver_applied)
    local screws = {'Layer_vintik1', 'Layer_vintik2', 'Layer_vintik3', 'Layer_vintik4'}
    RegisterToolApplyInfo('05_screwdriver',
                          screws,
                          on_screwdriver_get,
                          on_screwdriver_drop,
                          on_screwdriver_apply,
                          on_load_when_screwdriver_applied)

	local on_pinions_apply = function(tool_name, object_name)
	    play_field:GetLevelScreen():GetPanel():SetMode(PM_MINIGAME)
		if(i ~= 1 and i ~= 3) then
			for i = 1,PINIONS_AMOUNT do
				Pinions['sh'..i].Object:SetVisible(true);
				if (Pinions['sh'..i].Active == true) then
					PinonShow(Pinions['sh'..i].Object);
				end
			end
        PlayPutGearSound();
		end
		UnregisterActiveObject('area')
	end

    local on_load_when_pinions_applied = function(tool_name)
		for i = 1,PINIONS_AMOUNT do
			Pinions['sh'..i].Object:SetVisible(true);
		end
	end

	InitPinions();

    if HasGameState('MiniGameCompleted', 'Pinions') then
		screen:GetObject('area_zoom'):SetVisible(false);
		screen:GetObject('area'):SetVisible(false);
		--play_field:GetObject('Layer_door_Open'):SetOpacity(1.)
		LevelScreen:GetObject('Layer_door_Open'):SetOpacity(1.0);
		LevelScreen:GetObject('Layer_Door_Light'):SetOpacity(1.0);
		add_fibrillation_effector_door_light(play_field:GetObject('Layer_Door_Light'))
	else
		play_field:GetObject('Layer_door_Open'):SetOpacity(0.)
		play_field:GetObject('Layer_Door_Light'):SetOpacity(0.)
	end

    RegisterToolApplyInfo('02_gears', 'area', nil, nil, on_pinions_apply, on_load_when_pinions_applied);

	game_state.ignore_on_highlight['area_museum_street'] = true
    if HasGameState('ToolFound', '11_key') then
        game_state.ignore_on_highlight['area_museum_hall_2'] = true
		game_state.ignore_on_highlight['area_museum_street'] = false
        play_field:GetObject('Layer_Door_Light'):Hide()
    end

    if HasGameState('TaskCompleted', '10_AllGearsInstalled') then
		game_state.ignore_on_highlight['area'] = true
		game_state.ignore_on_highlight['area_zoom'] = true
    end

    LoadSound("10_Screw", "data/Sound/10_Museum_Hall_1/Screw.ogg");
    LoadSound("10_Put_gears", "data/Sound/10_Museum_Hall_1/Put_gears.ogg");
end

function PlayPutGearSound()

    if not (play_field.putGearSound)
    then
        play_field.putGearSound = MakeSoundEntity('10_Put_gears');
    end
    
    play_field.putGearSound:StopSound();
    play_field.putGearSound:Play(false);
end

function PlayScrewSound()

    if not (play_field.screwSound)
    then
        play_field.screwSound = MakeSoundEntity('10_Screw');
    end
    
    play_field.screwSound:StopSound();
    play_field.screwSound:Play(false);

end

function HideBox()
	if not (play_field:GetObject('Layer_cover'):GetOpacity() < 1.) then
		play_field:GetObject('Layer_cover'):ChangeOpacity(1., 0., 0.3)
	end
end

function HideZoomObj()
	zone_mech.SetObjectVisible('Layer_cover', false);
end

function OnSceneFree(screen)
    DefaultOnSceneFree()
    FreeData(screen)
    StopSound("Fireplace");
end

function OnUpdate(dt)
	PinionsRotating(dt);
    DefaultOnUpdate(dt)
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

	MiniGameMouseDown(object);
	
    DefaultOnObjectMouseDownProcessed(is_wrong_click);
end

function OnObjectMouseUp(object)
	StopDrag();
    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)
	UpdateDrag();
    DefaultOnMouseMove(previous_pos, current_pos)
end

function OnSetTool(tool)
    DefaultOnSetTool(tool)
end


-----------------------------------------------------------------------------------
--Mini game - pinions
function InitPinions()
	
	--количество шестеренок
	PINIONS_AMOUNT = 6; 
	
	-- 1 - начальный елемент крутиться вправо
	-- 2 - начальный елемент крутиться влево
	DIRECTION = 1

	-- номер начального елемета 
	NO_ACTIVE_ELEM = 1

	-- скорость вращения
	ROTATE_SPEED = 100
	
	Pinions = {};
     
    pinions_amount = 4;
 
	IsRotated = false;
    
    if HasGameState('Pinions_ButtonPush', 'press') == true then
		IsRotated = true;
		LevelScreen:GetObject("radial_glow"):SetVisible(true);
		LevelScreen:GetObject('Layer_Button_on'):SetVisible(true);
		LevelScreen:GetObject('Layer_Button_off'):SetVisible(false);
    end
    
	local j = 0;
    for i = 1,PINIONS_AMOUNT do
		Pinions['sh'..i] = {};
		Pinions['sh'..i].Object = play_field:GetObject('sh'..i);
		Pinions['sh'..i].Pos = {};
		Pinions['sh'..i].NeedPos = Pinions['sh'..i].Object:GetPosition();
		Pinions['sh'..i].Index = i;
		
		if(i ~= 1 and i ~= 3) then
			Pinions['sh'..i].Active = true;
			Pinions['sh'..i].Pos[0] = 320 + math.floor(j / 2) * 430;
			Pinions['sh'..i].Pos[1] = 270 + j % 2 * 100;
			Pinions['sh'..i].Object:SetXY(Pinions['sh'..i].Pos[0], Pinions['sh'..i].Pos[1]);
			j = j + 1;
		else
			Pinions['sh'..i].Active = false;
		end
		
		Pinions['sh'..i].Object:SetZ(151);
		Pinions['sh'..i].Object:SetVisible(false);
		Pinions['sh'..i].Rotate = -1;

		if HasGameState('Pinions'..i, 'set') == true then
			game_state.ignore_on_highlight[Pinions['sh'..i].Object:GetName()] = true
			Pinions['sh'..i].Object:SetXY(Pinions['sh'..i].NeedPos.x, Pinions['sh'..i].NeedPos.y);
			Pinions['sh'..i].Active = false;
			pinions_amount = pinions_amount - 1;
		end
    end
    
    Pinions['sh1'].Object:SetVisible(true);
    Pinions['sh3'].Object:SetVisible(true);
    
    if(IsRotated == true) then
		StopRotation();
		StartRotation();
	end
			
    DefaultDiameter = Pinions['sh'..NO_ACTIVE_ELEM].Object:GetAnimation():GetWidth();
end

function IsPinion(object)
	for i = 1,PINIONS_AMOUNT do
		if(object:GetName() == Pinions['sh'..i].Object:GetName()) then
			return true;
		end
	end
	
	return false;
end

function StartDrag(object)
	if(IsPinion(object) and Pinions[object:GetName()].Active == true) then
		DragObject = object;
		DragObject:SetZ(400);
	end
end

function StopDrag(doAbort)
	if (DragObject ~= nil) then
		DragObject:SetZ(151);
		if(math.abs(DragObject:GetX() - Pinions[DragObject:GetName()].NeedPos.x) < 50 and
           math.abs(DragObject:GetY() - Pinions[DragObject:GetName()].NeedPos.y) < 50) and not doAbort
        then
			DragObject:Move(Pinions[DragObject:GetName()].NeedPos.x - DragObject:GetX(), Pinions[DragObject:GetName()].NeedPos.y - DragObject:GetY(), 0.1);
			TimerDoString('PlayPutGearSound()', 0.1, play_field:GetTimer());
			Pinions[DragObject:GetName()].Active = false;
			pinions_amount = pinions_amount - 1;
			if(IsRotated == true) then
				StopRotation();
				StartRotation();
			end

			game_state.ignore_on_highlight[DragObject:GetName()] = true

			if HasGameState('Pinions'..Pinions[DragObject:GetName()].Index, 'set') == false then
				AddGameState('Pinions'..Pinions[DragObject:GetName()].Index, 'set');
			end
			
			if(pinions_amount == 0) then
				if(IsRotated == true) then
					LevelScreen:GetObject("radial_glow"):SetVisible(true);
					LevelScreen:GetObject("radial_glow_2"):SetVisible(false);
					game_state.custom_cursors['Layer_Lever_1'] = 'CursorActive'
				end
				
                if game_state.gears_installed ~= true then
                    game_state.gears_installed = true
                    --ShowMonolog('10_LockOpen', 'C_10_LOCK_OPEN')
                    RegisterMechStartActiveZone()
                    if not HasGameState('TaskCompleted', '10_AllGearsInstalled') then
                        AddGameState('TaskCompleted', '10_AllGearsInstalled')
						game_state.ignore_on_highlight['area'] = true
						game_state.ignore_on_highlight['area_zoom'] = true
						RegisterQuestObjects('Layer_Button_off')
                    end
                end
			end
		else
			DragObject:Move(Pinions[DragObject:GetName()].Pos[0] - DragObject:GetX(), Pinions[DragObject:GetName()].Pos[1] - DragObject:GetY(), 0.1);
		end
		DragObject = nil;
	end
end

function UpdateDrag()
	if (DragObject ~= nil) then
		DragObject:SetXY(GetMousePos().x, GetMousePos().y);
	end
end

-- вращение шестеренок
function PinionsRotating(dt)
	
	local rotate_koef = 10000;
	
    for i = 1,PINIONS_AMOUNT do
		if (Pinions['sh'..i].Rotate >= 0) then
			if (Pinions['sh'..i].Rotate == 1) then
				Angle = Pinions['sh'..i].Object:GetAngle() + ROTATE_SPEED * DefaultDiameter * dt * 80/ (Pinions['sh'..i].Object:GetAnimation():GetWidth() * rotate_koef);
			end
			if (Pinions['sh'..i].Rotate == 0) then
				Angle = Pinions['sh'..i].Object:GetAngle() - ROTATE_SPEED * DefaultDiameter * dt * 80/ (Pinions['sh'..i].Object:GetAnimation():GetWidth() * rotate_koef);
			end
			
			Pinions['sh'..i].Object:SetAngle(Angle);
			Pinions['sh'..i].Object:SetAngle(FixedAngle(Pinions['sh'..i].Object:GetAngle()));
        end
    end
end

function FixedAngle(Angle)
    if(Angle > 360) then
        Angle = Angle - 360;
    end
	if(Angle < 0) then
        Angle = 360 - Angle;
    end
    
    return Angle;
end

function StartRotation()
	Pinions['sh'..NO_ACTIVE_ELEM].Rotate = DIRECTION;
	
    repeat
        local Count = 0;
        for i = 1,PINIONS_AMOUNT do
            if (Pinions['sh'..i].Active == false and  Pinions['sh'..i].Rotate < 0) then
                if(i > 1  and Pinions['sh'..(i - 1)].Rotate >= 0) then
                    Pinions['sh'..i].Rotate = 1 - Pinions['sh'..(i - 1)].Rotate;
					Count = Count + 1;
                end
                if(i < PINIONS_AMOUNT - 1  and Pinions['sh'..(i + 1)].Rotate >= 0) then
                    Pinions['sh'..i].Rotate = 1 - Pinions['sh'..(i + 1)].Rotate;
					Count = Count + 1;
                end 
            end
        end
    until Count == 0
end

function StopRotation()
	for i = 1,PINIONS_AMOUNT do
		Pinions['sh'..i].Rotate = -1;
	end
end

function IsMiniGameCompleted()
	for i = 1,PINIONS_AMOUNT do
		if(Pinions['sh'..i].Active == true) then
			return false;
		end
	end

	return true;
end

function MiniGameMouseDown(object)
	if HasGameState('MiniGameCompleted', 'Pinions') == false then
		if(object:GetName() == 'Layer_Button_on' and MiniGameActive == true) then
			StopRotation();
			IsRotated = false;
			object:SetVisible(false);
			LevelScreen:GetObject('Layer_Button_off'):SetVisible(true);
			LevelScreen:GetObject("radial_glow"):SetVisible(false);
			LevelScreen:GetObject("radial_glow_2"):SetVisible(false);
			if HasGameState('Pinions_ButtonPush', 'press') == true then
				RemoveGameState('Pinions_ButtonPush', 'press');
			end
			
			game_state.ignore_on_highlight['Layer_Button_on'] = false
			game_state.ignore_on_highlight['Layer_Button_off'] = false
			game_state.custom_cursors['Layer_Lever_1'] = nil
			
			StopSound("Gears_working_loop");
		end
		
		if(object:GetName() == 'Layer_Button_off' and MiniGameActive == true) then
			object:SetVisible(false);
			IsRotated = true;
			LevelScreen:GetObject("radial_glow"):SetVisible(true);
			LevelScreen:GetObject('Layer_Button_on'):SetVisible(true);
			StartRotation();
			
			if HasGameState('Pinions_ButtonPush', 'press') == false then
				AddGameState('Pinions_ButtonPush', 'press');
			end

			game_state.ignore_on_highlight['Layer_Button_on'] = true
			game_state.ignore_on_highlight['Layer_Button_off'] = true

			PlaySoundCyclic("Gears_working_loop");
			
			if(IsMiniGameCompleted()) then
				game_state.custom_cursors['Layer_Lever_1'] = 'CursorActive'
				LevelScreen:GetObject("radial_glow"):SetVisible(true);
				LevelScreen:GetObject("radial_glow_2"):SetVisible(false);
			end
		end
		
		if(IsRotated == true and IsMiniGameCompleted() and object:GetName() == 'Layer_Lever_1') then
			object:SetVisible(false);
			play_field:GetObject('Layer_Lever_2'):SetVisible(true);
			play_field:IgnoreOnTestPoint('Layer_Button_off');
			play_field:IgnoreOnTestPoint('Layer_Button_on');
			TimerDoString("FinishMiniGame()", 1.5, play_field:GetTimer());
			LevelScreen:GetObject("radial_glow_2"):SetVisible(true);
			
			PlaySound("Lever");
		end
		
		StartDrag(object);
	end
end

function FinishMiniGame()
	if HasGameState('MiniGameCompleted', 'Pinions') == false then
		AddGameState('MiniGameCompleted', 'Pinions');
		game_state.ignore_on_highlight['area_museum_hall_2'] = false
		if HasGameState('IgnoreOnHighlight', 'area_museum_hall_2') then
		    RemoveGameState('IgnoreOnHighlight', 'area_museum_hall_2')
		end
	end

	LevelScreen:GetObject('area_museum_hall_2'):SetVisible(true);
	LevelScreen:GetObject('area'):SetVisible(false);
	zone_mech.SetVisible(false);
	zone_mech.Disable();

	TimerDoString("LevelScreen:GetObject('Layer_door_Open'):ChangeOpacity(0.0, 1.0, 1.5); " ..
                  "PlaySound(\"Bar_gate_opening\");",
                  0.4, LevelScreen:GetTimer())
	TimerDoString("LevelScreen:GetObject('Layer_Door_Light'):ChangeOpacity(0.0, 1.0, 1.5)", 0.4, LevelScreen:GetTimer())
	TimerDoString("add_fibrillation_effector_door_light(play_field:GetObject('Layer_Door_Light'))", 1.9, LevelScreen:GetTimer())
	game_state.custom_cursors['area_museum_hall_2'] = 'CursorDoorUp'
end

function SkipMiniGame()
	DragObject = nil;
	
	for i = 1,PINIONS_AMOUNT do
		if(Pinions['sh'..i].Active == true) then
			Pinions['sh'..i].Active = false;
			Pinions['sh'..i].Object:Move(Pinions['sh'..i].NeedPos.x - Pinions['sh'..i].Object:GetX(), Pinions['sh'..i].NeedPos.y - Pinions['sh'..i].Object:GetY(), 0.4);
		end
	end
				
	if HasGameState('MiniGameCompleted', 'Pinions') == false then
		AddGameState('MiniGameCompleted', 'Pinions');
	end
	
	TimerDoString("LevelScreen:GetObject('radial_glow'):SetVisible(true)", 0.6, LevelScreen:GetTimer());
	TimerDoString("PushButton(); " ..
                  "PlaySoundCyclic(\"Gears_working_loop\");",
                  0.6, LevelScreen:GetTimer());
	
	TimerDoString("LevelScreen:GetObject('radial_glow_2'):SetVisible(true)", 1.8, LevelScreen:GetTimer());
	TimerDoString("PushLever(); "..
                  "PlaySound(\"Lever\");",
                  1.8, LevelScreen:GetTimer())
	TimerDoString("FinishMiniGame()", 3.0, LevelScreen:GetTimer())
end

function PushButton()
	LevelScreen:GetObject('Layer_Button_off'):SetVisible(false);
	LevelScreen:GetObject('Layer_Button_on'):SetVisible(true);
	StartRotation()
end

function PushLever()
	--play_field:GetObject('Layer_Lever_1'):SetVisible(false);
	play_field:GetObject('Layer_Lever_2'):SetVisible(true);
	LevelScreen:GetObject('Layer_Lever_2'):ChangeOpacity(0.0, 1.0, 0.8);
	LevelScreen:GetObject('Layer_Lever_1'):ChangeOpacity(1.0, 0.0, 0.8);
end

function LevelLoaded(level)

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/Common/area.png',0,0,8,8,1,0)
	anim:SetHotSpot(4,4)
	anim:SetBlendMode(2)
	anim:SetColor('0x01FFFFFF')
	screen:CreateObject('area_museum_street',anim,70,367,100,0,12,25)
	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_museum_hall_2',anim,522,344,130,0,20,25)
	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_zoom',anim,630,353,130,0,5,10)
	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_ho',anim,731,437,100,0,12,20)
	local anim = CreateAnimation('data/Texture/Scenes/10_Museum_Hall_1/Zone_Main/Minigame_Mechanism/Layers/BG_Minigame.jpg',0,0,640,480,1,0)
	anim:SetHotSpot(320,240)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('BG_Minigame',anim,519,384,150,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/10_Museum_Hall_1/Zone_Main/Minigame_Mechanism/Layers/Layer_cover.PNG',0,0,165,386,1,0)
	anim:SetHotSpot(82,193)
	anim:SetBlendMode(2)
	anim:SetColor('0x00FFFFFF')
	screen:CreateObject('Layer_cover',anim,525,412,155,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/10_Museum_Hall_1/Zone_Main/Minigame_Mechanism/Layers/Layer_vintik.PNG',0,0,60,60,1,0)
	anim:SetHotSpot(30,30)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_vintik1',anim,462,242,180,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/10_Museum_Hall_1/Zone_Main/Minigame_Mechanism/Layers/Layer_vintik.PNG',0,0,60,60,1,0)
	anim:SetHotSpot(30,30)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_vintik2',anim,593,239,180,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/10_Museum_Hall_1/Zone_Main/Minigame_Mechanism/Layers/Layer_vintik.PNG',0,0,60,60,1,0)
	anim:SetHotSpot(30,30)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_vintik3',anim,462,562,180,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/10_Museum_Hall_1/Zone_Main/Minigame_Mechanism/Layers/Layer_vintik.PNG',0,0,60,60,1,0)
	anim:SetHotSpot(30,30)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_vintik4',anim,593,563,180,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/sh7.PNG',0,0,93,93,1,0)
	anim:SetHotSpot(46,46)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('sh6',anim,519,550,150,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/sh2.PNG',0,0,95,95,1,0)
	anim:SetHotSpot(47,47)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('sh1',anim,574,353,150,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/sh3.PNG',0,0,40,40,1,0)
	anim:SetHotSpot(20,20)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('sh2',anim,527,388,150,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/sh4.PNG',0,0,55,55,1,0)
	anim:SetHotSpot(27,27)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('sh4',anim,503,424,150,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/sh1.PNG',0,0,90,90,1,0)
	anim:SetHotSpot(45,45)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('sh5',anim,481,481,150,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/sh6.PNG',0,0,64,64,1,0)
	anim:SetHotSpot(32,32)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('sh3',anim,484,381,150,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/Layer_Button_off.PNG',0,0,20,20,1,0)
	anim:SetHotSpot(10,10)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_Button_off',anim,634,347,200,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/Layer_Button_on.PNG',0,0,20,20,1,0)
	anim:SetHotSpot(10,10)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_Button_on',anim,635,346,200,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/Layer_Lever_1.PNG',0,0,70,197,1,0)
	anim:SetHotSpot(31,63)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_Lever_1',anim,627,201,200,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/Layer_Lever_2.PNG',0,0,70,140,1,0)
	anim:SetHotSpot(35,70)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_Lever_2',anim,632,264,200,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',anim,529,411,152,0,24,48)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/Layer_Left.PNG',0,0,25,100,1,0)
	anim:SetHotSpot(12,50)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_Left',anim,430,490,159,0,1,1)
	local anim = CreateAnimation('data/Texture/Minigames/Pinions/Layer_Right.png',0,0,18,69,1,0)
	anim:SetHotSpot(9,34)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_Right',anim,617,359,159,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/10_Museum_Hall_1/Zone_Main/Layers/Layer_door_Open.png',0,0,183,199,1,0)
	anim:SetHotSpot(91,99)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_door_Open',anim,502,373,120,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/10_Museum_Hall_1/Zone_Main/Layers/Layer_Door_Light.png',0,0,200,337,1,0)
	anim:SetHotSpot(100,168)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('Layer_Door_Light',anim,523,306,121,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/10_Museum_Hall_1/Zone_Main/Layers/BG_Museum.jpg',0,0,1024,768,1,0)
	anim:SetHotSpot(512,384)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFFFFFFF')
	screen:CreateObject('BG_Museum',anim,512,384,40,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/Common/radial_glow.png',0,0,97,99,1,0)
	anim:SetHotSpot(48,49)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFDDDD00')
	screen:CreateObject('radial_glow',anim,463,280,151,0,1,1)
	local anim = CreateAnimation('data/Texture/Scenes/Common/radial_glow.png',0,0,97,99,1,0)
	anim:SetHotSpot(48,49)
	anim:SetBlendMode(2)
	anim:SetColor('0xFFDDDD00')
	screen:CreateObject('radial_glow_2',anim,508,285,152,0,1,1)
end

function FreeData(screen)
end
-- CLEAR_ON_SAVE_END
