surface.CreateFont("FamilySystem_MainTitle", {font = "BebasNeue", size = 30, weight = 300, antialias = true})
surface.CreateFont("FamilySystem_InviteText", {font = "Open Sans", size = 18, weight = 400, antialias = true})
surface.CreateFont("FamilySystem_Text", {font = "Roboto Cn", size = 30, weight = 800, antialias = true})
surface.CreateFont("FamilySystem_GenericTitle", {font = "Roboto Cn", size = 30, weight = 400, antialias = true})
surface.CreateFont("FamilySystem_MOTD", {font = "Open Sans", size = 22, weight = 400, antialias = true})
surface.CreateFont("FamilySystem_Name", {font = "Roboto Cn", size = 24, weight = 400, antialias = true})
surface.CreateFont("FamilySystem_Rank", {font = "Roboto Cn", size = 22, weight = 400, antialias = true})
surface.CreateFont("FamilySystem_State", {font = "Roboto Cn", size = 20, weight = 400, antialias = true})
surface.CreateFont("FamilySystem_Button", {font = "Roboto Cn", size = 22, weight = 1000, antialias = true})
surface.CreateFont("FamilySystem_ButtonInfo", {font = "Roboto Cn", size = 18, weight = 500, antialias = true})
surface.CreateFont("FamilySystem_StatusBar", {font = "Roboto Cn", size = 24, weight = 1000, antialias = true})

local function AddLog(l)
	local text
	local typ = tonumber(l.typ)
	local a = l.a
	local b = l.b
	local c = l.c
	if typ == 1 and a and b then
		text = a.." hat $"..string.Comma(b).." von der Bank abgehoben."
	elseif typ == 2 and a and b then
		text = a.." hat $"..string.Comma(b).." in die Bank eingezahlt."
	elseif typ == 3 and a and b then
		text = a.." hat "..b.." in die Familie eingeladen."
	elseif typ == 4 and a then
		text = a.." ist der Familie beigetreten."
	elseif typ == 5 and a then
		text = a.." hat die Familie verlassen."
	elseif typ == 6 and a then
		text = a.." hat die Familie erstellt."
	elseif typ == 7 and a then
		text = a.." hat die Motd editiert."
	elseif typ == 8 and a and b then
		text = a.." hat "..b.." aus der Familie geworfen."
	elseif typ == 9 and a and b and c then
		text = a.." hat "..b.." zu "..c.." zugeteilt."
	elseif typ == 10 and a and b then
		text = a.." hat den Rang "..b.." erstellt."
	elseif typ == 11 and a and b then
		text = a.." hat den Rang "..b.." editiert."
	elseif typ == 12 and a and b and c then
		text = a.." hat den Rangnamen von "..b.." zu "..c.." geändert."
	elseif typ == 13 and a and b then
		text = a.." hat den Rang "..b.." gelöscht."
	elseif typ == 14 and a and b then
		text = a.." hat die Familie auf Lv. "..b.." verbessert."
	elseif typ == 15 and a and b then
		text = a.." hat die Familie zu "..b.." umbenannt."
	elseif typ == 16 and a and b then
		text = a.." hat $"..string.Comma(b).." von der Bank abgezogen."
	elseif typ == 17 and a and b then
		text = a.." hat $"..string.Comma(b).." zur Bank hinzugefügt."
	elseif typ == 18 and a and b then
		text = a.." hat die Familie an "..b.." übertragen."
	elseif typ == 19 and a then
		text = a.." hat die Logs zurückgesetzt."
	elseif typ == 20 and a then
		text = a.." hat die Finanzübersicht zurückgesetzt."
	elseif typ == 21 and a then
		text = a.." hat die Ränge zurückgesetzt."
	else
		text = "Ein unbekannter Fehler ist aufgetreten."
	end
	return text
end

local LookupFrame
local AdminFrame
net.Receive("FamilySystem_LookupFamily", function()
	local isvalid = IsValid(AdminFrame)
	if !isvalid then return end
	if isvalid then AdminFrame:Close() end
	local should_open = net.ReadBool()
	if !should_open then return end
	local leng = net.ReadUInt(32)
	local family = net.ReadData(leng)
	family = util.JSONToTable(util.Decompress(family))
	local name = family["name"]
	local bankbalance = tonumber(family["bankbalance"])
	local slots = family["slots"]
	local capacity = family["capacity"]
	local motd = family["motd"]
	local members = family["members"]
	local rankslist = family["ranks"]
	if !name or !bankbalance or !slots or !capacity or !members or !rankslist then Derma_Message("Ein unbekannter Fehler in Zusammenhang mit dem Laden der ausgewählten Familie ist aufgetreten!", "Unbekannter Fehler", "Okay") return end
	local memberslist = {}
	for k,v in pairs(members) do
		table.insert(memberslist, {steamid = k, name = v["name"], rank = v["rank"], jointime = v["jointime"], lastseen = v["lastseen"]})
	end
	table.sort(memberslist, function(b, c) return tonumber(b.jointime) < tonumber(c.jointime) end)
	LookupFrame = vgui.Create("DFrame")
	LookupFrame:SetSize(540, 600)
	LookupFrame:SetTitle("")
	LookupFrame:SetVisible(true)
	LookupFrame:SetDraggable(true)
	LookupFrame:ShowCloseButton(false)
	LookupFrame:Center()
	LookupFrame:MakePopup()
	LookupFrame.Paint = function()
		draw.RoundedBox(0, 0, 0, LookupFrame:GetWide(), LookupFrame:GetTall(), Color(226, 226, 226))
		draw.RoundedBox(0, 0, 0, LookupFrame:GetWide(), 30, Color(52, 73, 94))
	end
	local Close = vgui.Create("DButton", LookupFrame)
	Close:SetSize(70, 30)
	Close:SetPos(470 , 0)
	Close:SetColor(color_white)
	Close:SetText("X")
	Close:SetVisible(true)
	Close.Paint = function()
		if Close:IsHovered() then
			draw.RoundedBox(0, 0, 0, Close:GetWide(), Close:GetTall(), Color(192, 57, 43))
		else
			draw.RoundedBox(0, 0, 0, Close:GetWide(), Close:GetTall(), Color(231, 76, 60))
		end
	end
	Close.DoClick = function()
		surface.PlaySound("ui/buttonclick.wav")
		LookupFrame:Close()
	end
	local Title = vgui.Create("DLabel", LookupFrame)
	Title:SetText("Familie: "..name.." (Lv. "..(((tonumber(slots) - FamilySystem_Config.StandardSlots) / FamilySystem_Config.AddSlots) + 1)..") - Adminübersicht")
	Title:SetFont("FamilySystem_MainTitle")
	Title:SetColor(color_white)
	Title:SizeToContents()
	Title:SetPos(6, 2)
	local FirstStage = vgui.Create("DPanel", LookupFrame)
	FirstStage:SetSize(520, 555)
	FirstStage:SetPos(10, 40)
	local NameLabel = vgui.Create("DLabel", FirstStage)
	NameLabel:SetPos(10, 10)
	NameLabel:SetText("Name:")
	NameLabel:SetFont("FamilySystem_Name")
	NameLabel:SetColor(Color(52, 73, 94))
	NameLabel:SizeToContents()
	local NameText = vgui.Create("DTextEntry", FirstStage)
	NameText:SetPos(10, 35)
	NameText:SetSize(500, 30)
	NameText:SetFont("FamilySystem_Name")
	NameText:SetText(name)
	local BankBalanceLabel = vgui.Create("DLabel", FirstStage)
	BankBalanceLabel:SetPos(10, 75)
	BankBalanceLabel:SetText("Familienbank-Guthaben (Max: $"..string.Comma(capacity)..") :")
	BankBalanceLabel:SetFont("FamilySystem_Name")
	BankBalanceLabel:SetColor(Color(52, 73, 94))
	BankBalanceLabel:SizeToContents()
	local BankBalanceText = vgui.Create("DTextEntry", FirstStage)
	BankBalanceText:SetPos(10, 100)
	BankBalanceText:SetSize(500, 30)
	BankBalanceText:SetFont("FamilySystem_Name")
	BankBalanceText:SetText("$"..string.Comma(bankbalance))
	local MOTDLabel = vgui.Create("DLabel", FirstStage)
	MOTDLabel:SetPos(10, 140)
	MOTDLabel:SetText("Motd:")
	MOTDLabel:SetFont("FamilySystem_Name")
	MOTDLabel:SetColor(Color(52, 73, 94))
	MOTDLabel:SizeToContents()
	local MOTDBackground = vgui.Create("DPanel", FirstStage)
	MOTDBackground:SetSize(500, 140)
	MOTDBackground:SetPos(10, 165)
	local MOTDScrollPanel = vgui.Create("DScrollPanel", MOTDBackground)
	MOTDScrollPanel:Dock(FILL)
	local MOTDText = vgui.Create("DLabel", MOTDScrollPanel)
	MOTDText:SetPos(5, 5)
	MOTDText:SetAutoStretchVertical(true)
	MOTDText:SetWide(490)
	MOTDText:SetWrap(true)
	MOTDText:SetFont("FamilySystem_MOTD")
	MOTDText:SetColor(color_black)
	MOTDText:SetText((!motd or motd == "NULL") and "Kein Text spezifiziert." or motd)
	local MembersLabel = vgui.Create("DLabel", FirstStage)
	MembersLabel:SetPos(10, 310)
	MembersLabel:SetText("Mitglieder ("..#memberslist.." / "..slots.."):")
	MembersLabel:SetFont("FamilySystem_Name")
	MembersLabel:SetColor(Color(52, 73, 94))
	MembersLabel:SizeToContents()
	local MembersList = vgui.Create("DListView", FirstStage)
	MembersList:SetSize(500, 155)
	MembersList:SetPos(10, 340)
	MembersList:AddColumn("Mitglied"):SetFixedWidth(140)
	MembersList:AddColumn("Rang"):SetFixedWidth(140)
	MembersList:AddColumn("Status"):SetFixedWidth(140)
	MembersList:AddColumn("Zuletzt"):SetFixedWidth(80)

	local function AddPlayers()
		MembersList:Clear()
		for _,v in ipairs(memberslist) do
			local online = v.online
			local ply = player.GetBySteamID(v.steamid)
			if ply then
				if ply:getDarkRPVar("job") == "AFK" then
					online = "AFK"
				else
					online = "Online"
				end
			else
				online = "Offline"
			end
			local rank = v.rank
			local rename = rankslist[rank] and rankslist[rank].rename
			if rename then
				rank = rename
			end
			MembersList:AddLine(v.name, rank, online, os.date("%d. %m. %y", v.lastseen))
		end
	end

	AddPlayers()

	MembersList.OnRowSelected = function(btn, line)
		local column = MembersList:GetLine(line)
		local ply_name = column:GetColumnText(1)
		local steamid
		for _,v in ipairs(memberslist) do
			if v.name == ply_name then
				steamid = v.steamid
			end
		end
		if !steamid then return end
		local menu = DermaMenu(btn)
		menu:AddOption("Mitglied rauswerfen", function()
			surface.PlaySound("ui/buttonclick.wav")
			RunConsoleCommand("family_kick", steamid, 1, name)
		end):SetIcon("icon16/delete.png")
		menu:AddOption("Familie übertragen", function()
			surface.PlaySound("ui/buttonclick.wav")
			RunConsoleCommand("family_transfer_admin", steamid, name)
			for _,v in ipairs(memberslist) do
				if v.rank == "o" then
					v.rank = "n"
				end
				if v.steamid == steamid then
					v.rank = "o"
				end
			end
			AddPlayers()
		end):SetIcon("icon16/user_suit.png")
		menu:AddOption("SteamID kopieren", function()
			surface.PlaySound("ui/buttonclick.wav")
			SetClipboardText(steamid)
			LocalPlayer():ChatPrint("SteamID kopiert.")
		end):SetIcon("icon16/application_xp_terminal.png")
		menu:Open()
	end
	local EditBalance = vgui.Create("DButton", FirstStage)
	EditBalance:SetSize(200, 40)
	EditBalance:SetPos(10, 510)
	EditBalance:SetColor(color_white)
	EditBalance:SetFont("FamilySystem_Rank")
	EditBalance:SetText("Änderungen übernehmen")
	EditBalance.DoClick = function()
		surface.PlaySound("ui/buttonclick.wav")
		local balance = BankBalanceText:GetValue()
		balance = string.Replace(balance, "$", "")
		balance = string.Replace(balance, ",", "")
		balance = tonumber(balance)
		if balance then
			balance = math.ceil(balance)
			local diff = balance - bankbalance
			if diff != 0 then
				bankbalance = balance
				RunConsoleCommand("family_setmoney", name, balance)
				BankBalanceText:SetText("$"..string.Comma(balance))
			end
		else
			notification.AddLegacy("Du musst eine gültige Zahl angeben!", NOTIFY_ERROR, 4)
		end
		local newname = NameText:GetValue()
		newname = string.TrimLeft(newname)
		newname = string.TrimRight(newname)
		if newname != name then
			if #newname > 0 and string.Trim(newname) != "" then
				RunConsoleCommand("family_rename", newname, 1, name)
				name = newname
				Title:SetText("Familie: "..name.." - Adminübersicht")
				Title:SizeToContents()
			else
				notification.AddLegacy("Dieser Name ist nicht akzeptabel!", NOTIFY_ERROR, 4)
			end
		end
	end
	EditBalance.Paint = function()
		draw.RoundedBox(0, 0, 0, EditBalance:GetWide(), EditBalance:GetTall(), Color(46, 204, 113))
	end
	local OpenLogs = vgui.Create("DButton", FirstStage)
	OpenLogs:SetSize(125, 40)
	OpenLogs:SetPos(220, 510)
	OpenLogs:SetColor(color_white)
	OpenLogs:SetFont("FamilySystem_Rank")
	OpenLogs:SetText("Logs öffnen")
	OpenLogs.DoClick = function()
		surface.PlaySound("ui/buttonclick.wav")
		if IsValid(LookupFrame.LogPanel) then LookupFrame.LogPanel:Remove() end
		local LogPanel = vgui.Create("DFrame")
		LookupFrame.LogPanel = LogPanel
		LogPanel:SetSize(500, 400)
		LogPanel:SetTitle("")
		LogPanel:SetVisible(true)
		LogPanel:ShowCloseButton(false)
		LogPanel:Center()
		LogPanel:MakePopup()
		LogPanel.Paint = function()
			draw.RoundedBox(0, 0, 0, LogPanel:GetWide(), LogPanel:GetTall(), Color(226, 226, 226))
			draw.RoundedBox(0, 0, 0, LogPanel:GetWide(), 30, Color(52, 73, 94))
		end
		local Close = vgui.Create("DButton", LogPanel)
		Close:SetSize(70, 30)
		Close:SetPos(430 , 0)
		Close:SetColor(color_white)
		Close:SetText("X")
		Close:SetVisible(true)
		Close.Paint = function()
			if Close:IsHovered() then
				draw.RoundedBox(0, 0, 0, Close:GetWide(), Close:GetTall(), Color(192, 57, 43))
			else
				draw.RoundedBox(0, 0, 0, Close:GetWide(), Close:GetTall(), Color(231, 76, 60))
			end
		end
		Close.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			LogPanel:Close()
		end
		local Title = vgui.Create("DLabel", LogPanel)
		Title:SetText("Adminübersicht: Logs")
		Title:SetFont("FamilySystem_MainTitle")
		Title:SetColor(color_white)
		Title:SizeToContents()
		Title:SetPos(6, 2)

		local LogList
		local loglist = {}
		local floglist = {}

		local function AddLogs()
			if IsValid(LogList) then
				LogList:Clear()
				for _,v in ipairs(loglist) do
					LogList:AddLine(os.date("%d.%m.%y", v.time).." / "..os.date("%H:%M", v.time), AddLog(v))
				end
				if #LogList:GetLines() <= 0 then
					local time = os.time()
					LogList:AddLine(os.date("%d.%m.%y", time).." / "..os.date("%H:%M", time), "Keine Logs vorhanden.")
				end
			end
		end

		local function AddFinanceLogs()
			if IsValid(LogList) then
				LogList:Clear()
				local tot = 0
				local mon = 0
				for _,v in ipairs(floglist) do
					local total = tonumber(v.total)
					local month = tonumber(v.month)
					local data = v["data"]
					if !data then continue end
					tot = tot + total
					mon = mon + month
					local rank = data["rank"]
					local rename = rankslist[rank] and rankslist[rank].rename
					if rename then
						rank = rename
					end
					local text1 = string.sub(total, 1, 1) == "-" and "-$"..string.Comma(math.abs(total)) or "+$"..string.Comma(total)
					local text2 = string.sub(month, 1, 1) == "-" and "-$"..string.Comma(math.abs(month)) or "+$"..string.Comma(month)
					local line = LogList:AddLine(data["name"], rank, text1, text2)
					line.Columns[3]:SetTextColor(total > 0 and Color(0, 150, 0) or total < 0 and Color(255, 0, 0) or color_black)
					line.Columns[4]:SetTextColor(month > 0 and Color(0, 150, 0) or month < 0 and Color(255, 0, 0) or color_black)
				end
				local text1 = string.sub(tot, 1, 1) == "-" and "-$"..string.Comma(math.abs(tot)) or "+$"..string.Comma(tot)
				local text2 = string.sub(mon, 1, 1) == "-" and "-$"..string.Comma(math.abs(mon)) or "+$"..string.Comma(mon)
				local line = LogList:AddLine("Gesamt:", "", text1, text2)
				line.Columns[3]:SetTextColor(tot > 0 and Color(0, 150, 0) or tot < 0 and Color(255, 0, 0) or color_black)
				line.Columns[4]:SetTextColor(mon > 0 and Color(0, 150, 0) or mon < 0 and Color(255, 0, 0) or color_black)
			end
		end

		local function GenerateLogList(noadd)
			if IsValid(LogList) then
				LogList:Remove()
			end
			LogList = vgui.Create("DListView", LogPanel)
			LogList:SetMultiSelect(false)
			LogList:SetPos(10, 60)
			LogList:SetSize(480, 330)
			LogList:AddColumn("Datum"):SetFixedWidth(95)
			LogList:AddColumn("Log"):SetFixedWidth(385)
			LogList.OnRowSelected = function(parent, line)
				local column = LogList:GetLine(line)
				local log = column:GetColumnText(2)
				local menu = DermaMenu(parent)
				menu:AddOption("Zeile kopieren", function() 
					SetClipboardText(log)
					LocalPlayer():ChatPrint("Zeile kopiert.")
				end)
				menu:Open()
			end
			if noadd then return end
			AddLogs()
		end

		local function GenerateFinancesList()
			if IsValid(LogList) then
				LogList:Remove()
			end
			LogList = vgui.Create("DListView", LogPanel)
			LogList:SetMultiSelect(false)
			LogList:SetPos(10, 60)
			LogList:SetSize(480, 330)
			LogList:AddColumn("Mitglied"):SetFixedWidth(150)
			LogList:AddColumn("Rang"):SetFixedWidth(100)
			LogList:AddColumn("Gesamtbilanz"):SetFixedWidth(115)
			LogList:AddColumn("Monatsbilanz"):SetFixedWidth(115)
			AddFinanceLogs()
		end

		GenerateLogList(true)
		local SwitchButton = vgui.Create("DButton", LogPanel)
		SwitchButton:SetPos(340, 35)
		SwitchButton:SetSize(150, 20)
		SwitchButton:SetText("Zu Finanzen wechseln")
		local selected = 0
		SwitchButton.DoClick = function()
			if selected == 0 then
				SwitchButton:SetText("Zu Logs wechseln")
				selected = 1
				GenerateFinancesList()
			else
				SwitchButton:SetText("Zu Finanzen wechseln")
				selected = 0
				GenerateLogList()
			end
		end
		local RefreshButton = vgui.Create("DButton", LogPanel)
		RefreshButton:SetPos(235, 35)
		RefreshButton:SetSize(100, 20)
		RefreshButton:SetText("Aktualisieren")
		RefreshButton.DoClick = function()
			if selected == 0 then
				net.Start("FamilySystem_LoadLogs_Admin")
					net.WriteString(name)
				net.SendToServer()
			else
				net.Start("FamilySystem_LoadFinances_Admin")
					net.WriteString(name)
				net.SendToServer()
			end
		end
		LogList:AddLine(os.date("%d.%m.%y", time).." / "..os.date("%H:%M", time), "Logs werden geladen...")

		net.Receive("FamilySystem_LoadLogs_Admin", function()
			local leng = net.ReadUInt(32)
			local logdata = net.ReadData(leng)
			logdata = util.JSONToTable(util.Decompress(logdata))
			loglist = {}
			for _,v in ipairs(logdata) do
				table.insert(loglist, v)
			end
			table.sort(loglist, function(a, b) return tonumber(a.time) > tonumber(b.time) end)
			if selected == 0 and #loglist > 0 then
				AddLogs()
			end
		end)

		net.Start("FamilySystem_LoadLogs_Admin")
			net.WriteString(name)
		net.SendToServer()

		net.Receive("FamilySystem_LoadFinances_Admin", function()
			local leng = net.ReadUInt(32)
			local logdata = net.ReadData(leng)
			logdata = util.JSONToTable(util.Decompress(logdata))
			floglist = {}
			for k,v in pairs(logdata) do
				v["steamid"] = k
				v["data"] = members[k]
				table.insert(floglist, v)
			end
			table.sort(floglist, function(a, b) return tonumber(a.month) > tonumber(b.month) end)
			if selected == 1 then
				AddFinanceLogs()
			end
		end)

		net.Start("FamilySystem_LoadFinances_Admin")
			net.WriteString(name)
		net.SendToServer()
	end
	OpenLogs.Paint = function()
		draw.RoundedBox(0, 0, 0, OpenLogs:GetWide(), OpenLogs:GetTall(), Color(150, 150, 150))
	end
	local DeleteFamily = vgui.Create("DButton", FirstStage)
	DeleteFamily:SetSize(155, 40)
	DeleteFamily:SetPos(355, 510)
	DeleteFamily:SetColor(color_white)
	DeleteFamily:SetFont("FamilySystem_Rank")
	DeleteFamily:SetText("Familie löschen")
	DeleteFamily.DoClick = function()
		surface.PlaySound("ui/buttonclick.wav")
		Derma_Query("Möchtest du diese Familie wirklich unwiderruflich löschen?", "Familie löschen", "Ja", function()
			RunConsoleCommand("family_leave", 1, name)
			LookupFrame:Close()
		end, "Nein")
	end
	DeleteFamily.Paint = function()
		draw.RoundedBox(0, 0, 0, DeleteFamily:GetWide(), DeleteFamily:GetTall(), Color(231, 76, 60))
	end
end)

concommand.Add("family_admin", function(ply)
	if !IsValid(ply) then return end
	if ply:IsSuperAdmin() then
		if IsValid(AdminFrame) then AdminFrame:Close() end
		AdminFrame = vgui.Create("DFrame")
		AdminFrame:SetSize(400, 200)
		AdminFrame:SetTitle("")
		AdminFrame:SetVisible(true)
		AdminFrame:SetDraggable(true)
		AdminFrame:ShowCloseButton(false)
		AdminFrame:Center()
		AdminFrame:MakePopup()
		AdminFrame.Paint = function()
			draw.RoundedBox(0, 0, 0, AdminFrame:GetWide(), AdminFrame:GetTall(), Color(226,226,226))
		end
		local NamePanel = vgui.Create("DLabel", AdminFrame)
		NamePanel:SetText("Familiensystem: Adminbereich")
		NamePanel:SetFont("FamilySystem_State")
		NamePanel:SetColor(Color(52, 73, 94))
		NamePanel:SizeToContents()
		NamePanel:SetPos(5, 3)
		local Close = vgui.Create("DButton", AdminFrame)
		Close:SetSize(70, 20)
		Close:SetPos(330,0)
		Close:SetColor(color_white)
		Close:SetText("X")
		Close.Paint = function()
			if Close:IsHovered() then
				draw.RoundedBox(0, 0, 0, Close:GetWide(), Close:GetTall(), Color(192, 57, 43))
			else
				draw.RoundedBox(0, 0, 0, Close:GetWide(), Close:GetTall(), Color(231, 76, 60))
			end
		end
		Close.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			AdminFrame:Close()
		end
		local SearchByName
		local SearchByPlayer
		local SearchBySteamID
		SearchByName = vgui.Create("DTextEntry", AdminFrame)
		SearchByName:SetValue("Nach Name einer Familie suchen")
		SearchByName.OldMousePressed = SearchByName.OnMousePressed
		function SearchByName:OnMousePressed(...)
			self:OldMousePressed(...)
			if (self:GetValue() == "Nach Name einer Familie suchen") then
				self:SetValue("")
			end
		end
		SearchByName:SetFont("FamilySystem_FlatButton")
		SearchByName:SetSize(370, 35)
		SearchByName:SetPos(15, 35)
		SearchByName.Paint = function(me)
			draw.RoundedBox(0, 0, 0, SearchByName:GetWide(), SearchByName:GetTall(), SearchByName._Selected and color_white or Color(245, 245, 255))
			surface.SetDrawColor(189, 195, 199, 255)
			surface.DrawOutlinedRect(0, 0, SearchByName:GetWide(), SearchByName:GetTall())
			me:DrawTextEntryText(Color(52, 73, 94, 255), Color(52, 73, 94, 255), Color(52, 73, 94, 255))
		end
		SearchByName.OnTextChanged = function()
			SearchByName._Selected = true
			SearchByPlayer:SetText("Nach Familie eines Spielers suchen")
			SearchByPlayer._Selected = false
			SearchBySteamID:SetText("Nach Familie eines Spielers über SteamID suchen")
			SearchBySteamID._Selected = false
		end
		SearchByPlayer = vgui.Create("DComboBox", AdminFrame)
		SearchByPlayer:SetValue("Nach Familie eines Spielers suchen")
		SearchByPlayer:SetFont("FamilySystem_FlatButton")
		SearchByPlayer:SetSize(370, 35)
		SearchByPlayer:SetPos(15, 75)
		local players = player.GetAll()
		table.sort(players, function(a, b) return a:Name() < b:Name() end)
		for _,v in ipairs(players) do
			SearchByPlayer:AddChoice(v:Name())
		end
		SearchByPlayer.Paint = function()
			draw.RoundedBox(0, 0, 0, SearchByPlayer:GetWide(), SearchByPlayer:GetTall(), SearchByPlayer._Selected and color_white or Color(245, 245, 255))
			surface.SetDrawColor(189, 195, 199, 255)
			surface.DrawOutlinedRect(0, 0, SearchByPlayer:GetWide(), SearchByPlayer:GetTall())
		end
		SearchByPlayer.OnSelect = function()
			SearchByPlayer._Selected = true
			SearchByName:SetText("Nach Name einer Familie suchen")
			SearchByName._Selected = false
			SearchBySteamID:SetText("Nach Familie eines Spielers über SteamID suchen")
			SearchBySteamID._Selected = false
		end
		SearchBySteamID = vgui.Create("DTextEntry", AdminFrame)
		SearchBySteamID:SetValue("Nach Familie eines Spielers über SteamID suchen")
		SearchBySteamID.OldMousePressed = SearchBySteamID.OnMousePressed
		function SearchBySteamID:OnMousePressed(...)
			self:OldMousePressed(...)
			if (self:GetValue() == "Nach Familie eines Spielers über SteamID suchen") then
				self:SetValue("")
			end
		end
		SearchBySteamID:SetFont("FamilySystem_FlatButton")
		SearchBySteamID:SetSize(370, 35)
		SearchBySteamID:SetPos(15, 115)
		SearchBySteamID.Paint = function(me)
			draw.RoundedBox(0, 0, 0, SearchBySteamID:GetWide(), SearchBySteamID:GetTall(), SearchBySteamID._Selected and color_white or Color(245, 245, 255))
			surface.SetDrawColor(189, 195, 199, 255)
			surface.DrawOutlinedRect(0, 0, SearchBySteamID:GetWide(), SearchBySteamID:GetTall())
			me:DrawTextEntryText(Color(52, 73, 94, 255), Color(52, 73, 94, 255), Color(52, 73, 94, 255))
		end
		SearchBySteamID.OnTextChanged = function()
			SearchBySteamID._Selected = true
			SearchByName:SetText("Nach Name einer Familie suchen")
			SearchByName._Selected = false
			SearchByPlayer:SetText("Nach Familie eines Spielers suchen")
			SearchByPlayer._Selected = false
		end
		local LookupPlayer = vgui.Create("DFlatButton", AdminFrame)
		LookupPlayer:SetSize(250, 35)
		LookupPlayer:SetPos(75, 160)
		LookupPlayer:SetText("Familie öffnen")
		LookupPlayer.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			if SearchByName._Selected then
				local value = SearchByName:GetValue()
				if value != "Nach Name einer Familie suchen" and string.Trim(value) != "" and string.Trim(value) != "Nach Name einer Familie suchen" then
					local leng = #value
					if leng >= 3 and leng <= 25 then
						SearchByName:SetDisabled(true)
						SearchByPlayer:SetDisabled(true)
						SearchBySteamID:SetDisabled(true)
						LookupPlayer:SetDisabled(true)
						LookupPlayer:SetText("Bitte warten...")
						RunConsoleCommand("family_lookup", 1, value)
					else
						Derma_Message("Ein Familien-Name kann nur 3 bis 25 Zeichen lang sein!", "Ungültige Namenslänge!", "Okay")
					end
				else
					Derma_Message("So heisst definitiv keine Familie!", "Ungültiger Familienname!", "Okay")
				end
			elseif SearchByPlayer._Selected then
				local value = SearchByPlayer:GetValue()
				if value != "Nach Familie eines Spielers suchen" then
					SearchByName:SetDisabled(true)
					SearchByPlayer:SetDisabled(true)
					SearchBySteamID:SetDisabled(true)
					LookupPlayer:SetDisabled(true)
					LookupPlayer:SetText("Bitte warten...")
					RunConsoleCommand("family_lookup", 2, value)
				else
					Derma_Message("Bitte wähle zuerst einen gültigen Spieler aus!", "Kein Spieler ausgewählt!", "Okay")
				end
			elseif SearchBySteamID._Selected then
				local value = SearchBySteamID:GetValue()
				if value != "Nach Familie eines Spielers über SteamID suchen" and string.Trim(value) != "Nach Familie eines Spielers über SteamID suchen"  then
					value = string.upper(string.Trim(value))
					if value:match("^(STEAM_[0-9]+:[0-9]+:[0-9]+)$") then
						SearchByName:SetDisabled(true)
						SearchByPlayer:SetDisabled(true)
						SearchBySteamID:SetDisabled(true)
						LookupPlayer:SetDisabled(true)
						LookupPlayer:SetText("Bitte warten...")
						RunConsoleCommand("family_lookup", 3, value)
					else
						Derma_Message("Du musst eine gültige SteamID angeben!", "Keine gültige SteamID angegeben!", "Okay")
					end
				else
					Derma_Message("Du musst schon eine SteamID angeben!", "Keine SteamID angegeben!", "Okay")
				end
			else
				Derma_Message("Du musst eine der 3 Schaltflächen benutzen, um nach einer Familie zu suchen!", "Keine Suchmethode ausgewählt!", "Okay")
			end
		end
	else
		Derma_Query("Du hast nicht die benötigten Privilegien hierfür!", "Familiensystem: Adminbereich", "Zurück")
	end
end)

local FS_Frame
local size_x, size_y = 700, 400
local bar_start, bar_dest, bar_text, bar_color = 0, 0, "", color_white

local gradientup = Material("gui/gradient_up")
local gradientdown = Material("gui/gradient_down")
local function DrawBar()
	local filled = math.Clamp((CurTime() - bar_start) / bar_dest, 0, 1)
	local color = bar_color
	local w, h = size_x, 30
	local centerx, centery = ScrW() / 2, ScrH() / 2 + (size_y / 2) + (h / 2)
	if IsValid(FS_Frame) then
		local x, y = FS_Frame:GetPos()
		centerx = x + (w / 2)
		centery = y + size_y + (h / 2)
	end
	local x, y = centerx - w / 2, centery - h / 2
	surface.SetDrawColor(Color(255, 255, 255, 200))
	surface.DrawOutlinedRect(x, y, w, h)
	surface.SetDrawColor(color)
	surface.SetMaterial(gradientdown)
	surface.DrawTexturedRect(x + 1, y + 1, (w - 2) * filled, h - 2)
	surface.SetDrawColor(Color(color.r / 2, color.g / 2, color.b/ 2))
	surface.SetMaterial(gradientup)
	surface.DrawTexturedRect(x + 1, y + 1, (w - 2) * filled, h - 2)
	draw.SimpleTextOutlined(bar_text, "FamilySystem_StatusBar", centerx, centery, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, color_black)
	if filled == 1 then
		hook.Remove("HUDPaint", "FamilySystem_DrawBar")
	end
end

net.Receive("FamilySystem_QueueAction", function()
	bar_start = CurTime()
	bar_dest = net.ReadFloat(16)
	if bar_dest <= 0.1 then
		bar_text = ""
		hook.Remove("HUDPaint", "FamilySystem_DrawBar")
		return
	end
	bar_text = net.ReadString()
	bar_color = net.ReadColor()
	hook.Add("HUDPaint", "FamilySystem_DrawBar", DrawBar, HOOK_MONITOR_LOW or 2)
end)

net.Receive("FamilySystem_OpenMenu", function()
	if IsValid(FS_Frame) then return end
	local local_ply = LocalPlayer()
	local leng = net.ReadUInt(32)
	local tab = net.ReadData(leng)
	tab = util.JSONToTable(util.Decompress(tab))
	local familyname = tab["name"]
	local bankbalance = tab["bankbalance"]
	local slots = tab["slots"]
	local capacity = tab["capacity"]
	local motd = tab["motd"]
	local members = tab["members"]
	if !familyname or !bankbalance or !slots or !capacity or !members then Derma_Message("Ein unbekannter Fehler in Zusammenhang mit deiner Familie ist aufgetreten!", "Unbekannter Fehler", "Okay") return end
	local online = {}
	for _,v in ipairs(player.GetAll()) do
		local sid = v:SteamID()
		if members[sid] then
			online[sid] = v
		end
	end
	local memberslist = {}
	for k,v in pairs(members) do
		table.insert(memberslist, {steamid = k, name = v["name"], rank = v["rank"], jointime = v["jointime"], lastseen = v["lastseen"], ["online"] = online[k] and true or false})
	end
	table.sort(memberslist, function(b, c) return tonumber(b.jointime) < tonumber(c.jointime) end)
	local rankslist = tab["ranks"]
	local ply_rank = members[local_ply:SteamID()] and members[local_ply:SteamID()]["rank"]
	if !ply_rank then return end
	ply_rank = rankslist[ply_rank]
	if !ply_rank then return end
	local rank_name = ply_rank["name"]
	local rank_flags = ply_rank["flags"]
	FS_Frame = vgui.Create("DFrame")
	FS_Frame:SetSize(size_x, size_y)
	FS_Frame:SetTitle("")
	FS_Frame:SetVisible(true)
	FS_Frame:SetDraggable(true)
	FS_Frame:ShowCloseButton(false)
	FS_Frame:Center()
	FS_Frame:MakePopup()
	FS_Frame:ParentToHUD()
	FS_Frame.Paint = function()
		draw.RoundedBox(0, 0, 0, FS_Frame:GetWide(), FS_Frame:GetTall(), Color(226, 226, 226))
	end
	FS_Frame.OnRemove = function()
		net.Start("FamilySystem_CloseMenu")
		net.SendToServer()
	end
	local Close = vgui.Create("DButton", FS_Frame)
	Close:SetSize(70, 20)
	Close:SetPos(630,0)
	Close:SetColor(color_white)
	Close:SetText("X")
	Close.Paint = function()
		if Close:IsHovered() then
			draw.RoundedBox(0, 0, 0, Close:GetWide(), Close:GetTall(), Color(192, 57, 43))
		else
			draw.RoundedBox(0, 0, 0, Close:GetWide(), Close:GetTall(), Color(231, 76, 60))
		end
	end
	Close.DoClick = function()
		surface.PlaySound("ui/buttonclick.wav")
		FS_Frame:Close()
	end
	local NamePanel = vgui.Create("DLabel", FS_Frame)
	NamePanel:SetText(familyname.." (Lv. "..(((tonumber(slots) - FamilySystem_Config.StandardSlots) / FamilySystem_Config.AddSlots) + 1)..")")
	NamePanel:SetFont("FamilySystem_GenericTitle")
	NamePanel:SetColor(Color(52, 73, 94))
	NamePanel:SizeToContents()
	NamePanel:SetPos(210, 3)

	net.Receive("FamilySystem_RefreshName", function()
		local name = net.ReadString()
		if IsValid(NamePanel) then
			NamePanel:SetText(name)
			NamePanel:SizeToContents()
		end
		familyname = name
	end)

	local SideMenu = vgui.Create("DSideMenu", FS_Frame)
	SideMenu:SetPos(0, 0)
	SideMenu:SetSize(200, 400)
	local Dashboard = vgui.Create("DCustomPanel", FS_Frame)
	Dashboard:Title("Dashboard")
	local PanelsHolder = vgui.Create("DPanelList", Dashboard)
	PanelsHolder:SetPos(10, 45)
	PanelsHolder:SetSize(480, 200)
	PanelsHolder:SetSpacing(15)
	PanelsHolder:EnableHorizontal(true) 
	local MembersBlock = vgui.Create("DPanel")
	MembersBlock:SetTall(120)
	MembersBlock:SetWide(150)
	MembersBlock.Paint = function()
		draw.RoundedBox(0, 0, 0, MembersBlock:GetWide(), MembersBlock:GetTall(), Color(59, 174, 218))
		draw.RoundedBox(0, 0,  MembersBlock:GetTall() - 30, MembersBlock:GetWide(), 30, color_white)
	end
	local MembersBlockLabel = vgui.Create("DLabel", MembersBlock)
	MembersBlockLabel:SetColor(Color(148, 148, 150))
	MembersBlockLabel:SetFont("FamilySystem_FlatButton")
	MembersBlockLabel:SetText("Mitglieder")
	MembersBlockLabel:SizeToContents()
	MembersBlockLabel:SetPos(MembersBlock:GetWide() / 2 - MembersBlockLabel:GetWide() / 2, 93)
	local MembersBlockImage = vgui.Create("DImage", MembersBlock)
	MembersBlockImage:SetImage("fsystem/members.png")
	MembersBlockImage:SizeToContents()
	MembersBlockImage:SetPos(MembersBlock:GetWide() / 2 - MembersBlockImage:GetWide() / 2, 12)
	local MembersBlockLabel2 = vgui.Create("DLabel", MembersBlock)
	MembersBlockLabel2:SetColor(color_white)
	MembersBlockLabel2:SetFont("FamilySystem_Text")
	MembersBlockLabel2:SetText(#memberslist.."/"..slots)
	MembersBlockLabel2:SizeToContents()
	MembersBlockLabel2:SetPos(MembersBlock:GetWide() / 2 - MembersBlockLabel2:GetWide() / 2, 50)
	PanelsHolder:AddItem(MembersBlock)

	local LevelLabel
	net.Receive("FamilySystem_RefreshSlots", function()
		local max = net.ReadUInt(32)
		if IsValid(MembersBlockLabel2) then
			MembersBlockLabel2:SetText(#memberslist.."/"..max)
		end
		slots = max
		if IsValid(NamePanel) then
			NamePanel:SetText(familyname.." (Lv. "..(((tonumber(slots) - FamilySystem_Config.StandardSlots) / FamilySystem_Config.AddSlots) + 1)..")")
		end
		if IsValid(LevelLabel) then
			LevelLabel:SetText("Level erhöhen ("..(tonumber(slots) >= FamilySystem_Config.MaxSlots and "Max. Level" or "$"..string.Comma(FamilySystem_Config.SlotPrice * tonumber(slots)))..")")
		end
	end)

	local OnlineMembersBlock = vgui.Create("DPanel")
	OnlineMembersBlock:SetTall(120)
	OnlineMembersBlock:SetWide(150)
	OnlineMembersBlock.Paint = function()
		draw.RoundedBox(0, 0, 0, OnlineMembersBlock:GetWide(), OnlineMembersBlock:GetTall(), Color(246, 187, 67))
		draw.RoundedBox(0, 0, OnlineMembersBlock:GetTall() - 30, OnlineMembersBlock:GetWide(), 30, color_white)
	end
	local OnlineMembersBlockLabel = vgui.Create("DLabel", OnlineMembersBlock)
	OnlineMembersBlockLabel:SetColor(Color(148, 148, 150))
	OnlineMembersBlockLabel:SetFont("FamilySystem_FlatButton")
	OnlineMembersBlockLabel:SetText("Online")
	OnlineMembersBlockLabel:SizeToContents()
	OnlineMembersBlockLabel:SetPos(OnlineMembersBlock:GetWide() / 2 - OnlineMembersBlockLabel:GetWide() / 2, 93)
	local OnlineMembersBlockImage = vgui.Create("DImage", OnlineMembersBlock)
	OnlineMembersBlockImage:SetImage("fsystem/online.png")
	OnlineMembersBlockImage:SizeToContents()
	OnlineMembersBlockImage:SetPos(OnlineMembersBlock:GetWide() / 2 - OnlineMembersBlockImage:GetWide() / 2, 12)
	local OnlineMembersLabel = vgui.Create("DLabel", OnlineMembersBlock)
	OnlineMembersLabel:SetColor(color_white)
	OnlineMembersLabel:SetFont("FamilySystem_Text")
	OnlineMembersLabel:SetText(table.Count(online))
	OnlineMembersLabel:SizeToContents()
	OnlineMembersLabel:SetPos(OnlineMembersBlock:GetWide() / 2 - OnlineMembersLabel:GetWide() / 2, 50)
	PanelsHolder:AddItem(OnlineMembersBlock)
	local BalanceBlock = vgui.Create("DPanel")
	BalanceBlock:SetTall(120)
	BalanceBlock:SetWide(150)
	BalanceBlock.Paint = function()
		draw.RoundedBox(0, 0, 0, BalanceBlock:GetWide(), BalanceBlock:GetTall(), Color(54, 188, 155))
		draw.RoundedBox(0, 0,  BalanceBlock:GetTall() - 30, BalanceBlock:GetWide(), 30, color_white)
	end
	local BalanceBlockLabel = vgui.Create("DLabel", BalanceBlock)
	BalanceBlockLabel:SetColor(Color(148, 148, 150))
	BalanceBlockLabel:SetFont("FamilySystem_FlatButton")
	BalanceBlockLabel:SetText("Guthaben")
	BalanceBlockLabel:SizeToContents()
	BalanceBlockLabel:SetPos(BalanceBlock:GetWide() / 2 - BalanceBlockLabel:GetWide() / 2, 93)
	local BalanceBlockImage = vgui.Create("DImage", BalanceBlock)
	BalanceBlockImage:SetImage("fsystem/dollar.png")
	BalanceBlockImage:SizeToContents()
	BalanceBlockImage:SetPos(BalanceBlock:GetWide() / 2 - BalanceBlockImage:GetWide() / 2, 12)
	local BalanceBlockString = vgui.Create("DLabel", BalanceBlock)
	BalanceBlockString:SetColor(color_white)
	BalanceBlockString:SetFont("FamilySystem_Text")
	BalanceBlockString:SetText("$"..string.Comma(bankbalance))
	BalanceBlockString:SizeToContents()
	BalanceBlockString:SetPos(BalanceBlock:GetWide() / 2 - BalanceBlockString:GetWide() / 2, 50)
	PanelsHolder:AddItem(BalanceBlock)
	local MOTDTitle = vgui.Create("DLabel", Dashboard)
	MOTDTitle:SetText("MOTD")
	MOTDTitle:SetFont("FamilySystem_Title")
	MOTDTitle:SetPos(5, 185)
	MOTDTitle:SizeToContents()
	MOTDTitle:SetColor(Color(52, 73, 94))
	local MOTDBackground = vgui.Create("DPanel", Dashboard)
	MOTDBackground:SetSize(480, 140)
	MOTDBackground:SetPos(10, 220)
	local MOTDScrollPanel = vgui.Create("DScrollPanel", MOTDBackground)
	MOTDScrollPanel:Dock(FILL)
	local MOTD = vgui.Create("DLabel", MOTDScrollPanel)
	MOTD:SetPos(5, 5)
	MOTD:SetAutoStretchVertical(true)
	MOTD:SetWide(465)
	MOTD:SetWrap(true)
	MOTD:SetFont("FamilySystem_MOTD")
	MOTD:SetColor(color_black)
	MOTD:SetText((!motd or motd == "NULL") and "Kein Text spezifiziert." or motd)
	
	net.Receive("FamilySystem_RefreshMOTD", function()
		if IsValid(MOTD) then
			MOTD:SetText(net.ReadString())
		end
	end)

	SideMenu:AddMenuButton("Dashboard", "fsystem/online.png", Dashboard)
	Dashboard.Target = Dashboard
	SideMenu:switchPanel(Dashboard)
	local MembersPanel = vgui.Create("DCustomPanel", FS_Frame)
	MembersPanel:Title("Mitglieder")
	local PlayerListHolder = vgui.Create("DPanelList", MembersPanel)
	PlayerListHolder:SetPos(10, 45)
	PlayerListHolder:SetSize(480, 310)
	PlayerListHolder:SetSpacing(7)
	PlayerListHolder:EnableVerticalScrollbar(true)

	local function AddMember(name, rank, online, ply, steamid, lastseen)
		local PlayerPanel = vgui.Create("DPanel")
		PlayerPanel:SetTall(65)
		PlayerPanel.Paint = function()
			draw.RoundedBox(2, 0, 0, PlayerPanel:GetWide(), PlayerPanel:GetTall(), Color(247, 246, 241))
			surface.SetDrawColor(231, 230, 225)
			surface.DrawLine(60, 35, PlayerPanel:GetWide() - 10, 35)
		end
		local PlayerName = vgui.Create("DLabel", PlayerPanel)
		PlayerName:SetText(name)
		PlayerName:SetColor(Color(126, 127, 131))
		PlayerName:SetPos(62, 10)
		PlayerName:SetFont("FamilySystem_Name")
		PlayerName:SizeToContents()
		local PlayerRank = vgui.Create("DLabel", PlayerPanel)
		PlayerRank:SetText(rank)
		PlayerRank:SetColor(Color(180, 180, 180))
		PlayerRank:SetPos(63, 38)
		PlayerRank:SetFont("FamilySystem_Rank")
		PlayerRank:SizeToContents()
		local PlayerState = vgui.Create("DLabel", PlayerPanel)
		PlayerState:SetText(online)
		PlayerState:SetColor(Color(180, 180, 180))
		PlayerState:SetPos(415, 11)
		PlayerState:SetFont("FamilySystem_State")
		PlayerState:SizeToContents()
		local hasvalue_e = string.find(rank_flags, "e")
		local hasvalue_f = string.find(rank_flags, "f")
		if (hasvalue_e or hasvalue_f) then
			local PlayerOptions = vgui.Create("DButton", PlayerPanel)
			PlayerOptions:SetPos(410, 40)
			PlayerOptions:SetSize(24, 24)
			PlayerOptions:SetImage("fsystem/option.png")
			PlayerOptions:SetText("")
			PlayerOptions.DoClick = function(slf)
				surface.PlaySound("ui/buttonclick.wav")
				local MembersOptions = DermaMenu(slf)
				if hasvalue_e then
					MembersOptions:AddOption("Mitglied rauswerfen", function()
						surface.PlaySound("ui/buttonclick.wav")
						Derma_Query("Bist du dir sicher, dass du "..name.." aus der Familie werfen möchtest?", "Familienrauswurf bestätigen", "Ja", function()
							surface.PlaySound("ui/buttonclick.wav")
							RunConsoleCommand("family_kick", steamid)
						end, "Nein")
					end):SetIcon("icon16/delete.png")
				end
				if hasvalue_f then
					local AssignRank, Parent = MembersOptions:AddSubMenu("Rang zuteilen")
					Parent:SetIcon("icon16/cog.png")
					local found
					local ranks = table.Copy(rankslist)
					local newranks = {}
					for _,v in pairs(ranks) do
						table.insert(newranks, v)
					end
					table.sort(newranks, function(a, b)
						local name = a.rename != "NULL" and a.rename or a.name
						local name2 = b.rename != "NULL" and b.rename or b.name
						return name < name2
					end)
					for _,v in ipairs(newranks) do
						local name = v.name
						local rename = v.rename
						if name != "o" and (rename or name) != rank then
							AssignRank:AddOption(rename and rename.." (Standard-Rang)" or name, function()
								surface.PlaySound("ui/buttonclick.wav")
								RunConsoleCommand("family_setrank", steamid, name)
							end)
							found = true
						end
					end
					if !found then
						AssignRank:AddOption("Keine Ränge verfügbar!")
					end
				end
				MembersOptions:Open()
			end
			PlayerOptions.Paint = function()
			end
		end
		local steamid64 = util.SteamIDTo64(steamid)
		local PlayerAvatar = vgui.Create("CircledAvatar", PlayerPanel)
		PlayerAvatar:SetPos(7, 8)
		PlayerAvatar:SetSize(50, 50)
		PlayerAvatar:SetSteamID(steamid64, 64)
		local PlayerSteamURL = vgui.Create("DButton", PlayerPanel)
		PlayerSteamURL:SetPos(433, 40)
		PlayerSteamURL:SetSize(24, 24)
		PlayerSteamURL:SetImage("fsystem/steam.png")
		PlayerSteamURL:SetText("")
		PlayerSteamURL.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			gui.OpenURL("http://steamcommunity.com/profiles/"..steamid64)
		end
		PlayerSteamURL.Paint = function()
		end
		if !ply then
			local PlayerLastSeen = vgui.Create("DLabel", PlayerPanel)
			PlayerLastSeen:SetText("Zuletzt gesehen: "..os.date("%d.%m.%y", lastseen))
			PlayerLastSeen:SetColor(Color(180, 180, 180))
			PlayerLastSeen:SetPos(215, 40)
			PlayerLastSeen:SetFont("FamilySystem_State")
			PlayerLastSeen:SizeToContents()
		end
		PlayerListHolder:AddItem(PlayerPanel)		
	end

	local function AddMembers()
		for _,v in ipairs(memberslist) do
			local sid = v.steamid
			local ply = online[sid]
			local afk = IsValid(ply) and ply:getDarkRPVar("job") == "AFK"
			local is_online = v.online
			local online = afk and "AFK" or is_online and "Online" or "Offline"
			local rank = v.rank
			local rename = rankslist[rank] and rankslist[rank].rename
			if rename then
				rank = rename
			end
			AddMember(v.name, rank, online, ply, sid, v.lastseen)
		end
	end

	AddMembers()

	local SortBy = vgui.Create("DLabel", MembersPanel)
	SortBy:SetPos(225, 14)
	SortBy:SetSize(150, 20)
	SortBy:SetFont("FamilySystem_Rank")
	SortBy:SetColor(Color(126, 127, 131))
	SortBy:SetText("Sortieren nach: ")
	local SelectSortMethod = vgui.Create("DComboBox", MembersPanel)
	SelectSortMethod:SetFont("FamilySystem_FlatButton")
	SelectSortMethod:SetPos(340, 14)
	SelectSortMethod:SetSize(150, 20)
	SelectSortMethod:AddChoice("Beitrittsdatum")
	SelectSortMethod:AddChoice("Zuletzt gesehen")
	SelectSortMethod:AddChoice("Name")
	SelectSortMethod:AddChoice("Rang")
	SelectSortMethod:AddChoice("Online")
	SelectSortMethod:SetValue("Beitrittsdatum")
	SelectSortMethod.Selected = "Beitrittsdatum"
	SelectSortMethod.Paint = function()
		draw.RoundedBox(0, 0, 0, SelectSortMethod:GetWide(), SelectSortMethod:GetTall(), color_white)
		surface.SetDrawColor(189, 195, 199, 255)
		surface.DrawOutlinedRect(0, 0, SelectSortMethod:GetWide(), SelectSortMethod:GetTall())
	end
	SelectSortMethod.OnSelect = function(panel, _, value)
		surface.PlaySound("ui/buttonclick.wav")
		local selected = panel.Selected
		if value == "Beitrittsdatum" and selected != value then
			table.sort(memberslist, function(b, c) return tonumber(b.jointime) < tonumber(c.jointime) end)
		elseif value == "Zuletzt gesehen" and selected != value then
			table.sort(memberslist, function(b, c) return tonumber(b.lastseen) > tonumber(c.lastseen) end)
		elseif value == "Name" and selected != value then
			table.sort(memberslist, function(b, c) return tostring(b.name) < tostring(c.name) end)
		elseif value == "Rang" and selected != value then
			table.sort(memberslist, function(b, c) return tostring(b.rank) > tostring(c.rank) end)
		elseif value == "Online" and selected != value then
			table.sort(memberslist, function(b, c) return tostring(b.online) > tostring(c.online) end)
		else
			return
		end
		SelectSortMethod.Selected = value
		PlayerListHolder:Clear()
		AddMembers()
	end
	SideMenu:AddMenuButton("Mitglieder", "fsystem/members.png", MembersPanel)

	net.Receive("FamilySystem_RefreshPlayerList", function()
		local leng = net.ReadUInt(32)
		members = net.ReadData(leng)
		members = util.JSONToTable(util.Decompress(members))
		online = {}
		for _,v in ipairs(player.GetAll()) do
			local sid = v:SteamID()
			if members[sid] then
				online[sid] = v
			end
		end
		memberslist = {}
		for k,v in pairs(members) do
			table.insert(memberslist, {steamid = k, name = v["name"], rank = v["rank"], jointime = v["jointime"], lastseen = v["lastseen"], ["online"] = online[k] and true or false})
		end
		if IsValid(PlayerListHolder) then
			local method = SelectSortMethod.Selected and SelectSortMethod.Selected or "Beitrittsdatum"
			SelectSortMethod.Selected = nil
			SelectSortMethod:OnSelect(SelectSortMethod, method)
		end
		if IsValid(OnlineMembersLabel) then
			OnlineMembersLabel:SetText(table.Count(online))
		end
		if IsValid(MembersBlockLabel2) then
			MembersBlockLabel2:SetText(#memberslist.."/"..slots)
		end
	end)

	local BalanceLabel
	local BalanceBlock2
	net.Receive("FamilySystem_RefreshBank", function()
		bankbalance = net.ReadString()
		if IsValid(BalanceBlockString) then
			BalanceBlockString:SetText("$"..string.Comma(bankbalance))
			BalanceBlockString:SizeToContents()
			BalanceBlockString:SetPos(BalanceBlock:GetWide() / 2 - BalanceBlockString:GetWide() / 2, 50)
		end
		if IsValid(BalanceLabel) then
			BalanceLabel:SetText("$"..string.Comma(bankbalance))
			BalanceLabel:SizeToContents()
			BalanceLabel:SetPos(BalanceBlock2:GetWide() / 2 - BalanceLabel:GetWide() / 2, 8)
		end
	end)

	if string.find(rank_flags, "a") or string.find(rank_flags, "b") then
		local BankPanel = vgui.Create("DCustomPanel", FS_Frame)
		BankPanel:Title("Familienbank")
		local WelcomeScreen = vgui.Create("DPanel", BankPanel)
		WelcomeScreen:SetPos(10, 45)
		WelcomeScreen:SetSize(478, 310)
		WelcomeScreen.Paint = function() end
		local BankPanels = vgui.Create("DPanelList", WelcomeScreen)
		BankPanels:SetPos(0, 5)
		BankPanels:SetSize(478, 400)
		BankPanels:SetSpacing(10)
		BalanceBlock2 = vgui.Create("DPanel")
		BalanceBlock2:SetSize(478, 85)
		BalanceBlock2.Paint = function()
			draw.RoundedBox(6, 0, 0, BalanceBlock2:GetWide(), BalanceBlock2:GetTall(), Color(236, 240, 241))
		end
		BalanceLabel = vgui.Create("DLabel", BalanceBlock2)
		BalanceLabel:SetText("$"..string.Comma(bankbalance))
		BalanceLabel:SetFont("FamilySystem_Text")
		BalanceLabel:SetColor(Color(52, 152, 219))
		BalanceLabel:SizeToContents()
		BalanceLabel:SetPos(BalanceBlock2:GetWide() / 2 - BalanceLabel:GetWide() / 2, 8)
		local SubBalanceLabel = vgui.Create("DLabel", BalanceBlock2)
		SubBalanceLabel:SetText("Familienbank-Guthaben")
		SubBalanceLabel:SetFont("FamilySystem_FlatButton")
		SubBalanceLabel:SetColor(Color(126, 127, 131))
		SubBalanceLabel:SizeToContents()
		SubBalanceLabel:SetPos(BalanceBlock2:GetWide() / 2 - SubBalanceLabel:GetWide() / 2, 40)
		local MaxBalanceLabel = vgui.Create("DLabel", BalanceBlock2)
		MaxBalanceLabel:SetText("Max. Kapazität: $"..string.Comma(capacity))
		MaxBalanceLabel:SetFont("FamilySystem_FlatButton")
		MaxBalanceLabel:SetColor(Color(126, 127, 131))
		MaxBalanceLabel:SizeToContents()
		MaxBalanceLabel:SetPos(BalanceBlock2:GetWide() / 2 - MaxBalanceLabel:GetWide() / 2, 60)

		net.Receive("FamilySystem_RefreshCapacity", function()
			local max = net.ReadUInt(32)
			capacity = max
			if IsValid(MaxBalanceLabel) then
				MaxBalanceLabel:SetText("Max. Kapazität: $"..string.Comma(capacity))
			end
		end)
	
		BankPanels:AddItem(BalanceBlock2)
		local DepositBlock = vgui.Create("DButton")
		DepositBlock:SetText("")
		DepositBlock:SetTall(65)
		DepositBlock:SetWide(478)
		DepositBlock.Paint = function()
			draw.RoundedBox(6, 0, 0, DepositBlock:GetWide(), DepositBlock:GetTall(), Color(236, 240, 241))
		end
		local DepositLabel = vgui.Create("DLabel", DepositBlock)
		DepositLabel:SetText("Einzahlen")
		DepositLabel:SetFont("FamilySystem_Text")
		DepositLabel:SetColor(Color(52, 152, 219))
		DepositLabel:SizeToContents()
		DepositLabel:SetPos(8, 8)
		local SubDepositLabel = vgui.Create("DLabel", DepositBlock)
		SubDepositLabel:SetText("Zahle Geld in die Familienbank ein.")
		SubDepositLabel:SetFont("FamilySystem_FlatButton")
		SubDepositLabel:SetColor(Color(126, 127, 131))
		SubDepositLabel:SizeToContents()
		SubDepositLabel:SetPos(8, 35)
		DepositBlock.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			Derma_StringRequest("Familienbank einzahlen", "Wie viel möchtest du einzahlen? (Du hast: $"..string.Comma(LocalPlayer():getDarkRPVar("money"))..")", "Betrag angeben", function(t)
				t = tonumber(t)
				if !t then surface.PlaySound("buttons/button10.wav") return end
				t = math.abs(math.ceil(t))
				surface.PlaySound("ui/buttonclick.wav")
				net.Start("FamilySystem_Deposit")
					net.WriteUInt(t, 32)
				net.SendToServer()
			end, nil, "Einzahlen", "Abbrechen")
		end
		BankPanels:AddItem(DepositBlock)
		local WithdrawBlock = vgui.Create("DButton")
		WithdrawBlock:SetText("")
		WithdrawBlock:SetTall(65)
		WithdrawBlock:SetWide(478)
		WithdrawBlock.Paint = function()
			draw.RoundedBox(6, 0, 0, WithdrawBlock:GetWide(), WithdrawBlock:GetTall(), Color(236, 240, 241))
		end
		local WithDrawLabel = vgui.Create("DLabel", WithdrawBlock)
		WithDrawLabel:SetText("Abheben")
		WithDrawLabel:SetFont("FamilySystem_Text")
		WithDrawLabel:SetColor(Color(52, 152, 219))
		WithDrawLabel:SizeToContents()
		WithDrawLabel:SetPos(8, 8)
		local SubwithdrawLabel = vgui.Create("DLabel", WithdrawBlock)
		SubwithdrawLabel:SetText("Hebe Geld von der Familienbank ab.")
		SubwithdrawLabel:SetFont("FamilySystem_FlatButton")
		SubwithdrawLabel:SetColor(Color(126, 127, 131))
		SubwithdrawLabel:SizeToContents()
		SubwithdrawLabel:SetPos(8, 35)
		WithdrawBlock.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			Derma_StringRequest("Familienbank abheben", "Wie viel möchtest du abheben? (Familienbank: $"..string.Comma(bankbalance)..")", "Betrag angeben", function(t)
				t = tonumber(t)
				if !t then surface.PlaySound("buttons/button10.wav") return end
				t = math.abs(math.ceil(t))
				surface.PlaySound("ui/buttonclick.wav")
				net.Start("FamilySystem_Withdraw")
					net.WriteUInt(t, 32)
				net.SendToServer()
			end, nil, "Abheben", "Abbrechen")
		end
		BankPanels:AddItem(WithdrawBlock)
		SideMenu:AddMenuButton("Familienbank", "fsystem/bank.png", BankPanel)
	end
	if string.find(rank_flags, "j") then
		local LogPanel = vgui.Create("DCustomPanel", FS_Frame)
		LogPanel:Title("Logs")
		SideMenu:AddMenuButton("Logs", "fsystem/logs.png", LogPanel)

		local LogList
		local loglist = {}
		local floglist = {}

		local function AddLogs()
			if IsValid(LogList) then
				LogList:Clear()
				for _,v in ipairs(loglist) do
					LogList:AddLine(os.date("%d.%m.%y", v.time).." / "..os.date("%H:%M", v.time), AddLog(v))
				end
				if #LogList:GetLines() <= 0 then
					local time = os.time()
					LogList:AddLine(os.date("%d.%m.%y", time).." / "..os.date("%H:%M", time), "Keine Logs vorhanden.")
				end
			end
		end

		local function AddFinanceLogs()
			if IsValid(LogList) then
				LogList:Clear()
				local tot = 0
				local mon = 0
				for _,v in ipairs(floglist) do
					local total = tonumber(v.total)
					local month = tonumber(v.month)
					local data = v["data"]
					if !data then continue end
					tot = tot + total
					mon = mon + month
					local rank = data["rank"]
					local rename = rankslist[rank] and rankslist[rank].rename
					if rename then
						rank = rename
					end
					local text1 = string.sub(total, 1, 1) == "-" and "-$"..string.Comma(math.abs(total)) or "+$"..string.Comma(total)
					local text2 = string.sub(month, 1, 1) == "-" and "-$"..string.Comma(math.abs(month)) or "+$"..string.Comma(month)
					local line = LogList:AddLine(data["name"], rank, text1, text2)
					line.Columns[3]:SetTextColor(total > 0 and Color(0, 150, 0) or total < 0 and Color(255, 0, 0) or color_black)
					line.Columns[4]:SetTextColor(month > 0 and Color(0, 150, 0) or month < 0 and Color(255, 0, 0) or color_black)
				end
				local text1 = string.sub(tot, 1, 1) == "-" and "-$"..string.Comma(math.abs(tot)) or "+$"..string.Comma(tot)
				local text2 = string.sub(mon, 1, 1) == "-" and "-$"..string.Comma(math.abs(mon)) or "+$"..string.Comma(mon)
				local line = LogList:AddLine("Gesamt:", "", text1, text2)
				line.Columns[3]:SetTextColor(tot > 0 and Color(0, 150, 0) or tot < 0 and Color(255, 0, 0) or color_black)
				line.Columns[4]:SetTextColor(mon > 0 and Color(0, 150, 0) or mon < 0 and Color(255, 0, 0) or color_black)
			end
		end

		local function GenerateLogList(noadd)
			if IsValid(LogList) then
				LogList:Remove()
			end
			LogList = vgui.Create("DListView", LogPanel)
			LogList:SetMultiSelect(false)
			LogList:SetPos(10, 45)
			LogList:SetSize(480, 310)
			LogList:AddColumn("Datum"):SetFixedWidth(95)
			LogList:AddColumn("Log"):SetFixedWidth(385)
			LogList.OnRowSelected = function(parent, line)
				local column = LogList:GetLine(line)
				local log = column:GetColumnText(2)
				local menu = DermaMenu(parent)
				menu:AddOption("Zeile kopieren", function() 
					SetClipboardText(log)
					local_ply:ChatPrint("Zeile kopiert.")
				end)
				menu:Open()
			end
			if noadd then return end
			AddLogs()
		end

		local function GenerateFinancesList()
			if IsValid(LogList) then
				LogList:Remove()
			end
			LogList = vgui.Create("DListView", LogPanel)
			LogList:SetMultiSelect(false)
			LogList:SetPos(10, 45)
			LogList:SetSize(480, 310)
			LogList:AddColumn("Mitglied"):SetFixedWidth(150)
			LogList:AddColumn("Rang"):SetFixedWidth(100)
			LogList:AddColumn("Gesamtbilanz"):SetFixedWidth(115)
			LogList:AddColumn("Monatsbilanz"):SetFixedWidth(115)
			LogList.OnClickLine = function()
			end
			local RefreshButton = vgui.Create("DButton", LogPanel)
			RefreshButton:SetPos(235, 15)
			RefreshButton:SetSize(100, 20)
			RefreshButton:SetText("Aktualisieren")
			RefreshButton.DoClick = function()
				net.Start("FamilySystem_LoadFinances")
				net.SendToServer()
			end
			LogList.OnRemove = function()
				if IsValid(RefreshButton) then
					RefreshButton:Remove()
				end
			end
			AddFinanceLogs()
		end

		GenerateLogList(true)
		local SwitchButton = vgui.Create("DButton", LogPanel)
		SwitchButton:SetPos(340, 15)
		SwitchButton:SetSize(150, 20)
		SwitchButton:SetText("Zu Finanzen wechseln")
		local selected = 0
		SwitchButton.DoClick = function()
			if selected == 0 then
				SwitchButton:SetText("Zu Logs wechseln")
				selected = 1
				GenerateFinancesList()
			else
				SwitchButton:SetText("Zu Finanzen wechseln")
				selected = 0
				GenerateLogList()
			end
		end
		LogList:AddLine(os.date("%d.%m.%y", time).." / "..os.date("%H:%M", time), "Logs werden geladen...")

		net.Receive("FamilySystem_AddLog", function()
			local leng = net.ReadUInt(32)
			local logdata = net.ReadData(leng)
			logdata = util.JSONToTable(util.Decompress(logdata))
			table.insert(loglist, logdata)
			table.sort(loglist, function(a, b) return tonumber(a.time) > tonumber(b.time) end)
			if selected == 0 then
				AddLogs()
			end
		end)

		net.Receive("FamilySystem_LoadLogs", function()
			local leng = net.ReadUInt(32)
			local logdata = net.ReadData(leng)
			logdata = util.JSONToTable(util.Decompress(logdata))
			loglist = {}
			for _,v in ipairs(logdata) do
				table.insert(loglist, v)
			end
			table.sort(loglist, function(a, b) return tonumber(a.time) > tonumber(b.time) end)
			if selected == 0 and #loglist > 0 then
				AddLogs()
			end
		end)

		net.Start("FamilySystem_LoadLogs")
		net.SendToServer()

		net.Receive("FamilySystem_LoadFinances", function()
			local leng = net.ReadUInt(32)
			local logdata = net.ReadData(leng)
			logdata = util.JSONToTable(util.Decompress(logdata))
			floglist = {}
			for k,v in pairs(logdata) do
				v["steamid"] = k
				v["data"] = members[k]
				table.insert(floglist, v)
			end
			table.sort(floglist, function(a, b) return tonumber(a.month) > tonumber(b.month) end)
			if selected == 1 then
				AddFinanceLogs()
			end
		end)

		net.Start("FamilySystem_LoadFinances")
		net.SendToServer()
	end
	if string.find(rank_flags, "h") then
		local MarkerPanel = vgui.Create("DCustomPanel", FS_Frame)
		MarkerPanel:Title("Marker")
		SideMenu:AddMenuButton("Marker", "fsystem/marker.png", MarkerPanel)
		local MarkerText = vgui.Create("DLabel", MarkerPanel)
		MarkerText:SetPos(10, 40)
		MarkerText:SetAutoStretchVertical(true)
		MarkerText:SetWide(450)
		MarkerText:SetWrap(true)
		MarkerText:SetFont("DermaDefault")
		MarkerText:SetColor(color_black)
		MarkerText:SetText("Hier kannst du Marker, welche für deine gesamte Familie sichtbar sind, erstellen.\nStelle dich einfach an die zu markierende Position und klicke auf \"Marker platzieren\".\nOptional kannst du hier einige Anpassungen für deinen Marker vornehmen.")
		local HoldingLengthSlider = vgui.Create("DNumSlider", MarkerPanel)
		HoldingLengthSlider:SetPos(10, 100)
		HoldingLengthSlider:SetSize(420, 20)
		HoldingLengthSlider:SetText("Bleibelänge in Minuten")
		HoldingLengthSlider:SetDecimals(0)
		HoldingLengthSlider:SetMin(1)
		HoldingLengthSlider:SetMax(FamilySystem_Config.MaxMarkerLength)
		HoldingLengthSlider:SetValue(FamilySystem_Config.MaxMarkerLength / 2)
		HoldingLengthSlider:SetDark(true)
		HoldingLengthSlider.TextArea:SetFont("FamilySystem_Rank")
		HoldingLengthSlider.Label:SetFont("FamilySystem_FlatButton")
		local ColorMixer = vgui.Create("DColorMixer", MarkerPanel)
		ColorMixer:SetPos(10, 140)
		ColorMixer:SetSize(400, 100)
		ColorMixer:SetPalette(false)
		ColorMixer:SetAlphaBar(true)
		ColorMixer:SetWangs(true)
		ColorMixer:SetColor(color_white)
		local SinglePlayerOption = vgui.Create("DCheckBoxLabel", MarkerPanel)
		SinglePlayerOption:SetPos(10, 255)
		SinglePlayerOption:SetSize(100, 20)
		SinglePlayerOption:SetText("Marker nur für Ersteller sichtbar?")
		SinglePlayerOption:SetTextColor(color_black)
		local CreateMarkerButton = vgui.Create("DFlatButton", MarkerPanel)
		CreateMarkerButton:SetSize(150, 40)
		CreateMarkerButton:SetPos(315, 300)
		CreateMarkerButton:SetText("Marker platzieren")
		CreateMarkerButton.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			RunConsoleCommand("family_addmarker", HoldingLengthSlider:GetValue() or FamilySystem_Config.MaxMarkerLength / 2, ColorMixer:GetColor() and string.FromColor(ColorMixer:GetColor()) or string.FromColor(color_white), SinglePlayerOption:GetChecked() and 1 or 0)
		end
		local DeleteMarkerButton = vgui.Create("DFlatButton", MarkerPanel)
		DeleteMarkerButton:SetState(false)
		DeleteMarkerButton:SetSize(150, 40)
		DeleteMarkerButton:SetPos(160, 300)
		DeleteMarkerButton:SetText("Marker entfernen")
		DeleteMarkerButton.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			RunConsoleCommand("family_removemarker")
		end
	end
	local RankList
	local ManagePanel = vgui.Create("DCustomPanel", FS_Frame)
	ManagePanel:Title("Einstellungen")
	SideMenu:AddMenuButton("Einstellungen", "fsystem/manage.png", ManagePanel)
	local ManageTabs = vgui.Create("DPropertySheet", ManagePanel)
	ManageTabs:SetSize(480, 310)
	ManageTabs:SetPos(10, 45)
	ManageTabs:SetPadding(5)
	ManageTabs.Paint = function(panel)
		surface.SetDrawColor(Color(52, 73, 94, 250))
		surface.DrawRect(0, 0, panel:GetWide(), panel:GetTall())
	end
	ManageTabs:SetSkin("ManagerTab")
	if string.find(rank_flags, "g") then
		local ranks = vgui.Create("DCustomPanel")
		local NewRankName = vgui.Create("DTextEntry", ranks)
		NewRankName:SetSize(450, 35)
		NewRankName:SetPos(5, 15)
		NewRankName:SetText("Rangname")
		NewRankName.OldMousePressed = NewRankName.OnMousePressed
		function NewRankName:OnMousePressed(...)
			self:OldMousePressed(...)
			if (self:GetValue() == "Rangname") then
				self:SetValue("")
			end
		end
		NewRankName:SetFont("FamilySystem_FlatButton")
		NewRankName.Paint = function(me)
			draw.RoundedBox(0, 0, 0, NewRankName:GetWide(), NewRankName:GetTall(), color_white)
			surface.SetDrawColor(189, 195, 199, 255)
			surface.DrawOutlinedRect(0, 0, NewRankName:GetWide(), NewRankName:GetTall())
			me:DrawTextEntryText(Color(52, 73, 94, 255), Color(52, 73, 94, 255), Color(52, 73, 94, 255))
		end
		local FlagList = vgui.Create("DPanelList", ranks)
		FlagList:SetSize(450, 200)
		FlagList:SetPos(8, 65)
		FlagList:EnableHorizontal(true)
		FlagList:SetSpacing(15)
		local flags = {}
		flags[1] = vgui.Create("DCheckBoxLabel")
		flags[1]:SetText("Geld einzahlen")
		flags[1]:SetTextColor(color_black)
		flags[1]:SizeToContents()
		flags[1]:SetWide(130)
		flags[1].flag = "a"
		FlagList:AddItem(flags[1])
		flags[2] = vgui.Create("DCheckBoxLabel")
		flags[2]:SetText("Geld abheben")
		flags[2]:SetTextColor(color_black)
		flags[2]:SizeToContents()
		flags[2]:SetWide(130)
		flags[2].flag = "b"
		FlagList:AddItem(flags[2])
		flags[3] = vgui.Create("DCheckBoxLabel")
		flags[3]:SetText("Logs einsehen")
		flags[3]:SetTextColor(color_black)
		flags[3]:SizeToContents()
		flags[3]:SetWide(130)
		flags[3].flag = "j"
		FlagList:AddItem(flags[3])
		flags[4] = vgui.Create("DCheckBoxLabel")
		flags[4]:SetText("Mitglieder rauswerfen")
		flags[4]:SetTextColor(color_black)
		flags[4]:SizeToContents()
		flags[4]:SetWide(130)
		flags[4].flag = "e"
		FlagList:AddItem(flags[4])
		flags[5] = vgui.Create("DCheckBoxLabel")
		flags[5]:SetText("Ränge zuteilen")
		flags[5]:SetTextColor(color_black)
		flags[5]:SizeToContents()
		flags[5]:SetWide(130)
		flags[5].flag = "f"
		FlagList:AddItem(flags[5])
		flags[6] = vgui.Create("DCheckBoxLabel")
		flags[6]:SetText("Ränge editieren")
		flags[6]:SetTextColor(color_black)
		flags[6]:SizeToContents()
		flags[6]:SetWide(130)
		flags[6].flag = "g"
		FlagList:AddItem(flags[6])
		flags[7] = vgui.Create("DCheckBoxLabel")
		flags[7]:SetText("Spieler einladen")
		flags[7]:SetTextColor(color_black)
		flags[7]:SizeToContents()
		flags[7]:SetWide(130)
		flags[7].flag = "c"
		FlagList:AddItem(flags[7])
		flags[8] = vgui.Create("DCheckBoxLabel")
		flags[8]:SetText("Motd editieren")
		flags[8]:SetTextColor(color_black)
		flags[8]:SizeToContents()
		flags[8]:SetWide(130)
		flags[8].flag = "d"
		FlagList:AddItem(flags[8])
		flags[9] = vgui.Create("DCheckBoxLabel")
		flags[9]:SetText("Marker platzieren")
		flags[9]:SetTextColor(color_black)
		flags[9]:SizeToContents()
		flags[9]:SetWide(130)
		flags[9].flag = "k"
		FlagList:AddItem(flags[9])
		flags[10] = vgui.Create("DCheckBoxLabel")
		flags[10]:SetText("Limitiert")
		flags[10]:SetTextColor(color_black)
		flags[10]:SizeToContents()
		flags[10]:SetWide(130)
		flags[10].flag = "h"
		flags[10]:SetTooltip("Kann nicht mehr von der Familienbank abbuchen, als insgesamt von dem Spieler eingezahlt wurde.")
		FlagList:AddItem(flags[10])
		flags[11] = vgui.Create("DCheckBoxLabel")
		flags[11]:SetText("Unantastbar")
		flags[11]:SetTextColor(color_black)
		flags[11]:SizeToContents()
		flags[11]:SetWide(130)
		flags[11].flag = "i"
		flags[11]:SetTooltip("Spieler mit einem unantastbaren Rang können von Mitgliedern ohne unantastbaren Rang nicht verwaltet werden.\nNur der Familiengründer kann Spieler mit unantastbaren Rang verwalten.")
		FlagList:AddItem(flags[11])
		local CreateRankButton = vgui.Create("DFlatButton", ranks)
		CreateRankButton:SetSize(150, 40)
		CreateRankButton:SetPos(300, 230)
		CreateRankButton:SetText("Rang erstellen")
		CreateRankButton:SetState(false)
		NewRankName.OnTextChanged = function(text)
			local value = NewRankName:GetValue()
			local leng = #value
			if leng <= 0 or leng > 20 or string.Trim(value) == "Rangname" or string.Trim(value) == "" then
				CreateRankButton:SetState(false)
			else
				CreateRankButton:SetState(true)
			end
		end
		CreateRankButton.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			local flag_str = ""
			for k,v in pairs(flags) do
				if flags[k]:GetChecked() then
					flag_str = flag_str..flags[k].flag
				end
			end
			RunConsoleCommand("family_newrank", NewRankName:GetValue(), flag_str)
		end
		ManageTabs:AddSheet("Ränge erstellen", ranks, nil, false, false, "Ränge erstellen")
		local EditRanks = vgui.Create("DCustomPanel")
		RankList = vgui.Create("DComboBox", EditRanks)
		RankList:SetFont("FamilySystem_FlatButton")
		RankList:SetPos(5, 15)
		RankList:SetSize(450, 35)
		RankList:SetValue("Rang auswählen")
		local SelectedID
		for _,v in pairs(rankslist) do
			local name = v["name"]
			local rename = v["rename"] or name
			local rank = v["rename"] and v["rename"].." (Standard-Rang)" or name
			RankList:AddChoice(rank, {name, v["flags"], rename})
		end
		RankList.Paint = function()
			draw.RoundedBox(0, 0, 0, RankList:GetWide(), RankList:GetTall(), color_white)
			surface.SetDrawColor(189, 195, 199, 255)
			surface.DrawOutlinedRect(0, 0, RankList:GetWide(), RankList:GetTall())
		end
		local EditRankName = vgui.Create("DTextEntry", EditRanks)
		EditRankName:SetSize(450, 35)
		EditRankName:SetPos(5, 55)
		EditRankName:SetText("Rangname")
		EditRankName.OldMousePressed = EditRankName.OnMousePressed
		function EditRankName:OnMousePressed(...)
			self:OldMousePressed(...)
			if (self:GetValue() == "Rangname") then
				self:SetValue("")
			end
		end
		EditRankName:SetFont("FamilySystem_FlatButton")
		EditRankName.Paint = function()
			draw.RoundedBox(0, 0, 0, EditRankName:GetWide(), EditRankName:GetTall(), color_white)
			surface.SetDrawColor(189, 195, 199, 255)
			surface.DrawOutlinedRect(0, 0, EditRankName:GetWide(), EditRankName:GetTall())
			EditRankName:DrawTextEntryText(Color(52, 73, 94, 255), Color(52, 73, 94, 255), Color(52, 73, 94, 255))
		end
		local FlagList = vgui.Create("DPanelList", EditRanks)
		FlagList:SetSize(450, 200)
		FlagList:SetPos(8, 105)
		FlagList:SetSpacing(11)
		FlagList:EnableHorizontal(true) 
		local flags = {}
		flags[1] = vgui.Create("DCheckBoxLabel")
		flags[1]:SetText("Geld einzahlen")
		flags[1]:SetTextColor(color_black)
		flags[1]:SizeToContents()
		flags[1]:SetWide(130)
		flags[1].flag = "a"
		FlagList:AddItem(flags[1])
		flags[2] = vgui.Create("DCheckBoxLabel")
		flags[2]:SetText("Geld abheben")
		flags[2]:SetTextColor(color_black)
		flags[2]:SizeToContents()
		flags[2]:SetWide(130)
		flags[2].flag = "b"
		FlagList:AddItem(flags[2])
		flags[3] = vgui.Create("DCheckBoxLabel")
		flags[3]:SetText("Logs einsehen")
		flags[3]:SetTextColor(color_black)
		flags[3]:SizeToContents()
		flags[3]:SetWide(130)
		flags[3].flag = "j"
		FlagList:AddItem(flags[3])
		flags[4] = vgui.Create("DCheckBoxLabel")
		flags[4]:SetText("Mitglieder rauswerfen")
		flags[4]:SetTextColor(color_black)
		flags[4]:SizeToContents()
		flags[4]:SetWide(130)
		flags[4].flag = "e"
		FlagList:AddItem(flags[4])
		flags[5] = vgui.Create("DCheckBoxLabel")
		flags[5]:SetText("Ränge zuteilen")
		flags[5]:SetTextColor(color_black)
		flags[5]:SizeToContents()
		flags[5]:SetWide(130)
		flags[5].flag = "f"
		FlagList:AddItem(flags[5])
		flags[6] = vgui.Create("DCheckBoxLabel")
		flags[6]:SetText("Ränge editieren")
		flags[6]:SetTextColor(color_black)
		flags[6]:SizeToContents()
		flags[6]:SetWide(130)
		flags[6].flag = "g"
		FlagList:AddItem(flags[6])
		flags[7] = vgui.Create("DCheckBoxLabel")
		flags[7]:SetText("Spieler einladen")
		flags[7]:SetTextColor(color_black)
		flags[7]:SizeToContents()
		flags[7]:SetWide(130)
		flags[7].flag = "c"
		FlagList:AddItem(flags[7])
		flags[8] = vgui.Create("DCheckBoxLabel")
		flags[8]:SetText("Motd editieren")
		flags[8]:SetTextColor(color_black)
		flags[8]:SizeToContents()
		flags[8]:SetWide(130)
		flags[8].flag = "d"
		FlagList:AddItem(flags[8])
		flags[9] = vgui.Create("DCheckBoxLabel")
		flags[9]:SetText("Marker platzieren")
		flags[9]:SetTextColor(color_black)
		flags[9]:SizeToContents()
		flags[9]:SetWide(130)
		flags[9].flag = "h"
		FlagList:AddItem(flags[9])
		flags[10] = vgui.Create("DCheckBoxLabel")
		flags[10]:SetText("Limitiert")
		flags[10]:SetTextColor(color_black)
		flags[10]:SizeToContents()
		flags[10]:SetWide(130)
		flags[10].flag = "k"
		flags[10]:SetTooltip("Kann nicht mehr von der Familienbank abbuchen, als insgesamt von dem Spieler eingezahlt wurde.")
		FlagList:AddItem(flags[10])
		flags[11] = vgui.Create("DCheckBoxLabel")
		flags[11]:SetText("Unantastbar")
		flags[11]:SetTextColor(color_black)
		flags[11]:SizeToContents()
		flags[11]:SetWide(130)
		flags[11].flag = "i"
		flags[11]:SetTooltip("Spieler mit einem unantastbaren Rang können von Mitgliedern ohne unantastbaren Rang nicht verwaltet werden.\nNur der Familiengründer kann Spieler mit unantastbaren Rang verwalten.")
		FlagList:AddItem(flags[11])
		RankList.OnSelect = function(panel, index, value, data)
			EditRankName:SetText(data[3])
			for k,v in pairs(flags) do
				local flag = flags[k]
				if data[1] == "o" then
					flag:SetDisabled(true)
				else
					flag:SetDisabled(false)
				end
				flag:SetChecked(false)
				if string.find(data[2], flag.flag) then
					flag:SetChecked(true)
				end
			end
			SelectedID = data[1]
		end
		local EditButton = vgui.Create("DFlatButton", EditRanks)
		EditButton:SetSize(150, 40)
		EditButton:SetPos(300, 230)
		EditButton:SetText("Rang editieren")
		EditButton.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			local flag_str = ""
			for k,v in pairs(flags) do
				local flag = flags[k]
				if flag:GetChecked() then
					flag_str = flag_str..flag.flag
				end
			end
			local _, rankname = RankList:GetSelected()
			RunConsoleCommand("family_editrank", rankname and rankname[1], flag_str, EditRankName:GetValue())
		end
		local DeleteButton = vgui.Create("DFlatButton", EditRanks)
		DeleteButton:SetState(false)
		DeleteButton:SetSize(150, 40)
		DeleteButton:SetPos(145, 230)
		DeleteButton:SetText("Rang löschen")
		DeleteButton.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			local _, rankname = RankList:GetSelected()
			RunConsoleCommand("family_deleterank", rankname and rankname[1])
		end
		ManageTabs:AddSheet("Ränge editieren", EditRanks, nil, false, false, "Ränge editieren")	
	end
	if string.find(rank_flags, "d") then
		local MOTD = vgui.Create("DCustomPanel")
		local MOTDEntry = vgui.Create("DTextEntry", MOTD)
		MOTDEntry:SetSize(450, 205)
		MOTDEntry:SetPos(5, 15)
		MOTDEntry:SetFont("FamilySystem_FlatButton")
		MOTDEntry:SetText((!motd or motd == "NULL") and "Kein Text spezifiziert." or motd)
		MOTDEntry:SetMultiline(true)
		MOTDEntry.Paint = function()
			draw.RoundedBox(0, 0, 0, MOTDEntry:GetWide(), MOTDEntry:GetTall(), color_white)
			surface.SetDrawColor(189, 195, 199, 255)
			surface.DrawOutlinedRect(0, 0, MOTDEntry:GetWide(), MOTDEntry:GetTall())
			MOTDEntry:DrawTextEntryText(Color(52, 73, 94, 255), Color(52, 73, 94, 255), Color(52, 73, 94, 255))
		end
		local MOTDButton = vgui.Create("DFlatButton", MOTD)
		MOTDButton:SetSize(150, 40)
		MOTDButton:SetPos(300, 230)
		MOTDButton:SetText("Motd editieren")
		MOTDButton.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			if #MOTDEntry:GetValue() > FamilySystem_Config.MaxMOTDLength then
				Derma_Message("Du hast das Zeichenlimit erreicht! (Das Limit liegt bei "..FamilySystem_Config.MaxMOTDLength.." Zeichen)", "Zu viele Zeichen!", "Ok")
			else
				net.Start("FamilySystem_SetMOTD")
					net.WriteString(MOTDEntry:GetValue())
				net.SendToServer()
			end
		end
		ManageTabs:AddSheet("Motd", MOTD, nil, false, false, "Motd editieren")
	end
	if string.find(rank_flags, "c") then
		local Invite = vgui.Create("DCustomPanel")
		local PlayerList = vgui.Create("DComboBox", Invite)
		PlayerList:SetValue("Wähle einen Spieler")
		PlayerList:SetFont("FamilySystem_FlatButton")
		PlayerList:SetSize(450, 35)
		PlayerList:SetPos(5, 15)
		local found = false
		for _,v in ipairs(player.GetAll()) do
			if v == local_ply then continue end
			found = true
			PlayerList:AddChoice(v:Name(), v)
		end
		if !found then
			PlayerList:AddChoice("Niemand verfügbar")
		end
		PlayerList.Paint = function()
			draw.RoundedBox(0, 0, 0, PlayerList:GetWide(), PlayerList:GetTall(), color_white)
			surface.SetDrawColor(189, 195, 199, 255)
			surface.DrawOutlinedRect(0, 0, PlayerList:GetWide(), PlayerList:GetTall())
		end
		local MessageEntry = vgui.Create("DTextEntry", Invite)
		MessageEntry:SetMultiline(true)
		MessageEntry:SetPos(5, 55)
		MessageEntry:SetSize(450, 165)
		MessageEntry:SetFont("FamilySystem_FlatButton")
		MessageEntry:SetText("Du wurdest in die Familie "..familyname.." von "..local_ply:Name().." eingeladen.")
		MessageEntry.Paint = function()
			draw.RoundedBox(0, 0, 0, MessageEntry:GetWide(), MessageEntry:GetTall(), color_white)
			surface.SetDrawColor(189, 195, 199, 255)
			surface.DrawOutlinedRect(0, 0, MessageEntry:GetWide(), MessageEntry:GetTall())
			MessageEntry:DrawTextEntryText(Color(52, 73, 94, 255), Color(52, 73, 94, 255), Color(52, 73, 94, 255))
		end
		local InvitePlayerButton = vgui.Create("DFlatButton", Invite)
		InvitePlayerButton:SetSize(150, 40)
		InvitePlayerButton:SetPos(300, 230)
		InvitePlayerButton:SetText("Spieler einladen")
		InvitePlayerButton.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			if PlayerList:GetValue() != "Wähle einen Spieler" then
				if #MessageEntry:GetValue() > FamilySystem_Config.MaxInvitationLength then
					Derma_Message("Du hast das Zeichenlimit erreicht! (Das Limit liegt bei "..FamilySystem_Config.MaxInvitationLength.." Zeichen)", "Zu viele Zeichen!", "Ok")
				else
					local _, selected_ply = PlayerList:GetSelected()
					if IsValid(selected_ply) then
						net.Start("FamilySystem_InvitePlayer")
							net.WriteEntity(selected_ply)
							net.WriteString(MessageEntry:GetValue())
						net.SendToServer()
					else
						notification.AddLegacy("Der ausgewählte Spieler konnte nicht gefunden werden!", NOTIFY_ERROR, 4)
					end
				end
			else
				notification.AddLegacy("Bitte wähle einen Spieler aus!", NOTIFY_ERROR, 3)
			end
		end
		ManageTabs:AddSheet("Einladen", Invite, nil, false, false, "Spieler einladen")
	end
	local Settings = vgui.Create("DCustomPanel")
	local FamilyChatSettings = vgui.Create("DLabel", Settings)
	FamilyChatSettings:SetPos(10, 10)
	FamilyChatSettings:SetSize(130, 25)
	FamilyChatSettings:SetText("Familien-Chat")
	FamilyChatSettings:SetFont("FamilySystem_Rank")
	FamilyChatSettings:SetColor(color_black)
	local DisableChatPerm = vgui.Create("DCheckBoxLabel", Settings)
	DisableChatPerm:SetPos(10, 45)
	DisableChatPerm:SetSize(100, 20)
	DisableChatPerm:SetText("Permanent deaktivieren")
	DisableChatPerm:SetTextColor(color_black)
	DisableChatPerm:SetChecked(GetConVar("cl_family_disablechat"):GetBool())
	DisableChatPerm.OnChange = function(panel, bool)
		surface.PlaySound("ui/buttonclick.wav")
		RunConsoleCommand("cl_family_disablechat", bool and 1 or 0)
	end
	local DisableChatTemp = vgui.Create("DCheckBoxLabel", Settings)
	DisableChatTemp:SetPos(10, 70)
	DisableChatTemp:SetSize(100, 23)
	DisableChatTemp:SetText("Temporär deaktivieren")
	DisableChatTemp:SetTooltip("Temporär: Bis Neuverbinden zum Server.")
	DisableChatTemp:SetTextColor(color_black)
	DisableChatTemp:SetChecked(!FS_FamilyChat)
	DisableChatTemp.OnChange = function(panel, bool)
		surface.PlaySound("ui/buttonclick.wav")
		FamilySystem.ToggleChat(!bool)
	end
	local ShowRanks = vgui.Create("DCheckBoxLabel", Settings)
	ShowRanks:SetPos(10, 95)
	ShowRanks:SetSize(100, 23)
	ShowRanks:SetText("Ränge im Chat anzeigen")
	ShowRanks:SetTextColor(color_black)
	ShowRanks:SetChecked(!GetConVar("cl_family_disablechatranks"):GetBool())
	ShowRanks.OnChange = function(panel, bool)
		surface.PlaySound("ui/buttonclick.wav")
		RunConsoleCommand("cl_family_disablechatranks", bool and 0 or 1)
	end
	local FamilyMarkerSettings = vgui.Create("DLabel", Settings)
	FamilyMarkerSettings:SetPos(10, 125)
	FamilyMarkerSettings:SetSize(130, 25)
	FamilyMarkerSettings:SetText("Familien-Marker")
	FamilyMarkerSettings:SetFont("FamilySystem_Rank")
	FamilyMarkerSettings:SetColor(color_black)
	local DisableMarkersPerm = vgui.Create("DCheckBoxLabel", Settings)
	DisableMarkersPerm:SetPos(10, 160)
	DisableMarkersPerm:SetSize(100, 20)
	DisableMarkersPerm:SetText("Permanent deaktivieren")
	DisableMarkersPerm:SetTextColor(color_black)
	DisableMarkersPerm:SetChecked(GetConVar("cl_family_disablemarkers"):GetBool())
	DisableMarkersPerm.OnChange = function(panel, bool)
		surface.PlaySound("ui/buttonclick.wav")
		RunConsoleCommand("cl_family_disablemarkers", bool and 1 or 0)
	end
	local DisableMarkersTemp = vgui.Create("DCheckBoxLabel", Settings)
	DisableMarkersTemp:SetPos(10, 185)
	DisableMarkersTemp:SetSize(100, 20)
	DisableMarkersTemp:SetText("Temporär deaktivieren")
	DisableMarkersTemp:SetTooltip("Temporär: Bis Neuverbinden zum Server.")
	DisableMarkersTemp:SetTextColor(color_black)
	DisableMarkersTemp:SetChecked(!FS_FamilyMarkers)
	DisableMarkersTemp.OnChange = function(panel, bool)
		surface.PlaySound("ui/buttonclick.wav")
		FamilySystem.ToggleMarkers(!bool)
	end
	local MinimizedMarkers = vgui.Create("DCheckBoxLabel", Settings)
	MinimizedMarkers:SetPos(10, 210)
	MinimizedMarkers:SetSize(100, 20)
	MinimizedMarkers:SetText("Marker minimieren")
	MinimizedMarkers:SetTextColor(color_black)
	MinimizedMarkers:SetChecked(GetConVar("cl_family_minimizemarkers"):GetBool())
	MinimizedMarkers.OnChange = function(panel, bool)
		surface.PlaySound("ui/buttonclick.wav")
		RunConsoleCommand("cl_family_minimizemarkers", bool and 1 or 0)
	end
	local DisableChatNotifications = vgui.Create("DCheckBoxLabel", Settings)
	DisableChatNotifications:SetPos(10, 235)
	DisableChatNotifications:SetSize(100, 20)
	DisableChatNotifications:SetText("Chatbenachrichtiungen deaktivieren")
	DisableChatNotifications:SetTextColor(color_black)
	DisableChatNotifications:SetChecked(GetConVar("cl_family_disablechatnotifications"):GetBool())
	DisableChatNotifications.OnChange = function(panel, bool)
		surface.PlaySound("ui/buttonclick.wav")
		RunConsoleCommand("cl_family_disablechatnotifications", bool and 1 or 0)
	end
	ManageTabs:AddSheet("Spielerseitig", Settings, nil, false, false, "Spielerseitige Einstellungen")
	if rank_name == "o" then
		local Manage = vgui.Create("DCustomPanel")
		local ManageOptions = vgui.Create("DPanelList", Manage)
		ManageOptions:SetPos(5, 10)
		ManageOptions:SetSize(460, 300)
		ManageOptions:SetSpacing(5)
		if FamilySystem_Config.EnableLevels then
			local BuyLevel = vgui.Create("DButton")
			BuyLevel:SetText("")
			BuyLevel:SetTall(48)
			BuyLevel:SetWide(478)
			BuyLevel.Paint = function()
				draw.RoundedBox(0, 0, 0, BuyLevel:GetWide(), BuyLevel:GetTall(), Color(59, 174, 218))
			end
			BuyLevel.DoClick = function()
				surface.PlaySound("ui/buttonclick.wav")
				if !LocalPlayer():canAfford(FamilySystem_Config.SlotPrice * tonumber(slots)) then
					notification.AddLegacy("Du hast nicht genügend Geld hierfür!", NOTIFY_ERROR, 4)
					return
				end
				if tonumber(slots) < FamilySystem_Config.MaxSlots then
					Derma_Query("Möchtest du das Level deiner Familie wirklich für $"..string.Comma(FamilySystem_Config.SlotPrice * tonumber(slots)).." erhöhen?", "Level erhöhen", "Ja", function()
						RunConsoleCommand("family_upgrade")
					end, "Nein")
				end
			end
			LevelLabel = vgui.Create("DLabel", BuyLevel)
			LevelLabel:SetText("Level erhöhen ("..(tonumber(slots) >= FamilySystem_Config.MaxSlots and "Max. Level" or "$"..string.Comma(FamilySystem_Config.SlotPrice * tonumber(slots)))..")")
			LevelLabel:SetFont("FamilySystem_Button")
			LevelLabel:SetColor(color_white)
			LevelLabel:SizeToContents()
			LevelLabel:SetPos(5, 5)
			LevelLabel.Think = function()
				if tonumber(slots) >= FamilySystem_Config.MaxSlots or LocalPlayer():canAfford(FamilySystem_Config.SlotPrice * tonumber(slots)) then
					LevelLabel:SetColor(color_white)
				else
					LevelLabel:SetColor(Color(215, 50, 30))
				end
			end
			local SubLevelLabel = vgui.Create("DLabel", BuyLevel)
			SubLevelLabel:SetText("Erhöhe max. Mitgliederanzahl um "..FamilySystem_Config.AddSlots.." und Bankkapazität um $"..string.Comma(FamilySystem_Config.AddCapacity)..".")
			SubLevelLabel:SetFont("FamilySystem_ButtonInfo")
			SubLevelLabel:SetColor(color_white)
			SubLevelLabel:SizeToContents()
			SubLevelLabel:SetPos(5, 28)
			ManageOptions:AddItem(BuyLevel)
		end
		if FamilySystem_Config.EnableRename then
			local RenameFamily = vgui.Create("DButton")
			RenameFamily:SetText("")
			RenameFamily:SetTall(48)
			RenameFamily:SetWide(478)
			RenameFamily.Paint = function()
				draw.RoundedBox(0, 0, 0, RenameFamily:GetWide(), RenameFamily:GetTall(), Color(59, 174, 218))
			end
			RenameFamily.DoClick = function()
				surface.PlaySound("ui/buttonclick.wav")
				if !LocalPlayer():canAfford(FamilySystem_Config.RenamePrice) then
					notification.AddLegacy("Du hast nicht genügend Geld hierfür!", NOTIFY_ERROR, 4)
					return
				end
				Derma_StringRequest("Familie umbenennen", [[Wie soll der neue Name deiner Familie lauten?]], "Neuer Name", function(t)
					surface.PlaySound("ui/buttonclick.wav")
					t = string.TrimLeft(t)
					t = string.TrimRight(t)
					local leng = #t
					if t != "Neuer Name" and leng >= FamilySystem_Config.MinNameLength and leng <= FamilySystem_Config.MaxNameLength and string.Trim(t) != "" then
						RunConsoleCommand("family_rename", t)
					else
						notification.AddLegacy("Dieser Name ist nicht akzeptabel!", NOTIFY_ERROR, 4)
					end
				end, nil, "Umbenennen", "Abbrechen")
			end
			local RenameLabel = vgui.Create("DLabel", RenameFamily)
			RenameLabel:SetText("Familie umbenennen ($"..string.Comma(FamilySystem_Config.RenamePrice)..")")
			RenameLabel:SetFont("FamilySystem_Button")
			RenameLabel:SetColor(color_white)
			RenameLabel:SizeToContents()
			RenameLabel:SetPos(5, 5)
			RenameLabel.Think = function()
				if LocalPlayer():canAfford(FamilySystem_Config.RenamePrice) then
					RenameLabel:SetColor(color_white)
				else
					RenameLabel:SetColor(Color(215, 50, 30))
				end
			end
			local SubRenameLabel = vgui.Create("DLabel", RenameFamily)
			SubRenameLabel:SetText("Benenne deine Familie um.")
			SubRenameLabel:SetFont("FamilySystem_ButtonInfo")
			SubRenameLabel:SetColor(color_white)
			SubRenameLabel:SizeToContents()
			SubRenameLabel:SetPos(5, 28)
			ManageOptions:AddItem(RenameFamily)
		end
		if FamilySystem_Config.EnableTransfer then
			local TransferFamily = vgui.Create("DButton")
			TransferFamily:SetText("")
			TransferFamily:SetTall(48)
			TransferFamily:SetWide(478)
			TransferFamily.Paint = function()
				draw.RoundedBox(0, 0, 0, TransferFamily:GetWide(), TransferFamily:GetTall(), Color(59, 174, 218))
			end
			TransferFamily.DoClick = function()
				surface.PlaySound("ui/buttonclick.wav")
				if !LocalPlayer():canAfford(FamilySystem_Config.TransferPrice) then
					notification.AddLegacy("Du hast nicht genug Geld hierfür!", NOTIFY_ERROR, 4)
					return
				end
				local menu = DermaMenu(TransferFamily)
				local submenu, parent = menu:AddSubMenu("Nachfolger wählen")
				parent:SetIcon("icon16/user_suit.png")
				local members_sorted = table.Copy(members)
				table.sort(members_sorted, function(a, b) return a.name < b.name end)
				local found = false
				for k,v in pairs(members) do
					if k == LocalPlayer():SteamID() then continue end
					local rank = rankslist[v.rank].rename or rankslist[v.rank].name
					submenu:AddOption(v.name.." ("..rank..")", function()
						Derma_Query("Möchtest du "..v.name.." wirklich die Familie übertragen und deinen Rang abgeben?", "Familie übertragen", "Ja", function()
							surface.PlaySound("ui/buttonclick.wav")
							RunConsoleCommand("family_transfer", k)
						end, "Nein")
					end)
					found = true
				end
				if !found then
					submenu:AddOption("Niemand verfügbar")
				end
				menu:Open()
			end
			local TranferLabel = vgui.Create("DLabel", TransferFamily)
			TranferLabel:SetText("Familie übertragen ($"..string.Comma(FamilySystem_Config.TransferPrice)..")")
			TranferLabel:SetFont("FamilySystem_Button")
			TranferLabel:SetColor(color_white)
			TranferLabel:SizeToContents()
			TranferLabel:SetPos(5, 5)
			TranferLabel.Think = function()
				if LocalPlayer():canAfford(FamilySystem_Config.TransferPrice) then
					TranferLabel:SetColor(color_white)
				else
					TranferLabel:SetColor(Color(215, 50, 30))
				end
			end
			local SubTransferLabel = vgui.Create("DLabel", TransferFamily)
			SubTransferLabel:SetText("Trete den Familiengründer-Rang ab und vermache ihn einem anderen Mitglied.")
			SubTransferLabel:SetFont("FamilySystem_ButtonInfo")
			SubTransferLabel:SetColor(color_white)
			SubTransferLabel:SizeToContents()
			SubTransferLabel:SetPos(5, 28)
			ManageOptions:AddItem(TransferFamily)
		end
		local ResetFamily = vgui.Create("DButton")
		ResetFamily:SetText("")
		ResetFamily:SetTall(48)
		ResetFamily:SetWide(478)
		ResetFamily.Paint = function()
			draw.RoundedBox(0, 0, 0, ResetFamily:GetWide(), ResetFamily:GetTall(), Color(231, 76, 60))
		end
		ResetFamily.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			Derma_Query("Was möchtest du zurücksetzen?", "Zurücksetzen", "Logs", function()
				surface.PlaySound("ui/buttonclick.wav")
				RunConsoleCommand("family_resetlogs")
			end, "Finanzen", function()
				surface.PlaySound("ui/buttonclick.wav")
				RunConsoleCommand("family_resetfinances")
			end, "Ränge", function()
				surface.PlaySound("ui/buttonclick.wav")
				RunConsoleCommand("family_resetranks")
			end, "Gar nichts")
		end
		local DeleteLabel = vgui.Create("DLabel", ResetFamily)
		DeleteLabel:SetText("Zurücksetzen")
		DeleteLabel:SetFont("FamilySystem_Button")
		DeleteLabel:SetColor(color_white)
		DeleteLabel:SizeToContents()
		DeleteLabel:SetPos(5, 5)
		local SubDeleteLabel = vgui.Create("DLabel", ResetFamily)
		SubDeleteLabel:SetText("Setze Logs, Finanzen oder Ränge zurück.")
		SubDeleteLabel:SetFont("FamilySystem_ButtonInfo")
		SubDeleteLabel:SetColor(color_white)
		SubDeleteLabel:SizeToContents()
		SubDeleteLabel:SetPos(5, 28)
		ManageOptions:AddItem(ResetFamily)
		local DeleteFamily = vgui.Create("DButton")
		DeleteFamily:SetText("")
		DeleteFamily:SetTall(48)
		DeleteFamily:SetWide(478)
		DeleteFamily.Paint = function()
			draw.RoundedBox(0, 0, 0, DeleteFamily:GetWide(), DeleteFamily:GetTall(), Color(231, 76, 60))
		end
		DeleteFamily.DoClick = function()
			surface.PlaySound("ui/buttonclick.wav")
			Derma_Query("Möchtest du deine Familie wirklich auflösen?", "Familie auflösen", "Ja", function()
				surface.PlaySound("ui/buttonclick.wav")
				RunConsoleCommand("family_leave")
				FS_Frame:Close()
			end, "Nein")
		end
		local DeleteLabel = vgui.Create("DLabel", DeleteFamily)
		DeleteLabel:SetText("Familie auflösen")
		DeleteLabel:SetFont("FamilySystem_Button")
		DeleteLabel:SetColor(color_white)
		DeleteLabel:SizeToContents()
		DeleteLabel:SetPos(5, 5)
		local SubDeleteLabel = vgui.Create("DLabel", DeleteFamily)
		SubDeleteLabel:SetText("Lösche deine Familie permanent.")
		SubDeleteLabel:SetFont("FamilySystem_ButtonInfo")
		SubDeleteLabel:SetColor(color_white)
		SubDeleteLabel:SizeToContents()
		SubDeleteLabel:SetPos(5, 28)
		ManageOptions:AddItem(DeleteFamily)
		ManageTabs:AddSheet("Verwaltung", Manage, nil, false, false, "Familie verwalten")
	end

	net.Receive("FamilySystem_RefreshRanks", function()
		local leng = net.ReadUInt(32)
		ranks = net.ReadData(leng)
		ranks = util.JSONToTable(util.Decompress(ranks))
		if IsValid(RankList) then
			RankList:Clear()
			for _,v in pairs(ranks) do
				local name = v["name"]
				local rename = v["rename"] or name
				local rank = v["rename"] and v["rename"].." (Standard-Rang)" or name
				RankList:AddChoice(rank, {name, v["flags"], rename})
			end
			RankList:SetValue("Rang auswählen")
		end
		rankslist = ranks
	end)

	local text = "Familie verlassen"
	local text2 = "verlassen"
	if rank_name == "o" then
		text = "Familie auflösen"
		text2 = "auflösen"
	end
	SideMenu:AddSwitchButton(text, "fsystem/leave.png", function()
		Derma_Query("Möchtest du deine Familie wirklich "..text2.."?", text, "Ja", function()
			surface.PlaySound("ui/buttonclick.wav")
			RunConsoleCommand("family_leave")
			FS_Frame:Close()
		end, "Nein")
	end)

	net.Receive("FamilySystem_KillMenu", function()
		if IsValid(FS_Frame) then
			FS_Frame:Close()
		end
	end)
end)

local ignoreinvites = CreateClientConVar("cl_family_ignoreinvites", 0, FCVAR_ARCHIVE)
net.Receive("FamilySystem_SendInvitation", function()
	if ignoreinvites:GetBool() then return end
	surface.PlaySound("Town.d1_town_02_elevbell1")
	local text = net.ReadString()
	local family = net.ReadString()
	local InviteFrame = vgui.Create("DFrame")
	InviteFrame:SetSize(360, 205)
	InviteFrame:SetTitle("Familien-Einladung ("..family..")")
	InviteFrame:SetVisible(true)
	InviteFrame:SetDraggable(true)
	InviteFrame:ShowCloseButton(false)
	InviteFrame.StartTime = CurTime()
	InviteFrame.Paint = function()
		draw.RoundedBox(0, 0, 0, InviteFrame:GetWide(), 25, Color(52, 73, 94))
		draw.RoundedBox(0, 0, 25, InviteFrame:GetWide(), InviteFrame:GetTall() - 25, Color(226, 226, 226))
		draw.SimpleText("Einladung von Familie "..family, "FamilySystem_InviteText", 180, 130, Color(50, 50, 50, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
		local delta = CurTime() - InviteFrame.StartTime
		draw.SimpleText("Schließt sich in "..math.Round(30 - delta).."s", "FamilySystem_InviteText", 180, 150, Color(50, 50, 50, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
	end
	InviteFrame.Think = function()
		local delta = CurTime() - InviteFrame.StartTime
		InviteFrame:SetPos(ScrW() - 410, ScrH() - math.min(delta, 0.2) * 1150)
		if InviteFrame.StartTime + 30 <= CurTime() then
			InviteFrame:Close()
		end
	end
	local InvitePanel = vgui.Create("DPanel", InviteFrame)
	InvitePanel:SetSize(350, 80)
	InvitePanel:SetPos(5, 35)
	local InvitePanel_Paint = InvitePanel.Paint
	InvitePanel.Paint = function(s, w, h)
		InvitePanel_Paint(s, w, h)
		surface.SetDrawColor(189, 195, 199, 255)
		surface.DrawOutlinedRect(0, 0, InvitePanel:GetWide(), InvitePanel:GetTall())
	end
	local TextLabel = vgui.Create("DLabel", InvitePanel)	
	TextLabel:SetPos(5, 5)
	TextLabel:SetColor(Color(50, 50, 50))
	TextLabel:SetText(text)
	TextLabel:SetFont("FamilySystem_InviteText")
	TextLabel:SetAutoStretchVertical(true)
	TextLabel:SetWide(345)
	TextLabel:SetWrap(true)
	local AcceptButton = vgui.Create("DFlatButton", InviteFrame)
	AcceptButton:SetState(true)
	AcceptButton:SetPos(0, 165)
	AcceptButton:SetText("Einladung akzeptieren")
	AcceptButton.DoClick = function()
		surface.PlaySound("ui/buttonclick.wav")
		RunConsoleCommand("family_accept")
		InviteFrame:Close()
	end
	local DeclineButton = vgui.Create("DFlatButton", InviteFrame)
	DeclineButton:SetState(false)
	DeclineButton:SetPos(181, 165)
	DeclineButton:SetText("Einladung abblehnen")
	DeclineButton.DoClick = function()
		surface.PlaySound("ui/buttonclick.wav")
		RunConsoleCommand("family_deny")
		InviteFrame:Close()
	end
end)