game_menu = {}

function CreateMenu(title,txt)
	if title then
		game_menu[title] = {}
		game_menu[title].title = title
		setmetatable(game_menu[title], {__index = class_menu})

		game_menu[title]:SetText(txt)
		return game_menu[title]
	end
end

class_menu = {}

function ButtonPage(b)
	if b < 9 then return 1 end
	if b >= 9 then
		local bt = b - 9
		return math.floor(bt/7) + 2
	end
end

function PageButtons(p)
	if p == 1 then return 8 end
	return 7
end

function GetButtons(page)
	local t = {}
	if page == 1 then
		for i = 1, 8 do table.insert(t, i) end
	elseif page > 1 then
		for i = 1, 7 do table.insert(t, 8 + i + (page-2)*7) end
	end
	return t
end

function class_menu:SetText(txt)
	if type(txt) == "string" then
		self.buttonText = txt:split(",")
	elseif type(txt) == "table" then
		self.buttonText = txt
	else
		self.buttonText = {}
	end
end

function class_menu:getcustombutton(button,id,default)
end

function class_menu:click(id,button,page)
end

function class_menu:getbutton(b,p,id)
	local button = GetButtons(p)[b]
	local defaultBtText = self.buttonText[button]
	local btText = self:getcustombutton(button, id, defaultBtText) or defaultBtText or ""
	return btText
end

function class_menu:PageText(p, id)
	local text = ""
	for i = 1, PageButtons(p) do
		text = text .. self:getbutton(i, p, id) ..","
	end
	if p == 1 then
		text = text.."Next Page|Page "..p+1
	elseif p > 1 then
		text = text.."Previous Page|Page "..(p-1)..",Next Page|Page "..p+1
	end
	return text
end

function class_menu:OpenPlayer(id,page)
	local page = page or 1
	menu(id, self.title.." | Page "..page..","..self:PageText(page, id))
end

addhook("menu","menu_click")
function menu_click(id,men,sel)
	local f = string.find(men, "| Page")
	if f then
		local menu_page = tonumber(string.sub(men, f+7))
		local menu_name = string.sub(men, 1, f-2)
		local menu_object = game_menu[menu_name]
		local button = GetButtons(menu_page)[sel] or 0
		
		if menu_page then
			if sel == 9 then
				menu_object:OpenPlayer(id, menu_page+1)
			elseif sel == 8 and menu_page > 1 then
				menu_object:OpenPlayer(id, menu_page-1)
			else
				menu_object:click(id, button, menu_page)
			end
		end
	end
end