

function init()
floors = FindLocations("floor")
floorLoc = findFloors()
button = FindShape("button")
cabin = FindBody("cabin")

ldjointup = FindJoint("ldjointup")
ldjointdown = FindJoint("ldjointdown")
rdjointup = FindJoint("rdjointup")
rdjointdown = FindJoint("rdjointdown")

SetTag(button, "interact", "Use elevator")

Motor = FindJoint("jointmotor")
SetJointMotor(Motor, 0)
SetJointMotor(ldjointup, 0, 0)
SetJointMotor(ldjointdown, 0, 0)
SetJointMotor(rdjointup, 0, 0)
SetJointMotor(rdjointdown, 0, 0)

isMoving = true
isDoorClosing = false
speed = 2

CurrentPoint = 2
TargetPoint = 2

light = FindLight("elevatorlight")

if not (GetInt("savegame.mod.message.ravine_motivational") > 0) then
	SetLightEnabled(light, false)
	SetLightIntensity(light, 0)
end
	
end


function findFloors()
	local floorLoc = {}
	for i=1, #floors do
		floorLoc[i] = GetLocationTransform(floors[i]).pos[2]
	end
	
	table.sort(floorLoc)
	
	return floorLoc
end



function tick(dt)


	
	if isDoorClosing then
		DoorClosing()
	end
	if GetPlayerInteractShape() == button and InputPressed("interact") then
		if (CurrentPoint~=1) then
			TargetPoint=CurrentPoint-1
		else
			TargetPoint=CurrentPoint+1
		end
		isDoorClosing = true
	end
	
	if (CurrentPoint~=TargetPoint) and not isDoorClosing then
		if not isMove(TargetPoint) then
			Movement(TargetPoint)
		else
			SetJointMotor(ldjointup, 0, 0)
			SetJointMotor(ldjointdown, 0, 0)
			SetJointMotor(rdjointup, 0, 0)
			SetJointMotor(rdjointdown, 0, 0)
			CurrentPoint=TargetPoint
		end
	end
end

function DoorClosing()
	SetJointMotor(ldjointup, 90, 180)
	SetJointMotor(ldjointdown, 90, 180)
	SetJointMotor(rdjointup, 90, 180)
	SetJointMotor(rdjointdown, 90, 180)
	local leftDoorPos = GetJointMovement(ldjointup)
	local rightDoorPos = GetJointMovement(rdjointup)

	if leftDoorPos < 0.2 and rightDoorPos < 0.2 then
		isDoorClosing = false
	end
	DebugWatch("s", isDoorClosing)
end

function getCabinBottomPos()
	local min, max = GetBodyBounds(cabin)
	return min[2]
end


function isMove(TargetPoint)
	local currentCabinPos = getCabinBottomPos()
	local targetCabinPos = floorLoc[TargetPoint]
	
	if math.abs( targetCabinPos - currentCabinPos) < 0.2 then
		isMoving = true
	else
		isMoving = false
	end
	return isMoving
end


function Movement(targetID)
	local targetPos = floorLoc[targetID]
	SetJointMotorTarget(Motor, targetPos-floorLoc[2], speed)
end

