-- write out that we loaded sucessfully (mor or less, anyway)
io.write("Starting script for Level 1tom ",_VERSION,"!\n")
bs.callback.engine.init("initLevel");

CFG_JUMPTILES_COUNT = 4;
CFG_JUMPTILES_Y = { 51,47,43,40 };
CFG_JUMPTILES_X = { 5, 7,10, 14 };

-- Required function: Initializing the level
function initLevel ()
    -- preload all gfx (on-the-fly loading is NOT recommended)
    GFX_DOOR_CLOSED = bs.gfx.load("fg_door_closed.bmp");
    GFX_DOOR_OPEN = bs.gfx.load("fg_door_open.bmp");
    GFX_SWITCH_RED = bs.gfx.load("fg_switch_red.bmp");
    GFX_SWITCH_GREEN = bs.gfx.load("fg_switch_green.bmp");
	

    -- create door and switch
	switchon = 0;
    OBJ_SWITCH = bs.obj.new(3*32, 52*32, GFX_SWITCH_RED, "visible");
    OBJ_DOOR = bs.obj.new(10*32, 34*32, GFX_DOOR_CLOSED, "visible,ontop,blocking");
	OBJ_SWITCH.callback.playeraction("handleDoorAction");
	
    -- load extra sound
    SND_DOOR_OPEN = bs.snd.load("fx_open_door.ogg");
    SND_DOOR_CLOSE = bs.snd.load("fx_open_door.ogg");

	bs.callback.engine.physics("scriptPhysics");
end

-- Required function: Physics-loop for scripting part
function scriptPhysics ()
    if switchon == 1 then
        -- Block the door after a certain time
        timer = timer - 1;
        if timer == 0 then
            closeDoor();
        end
    end


	px = bs.player.x();
	py = bs.player.y(); 
	if px > 159 and px < 353 and py > 840 and py < 850 then
		bs.player.kill();
	end

   for i=1,CFG_JUMPTILES_COUNT do
        if py == (CFG_JUMPTILES_Y[i]-1)*32 and px > CFG_JUMPTILES_X[i]*32-55 and px <CFG_JUMPTILES_X[i]*32 +5 then
		jumpPlayer( py ); 
	end
    end


end



function jumpPlayer( ypos ) 
	bs.player.speed_y(-23); 
end


-- Required function: Callback on "Action"-Button on FG-Objects
function handleDoorAction(obj_id)
    -- Open door if not open
    if switchon == 0 then
        openDoor();
    end
end

-- Script-internal functions
function openDoor()
    switchon = 1;

    -- exchange GFX for door and button
    OBJ_SWITCH.gfx(GFX_SWITCH_GREEN);
    OBJ_DOOR.gfx(GFX_DOOR_OPEN);

    -- make door nonblocking
    OBJ_DOOR.blocking(bs.no);
    timer = 1000; -- 5 secs    

   -- play sound
   SND_DOOR_OPEN.play();
end

function closeDoor()
    switchon = 0;

    -- exchange GFX for door and button
    OBJ_SWITCH.gfx(GFX_SWITCH_RED);
    OBJ_DOOR.gfx(GFX_DOOR_CLOSED);

    -- Block the door again
    OBJ_DOOR.blocking(bs.yes);

   -- play sound
   SND_DOOR_CLOSE.play();
end
