----------------------------------------------
---  Settings and Shit -----------------------
----------------------------------------------
local canAccess = LocalPlayer():IsAdmin() or  LocalPlayer():IsSuperAdmin() -- Change this to 'LocalPlayer():IsUserGroup( 'admin' )' etc..

CreateClientConVar( "clicker_sound", 1, true, false )
CreateClientConVar( "clicker_itemHoverSound", 1, true, false )
CreateClientConVar( "clicker_textComma", 1, true, false )
CreateClientConVar( "clicker_melonSpin", 1, true, false )
CreateClientConVar( "clicker_hideSell", 1, true, false )
CreateClientConVar( "clicker_buySellNotify", 1, true, false )
CreateClientConVar( "clicker_itemProduction", 1, true, false )
CreateClientConVar( "clicker_openKeyBind", clickerSettings.openFKey, true, false )
CreateClientConVar( "clicker_updateStats", 10, true, false )
CreateClientConVar( "clicker_highScoreNotify", 1, true, false )
CreateClientConVar( "clicker_targetPly", "", false, false )
concommand.Add( "ClickerResetCount", function(ply, cmd, notify)
	ply:Clicker_AddToCount(-ply:Clicker_GetCount())
	if notify[1] == "true" then ply:Clicker_Notify("Your "..clickerSettings.melonName.." count has been reset!") end
end)

concommand.Add( "ClickerResetItems", function(ply, cmd, notify)
	ply:Clicker_ResetItems()
	if notify[1] == "true" then ply:Clicker_Notify("Your items have all been reset!") end
end)

local hsTime = 0
concommand.Add( "ClickerUpdateHS", function(ply, cmd, notify)
	ply:Clicker_LoadHighScores(1)
	timer.Simple(1, function() Clicker_UpdateHighScores() end)
	hsTime = 1
end)

concommand.Add( "ClickerResetStats", function(ply, cmd, notify)
	local stats = ply:Clicker_GetStats()
	clickerSettings.secretSessionStartCount = 0
	for k, v in pairs(stats) do
		ply:Clicker_ModifyStats(v.Name, 0)
	end
	if notify[1] == "true" then ply:Clicker_Notify("Your statistics have all been reset!") end
end)
concommand.Add( "ClickerResetAll", function(ply, cmd, notify)
	ply:ConCommand("ClickerResetCount", "false")
	ply:ConCommand("ClickerResetItems", "false")
	ply:ConCommand("ClickerResetStats", "false")
	ply:Clicker_Notify("Everything has been reset!")
end)

clickerSettings.secretTotalAmountOwned = 0
clickerSettings.resetItems = false
if clickerSettings.secretSessionStartCount and LocalPlayer():Clicker_FindStats('Total '..clickerSettings.melonPlural..' Produced') then
	clickerSettings.secretSessionStartCount = tonumber(LocalPlayer():Clicker_FindStats('Total '..clickerSettings.melonPlural..' Produced'))
else
	clickerSettings.secretSessionStartCount = 0
end
clickerSettings.secretSessionDuringCount = 0

LocalPlayer():Clicker_Notify("Hit F"..GetConVarNumber("clicker_openKeyBind")..",or type '"..clickerSettings.openChatCommand.."', to open "..clickerSettings.melonName.." Clicker!")

local lastSaveTime = 0
concommand.Add("Clicker_ForceSave", function()
	if (SysTime() - lastSaveTime) > 5 then
		net.Start("ClickerForceSave")
			net.WriteEntity(LocalPlayer())
			net.WriteInt(1, 1)
		net.SendToServer()
	else
		LocalPlayer():Clicker_Notify("Please wait a few seconds before trying to save again!")
	end
	lastSaveTime = SysTime()
end)
concommand.Add("Clicker_ForceAllSave", function()
	if (SysTime() - lastSaveTime) > 5 then
		for _, ply in pairs(player.GetAll()) do
			if IsValid(ply) then
				net.Start("ClickerForceSave")
					net.WriteEntity(ply)
					net.WriteInt(1, 1)
				net.SendToServer()
			end
		end
	else
		LocalPlayer():Clicker_Notify("Please wait a few seconds before trying to save again!")
	end
	lastSaveTime = SysTime()
end)
if clickerSettings.pointConversionEnabled then
	concommand.Add( "clicker_pointConvert", function()
		if (SysTime() - lastSaveTime) > 5 then
			local startPoints = LocalPlayer():Clicker_GetCount()
			local pointsToAdd = math.Round((startPoints / clickerSettings.pointConversionRate)-0.5)
			local melonsSaved = startPoints % clickerSettings.pointConversionRate
			if pointsToAdd > 0 then
				LocalPlayer():Clicker_AddToCount((-startPoints)+melonsSaved)
				LocalPlayer():Clicker_ModifyStats('Total Points from Conversion', LocalPlayer():Clicker_FindStats('Total Points from Conversion') + pointsToAdd)
				net.Start('ClickerAddToPoints')
					net.WriteString(pointsToAdd)
				net.SendToServer()
				LocalPlayer():Clicker_Notify(tostring(startPoints-melonsSaved).." "..clickerSettings.melonPlural.." have been exchanged for "..pointsToAdd.." "..PS.Config.PointsName.."!")
			else
				LocalPlayer():Clicker_Notify("You don't have enough "..clickerSettings.melonPlural.." to convert into points!")
			end
		end
		lastSaveTime = SysTime()
	end)
end

-------------------------------
---  Main Bit -----------------
-------------------------------

local wOffset = (100/1920)*ScrW()
local hOffset = (365/1080)*ScrH()
local widthPortion = (ScrW()- wOffset)/3
local heightPortion = widthPortion - 35

surface.CreateFont("Clicker14",   {font = "BFHud SemiBold",
                                size = 14,
                                weight = 1})
surface.CreateFont("Clicker16",   {font = "BFHud SemiBold",
                                size = 16,
                                weight = 5})
surface.CreateFont("Clicker18",   {font = "BFHud SemiBold",
                                size = 18,
                                weight = 5})
surface.CreateFont("Clicker20",   {font = "BFHud SemiBold",
                                size = 20,
                                weight = 5})
surface.CreateFont("Clicker24",   {font = "BFHud SemiBold",
                                size = 24,
                                weight = 5})
surface.CreateFont("Clicker28",   {font = "BFHud SemiBold",
                                size = 28,
                                weight = 5})

-- Taken from http://lua-users.org/wiki/FormattingNumbers
function CommaValue(amount)
	if not amount then return 0 end
	if GetConVar( "clicker_textComma" ):GetBool() then
		local formatted = amount
		while true do  
		formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
		if (k==0) then
		  break
		end
		end
		return formatted
	else
		return amount
	end
end
-- End 'Taken from http://lua-users.org/wiki/FormattingNumbers'

----------------------------------------------
--- Main Bit ---------------------------------
----------------------------------------------

local currentVisible = false
local clickerFrame = vgui.Create( "DFrame" )
clickerFrame:SetPos( 50, 5 )
clickerFrame:SetSize( ScrW()-wOffset, widthPortion )
clickerFrame:SetTitle( "" )
clickerFrame:SetVisible( false )
clickerFrame:SetScreenLock( true )
clickerFrame:SetDeleteOnClose( false )
clickerFrame:SetDraggable( true )
clickerFrame:ShowCloseButton( true )
clickerFrame:MakePopup()
clickerFrame.OnClose = function(slf, w, h) currentVisible = not currentVisible end
clickerFrame.Paint = function(slf, w, h)
	draw.RoundedBox(0, 0, 0, w, h, clickerSettings.backgroundColor)
	draw.RoundedBox(0, 0, 0, w, 25, clickerSettings.mainColor)
	draw.DrawText(clickerSettings.melonName.." Clicker", "Clicker28", 5, -3, Color(255, 255, 255, 255), TEXT_ALIGN_LEFT)
end

local clickItem = vgui.Create( "clickerObject" , clickerFrame ) -- SpawnIcon
clickItem:SetPos( 5, 30 )
clickItem:SetSize( widthPortion, heightPortion)

local clickerPSheet = vgui.Create( "DPropertySheet", clickerFrame )
clickerPSheet:SetPos( widthPortion + 10, 30 )
clickerPSheet:SetSize( widthPortion*2-15, heightPortion )
clickerPSheet.Paint = function(self,w,h) draw.RoundedBox( 0, 0, 0, w, h, clickerSettings.mainColor) end
 
local settingsSheet = vgui.Create("DPanelList", clickerFrame)
settingsSheet:StretchToParent(0, 0, 5, 0)
settingsSheet:EnableVerticalScrollbar(false)

----------------------------------------------
--- Settings Bit -----------------------------
----------------------------------------------

	local settingsPart = vgui.Create("DPanelList", settingsSheet)
	settingsPart:SetSize( (clickerPSheet:GetWide()/2)-10, clickerPSheet:GetTall()-37 )
	settingsPart:EnableVerticalScrollbar(true)
	settingsPart.VBar.Paint = function( s, w, h )
		surface.SetDrawColor( Color(28, 28, 28, 255) )
		surface.DrawRect( 0, 0, w, h )
	end
	settingsPart.VBar.btnUp.Paint = function( s, w, h ) 
		surface.SetDrawColor( Color(18, 155, 235, 255) )
		surface.DrawRect( 0, 0, w-1, h )
		surface.SetDrawColor( Color(28, 28, 28, 255) )
		surface.DrawRect( 1, 1, w-3, h-2 )
	end
	settingsPart.VBar.btnDown.Paint = function( s, w, h ) 
		surface.SetDrawColor( Color(18, 155, 235, 255) )
		surface.DrawRect( 0, 0, w-1, h )
		surface.SetDrawColor( Color(28, 28, 28, 255) )
		surface.DrawRect( 1, 1, w-3, h-2 )
	end
	settingsPart.VBar.btnGrip.Paint = function( s, w, h )
		surface.SetDrawColor( Color(18, 155, 235, 255) )
		surface.DrawRect( 0, 0, w-1, h )
		surface.SetDrawColor( Color(28, 28, 28, 255) )
		surface.DrawRect( 1, 1, w-3, h-2 )
	end

	local mainForm = vgui.Create("DForm", settingsPart)
	mainForm:SetName("Main Settings")
	mainForm.Paint = function(s, w, h)
		surface.SetDrawColor( clickerSettings.secondaryColor )
		surface.DrawRect( 0, 0, w, h )
		surface.SetDrawColor( clickerSettings.settingsHeaderColor )
		surface.DrawRect( 0, 0, w, 20 )
	end

	function mainForm:KeyComboBox( strLabel )
		local left = vgui.Create( "DLabel", self )
		left:SetText( strLabel )
		left:SetDark( true )
		local right = vgui.Create( "DComboBox", self )
		local startKey = GetConVarNumber("clicker_openKeyBind")
		right:SetValue("Current: F"..startKey)
		right:Dock( FILL )
		local startWide = right:GetWide()
		if startKey >= 10 then right:SetSize(startWide+25,right:GetTall())
	    else right:SetSize(startWide+20,right:GetTall()) end
		right.OnSelect = function( panel, index, value, data )
			local newNum = tonumber(string.sub(value, 2))
			if newNum >= 10 then right:SetSize(startWide+25,right:GetTall())
	    	else right:SetSize(startWide+20,right:GetTall()) end
			right:SetValue( "Current: F"..newNum )
			RunConsoleCommand("clicker_openKeyBind", newNum)
			LocalPlayer():Clicker_Notify("You've changed your open/close key to F"..newNum.."!")
		end
		self:AddItem( left, right )
		return right, left
	end
	local chkBox1 = mainForm:CheckBox("Toggle "..clickerSettings.melonName.." Click Sound", "clicker_sound")
	local chkBox2 = mainForm:CheckBox("Toggle Item Hover Sound", "clicker_itemHoverSound")
	local chkBox3 = mainForm:CheckBox("Toggle Thousand Seperator", "clicker_textComma")
	local chkBox4 = mainForm:CheckBox("Toggle "..clickerSettings.melonName.." Spin", "clicker_melonSpin")
	local chkBox5 = mainForm:CheckBox("Toggle Buy/Sell Notifications", "clicker_buySellNotify")
	local chkBox6 = mainForm:CheckBox("Toggle High Scores Update Notifications", "clicker_highScoreNotify")
	local chkBox7 = mainForm:CheckBox("Toggle Item Production", "clicker_itemProduction")
	local chkBox8 = mainForm:CheckBox("Hide 'Sell Item' if Item is Not Owned", "clicker_hideSell")
	local numWang1 = mainForm:NumSlider("Statistics Update Timer:", "clicker_updateStats", 2, 30, 0)
	local comBox1, comBoxLabel1 = mainForm:KeyComboBox("Open "..clickerSettings.melonName.." Clicker Key:")
	comBoxLabel1:SizeToContents()
	comBox1:Dock( LEFT )
	comBox1:DockMargin( 5, 0, 0, 0 )
	for i=5, 12 do
		if not (tostring(i) == GetConVarString("clicker_openKeyBind")) then
			comBox1:AddChoice( "F"..i )
		end
	end
	settingsPart:AddItem(mainForm)

	local actionForm = vgui.Create("DForm", settingsPart)
	actionForm:SetName("Main Actions")
	actionForm.Paint = function(s, w, h)
		surface.SetDrawColor( clickerSettings.secondaryColor )
		surface.DrawRect( 0, 0, w, h )
		surface.SetDrawColor( clickerSettings.settingsHeaderColor )
		surface.DrawRect( 0, 0, w, 20 )
	end
	---------------------------------------------
	--- Delete me if you don't use Pointshop! ---
	---------------------------------------------
	/*if clickerSettings.pointConversionEnabled then
		local convertPoints = actionForm:Button("Convert "..clickerSettings.melonPlural.." into "..PS.Config.PointsName, "clicker_pointConvert")
		convertPoints:SetTextColor( Color(255, 255, 255, 255) )
		convertPoints.Paint = function(self, w, h)
		    draw.RoundedBox( 0, 0, 0, w, h, Color(17, 102, 190, 255) )
		    draw.RoundedBox( 0, 1, 1, w-2, h-2, Color(26, 132, 210, 255) )
		    surface.SetDrawColor( Color(10, 82, 212, 255) )
		    surface.SetTexture( surface.GetTextureID( "gui/gradient" ) )
		    surface.DrawTexturedRectRotated( w/2, h/2, h-1, w-2, 90 )
		    draw.RoundedBox( 0, 1, 1, w-2, 1, Color(61, 158, 219, 255) )
		end
		convertPoints.OnCursorEntered = function(self)
		    self:SetTextColor( Color(0, 0, 0, 255) )
		end
		convertPoints.OnCursorExited = function(self)
		    self:SetTextColor( Color(255, 255, 255, 255) )
		end
		timer.Create( "ClickerButtonUpdate", 1, 0, function() 
			local pointsToGain = math.Round((LocalPlayer():Clicker_GetCount() / clickerSettings.pointConversionRate)-0.5)
			local melonsToSpend = LocalPlayer():Clicker_GetCount() - (LocalPlayer():Clicker_GetCount() % clickerSettings.pointConversionRate)
			local buttonsText = "Convert "..melonsToSpend.." "..clickerSettings.melonPlural.." into "..pointsToGain.." "..PS.Config.PointsName
			convertPoints:SetText(buttonsText)
		end)
	end*/
	---------------------------------------------
	--- END -------------------------------------
	---------------------------------------------
	local forceHSUpdate = actionForm:Button("Force Update High Scores", "Clicker_UpdateHS")
	forceHSUpdate:SetTextColor( Color(255, 255, 255, 255) )
	forceHSUpdate.Paint = function(self, w, h)
	    draw.RoundedBox( 0, 0, 0, w, h, Color(17, 102, 190, 255) )
	    draw.RoundedBox( 0, 1, 1, w-2, h-2, Color(26, 132, 210, 255) )
	    surface.SetDrawColor( Color(10, 82, 212, 255) )
	    surface.SetTexture( surface.GetTextureID( "gui/gradient" ) )
	    surface.DrawTexturedRectRotated( w/2, h/2, h-1, w-2, 90 )
	    draw.RoundedBox( 0, 1, 1, w-2, 1, Color(61, 158, 219, 255) )
	end
	forceHSUpdate.OnCursorEntered = function(self)
	    self:SetTextColor( Color(0, 0, 0, 255) )
	end
	forceHSUpdate.OnCursorExited = function(self)
	    self:SetTextColor( Color(255, 255, 255, 255) )
	end

	local saveBtn = actionForm:Button("Force Save", "Clicker_ForceSave")
	saveBtn:SetTextColor( Color(255, 255, 255, 255) )
	saveBtn.Paint = function(self, w, h)
	    draw.RoundedBox( 0, 0, 0, w, h, Color(89, 166, 67, 255) )
	    draw.RoundedBox( 0, 1, 1, w-2, h-2, Color(106, 196, 81, 255) )
	    surface.SetDrawColor( Color(88, 164, 67, 255) )
	    surface.SetTexture( surface.GetTextureID( "gui/gradient" ) )
	    surface.DrawTexturedRectRotated( w/2, h/2, h-1, w-2, 90 )
	    draw.RoundedBox( 0, 1, 1, w-2, 1, Color(134, 208, 118, 255) )
	end
	saveBtn.OnCursorEntered = function(self)
	    self:SetTextColor( Color(0, 0, 0, 255) )
	end
	saveBtn.OnCursorExited = function(self)
	    self:SetTextColor( Color(255, 255, 255, 255) )
	end
	---------------------
	--- Reset Buttons ---
	---------------------
	local resetBtn = actionForm:Button("Reset "..clickerSettings.melonName.." Count", "ClickerResetCount", "true")
	resetBtn:SetTextColor( Color(255, 255, 255, 255) )
	resetBtn.Paint = function(self, w, h)
	    draw.RoundedBox( 0, 0, 0, w, h,Color(192, 73, 61, 255) )
	    draw.RoundedBox( 0, 1, 1, w-2, h-2, Color(233, 96, 86, 255) )

	    surface.SetDrawColor( Color(185, 56, 42, 255) )
	    surface.SetTexture( surface.GetTextureID( "gui/gradient" ) )
	    surface.DrawTexturedRectRotated( w/2, h/2, h-1, w-2, 90 )

	    draw.RoundedBox( 0, 1, 1, w-2, 1,  Color(237, 128, 121, 255) )
	end
	resetBtn.OnCursorEntered = function(self) self:SetTextColor( Color(0, 0, 0, 255) ) end
	resetBtn.OnCursorExited = function(self) self:SetTextColor( Color(255, 255, 255, 255) ) end

	local resetItmBtn = actionForm:Button("Reset Items", "ClickerResetItems", "true")
	resetItmBtn:SetTextColor( Color(255, 255, 255, 255) )
	resetItmBtn.Paint = resetBtn.Paint
	resetItmBtn.OnCursorEntered = resetBtn.OnCursorEntered
	resetItmBtn.OnCursorExited = resetBtn.OnCursorExited

	local resetStatsBtn = actionForm:Button("Reset Statistics", "ClickerResetStats", "true")
	resetStatsBtn:SetTextColor( Color(255, 255, 255, 255) )
	resetStatsBtn.Paint = resetBtn.Paint
	resetStatsBtn.OnCursorEntered = resetBtn.OnCursorEntered
	resetStatsBtn.OnCursorExited = resetBtn.OnCursorExited

	local resetAlHStn = actionForm:Button("Reset Everything", "ClickerResetAll", "true")
	resetAlHStn:SetTextColor( Color(255, 255, 255, 255) )
	resetAlHStn.Paint = resetBtn.Paint
	resetAlHStn.OnCursorEntered = resetBtn.OnCursorEntered
	resetAlHStn.OnCursorExited = resetBtn.OnCursorExited
	settingsPart:AddItem(actionForm)

	-------------------
	--- Player List ---
	-------------------

	local plyListForm = vgui.Create("DForm", settingsPart)
	plyListForm:SetName("Player List")
	if canAccess then
		plyListForm:SetName("Player List and Admin Commands")
	end
	plyListForm.Paint = function(s, w, h)
		surface.SetDrawColor( clickerSettings.secondaryColor )
		surface.DrawRect( 0, 0, w, h )
		surface.SetDrawColor( clickerSettings.settingsHeaderAdminColor )
		surface.DrawRect( 0, 0, w, 20 )
	end

	function plyListForm:PlayerList()
		local left = vgui.Create( "DListView", self )
		left:SetMultiSelect( false )
		local plyName = left:AddColumn( "Player Name" )
		local melons = left:AddColumn( clickerSettings.melonPlural )
		local melonsps = left:AddColumn( clickerSettings.melonPlural.." Per-Second" )
		local itemCnt = left:AddColumn( "Item Count" )
		plyName.Header:SetTextColor( Color(255, 255, 255, 255) )
		melons.Header:SetTextColor( Color(255, 255, 255, 255) )
		melonsps.Header:SetTextColor( Color(255, 255, 255, 255) )
		itemCnt.Header:SetTextColor( Color(255, 255, 255, 255) )
		plyName.Header.Paint = function(self, w, h)
			draw.RoundedBox( 0, 0, 0, w, h,  Color(0, 0, 0, 245) )
			draw.RoundedBox( 0, 1, 1, w-2, h-2,  Color(34, 34, 34, 255) )
			draw.RoundedBox( 0, 0, 0, w, h/2,  Color(255, 255, 255, 2) )
	   	end
	   	melons.Header.Paint = plyName.Header.Paint
	   	melonsps.Header.Paint = plyName.Header.Paint
	   	itemCnt.Header.Paint = plyName.Header.Paint
	   	left.Paint = function(slf, w, h) 
		   	surface.SetDrawColor( clickerSettings.plyListBackgroundColor )
			surface.DrawRect( 0, 0, w, h )
		end
		left.VBar.Paint = settingsPart.VBar.Paint
		left.VBar.btnUp.Paint = settingsPart.VBar.btnUp.Paint
		left.VBar.btnDown.Paint = settingsPart.VBar.btnDown.Paint
		left.VBar.btnGrip.Paint = settingsPart.VBar.btnGrip.Paint
		left:SetSize(left:GetWide(), 200)
		left.OnRowSelected = function( panel, line )
			if canAccess then
				local curPly = left:GetLine(line).Player
				if IsValid(curPly) then -- and not (curPly:IsBot()) then
					local options = DermaMenu()
					options:AddOption('Reset '..clickerSettings.melonPlural, function()
						curPly:Clicker_AddToCount(-curPly:Clicker_GetCount())
					end):SetImage("icon16/exclamation.png")
					options:AddOption('Reset Items', function()
						net.Start('ClickerResetItems')
							net.WriteEntity(curPly, 32)
						net.SendToServer()
					end):SetImage("icon16/exclamation.png")
					options:AddSpacer()
					options:AddOption('Add 50 '..clickerSettings.melonPlural, function()
						curPly:Clicker_AddToCount(50)
					end):SetImage("icon16/coins_add.png")
					options:AddOption('Add 500 '..clickerSettings.melonPlural, function()
						curPly:Clicker_AddToCount(500)
					end):SetImage("icon16/coins_add.png")
					options:AddOption('Add '..CommaValue(5000)..' '..clickerSettings.melonPlural, function()
						curPly:Clicker_AddToCount(5000)
					end):SetImage("icon16/coins_add.png")
					options:AddOption('Add '..CommaValue(50000)..' '..clickerSettings.melonPlural, function()
						curPly:Clicker_AddToCount(50000)
					end):SetImage("icon16/coins_add.png")
					options:AddOption('Add '..CommaValue(500000)..' '..clickerSettings.melonPlural, function()
						curPly:Clicker_AddToCount(500000)
					end):SetImage("icon16/coins_add.png")
					options:AddOption('Add '..CommaValue(5000000)..' '..clickerSettings.melonPlural, function()
						curPly:Clicker_AddToCount(5000000)
					end):SetImage("icon16/coins_add.png")
					options:AddOption('Add '..CommaValue(50000000000)..' '..clickerSettings.melonPlural, function()
						curPly:Clicker_AddToCount(50000000000)
					end):SetImage("icon16/coins_add.png")
					options:Open()
				end
			end
		end
		self:AddItem( left )
		return left
	end

	--------------------
	--- Player Think ---
	--------------------
	plyList, plyListLabel = plyListForm:PlayerList("")
	plyListForm.Think = function()
		local curLines = plyList:GetLines()
		for k, v in pairs(player.GetAll()) do
			found = false
			for i, j in pairs(curLines) do
				if (j.Player == v) then
					if not found then
						found = true
					end
				end
			end
			if not found then
				plyList:AddLine( v:Nick(), CommaValue(v:Clicker_GetCount()), CommaValue(v:Clicker_GetPerSecond()), 0).Player = v
			end
		end
		for _, j in pairs(curLines) do -- Update player names etc...
			if IsValid(j.Player) then
				local ply = j.Player
				local items = ply:Clicker_GetItems()
				local itemCount = 0
				if items then
					for _, k in pairs(items) do
						itemCount = itemCount + k
					end
				end
				j:SetValue(1, ply:Nick())
				j:SetValue(2, CommaValue(ply:Clicker_GetCount()))
				j:SetValue(3, CommaValue(ply:Clicker_GetPerSecond()))
				j:SetValue(4, CommaValue(itemCount))
			else
				plyList:RemoveLine(_)
			end
		end
	end

	-------------------------
	--- Reset All Buttons ---
	-------------------------
	if canAccess then
		local saveAlHStn = plyListForm:Button("Force Save on All Players", "Clicker_ForceAllSave")
		saveAlHStn:SetTextColor( Color(255, 255, 255, 255) )
		saveAlHStn.Paint = saveBtn.Paint
		saveAlHStn.OnCursorEntered = saveBtn.OnCursorEntered
		saveAlHStn.OnCursorExited = saveBtn.OnCursorExited
	end

	settingsPart:AddItem(plyListForm)

----------------------------------------------
--- Statistics Bit ---------------------------
----------------------------------------------

	local statsPart = vgui.Create("DPanelList", settingsSheet)
	statsPart:SetSize( (clickerPSheet:GetWide()/2)-10, clickerPSheet:GetTall()-37 )
	statsPart:MoveRightOf( settingsPart, 4 )
	statsPart:EnableVerticalScrollbar(true)
	statsPart.VBar.Paint = settingsPart.VBar.Paint
	statsPart.VBar.btnUp.Paint = settingsPart.VBar.btnUp.Paint
	statsPart.VBar.btnDown.Paint = settingsPart.VBar.btnDown.Paint
	statsPart.VBar.btnGrip.Paint = settingsPart.VBar.btnGrip.Paint

	-----------------------
	--- Main Statistics ---
	-----------------------

	local statTime = GetConVarNumber( "clicker_updateStats" )-1
	local initStatTime = statTime
	local mainStatsForm = vgui.Create("DForm", statsPart)
	mainStatsForm:SetName("Main Statistics - Updates in "..statTime.." Seconds!")
	mainStatsForm.Paint = function(s, w, h)
		surface.SetDrawColor( clickerSettings.secondaryColor )
		surface.DrawRect( 0, 0, w, h )
		surface.SetDrawColor( clickerSettings.settingsHeaderColor )
		surface.DrawRect( 0, 0, w, 20 )
	end

	function mainStatsForm:CustomText( strLabel )
		local left = vgui.Create( "DLabel", self )
		left:SetText( strLabel )
		left:SetDark( true )
		self:AddItem( left )
		return left
	end

	local statItemTable = {}
	for k, v in pairs(LocalPlayer():Clicker_GetStats()) do
		if k == 3 then
			mainStatsForm:CustomText("Current "..clickerSettings.melonName.."-to-Point Exchange Rate: "..CommaValue(tostring(clickerSettings.pointConversionRate)).." "..clickerSettings.melonPlural.." = 1 POINTS?")
		end
		local tempStat = mainStatsForm:CustomText(v.Name:gsub("Melons", clickerSettings.melonPlural)..": "..CommaValue(tostring(v.Value)))
		statItemTable[k] = tempStat
	end
	statsPart:AddItem(mainStatsForm)

	local function updateStats()
		LocalPlayer():Clicker_ModifyStats('Current '..clickerSettings.melonPlural..' Owned', tostring(LocalPlayer():Clicker_GetCount()))
		LocalPlayer():Clicker_ModifyStats('Current '..clickerSettings.melonPlural..' Per-Second', tostring(LocalPlayer():Clicker_GetPerSecond()))
		LocalPlayer():Clicker_ModifyStats('Total Items Owned', tostring(clickerSettings.secretTotalAmountOwned))
		LocalPlayer():Clicker_ModifyStats('Total '..clickerSettings.melonPlural..' Produced', tostring( clickerSettings.secretSessionDuringCount + clickerSettings.secretSessionStartCount))
		LocalPlayer():Clicker_ModifyStats('Total '..clickerSettings.melonPlural..' Produced (This Session)', tostring( clickerSettings.secretSessionDuringCount))
		timer.Simple(1, function() for k, v in pairs(statItemTable ) do v:SetText(LocalPlayer():Clicker_GetStats()[k].Name:gsub("Melons", clickerSettings.melonPlural)..": "..CommaValue(LocalPlayer():Clicker_GetStats()[k].Value)) end end)
	end
	timer.Create( "ClickerStatUpdate", GetConVarNumber( "clicker_updateStats" )-1, 0, function() updateStats() end)

	timer.Create( "ClickerStatUpdateLabel", 1, 0, function()
		statTime = statTime - 1
		if statTime == 0 then
			statTime = GetConVarNumber( "clicker_updateStats" )-1
			if not (initStatTime == GetConVarNumber( "clicker_updateStats" )) then
				timer.Adjust( "ClickerStatUpdate", GetConVarNumber( "clicker_updateStats" )-1, 0, function() updateStats() end)
				initStatTime = GetConVarNumber( "clicker_updateStats" )
			end
		end
		mainStatsForm:SetName("Main Statistics - Updates in "..statTime.." Seconds!")
	end)

	-------------------
	--- High Scores ---
	-------------------

	hsTime = clickerSettings.updateHighScoresTime
	local highScoreForm = vgui.Create("DForm", statsPart)
	highScoreForm:SetName("High Scores - Updates in "..hsTime.." Seconds!")
	highScoreForm.Paint = function(s, w, h)
		surface.SetDrawColor( clickerSettings.secondaryColor )
		surface.DrawRect( 0, 0, w, h )
		surface.SetDrawColor( clickerSettings.settingsHeaderColor )
		surface.DrawRect( 0, 0, w, 20 )
	end
	function highScoreForm:CustomText( strLabel )
		local left = vgui.Create( "DLabel", self )
		left:SetText( strLabel )
		left:SetDark( true )
		self:AddItem( left )
		return left
	end

	HMCLabel = highScoreForm:CustomText("Highest "..clickerSettings.melonName.." Count: UNKNOWN ( NONE )")
	MMCLabel = highScoreForm:CustomText("Highest Amount of "..clickerSettings.melonName.." Clicks: UNKNOWN ( NONE )")
	MPSLabel = highScoreForm:CustomText("Fastest "..clickerSettings.melonName.." Production: UNKNOWN ( NONE )")
	MPPLabel = highScoreForm:CustomText("Most Points from "..clickerSettings.melonPlural..": UNKNOWN ( NONE )")
	statsPart:AddItem(highScoreForm)

	function Clicker_UpdateHighScores()
		local HSTable = LocalPlayer():Clicker_GetHighScoreValue()
		HMCLabel:SetText("Highest "..clickerSettings.melonName.." Count: "..HSTable["HMC"][1]["name"].." ( "..CommaValue(HSTable["HMC"][1]["value"]).. " "..clickerSettings.melonPlural.."! )")
		MMCLabel:SetText("Highest Amount of "..clickerSettings.melonName.." Clicks: "..HSTable["MMC"][1]["name"].." ( "..CommaValue(HSTable["MMC"][1]["value"]).. " Clicks! )")
		MPSLabel:SetText("Fastest "..clickerSettings.melonName.." Production: "..HSTable["MPS"][1]["name"].." ( "..CommaValue(HSTable["MPS"][1]["value"]).. " "..clickerSettings.melonSingle.."PS! )")
		MPPLabel:SetText("Most Points from "..clickerSettings.melonPlural..": "..HSTable["MPP"][1]["name"].." ( "..CommaValue(HSTable["MPP"][1]["value"]).. " Points! )")
		if GetConVar( "clicker_highScoreNotify" ):GetBool() then
			LocalPlayer():Clicker_Notify("The high scores has been updated!")
		end
	end
	timer.Create( "ClickerHighScoresUpdate", clickerSettings.updateHighScoresTime, 0, function() Clicker_UpdateHighScores() end)
	timer.Create( "ClickerHighScoresUpdateLabel", 1, 0, function()
		hsTime = hsTime - 1
		if hsTime == 0 then
			hsTime =clickerSettings.updateHighScoresTime-1
		end
		highScoreForm:SetName("High Scores - Updates in "..hsTime.." Seconds!")
	end)
-----------------------------------------
--- Items Bit ---------------------------
-----------------------------------------

	local storeScrollSheet = vgui.Create( "DScrollPanel" )
	storeScrollSheet:SetSize( widthPortion*2-35, heightPortion-40)
	storeScrollSheet:SetPos( 10, 8 )
	storeScrollSheet.VBar.Paint = settingsPart.VBar.Paint
	storeScrollSheet.VBar.btnUp.Paint = settingsPart.VBar.btnUp.Paint
	storeScrollSheet.VBar.btnDown.Paint = settingsPart.VBar.btnDown.Paint
	storeScrollSheet.VBar.btnGrip.Paint = settingsPart.VBar.btnGrip.Paint

	local storeList   = vgui.Create( "DIconLayout", storeScrollSheet )--
	storeList:SetSize(storeScrollSheet:GetWide(), storeScrollSheet:GetTall())
	storeList:SetPos( 0, 8 )
	storeList:SetSpaceY( 5 )
	storeList:SetSpaceX( 5 )

	LocalPlayer():Clicker_Notify("Loading is successfull!")
	table.SortByMember(clickerItemList, "Cost", function(a, b) return a > b end)
	clickerSettings.secretAllowPurchase = true
	local itemList = {}
	for k, itemData in pairs(clickerItemList) do
		local listItem = storeList:Add( "clickerItem" )
		listItem:SetSize( (storeList:GetWide()/2)-10, 100 )
		listItem:SetData(itemData)
		table.insert(itemList, listItem)
	end

clickerPSheet:AddSheet( "Store", storeScrollSheet, "icon16/money.png", false, false, "A wide variety of items that help increase your melon production!" )
clickerPSheet:AddSheet( "Settings and Statistics", settingsSheet, "icon16/wrench.png", false, false, "A bunch of settings and statistics todo with your melon production!" )
for k, v in pairs(clickerPSheet.Items) do
  if (!v.Tab) then continue end
    v.Tab.Paint = function(self,w,h)
      if v.Tab == clickerPSheet:GetActiveTab() then
        draw.RoundedBox(0, 0, 0, w, h, Color(18, 155, 235, 255))
      else
        draw.RoundedBox(0, 0, 0, w, h, Color(25, 25, 25, 255))
      end
  end
end

-----------------------------------------
--- Think Hook --------------------------
-----------------------------------------
timer.Simple(2, function() updateStats() end)
local keyPressed = false
clickerSettings.secretRealCurrentClickerVisible = false
concommand.Add( "+ClickerMenu", function() clickerFrame:SetVisible(true) end )
concommand.Add( "-ClickerMenu", function() clickerFrame:SetVisible(false) end )
hook.Add("Think", "detectMenuOpen", function()
	local openKey = GetConVarNumber("clicker_openKeyBind")
	if (clickerSettings.secretForceOpen) or (input.IsKeyDown( KEY_F5 ) and openKey == 5) or (input.IsKeyDown( KEY_F6 ) and openKey == 6) or (input.IsKeyDown( KEY_F7 ) and openKey == 7) or  (input.IsKeyDown( KEY_F8 ) and openKey == 8) or (input.IsKeyDown( KEY_F9 ) and openKey == 9) or  (input.IsKeyDown( KEY_F10 ) and openKey == 10) or  (input.IsKeyDown( KEY_F11 ) and openKey == 11) or  (input.IsKeyDown( KEY_F5 ) and openKey == 12) then
		if keyPressed then
			return
		end
		if not currentVisible then
			RunConsoleCommand("+ClickerMenu")
			clickerSettings.secretRealCurrentClickerVisible = true
		else
			RunConsoleCommand("-ClickerMenu")
			clickerSettings.secretRealCurrentClickerVisible = false
		end
		currentVisible = not currentVisible
		keyPressed = true
		clickerSettings.secretForceOpen = false
	else
		keyPressed = false
	end
	if not clickerSettings.secretAllowPurchase then
		timer.Simple(0.5, function()
			clickerSettings.secretAllowPurchase = true
		end)
	end
	if clickerSettings.resetItems and not( clickerSettings.secretTotalAmountOwned == 0) then
		for k,v in pairs(itemList) do
			v:Reset()
		end
		clickerSettings.resetItems = false
	end
	if clickerSettings.secretLoadHS then
		Clicker_UpdateHighScores()
		clickerSettings.secretLoadHS = false
	end
end)