InventoryTable = {}

function AddItem(data)
	local itemdata = {}
	itemdata.Name = data:ReadString();
	itemdata.Class = data:ReadString();
	itemdata.Description = data:ReadString();
	itemdata.Model = data:ReadString();
	
	table.insert(InventoryTable, itemdata);
end
usermessage.Hook("addinventory", AddItem);

function ClearItems()
	
	InventoryTable = {}
	
end
usermessage.Hook("clearinventory", ClearItems);

BusinessTable = {};

function AddBusinessItem(data)
	local itemdata = {}
	itemdata.Name = data:ReadString();
	itemdata.Class = data:ReadString();
	itemdata.Description = data:ReadString();
	itemdata.Model = data:ReadString();
	itemdata.Price = data:ReadLong();
	
	table.insert(BusinessTable, itemdata);
end
usermessage.Hook("addbusiness", AddBusinessItem);

function ClearBusinessItems()
	
	BusinessTable = {}
	
end
usermessage.Hook("clearbusiness", ClearBusinessItems);

function InitHiddenButton()
	HiddenButton = vgui.Create("DButton")
	HiddenButton:SetSize(ScrW(), ScrH());
	HiddenButton:SetText("");
	HiddenButton:SetDrawBackground(false);
	HiddenButton:SetDrawBorder(false);
	HiddenButton.DoRightClick = function()
		local Vect = gui.ScreenToVector(gui.MouseX(), gui.MouseY());
		local tracedata = {};
		tracedata.start = LocalPlayer():GetShootPos();
		tracedata.endpos = LocalPlayer():GetShootPos() + (Vect * 100);
		tracedata.filter = LocalPlayer();
		local trace = util.TraceLine(tracedata);
		
		if(trace.HitNonWorld) then
			local target = trace.Entity;
			
			local ContextMenu = DermaMenu()
				if(IsDoor(target)) then
					ContextMenu:AddOption("Rent/Unrent Door", function() LocalPlayer():ConCommand("rp_purchasedoor " .. target:EntIndex()) end);
					ContextMenu:AddOption("Lock", function() LocalPlayer():ConCommand("rp_lockdoor " .. target:EntIndex()) end);
					ContextMenu:AddOption("Unlock", function() LocalPlayer():ConCommand("rp_unlockdoor " .. target:EntIndex()) end);
				elseif(target:GetClass() == "item_prop") then
					ContextMenu:AddOption("Pick Up", function() LocalPlayer():ConCommand("rp_pickup " .. target:EntIndex()) end);
					ContextMenu:AddOption("Use", function() LocalPlayer():ConCommand("rp_useitem " .. target:EntIndex()) end);
				elseif(target:IsPlayer()) then
					local function PopupCredits()
						local CreditPanel = vgui.Create( "DFrame" );
						CreditPanel:SetPos(gui.MouseX(), gui.MouseY());
						CreditPanel:SetSize( 200, 175 )
						CreditPanel:SetTitle( "Give " .. target:Nick() .. " Credits");
						CreditPanel:SetVisible(true);
						CreditPanel:SetDraggable(true);
						CreditPanel:ShowCloseButton(true);
						CreditPanel:MakePopup();
						
						local Credits = vgui.Create( "DNumSlider", CreditPanel );
						Credits:SetPos( 25, 50 );
						Credits:SetWide(150);
						Credits:SetText("Credits to Give");
						Credits:SetMin( 0 );
						Credits:SetMax( tonumber(LocalPlayer():GetNWString("money")) );
						Credits:SetDecimals( 0 );
						
						local Give = vgui.Create( "DButton", CreditPanel );
						Give:SetText("Give");
						Give:SetPos( 25, 125 );
						Give:SetSize( 150, 25 );
						Give.DoClick = function()
							LocalPlayer():ConCommand("rp_givemoney " .. target:EntIndex() .. " " .. Credits:GetValue());
							CreditPanel:Remove();
							CreditPanel = nil;
						end
					end
					
					ContextMenu:AddOption("Give Credits", PopupCredits);
				end
				
			ContextMenu:Open();
		end
	end
end

function InitHUDMenu()

	InitHiddenButton();

	--[[HUDMenu = vgui.Create( "DFrame" )
	HUDMenu:SetPos( ScrW() - 130 - 5, 5 )
	HUDMenu:SetSize( 130, 150 )
	HUDMenu:SetTitle( "Player Information" )
	HUDMenu:SetVisible( true )
	HUDMenu:SetDraggable( false )
	HUDMenu:ShowCloseButton( false )
	
	local label = vgui.Create("DLabel", HUDMenu);
	label:SetWide(0);
	label:SetPos(5, 25);
	label:SetText("Name: " .. LocalPlayer():Nick());
	
	local label3 = vgui.Create("DLabel", HUDMenu);
	label3:SetWide(0);
	label3:SetPos(5, 55);
	label3:SetText("Title: " .. LocalPlayer():GetNWString("title"));
	
	local label4 = vgui.Create("DLabel", HUDMenu);
	label4:SetWide(0);
	label4:SetPos(5, 70);
	label4:SetText("Assosciation: " .. team.GetName(LocalPlayer():Team()));

	local label5 = vgui.Create("DLabel", HUDMenu);
	label5:SetWide(0);
	label5:SetPos(5, 85);
	label5:SetText(LocalPlayer():GetNWString("money") .. " Credits");
	
	local spawnicon = vgui.Create( "SpawnIcon", HUDMenu);
	spawnicon:SetSize( 128, 128 );
	spawnicon:SetPos(1,21);
	spawnicon:SetIconSize( 128 )
	spawnicon:SetModel(LocalPlayer():GetModel());
	spawnicon:SetToolTip("Open Player Menu");
	
	local FadeSize = 130;
	
	function UpdateGUIData()
		label:SetText("Name: " .. LocalPlayer():Nick());
		
		label3:SetText("Title: " .. LocalPlayer():GetNWString("title"));
		
		label4:SetText("Assosciation: " .. team.GetName(LocalPlayer():Team()));

		label5:SetText(LocalPlayer():GetNWString("money") .. " Credits");

		spawnicon:SetModel(LocalPlayer():GetModel());
		spawnicon:SetToolTip("This is your player model and info!");
	end
	
	spawnicon.PaintOver = function()
		spawnicon:SetPos(FadeSize - 129, 21);
		HUDMenu:SetSize(FadeSize, 150);
		HUDMenu:SetPos(ScrW() - FadeSize - 5, 5 );
		
		label:SetWide(FadeSize - 128);
		label3:SetWide(FadeSize - 128);
		label4:SetWide(FadeSize - 128);
		label5:SetWide(FadeSize - 128);
		
		if(FadeSize > 130) then
			FadeSize = FadeSize - 5;
		end
		
		UpdateGUIData();
	end
	
	spawnicon.PaintOverHovered = function()
		
		spawnicon:SetPos(FadeSize - 129, 21);
		HUDMenu:SetSize(FadeSize, 150);
		HUDMenu:SetPos(ScrW() - FadeSize - 5, 5 );
		
		label:SetWide(FadeSize - 128);
		label3:SetWide(FadeSize - 128);
		label4:SetWide(FadeSize - 128);
		label5:SetWide(FadeSize - 128);
		
		if(FadeSize < 320) then
			FadeSize = FadeSize + 5;
		end
		
		UpdateGUIData();
	end
end]]--
end

function CreatePlayerMenu()
	if(PlayerMenu) then
		PlayerMenu:Remove();
		PlayerMenu = nil;
	end
	
	PlayerMenu = vgui.Create( "DFrame" )
	PlayerMenu:SetPos( ScrW() / 2 - 320, ScrH() / 2 - 240 )
	PlayerMenu:SetSize( 650, 480 )
	PlayerMenu:SetTitle( "Player Menu" )
	PlayerMenu:SetVisible( true )
	PlayerMenu:SetDraggable( true )
	PlayerMenu:ShowCloseButton( true )
	PlayerMenu:MakePopup()
	
	PropertySheet = vgui.Create( "DPropertySheet" )
	PropertySheet:SetParent(PlayerMenu)
	PropertySheet:SetPos( 2, 30 )
	PropertySheet:SetSize( 636, 448 )
	
	local PlayerInfo = vgui.Create( "DPanelList" )
	PlayerInfo:SetPadding(20);
	PlayerInfo:SetSpacing(20);
	PlayerInfo:EnableHorizontal(false);
	
	local icdata = vgui.Create( "DForm" );
	icdata:SetPadding(4);
	icdata:SetName(LocalPlayer():Nick() or "");
	
	local FullData = vgui.Create("DPanelList");
	FullData:SetSize(0, 84);
	FullData:SetPadding(10);
	
	local DataList = vgui.Create("DPanelList");
	DataList:SetSize(0, 64);
	
	local spawnicon = vgui.Create( "SpawnIcon");
	spawnicon:SetModel(LocalPlayer():GetModel());
	spawnicon:SetSize( 64, 64 );
	DataList:AddItem(spawnicon);
	
	local DataList2 = vgui.Create( "DPanelList" )
	
	local label2 = vgui.Create("DLabel");
	label2:SetText("Title: " .. LocalPlayer():GetNWString("title"));
	DataList2:AddItem(label2);
	
	local label3 = vgui.Create("DLabel");
	label3:SetText("Assosciation: " .. team.GetName(LocalPlayer():Team()));
	DataList2:AddItem(label3);

	local Divider = vgui.Create("DHorizontalDivider");
	Divider:SetLeft(spawnicon);
	Divider:SetRight(DataList2);
	Divider:SetLeftWidth(64);
	Divider:SetHeight(64);
	
	DataList:AddItem(spawnicon);
	DataList:AddItem(DataList2);
	DataList:AddItem(Divider);

	FullData:AddItem(DataList)
	
	icdata:AddItem(FullData)
	
	local vitals = vgui.Create( "DForm" );
	vitals:SetPadding(4);
	vitals:SetName("Vital Signs");
	
	local VitalData = vgui.Create("DPanelList");
	VitalData:SetAutoSize(true)
	VitalData:SetPadding(10);
	vitals:AddItem(VitalData);
	
	local healthstatus = ""
	local hp = LocalPlayer():Health();
	
	if(!LocalPlayer():Alive()) then healthstatus = "Dead";
	elseif(hp > 95) then healthstatus = "Healthy";
	elseif(hp > 50 and hp < 95) then healthstatus = "OK";
	elseif(hp > 30 and hp < 50) then healthstatus = "Near Death";
	elseif(hp > 1 and hp < 30) then healthstatus = "Death Imminent"; end
	
	local health = vgui.Create("DLabel");
	health:SetText("Vitals: " .. healthstatus);
	VitalData:AddItem(health);
	
	PlayerInfo:AddItem(icdata)
	PlayerInfo:AddItem(vitals)
	
	CharPanel = vgui.Create( "DPanelList" )
	CharPanel:SetPadding(20);
	CharPanel:SetSpacing(20);
	CharPanel:EnableHorizontal(false);
	
	local newcharform = vgui.Create( "DForm" );
	newcharform:SetPadding(4);
	newcharform:SetName("New Character");
	newcharform:SetAutoSize(true);
	
	local CharMenu = vgui.Create( "DPanelList" )
	newcharform:AddItem(CharMenu);
	CharMenu:SetSize( 316, 386 )
	CharMenu:SetPadding(10);
	CharMenu:SetSpacing(20);
	CharMenu:EnableVerticalScrollbar();
	CharMenu:EnableHorizontal(false);


	
	local label = vgui.Create("DLabel");
	CharMenu:AddItem(label);
	label:SetSize(400, 25);
	label:SetPos(5, 25);
	label:SetText("Why hallo thar.");

	local info = vgui.Create( "DForm" );
	info:SetName("Personal Information");
	CharMenu:AddItem(info);

	local label = vgui.Create("DLabel");
	info:AddItem(label);
	label:SetSize(30,25);
	label:SetPos(150, 50);
	label:SetText("First: ");

	local firstname = vgui.Create("DTextEntry");
	info:AddItem(firstname);
	firstname:SetSize(100,25);
	firstname:SetPos(185, 50);
	firstname:SetText("");

	local label = vgui.Create("DLabel");
	info:AddItem(label);
	label:SetSize(30,25);
	label:SetPos(5, 50);
	label:SetText("Last: ");

	local lastname = vgui.Create("DTextEntry");
	info:AddItem(lastname);
	lastname:SetSize(100,25);
	lastname:SetPos(40, 50);
	lastname:SetText("");

	local label = vgui.Create("DLabel");
	info:AddItem(label);
	label:SetSize(100,25);
	label:SetPos(5, 80);
	label:SetText("Title: ");

	local title = vgui.Create("DTextEntry");
	info:AddItem(title);
	title:SetSize(205, 25);
	title:SetPos(80, 80);
	title:SetText("Unemployed");

	local spawnicon = nil;

	local modelform = vgui.Create( "DForm" );
	modelform:SetPadding(4);
	modelform:SetName("Appearance");
	CharMenu:AddItem(modelform);

	local modellist = vgui.Create( "DPanelList" );
	modellist:EnableHorizontal(true);
	modellist:EnableVerticalScrollbar();
	modellist:SetSize(256, 128);
	modelform:AddItem(modellist);

	for n = 1, table.getn(models) do -- Yes, this is Rick's code.
		
		local spawnicon = vgui.Create( "SpawnIcon");
		spawnicon:SetPos( x, y );
		spawnicon:SetSize( 64, 64 );
		spawnicon:SetModel( models[n] );

		spawnicon.DoClick = function() SetChosenModel( models[n] ) end
		
		modellist:AddItem(spawnicon);
		
	end

	local apply = vgui.Create("DButton");
	apply:SetSize(100, 25);
	apply:SetText("Apply");
	apply.DoClick = function ( btn )

		
		if(firstname:GetValue() == "" or lastname:GetValue() == "") then
			LocalPlayer():PrintMessage(3, "You must enter a first and last name!");
			return;
		end
		
		if(!table.HasValue(models, ChosenModel)) then
			LocalPlayer():PrintMessage(3, ChosenModel .. " is not a valid model!");
			return;
		end
		
		LocalPlayer():ConCommand("rp_startcreate");
		LocalPlayer():ConCommand("rp_setmodel \"" .. ChosenModel .. "\"");
		LocalPlayer():ConCommand("rp_changename \"" .. firstname:GetValue() .. " " .. lastname:GetValue() .. "\"");
		LocalPlayer():ConCommand("rp_title \"" .. string.sub(title:GetValue(), 1, 32) .. "\"");
		LocalPlayer().MyModel = ""
		LocalPlayer():ConCommand("rp_finishcreate");
		
		PlayerMenu:Remove();
		PlayerMenu = nil;
		
	end
	CharMenu:AddItem(apply);

	local selectcharform = vgui.Create( "DForm" );
	selectcharform:SetPadding(4);
	selectcharform:SetName("Select Character");
	selectcharform:SetSize(316, 386);

	local charlist = vgui.Create( "DPanelList" );
	selectcharform:AddItem(charlist)
	charlist:SetSize( 316, 386 )
	charlist:SetPadding(10);
	charlist:SetSpacing(20);
	charlist:EnableVerticalScrollbar();
	charlist:EnableHorizontal(true);

	for n = 1, table.getn(ExistingChars) do

		local spawnicon = vgui.Create( "SpawnIcon");
		spawnicon:SetSize( 128, 128 );
		spawnicon:SetIconSize( 128 )
		spawnicon:SetModel(ExistingChars[n]['model']);
		spawnicon:SetToolTip(ExistingChars[n]['name']);
		spawnicon.DoClick = function ( btn )
		
			LocalPlayer():ConCommand("rp_selectchar " .. n);
			LocalPlayer().MyModel = ""
			
			PlayerMenu:Remove();
			PlayerMenu = nil;
			
		end
		charlist:AddItem(spawnicon);
		
		spawnicon.PaintOver = function()
			surface.SetTextColor(Color(255,255,255,255));
			surface.SetFont("Trebuchet18");
			surface.SetTextPos(64 - surface.GetTextSize(ExistingChars[n]['name']) / 2, 5);
			surface.DrawText(ExistingChars[n]['name'])
		end
		
		spawnicon.PaintOverHovered = function()
			surface.SetTextColor(Color(255,255,255,255));
			surface.SetFont("Trebuchet18");
			surface.SetTextPos(64 - surface.GetTextSize(ExistingChars[n]['name']) / 2, 5);
			surface.DrawText(ExistingChars[n]['name'])
		end
		
	end

	
	local divider = vgui.Create("DHorizontalDivider");
	divider:SetLeft(newcharform);
	divider:SetRight(selectcharform);
	divider:SetLeftWidth(316); 

	CharPanel:AddItem(newcharform);
	CharPanel:AddItem(selectcharform);
	CharPanel:AddItem(divider);
	
	Commands = vgui.Create( "DPanelList" )
	Commands:SetPadding(20);
	Commands:SetSpacing(20);
	Commands:EnableHorizontal(true);
	Commands:EnableVerticalScrollbar(true);
	
	local Flags = vgui.Create("DListView");
	Flags:SetSize(600,446);
	Flags:SetMultiSelect(false)
	Flags:AddColumn("Flag Name");
	Flags:AddColumn("Salary");
	Flags:AddColumn("Business Access");
	Flags:AddColumn("Public Flag?");
	Flags:AddColumn("Flag Key");
	
	function Flags:DoDoubleClick(LineID, Line)
	
		LocalPlayer():ConCommand("rp_flag " .. TeamTable[LineID].flagkey);
		PlayerMenu:Remove();
		PlayerMenu = nil;
		
	end
	
	for k, v in pairs(TeamTable) do
		local yesno = "";
		if(v.public) then
			yesno = "Yes";
		elseif(!v.public) then
			yesno = "No";
		end
		
		local yesno2 = "";
		if(v.business) then
			yesno2 = "Yes";
		elseif(!v.business) then
			yesno2 = "No";
		end
		
		Flags:AddLine(v.name, tostring(v.salary), yesno2, yesno, v.flagkey);
	end
	
	Commands:AddItem(Flags);
	
	Inventory = vgui.Create( "DPanelList" )
	Inventory:SetPadding(20);
	Inventory:SetSpacing(20);
	Inventory:EnableHorizontal(true);
	Inventory:EnableVerticalScrollbar(true);
	
	for k, v in pairs(InventoryTable) do
		local spawnicon = vgui.Create( "SpawnIcon");
		spawnicon:SetSize( 128, 128 );
		spawnicon:SetIconSize( 128 )
		spawnicon:SetModel(v.Model);
		spawnicon:SetToolTip(v.Description);
		
		local function DeleteMyself()
			spawnicon:Remove()
		end
		
		spawnicon.DoClick = function ( btn )
		
			local ContextMenu = DermaMenu()
				ContextMenu:AddOption("Drop", function() LocalPlayer():ConCommand("rp_dropitem " .. v.Class); DeleteMyself(); end);
			ContextMenu:Open();
			
		end
		
		spawnicon.PaintOver = function()
			surface.SetTextColor(Color(255,255,255,255));
			surface.SetFont("DefaultSmall");
			surface.SetTextPos(64 - surface.GetTextSize(v.Name) / 2, 5);
			surface.DrawText(v.Name)
		end
		
		spawnicon.PaintOverHovered = function()
			surface.SetTextColor(Color(255,255,255,255));
			surface.SetFont("DefaultSmall");
			surface.SetTextPos(64 - surface.GetTextSize(v.Name) / 2, 5);
			surface.DrawText(v.Name)
		end
		
		Inventory:AddItem(spawnicon);
	end
	
	Business = vgui.Create( "DPanelList" )
	Business:SetPadding(20);
	Business:SetSpacing(20);
	Business:EnableHorizontal(true);
	Business:EnableVerticalScrollbar(true);
	if(TeamTable[LocalPlayer():Team()] != nil) then
		if(TeamTable[LocalPlayer():Team()].business) then
			for k, v in pairs(BusinessTable) do
				local spawnicon = vgui.Create( "SpawnIcon");
				spawnicon:SetSize( 128, 128 );
				spawnicon:SetIconSize( 128 )
				spawnicon:SetModel(v.Model);
				spawnicon:SetToolTip(v.Description);
				
				spawnicon.DoClick = function ( btn )
				
					local ContextMenu = DermaMenu()
						if(tonumber(LocalPlayer():GetNWString("money")) >= v.Price) then
							ContextMenu:AddOption("Purchase", function() LocalPlayer():ConCommand("rp_buyitem " .. v.Class); end);
						else
							ContextMenu:AddOption("Not Enough Tokens!");
						end
					ContextMenu:Open();
					
				end
				
				spawnicon.PaintOver = function()
					surface.SetTextColor(Color(255,255,255,255));
					surface.SetFont("DefaultSmall");
					surface.SetTextPos(64 - surface.GetTextSize(v.Name .. " (" .. v.Price .. ")") / 2, 5);
					surface.DrawText(v.Name .. " (" .. v.Price .. ")")
				end
				
				spawnicon.PaintOverHovered = function()
					surface.SetTextColor(Color(255,255,255,255));
					surface.SetFont("DefaultSmall");
					surface.SetTextPos(64 - surface.GetTextSize(v.Name .. " (" .. v.Price .. ")") / 2, 5);
					surface.DrawText(v.Name .. " (" .. v.Price .. ")")
				end
				
				Business:AddItem(spawnicon);
			end
		elseif(!TeamTable[LocalPlayer():Team()].business) then
			local label = vgui.Create("DLabel")
			label:SetText("You do not have access to the Business tab!");
			label:SetWide(400);
			
			Business:AddItem(label);
		end
	end
	
	local Help = vgui.Create( "DPanelList" )
	Help:SetPadding(20);
	Help:EnableHorizontal(false);
	Help:EnableVerticalScrollbar(true);
	
	local function AddHelpLine(text)
			local label = vgui.Create("DLabel");
			label:SetText(text);
			label:SizeToContents();
			Help:AddItem(label);
	end
	
	local lines = {
	"See: Rules.";
	}

	for k, v in pairs(lines) do
		AddHelpLine(v);
	end

	local Rules = vgui.Create( "DPanelList" )
	Rules:SetPadding(20);
	Rules:EnableHorizontal(false);
	Rules:EnableVerticalScrollbar(true);
	
	local function AddRulesLine(text)
			local label = vgui.Create("DLabel");
			label:SetText(text);
			label:SizeToContents();
			Rules:AddItem(label);
	end
	
	local Ruleslines = {
	
    "* 1. A bad roleplay name (e.g. xXx Lemon MASTER xXx) will get you a kick, constantly refusing to get a good ",
	"roleplay name will get you a 60 minute ban.",
    "* 2. Dead people are to be revived, and injury roleplay is to take place.",
    "* 3. Flaming/trolling on OOC. Using caps lock and swearing to prove that you are right will get you a kick, ",
	"possibly a 30 minute ban, even if you are an admin. I'm tired of this.",
    "* 4. Bad roleplay. This rule is already greatly enforced though, thanks to our genius Sharpy, and a ",
	"few other good roleplaying department admins. Bad roleplay could extend from a kick to a permanent ban, ",
	"punishment is a choice of the online administrator.",
    "* 5. Prop/NPC spam. This is quite serious and if this is done, your NPC spawn or prop spawn ability will be ",
	"taken away and possibly a ban could be in file for you.",
    "* 6. Refusal to higher-ranked units. Not obeying shouldn't be considered bad roleplay because it is a possibility ",
	"in the army, would be classified under 'disobedience'. This is a problem that should be dealt in the roleplay, a ban ",
	"or kick is not necessary unless it is serious."
	}

	for k, v in pairs(Ruleslines) do
		AddRulesLine(v);
	end

	PropertySheet:AddSheet( "Player Menu", PlayerInfo, "gui/silkicons/user", false, false, "General information.");
	PropertySheet:AddSheet( "Character Menu", CharPanel, "gui/silkicons/group", false, false, "Switch to another character or create a new one.");
	PropertySheet:AddSheet( "Commands/Flagging", Commands, "gui/silkicons/wrench", false, false, "Execute some common commands or set your flag.");
	PropertySheet:AddSheet( "Backpack", Inventory, "gui/silkicons/box", false, false, "View your inventory.")
	PropertySheet:AddSheet( "Business", Business, "gui/silkicons/box", false, false, "Purchase items.");	
	PropertySheet:AddSheet( "Help", Help, "gui/silkicons/magnifier", false, false, "Get some help!");
	PropertySheet:AddSheet( "Rules", Rules, "gui/silkicons/magnifier", false, false, "The Rules, READ THEM NOW!");
end
usermessage.Hook("playermenu", CreatePlayerMenu);