local realtimer = timer
local hourtimer = timer

local function onLoaded(e)
	if (tes3.player.baseObject.level * 5) > tes3.findGlobal("4nm_lessons").value and tes3.findGlobal("4nm_stoptraining").value == 1 then
		tes3.findGlobal("4nm_stoptraining").value = 0
	end
end

local function onTraining()
	if hourtimer.state == timer.active then hourtimer:cancel() end
	if realtimer.state == timer.active then realtimer:cancel() end
	realtimer = timer.start({ duration = 0.5, callback = function () hourtimer:cancel() end })
	hourtimer = timer.start({ duration = 0.01, callback = function ()
	if realtimer.state == timer.active then
		realtimer:cancel()
		tes3.findGlobal("4nm_lessons").value = tes3.findGlobal("4nm_lessons").value + 1
		tes3.messageBox({ message = "Trained already " .. tes3.findGlobal("4nm_lessons").value .. " times.    " .. (tes3.player.baseObject.level * 5 - tes3.findGlobal("4nm_lessons").value) .. " left" })
		if (tes3.player.baseObject.level * 5) <= tes3.findGlobal("4nm_lessons").value then
			tes3.findGlobal("4nm_stoptraining").value = 1
			tes3.messageBox("It's time to put the acquired knowledge into practice")
		end
	end
	end, type = timer.game })
end

local function initialized(e)
	event.register("calcTrainingPrice", onTraining)
	event.register("loaded", onLoaded)
end
event.register("initialized", initialized)
