local function AddJobPanel(job, panel)
	local JobPanel = vgui.Create("DFrame", F4Menu_JobsMain)
	JobPanel:SetSize(F4Menu_JobsMain:GetWide(), 120)
	JobPanel:SetTitle("")
	JobPanel:ShowCloseButton(false)
	JobPanel:SetDraggable(false)
	JobPanel.Paint = function(self, w, h)
		draw.RoundedBox(0, 0, 0, w, h + 20, F4Menu_Reskin.Colors[1])
		draw.RoundedBox(0, 1, 1, w - 2, h - 2, F4Menu_Reskin.Colors[2])
		local x2, y2 = F4Menu_JobsMain:LocalToScreen(0, 0)
		local w2, h2 = F4Menu_JobsMain:GetSize()
		render.SetScissorRect(x2, y2, x2 + w2, y2 + h2, true)
		render.SetScissorRect(0, 0, 0, 0, false)
	end
	local Name = vgui.Create("DLabel", JobPanel)
	Name:SetPos(9, 6)
	local name = job.name
	local max = job.max
	local salary = string.Comma(job.salary)
	local tm = job.team
	Name:SetText(name.." - Lohn: $"..salary.." ("..team.NumPlayers(tm).."/"..max..")")
	Name:SetFont("F4Menu_JobFont")
	Name:SetTextColor(color_black)
	Name:SizeToContents()
	local nextcheck = CurTime()
	Name.Think = function()
		if nextcheck >= CurTime() then return end
		nextcheck = CurTime() + 0.1
		Name:SetText(name.." - Lohn: $"..salary.." ("..team.NumPlayers(tm).."/"..max..")")
		Name:SizeToContents()
	end
	local Desc = vgui.Create("DLabel", JobPanel)
	Desc:SetPos(10, 34)
	Desc:SetSize(JobPanel:GetWide() - 200, JobPanel:GetTall())
	Desc:SetTextColor(Color(0, 0, 0, 200))
	Desc:SetWrap(true)
	Desc:SetFont("F4Menu_MainFont")
	Desc:SetText(job.description)
	Desc:SetAutoStretchVertical(true)
	local Icon = vgui.Create("DModelPanel", JobPanel)
	Icon:SetPos(JobPanel:GetWide() - 148, 10)
	local model = job.model
	if istable(model) then
		local preferred = DarkRP.getPreferredJobModel(tm)
		if preferred then
			for _, mdl in ipairs(model) do
				if string.lower(preferred) == string.lower(mdl) then
					model = mdl
				end
			end
		end
		if istable(model) then
			model = model[math.random(#model)]
		end
	end
	Icon:SetModel(model)
	if job.skin then
		local ent = Icon.Entity
		if IsValid(ent) then
			ent:SetSkin(job.skin)
		end
	end
	Icon:SetSize(100, 100)
	Icon:SetCamPos(Vector(55, 0, 50))
	Icon:SetMouseInputEnabled(false)
	local ent = Icon:GetEntity()
	if IsValid(ent) then
		ent:SetEyeTarget(Vector(20, 00, 65))
	end
	Icon:SetAnimated(true)
	function Icon:LayoutEntity()
	end
	local ply = LocalPlayer()
	local Blocked = vgui.Create("DPanel", JobPanel)
	Blocked:SetSize(90, 10)
	Blocked:SetPos(JobPanel:GetWide() - 142, JobPanel:GetTall() - 41)

	local blockcheck = CurTime()
	local vip, level
	Blocked.Think = function(self)
		if blockcheck >= CurTime() then return end
		blockcheck = CurTime() + 1

		vip = job.vip and !MG_VIPGroups[ply:GetUserGroup()]
		level = job.level and ply:getLevel() < job.level
	end

	Blocked.Paint = function(self, w, h)
		if vip or level then
			if vip then
				draw.RoundedBox(0, 0, 0, w, h, F4Menu_Reskin.Colors[15])
				draw.SimpleText("VIP", "F4Menu_BuyItemFont", w / 2, h / 2 - 1, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
			else
				draw.RoundedBox(0, 0, 0, w, h, F4Menu_Reskin.Colors[15])
				draw.SimpleText("Level "..job.level, "F4Menu_BuyItemFont", w / 2, h / 2 - 1, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
			end
		end
	end
	Blocked:SetMouseInputEnabled(false)

	local SwitchJob = vgui.Create("DButton", JobPanel)
	SwitchJob:SetSize(90, 20)
	SwitchJob:SetPos(JobPanel:GetWide() - 142, JobPanel:GetTall() - 30)
	SwitchJob:SetText(DarkRP.getPhrase("become_job"))
	SwitchJob:SetFont("F4Menu_BuyItemFont")
	SwitchJob:SetTextColor(color_white)
	local unavailable
	SwitchJob.Paint = function(self, w, h)
		local col
		local col2 = F4Menu_Reskin.Colors[3]
		local col3 = F4Menu_Reskin.Colors[4]
		if self:IsHovered() then
			col = F4Menu_Reskin.Colors[5]
		else
			col = F4Menu_Reskin.Colors[6]
		end
		if unavailable then
			if self:IsHovered() then
				col = F4Menu_Reskin.Colors[7]
			else
				col = F4Menu_Reskin.Colors[8]
			end
			col2 = F4Menu_Reskin.Colors[9]
			col3 = F4Menu_Reskin.Colors[10]
		end
		draw.RoundedBox(0, 0, 0, w, h, col2)
		draw.RoundedBox(0, 1, 1, w - 2, h - 2, col)
		surface.SetDrawColor(col3)
		surface.DrawLine(1, 1, w - 2, 1)
		surface.DrawLine(1, 1, 1, 18)
		surface.DrawLine(1, 18, w - 2, 18)
		surface.DrawLine(w - 2, 1, w - 2, 18)
	end
	local customCheck = job.customCheck
	local nextcheck2 = CurTime()
	SwitchJob.Think = function(self, w, h)
		if nextcheck2 >= CurTime() then return end
		nextcheck2 = CurTime() + 0.25
		if (team.NumPlayers(tm) >= max and max != 0) then
			self:SetTooltip("Dieser Job ist voll!")
			unavailable = true
		elseif customCheck then
			local check = customCheck(ply)
			if check == false then
				if job.CustomCheckFailMsg then
					self:SetTooltip(job.CustomCheckFailMsg(ply))
				end
				unavailable = true
			else
				unavailable = false
			end
		else
			self:SetTooltip(nil)
		end
	end
	SwitchJob.DoClick = function(self)
		local command = job.command
		local model = job.model
		local vote = job.vote
		if istable(model) and #model > 0 then
			if unavailable then
				if vote then
					RunConsoleCommand("darkrp", "vote"..command)
				else
					RunConsoleCommand("darkrp", command)
				end
				return
			end
			local Background = vgui.Create("DFrame")
			Background:SetTitle("")
			Background:SetDraggable(false)
			Background:ShowCloseButton(false)
			Background:SetSize(ScrW(), ScrH())
			Background:SetPos(0, 0)
			Background:MakePopup()
			Background:ParentToHUD()
			Background.Paint = function()
			end
			Background.Think = function()
				if !IsValid(F4Menu) or !F4Menu:IsVisible() then
					Background:Close()
				end
			end
			local Main = vgui.Create("DFrame", Background)
			Main:SetSize(400, 500)
			Main:Center()
			Main:SetTitle("")
			Main:SetDraggable(false)
			Main:ShowCloseButton(false)
			Main.Init = function(self)
				self.StartTime = SysTime()
			end
			Main.Paint = function(self, w, h)
				Derma_DrawBackgroundBlur(self, self.StartTime)
				draw.RoundedBox(0, 0, 0, w, h, F4Menu_Reskin.Colors[1])
				draw.RoundedBox(0, 1, 1, w - 2, h - 2, F4Menu_Reskin.Colors[2])
				draw.RoundedBox(0, 0, 0, w, 40, F4Menu_Reskin.Colors[14])
				draw.SimpleText("Wähle ein Modell aus", "F4Menu_BoxTitleFont", 20, 10, color_white)
				surface.SetDrawColor(F4Menu_Reskin.Colors[16])
				surface.DrawLine(1, 1, w - 2, 1)
				surface.DrawLine(1, 1, 1, 38)
				surface.DrawLine(w - 2, 1, w - 2, 38)
			end
			local Close = vgui.Create("DButton", Main)
			Close:SetSize(50, 20)
			Close:SetPos(Main:GetWide() - 60, 0)
			Close:SetText("X")
			Close:SetFont("F4Menu_CloseFont")
			Close:SetTextColor(color_white)
			Close.Paint = function(self, w, h)
				local col
				if self:IsHovered() then
					col = Color(255, 150, 150, 255)
				else
					col = Color(175, 100, 100)
				end
				draw.RoundedBoxEx(0, 0, 0, w, h, Color(255, 150, 150, 255), false, false, true, true)
				draw.RoundedBoxEx(0, 1, 0, w - 2, h - 1, col, false, false, true, true)
			end
			Close.DoClick = function()
				Background:Close()
			end
			local CurrentModel
			local Pref = DarkRP.getPreferredJobModel(tm)
			if Pref then
				for _, mdl in ipairs(model) do
					if string.lower(Pref) == string.lower(mdl) then
						CurrentModel = mdl
					end
				end
			end
			if !CurrentModel then
				CurrentModel = model[1]
			end
			local ModelSelection = vgui.Create("DModelPanel", Main)
			ModelSelection:SetSize(500, 460)
			ModelSelection:SetModel(CurrentModel)
			if job.skin then
				local ent = ModelSelection.Entity
				if IsValid(ent) then
					ent:SetSkin(job.skin)
				end
			end
			ModelSelection:Center()
			ModelSelection.Angles = Angle(0, 45, 0)
			ModelSelection.DragMousePress = function(self)
				self.PressX, self.PressY = gui.MousePos()
				self.Pressed = true
			end
			ModelSelection.DragMouseRelease = function(self)
				self.Pressed = false
			end
			ModelSelection.LayoutEntity = function(self, ent)
				if self.bAnimated then
					self:RunAnimation()
				end
				if self.Pressed then
					local mx, my = gui.MousePos()
					self.Angles = self.Angles - Angle(0, (self.PressX or mx) - mx, 0)
					self.PressX, self.PressY = gui.MousePos()
				end
				ent:SetAngles(self.Angles)
			end
			local Previous = vgui.Create("DButton", Main)
			Previous:SetSize(40, 60)
			Previous:SetPos(50, Main:GetTall() / 2 - 30)
			Previous:SetText("<")
			Previous:SetFont("F4Menu_BoxTitleFont")
			Previous:SetTextColor(color_white)
			Previous.Paint = function(self, w, h)
				local col
				if self:IsHovered() then
					col = F4Menu_Reskin.Colors[5]
				else
					col = F4Menu_Reskin.Colors[6]
				end
				draw.RoundedBox(0, 0, 0, w, h, F4Menu_Reskin.Colors[3])
				draw.RoundedBox(0, 1, 1, w - 2, h - 2, col)
				surface.SetDrawColor(F4Menu_Reskin.Colors[17])
				surface.DrawLine(1, 1, w - 2, 1)
				surface.DrawLine(1, 1, 1, 58)
				surface.DrawLine(1, 58, w - 2, 58)
				surface.DrawLine(w - 2, 1, w - 2, 58)
			end
			Previous.DoClick = function()
				local NextModel = table.FindPrev(model, CurrentModel)
				ModelSelection:SetModel(NextModel)
				if job.skin then
					local ent = ModelSelection.Entity
					if IsValid(ent) then
						ent:SetSkin(job.skin)
					end
				end
				CurrentModel = NextModel
				DarkRP.setPreferredJobModel(tm, CurrentModel)
			end
			local Next = vgui.Create("DButton", Main)
			Next:SetSize(40, 60)
			Next:SetPos(Main:GetWide() - 90, Main:GetTall() / 2 - 30)
			Next:SetText(">")
			Next:SetFont("F4Menu_BoxTitleFont")
			Next:SetTextColor(color_white)
			Next.Paint = function(self, w, h)
				local col
				if self:IsHovered() then
					col = F4Menu_Reskin.Colors[5]
				else
					col = F4Menu_Reskin.Colors[6]
				end
				draw.RoundedBox(0, 0, 0, w, h, F4Menu_Reskin.Colors[3])
				draw.RoundedBox(0, 1, 1, w - 2, h - 2, col)
				surface.SetDrawColor(F4Menu_Reskin.Colors[17])
				surface.DrawLine(1, 1, w - 2, 1)
				surface.DrawLine(1, 1, 1, 58)
				surface.DrawLine(1, 58, w - 2, 58)
				surface.DrawLine(w - 2, 1, w - 2, 58)
			end
			Next.DoClick = function()
				local NextModel = table.FindNext(model, CurrentModel)
				ModelSelection:SetModel(NextModel)
				if job.skin then
					local ent = ModelSelection.Entity
					if IsValid(ent) then
						ent:SetSkin(job.skin)
					end
				end
				CurrentModel = NextModel
				DarkRP.setPreferredJobModel(tm, CurrentModel)
			end
			local Apply = vgui.Create("DButton", Main)
			Apply:SetSize(120, 30)
			Apply:SetPos(Main:GetWide() / 2 - 60, Main:GetTall() - 50)
			Apply:SetText("Akzeptieren")
			Apply:SetFont("F4Menu_BuyItemFont")
			Apply:SetTextColor(color_white)
			Apply.Paint = function(self, w, h)
				local col
				if self:IsHovered() then
					col = F4Menu_Reskin.Colors[5]
				else
					col = F4Menu_Reskin.Colors[6]
				end
				draw.RoundedBox(0, 0, 0, w, h, F4Menu_Reskin.Colors[3])
				draw.RoundedBox(0, 1, 1, w - 2, h - 2, col)
				surface.SetDrawColor(F4Menu_Reskin.Colors[17])
				surface.DrawLine(1, 1, w - 2, 1)
				surface.DrawLine(1, 1, 1, 28)
				surface.DrawLine(1, 28, w - 2, 28)
				surface.DrawLine(w - 2, 1, w - 2, 28)
			end
			Apply.DoClick = function()
				if vote then
					local menu = DermaMenu(Background)
					menu:AddOption("Abstimmung ausführen", function()
						RunConsoleCommand("darkrp", "vote"..command)
						if IsValid(Background) then
							Background:Close()
						end
					end)
					menu:AddOption("Abstimmung abbrechen", function()
						if IsValid(Background) then
							Background:Close()
						end
					end)
					menu:Open()
				else
					RunConsoleCommand("darkrp", command)
					if IsValid(Background) then
						Background:Close()
					end
				end
			end
		else
			if vote then
				if team.NumPlayers(tm) >= job.max then RunConsoleCommand("darkrp", "vote"..command) return end
				local menu = DermaMenu(F4Menu_JobsMain)
				menu:AddOption("Abstimmung ausführen", function()
					RunConsoleCommand("darkrp", "vote"..command)
				end)
				menu:AddOption("Abstimmung abbrechen", function()
				end)
				menu:Open()
			else
				RunConsoleCommand("darkrp", command)
			end
		end
	end
	if vote or job.RequiresVote and job.RequiresVote(ply, job.team) then
		SwitchJob:SetText(DarkRP.getPhrase("create_vote_for_job"))
	end
	local weps = job.weapons
	if weps and istable(weps) and #weps > 0 then
		local ShowWeapons = vgui.Create("DButton", JobPanel)
		ShowWeapons:SetSize(20, 20)
		ShowWeapons:SetPos(JobPanel:GetWide() - 167, JobPanel:GetTall() - 30)
		ShowWeapons:SetText("?")
		ShowWeapons:SetFont("F4Menu_BuyItemFont")
		ShowWeapons:SetTextColor(color_white)
		local valid_tooltip = false
		ShowWeapons.Paint = function(self, w, h)
			local col
			local col2 = F4Menu_Reskin.Colors[3]
			local col3 = F4Menu_Reskin.Colors[4]
			if self:IsHovered() then
				col = F4Menu_Reskin.Colors[5]
			else
				col = F4Menu_Reskin.Colors[6]
			end
			draw.RoundedBox(0, 0, 0, w, h, col2)
			draw.RoundedBox(0, 1, 1, w - 2, h - 2, col)
			surface.SetDrawColor(col3)
			surface.DrawLine(1, 1, w - 2, 1)
			surface.DrawLine(1, 1, 1, 18)
			surface.DrawLine(1, 18, w - 2, 18)
			surface.DrawLine(w - 2, 1, w - 2, 18)
			if !valid_tooltip then
				valid_tooltip = true
				local str = "Ausrüstung:"
				for _, v in ipairs(weps) do
					local wep = weapons.GetStored(v)
					if wep then
						str = str.."\n"..(wep.PrintName or wep.ClassName)
					else
						str = str.."\n"..v
					end
				end
				self:SetTooltip(str)
			end
		end
	end
	panel:AddItem(JobPanel)
end

function F4Menu_AddRefreshedJobs()
	local scrollbar = false
	local closedcats = {}
	if IsValid(F4Menu_JobsMain) then
		scrollbar = F4Menu_JobsMain.VBar:GetScroll()
		for k,v in ipairs(F4Menu_JobsMain:GetItems()) do
			if !v:GetExpanded() then
				closedcats[k] = true
			end
		end
		F4Menu_JobsMain:Remove()
	end
	F4Menu_JobsMain = vgui.Create("DPanelList", F4Menu_JobsPanel)
	F4Menu_JobsMain:SetSize(F4Menu_JobsPanel:GetWide(), F4Menu_JobsPanel:GetTall())
	F4Menu_JobsMain:SetSpacing(0)
	F4Menu_JobsMain:SetPos(0, 0)
	F4Menu_JobsMain:EnableVerticalScrollbar(true)
	F4Menu_JobsMain.Paint = function(s, w, h)
	end
	F4Menu_JobsMain.VBar.Paint = function(s, w, h)
		draw.RoundedBox(4, 3, 13, 8, h - 24, F4Menu_Reskin.Colors[11])
	end
	F4Menu_JobsMain.VBar.btnUp.Paint = function(s, w, h)
	end
	F4Menu_JobsMain.VBar.btnDown.Paint = function(s, w, h)
	end
	F4Menu_JobsMain.VBar.btnGrip.Paint = function(s, w, h)
		draw.RoundedBox(4, 5, 0, 4, h + 22, F4Menu_Reskin.Colors[11])
	end
	local F4Menu_JobCategories = {}
	local F4Menu_JobLists = {}
	local cats = DarkRP.getCategories()["jobs"]
	local ply = LocalPlayer()
	local tm = ply:Team()
	for key,data in pairs(cats) do
		if data["canSee"] and data["canSee"](ply) then
			local members = data["members"]
			if #members > 0 then
				if !F4Menu_JobLists[key] then
					local show
					for _,v in pairs(members) do
						local check = v.allowed
						if !check then check = {tm} end
						if table.HasValue(check, tm) then
							show = true
							break
						end
					end
					if !show then break end
					F4Menu_JobCategories[key] = vgui.Create("DCollapsibleCategory", F4Menu_JobsMain)
					local jobcat = F4Menu_JobCategories[key]
					jobcat:SetSize(F4Menu_JobsMain:GetWide(), 100)
					if (closedcats[key] == true) then
						jobcat:SetExpanded(false)
					else
						jobcat:SetExpanded(true)
					end
					jobcat:SetLabel("")
					local name = data["name"]
					jobcat.PaintOver = function(self, w, h)
						surface.SetDrawColor(F4Menu_Reskin.Colors[1])
						surface.DrawLine(0, 20, w, 20)
						draw.RoundedBox(0, 0, 0, w, 20, F4Menu_Reskin.Colors[13])
						draw.RoundedBox(0, 1, 1, w - 2, 20 - 2, F4Menu_Reskin.Colors[14])
						surface.SetDrawColor(F4Menu_Reskin.Colors[16])
						surface.DrawLine(1, 1, w - 1, 1)
						surface.DrawLine(1, 1, 1, 18)
						surface.DrawLine(1, 18, w - 1, 18)
						surface.DrawLine(w - 2, 1, w - 2, 18)
						draw.SimpleText(name, "F4Menu_CategoryTitle", 10, 3, color_white, TEXT_ALIGN_LEFT)
					end
					F4Menu_JobLists[key] = vgui.Create("DPanelList", jobcat)
					local joblist = F4Menu_JobLists[key]
					joblist:SetWide(F4Menu_JobsMain:GetWide())
					joblist:SetAutoSize(true)
					joblist:SetPadding(2)
					joblist:SetSpacing(0)
					joblist:SetPos(0, 20)
					joblist:EnableVerticalScrollbar(false)
					joblist.Paint = function(s, w, h)
						draw.RoundedBox(4, 3, 13, 8, h - 24, F4Menu_Reskin.Colors[11])
						draw.RoundedBox(0, 0, 0, w, h, F4Menu_Reskin.Colors[12])
					end
					F4Menu_JobsMain:AddItem(jobcat)
				end
				local name = team.GetName(tm)
				for _,job in pairs(members) do
					local j_name = job.name
					if F4Menu_Reskin.ShowNonAvailableJobsToAll then AddJobPanel(job, F4Menu_JobLists[key]) return end
					local changefrom = job.NeedToChangeFrom
					if (isnumber(changefrom) and tm == changefrom or istable(changefrom) and table.HasValue(changefrom, tm) or !changefrom) and (j_name != name) then
						local check = job.customCheck or function() return true end
						if (F4Menu_Reskin.JobExceptions[j_name] == true or check(ply)) then
							AddJobPanel(job, F4Menu_JobLists[key])
						end
					end
				end
			end
		end
	end
	for id in pairs(F4Menu_JobLists) do
		if #F4Menu_JobLists[id]:GetItems() == 0 then
			F4Menu_JobCategories[id]:Remove()
			F4Menu_JobCategories[id] = nil
		end
	end
	if scrollbar then
		F4Menu_JobsMain.VBar:AnimateTo(scrollbar, 0, 0, 1)
	end
end

function F4Menu_OpenJobs()
	F4Menu_JobsPanel = vgui.Create("DFrame", F4Menu_Main)
	F4Menu_JobsPanel:SetSize(F4Menu:GetWide() - 260, F4Menu:GetTall() - 50)
	F4Menu_JobsPanel:SetPos(30, 30)
	F4Menu_JobsPanel:ShowCloseButton(false)
	F4Menu_JobsPanel:SetTitle("")
	F4Menu_JobsPanel.Paint = function(self, w, h)
		draw.RoundedBox(0, 0, 0, w, h, F4Menu_Reskin.Colors[12])
	end
	F4Menu_AddRefreshedJobs()
	F4Menu_JobsPanel:SetVisible(false)
end