-- Buggy Racer
-- By JetBoom

_EntPrecacheModel("models/buggy.mdl")

function LoadTopTimes()
if _file.Exists("noxiousprofiles/".._GetCurrentMap().."_toptimes.lua") then
	_RunString(_file.Read("noxiousprofiles/".._GetCurrentMap().."_toptimes.lua"))
else
_file.Write("noxiousprofiles/".._GetCurrentMap().."_toptimes.lua", [[TopTimes = {} 
TopTimes[1] = 6000 
TopTimes[2] = 6000 
TopTimes[3] = 6000 
TopNames = {} 
TopNames[1] = "None" 
TopNames[2] = "None" 
TopNames[3] = "None" 
]])
_RunString(_file.Read("noxiousprofiles/".._GetCurrentMap().."_toptimes.lua"))
	end
end
LoadTopTimes()

function SaveTopTimes()
local str = [[TopTimes = {}
TopTimes[1] = ]]..TopTimes[1]..[[ 
TopTimes[2] = ]]..TopTimes[2]..[[ 
TopTimes[3] = ]]..TopTimes[3]..[[ 
TopNames = {} 
TopNames[1] = "]]..TopNames[1]..[[" 
TopNames[2] = "]]..TopNames[2]..[[" 
TopNames[3] = "]]..TopNames[3]..[[" 
]]
_file.Delete("noxiousprofiles/".._GetCurrentMap().."_toptimes.lua")
_file.Write("noxiousprofiles/".._GetCurrentMap().."_toptimes.lua", str)
end

function UpdateTopTimes(userid)
	_GModText_Start("Default")
	 _GModText_SetColor(255, 255, 255, 255)
	 _GModText_SetTime(99999, 0, 0)
	 _GModText_SetPos(0.75, 0.2)
	 _GModText_SetText("Best Lap Times - ".._GetCurrentMap())
	_GModText_Send(userid, 9076)
	_GModText_Start("Default")
	 _GModText_SetColor(255, 255, 255, 255)
	 _GModText_SetTime(99999, 0, 0)
	 _GModText_SetPos(0.75, 0.22)
	 _GModText_SetText("#1 "..TopNames[1].." - "..ToMinutesSecondsMilliseconds(TopTimes[1]))
	_GModText_Send(userid, 9077)
	_GModText_Start("Default")
	 _GModText_SetColor(255, 255, 255, 255)
	 _GModText_SetTime(99999, 0, 0)
	 _GModText_SetPos(0.75, 0.24)
	 _GModText_SetText("#2 "..TopNames[2].." - "..ToMinutesSecondsMilliseconds(TopTimes[2]))
	_GModText_Send(userid, 9078)
	_GModText_Start("Default")
	 _GModText_SetColor(255, 255, 255, 255)
	 _GModText_SetTime(99999, 0, 0)
	 _GModText_SetPos(0.75, 0.26)
	 _GModText_SetText("#3 "..TopNames[3].." - "..ToMinutesSecondsMilliseconds(TopTimes[3]))
	_GModText_Send(userid, 9079)
end

MAXLAPS = 2
MAXRACETIME = 7.5 -- In minutes before all racers are DQed
MAXNUMRACERS = 5 -- At one time
USEBATTERY = false
BATTERYRATE = 1.3 -- Higher = More battery loss.
MAXBATTERY = 145.0 -- Changing this will make the Battery bar look weird.
RACEMUSIC = false -- More annoying
RACEMUSIC2 = false -- Less annoying                                 - Combine to make ultra annoying.
CARTRAILS = false -- Effect to draw blur trails on cars moving fast enough. Disable this if it lags too much.
BETDEADLINE = 90 -- Seconds before betting is disabled when a race starts. Set to 0 to pretty much disable betting.
--------------------------------------------------------------
MaxCheckPoint = 3

_ServerCommand("gm_sv_allowspawning 0\n")
_ServerCommand("gm_sv_allownpc 0\n")
_ServerCommand("gm_sv_allweapons 0\n")
_ServerCommand("gm_sv_teamplay 1\n")
_ServerCommand("gm_sv_allowmultigun 0\n")
_ServerCommand("gm_sv_allowphysgun 0\n")
_ServerCommand("gm_sv_teamdamage 0\n")
_ServerCommand("gm_sv_playerdamage 1\n")
_ServerCommand("gm_sv_setrules\n")

airboats = false
UpdateHUDTimer = -1
SaveTimer = 0
players = {}
for i=1, _MaxPlayers() do
	players[i] = {}
	players[i].Vehicle = 0
	players[i].Checkpoint = 0
	players[i].Battery = MAXBATTERY
	players[i].Bet = 0
	players[i].BetOn = 0
	players[i].LapTime = 9999
	players[i].LastPos=vector3(-5000,-5000,5000)
	if _PlayerInfo(i, "connected") then
		_PlayerRemoveAllWeapons(i)
		eventPlayerActive(_PlayerInfo(i, "name"), i, _PlayerInfo(i, "networkid"))
		_PlayerChangeTeam(i, TEAM_RED)
		_PlayerKill(i)
	end
end

RacerQueue = {}
Racing = false
LastRace = -BETDEADLINE
PreRaceTimer = -1
RaceTimer = 0
CountDownTime = 10
StartVector = vector3(0, 0, 0)
NumOfRacers = 0

Tick = 0

function gamerulesThink()
	if not Racing then
		if table.getn(RacerQueue) >= 2 and PreRaceTimer < 0 then
			PreRaceTimer = AddTimer(1, CountDownTime+1, CountDownTimer)
		end
	end
end

--[[
function GetStartVector(sender, args)
	if IsJetHeadAdmin then
		StartVector = _PlayerGetShootAng(sender)
	end
end
CONCOMMAND("startvector", GetStartVector)
]]

function RaceMusic()
	if RACEMUSIC and Racing then
		if _CurTime() > LastRace+6 then
			_PlaySound("racing12.mp3")
		else
			_PlaySound("racing11.mp3")
		end
	end
end

function RaceMusic2()
	if RACEMUSIC2 and Racing then
		_PlaySound("racing13.mp3")
	end
end

function UpdateHUD()
	if USEBATTERY then
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "connected") and _PlayerInfo(i, "team") == TEAM_BLUE then
			if not IsInRadius(_EntGetPos(players[i].Vehicle), players[i].LastPos, 64) then
				players[i].Battery = players[i].Battery-BATTERYRATE
				if players[i].Battery >= 24 and players[i].Battery <= 26 then
 				_GModText_Start("ImpactMassive")
				 _GModText_SetColor(255, 0, 0, 255)
				 _GModText_SetTime(2, 0, 1)
				 _GModText_SetPos(-1, 0.3)
				 _GModText_SetText("Low batteries!\nVisit a pit stop!")
				_GModText_Send( i, 102 )
				end
			end
			_GModRect_Start("gmod/white")
		 	 _GModRect_SetPos(0.41, 0.91, (players[i].Battery * 0.001)*1.28, 0.07)
		 	 if(players[i].Battery > 25) then
				 _GModRect_SetColor(225, 225, 225, 201)
			 else
	 			 _GModRect_SetColor(255, 0, 0, 201)
			 end
			 _GModRect_SetTime(9999, 0, 0)
			_GModRect_Send(i, 5109)
			players[i].LastPos = _EntGetPos(players[i].Vehicle)
			if players[i].Battery<=0 then
			_EntFire(players[i].Vehicle, "TurnOff", "", 0)
			--[[
			_GModText_Start("ImpactMassive")
			 _GModText_SetColor(255, 0, 0, 255)
			 _GModText_SetTime(4, 0, 1)
			 _GModText_SetPos(-1, 0.3)
			 _GModText_SetText("Out of Batteries!\nVisit the pit stop next time!")
			_GModText_Send( i, 102 )
			]]
			end
		end
	end
	end
end

function gamerulesStartMap()
	_TeamSetName(TEAM_RED, "The Mistempered Crowd")
	_TeamSetName(TEAM_BLUE, "Racers")
	_TeamSetName(TEAM_GREEN, "Pit Crew")
	_TeamSetName(TEAM_YELLOW, "Stupid Faggots")
	if string.find(_GetCurrentMap(), "br_air_") ~= nil then
		airboats = true
	end
	UpdateHUDTimer = AddTimer(1, 0, UpdateHUD)
	SetMaxPoints()
	AddTimer(6.05, 0, RaceMusic)
	AddTimer(12.41, 0, RaceMusic2)
	AddTimer(60, 0, BookieRegenerate)
end

function SetMaxPoints()
	if _file.Exists("noxiousprofiles/".._GetCurrentMap()..".lua") then
		_RunString(_file.Read("noxiousprofiles/".._GetCurrentMap()..".lua"))
	else
		MaxCheckPoint = 2
		USEBATTERY=false
	end
end

function CountDownTimer()
	if table.getn(RacerQueue) < 2 then
		HaltTimer(PreRaceTimer)
		PreRaceTimer = -1
		CountDownTime = 10
		return
	end
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i,"connected") then
			if CountDownTime > 0 then
				_GModText_Start("ImpactMassive")
				 _GModText_SetColor(255, 255, 255, 255)
				 _GModText_SetTime(2, 0, 1)
				 _GModText_SetPos(-1, 0.4)
				 if IsGoingToRace(i) then
					 _GModText_SetText("You are racing in:\n"..CountDownTime)
				 else
		 			 _GModText_SetText("Spectating Race in:\n"..CountDownTime)
				 end
				_GModText_Send(i, 910)
			end
		end
	end
	_PlaySound("hl1/fvox/bell.wav")
	if CountDownTime < 1 and not Racing then
		for i=1, 4000 do
			if string.find(_EntGetType(i), "vehicle") ~= nil then
				_EntRemove(i)
			end
		end
		StartRace()
		_GModText_Start("ImpactMassive")
		 _GModText_SetColor(255, 255, 255, 255)
		 _GModText_SetTime(2, 0, 1)
		 _GModText_SetPos(-1, 0.4)
		 _GModText_SetText("Go!")
		_GModText_Send(0, 910)
	else
		CountDownTime = CountDownTime-1
		if CountDownTime == 5 then _PlaySound("racing11.mp3") end
	end
end

function StartRace()
	Racing = true
	LastRace = _CurTime()
	if MAXRACETIME > 0 then
		RaceTimer = AddTimer(MAXRACETIME*60, 1, FinishRace, 0)
	end
	for i=1, MAXNUMRACERS do
		if _PlayerInfo(RacerQueue[1], "connected") then
			_PlayerChangeTeam(RacerQueue[1], TEAM_BLUE)
			_PlayerRespawn(RacerQueue[1])
			players[RacerQueue[1]].LapTime = _CurTime()
			table.remove(RacerQueue, 1)
		end
	end
	HaltTimer(PreRaceTimer)
	PreRaceTimer = -1
	NumOfRacers = _TeamNumPlayers(TEAM_BLUE)
	onShowTeam(0)
end

function IsGoingToRace(userid)
	for i=1, table.getn(RacerQueue) do
		if i > MAXNUMRACERS then return false end
		if RacerQueue[i] == userid then
			return true
		end
	end
	return false
end

function InQueue(userid)
	for i=1, table.getn(RacerQueue) do
		if RacerQueue[i] == userid then
			return true
		end
	end
	return false
end

function HitPit(Activator, Caller, NewCP)
	if _PlayerInfo(Activator, "team") == TEAM_BLUE then
		players[Activator].Battery = MAXBATTERY
		_EntFire(players[Activator].Vehicle, "TurnOn", "", 0)
	end
end

function DrawLaps(userid)
	_GModText_Start("Default")
	 _GModText_SetColor(255, 255, 255, 255)
	 _GModText_SetTime(99999, 0, 0)
	 _GModText_SetPos(-1, 0.05)
	 _GModText_SetText("Lap: "..(_PlayerInfo(userid, "kills")+1).."/"..MAXLAPS)
	_GModText_Send( userid, 888 )
end

function HideLaps(userid)
	_GModText_Hide(userid, 888)
end

function HitCheckpoint(Activator, Caller, NewCP)
	local iPlayer = Activator
	if not IsPlayer(iPlayer) then return end
	if _PlayerInfo(iPlayer, "team") ~= TEAM_BLUE then return end
	local LastCP = players[iPlayer].Checkpoint
	if LastCP+1 ~= NewCP and LastCP ~= NewCP and NewCP ~= 0 then
		_GModText_Start("ImpactMassive")
		 _GModText_SetColor(255, 0, 0, 255)
		 _GModText_SetTime(3, 0, 1)
		 _GModText_SetPos(-1, 0.3)
		 _GModText_SetText("YOU MISSED A CHECKPOINT OR OBSTICLE!")
		_GModText_Send( iPlayer, 102 )
		return
	elseif LastCP == NewCP-1 then
		players[iPlayer].Checkpoint = NewCP
		_GModText_Start("Default")
		 _GModText_SetColor(255, 0, 0, 255)
		 _GModText_SetTime(3, 0, 1)
		 _GModText_SetPos(-1, 0.1)
		 _GModText_SetText("Checkpoint!")
		_GModText_Send( iPlayer, 102 )
	end

	if NewCP == 0 and LastCP == MaxCheckPoint then
		DrawLaps(iPlayer)
		players[iPlayer].Checkpoint = NewCP
		_PlayerAddScore(iPlayer, 1)
		CheckFinishRace(iPlayer)
		_GModText_Start("Default")
		 _GModText_SetColor(255, 0, 0, 255)
		 _GModText_SetTime(3, 0, 1)
		 _GModText_SetPos(-1, 0.1)
		 _GModText_SetText("Lap!")
		_GModText_Send(iPlayer, 102)
		local tim = _CurTime()-players[iPlayer].LapTime
		if TopTimes[1] > tim then
			TopTimes[3] = TopTimes[2]
			TopNames[3] = TopNames[2]
			TopTimes[2] = TopTimes[1]
			TopNames[2] = TopNames[1]
			TopTimes[1] = tim
			TopNames[1] = _PlayerInfo(iPlayer, "name")
			UpdateTopTimes(0)
			_PrintMessageAll(3, _PlayerInfo(iPlayer, "name").." has set a new track record!")
			_PlaySound("racing12.mp3")
			SaveTopTimes()
		elseif TopTimes[2] > tim then
			TopTimes[3] = TopTimes[2]
			TopNames[3] = TopNames[2]
			TopTimes[2] = tim
			TopNames[2] = _PlayerInfo(iPlayer, "name")
			UpdateTopTimes(0)
			SaveTopTimes()
		elseif TopTimes[3] > tim then
			TopTimes[3] = tim
			TopNames[3] = _PlayerInfo(iPlayer, "name")
			UpdateTopTimes(0)
			SaveTopTimes()
		end
		players[iPlayer].LapTime = _CurTime()
		_GModText_Start("Default")
		 _GModText_SetColor(255, 15, 15, 255)
		 _GModText_SetTime(5, 1, 1)
		 _GModText_SetPos(-1, 0.75)
		 _GModText_SetText(ToMinutesSecondsMilliseconds(tim))
		_GModText_Send( iPlayer, 1502 )
	end
end

function CheckFinishRace(userid)
	if _PlayerInfo(userid, "kills") >= MAXLAPS then
		FinishRace(userid)
	elseif _PlayerInfo(userid, "kills") == MAXLAPS-1 then
		_PrintMessageAll(3, _PlayerInfo(userid, "name").." is on their last lap!")
		_PrintMessageAll(2, _PlayerInfo(userid, "name").." is on their last lap!")
	end
end

function IsInRadius(a, b, dist)
	return math.abs(vecLength(vecSub(a,b))) <= dist
end

function DoBet(sender, args)
	if string.len(args) < 5 then return end
	args = string.gsub(args, " all ", " "..players[sender].money.." ")
	args = string.gsub(args, " everything ", " "..players[sender].money.." ")
	if players[sender].BetOn > 0 then _PrintMessage(sender, 3, "All bets are final.") _PrintMessage(sender, 2, "All bets are final.\n") return end
	if not Racing then _PrintMessage(sender, 3, "You can't bet on a non-existant race.") _PrintMessage(sender, 2, "You can't bet on a non-existant race.\n") return end
	if _CurTime() > LastRace+BETDEADLINE then _PrintMessage(sender, 3, "It's too late to make any bets on this race") _PrintMessage(sender, 2, "It's too late to make any bets on this race\n") return end
	local on, name = string.find(args, " on ")
	if on == nil or name == nil then _PrintMessage(sender, 3, "Syntax - I bet # on <name>") _PrintMessage(sender, 2, "Syntax - I bet # on <name>\n") return end
	local money = tonumber(string.sub(args, 1, on-1))
	if money == nil then _PrintMessage(sender, 3, "Syntax - I bet # on <name>") _PrintMessage(sender, 2, "Syntax - I bet # on <name>\n") return end
	local userid = 0
	for i=1, _MaxPlayers() do
		if players[i].Vehicle > 0 then
			if string.find(string.lower(_PlayerInfo(i,"name")), string.lower(string.sub(args, name+1))) ~= nil then
				userid = i
				break
			end
		end
	end

	if money < 10 then _PrintMessage(sender, 3, "You can't bet such a paltry amount of money.") _PrintMessage(sender, 2, "You can't bet such a paltry amount of money.\n") return end
	if money > 5000 then _PrintMessage(sender, 3, "You can only bet $5,000 at a time!") _PrintMessage(sender, 2, "You can only bet $5,000 at a time!") return end
	if money > players[sender].money then _PrintMessage(sender, 3, "You don't have that much money.") _PrintMessage(sender, 2, "You don't have that much money.\n") return end
	if money > tonumber(_file.Read("noxiousprofiles/brbookie.txt")) then _PrintMessage(sender, 3, "The bookie doesn't have that much money.") _PrintMessage(sender, 2, "The bookie doesn't have that much money.\n") return end
	if _PlayerInfo(userid, "team") ~= TEAM_BLUE then _PrintMessage(sender, 3, "You can't bet on someone who isn't racing.") _PrintMessage(sender, 2, "You can't bet on someone who isn't racing.\n") return end
	if _PlayerInfo(sender, "team") == TEAM_BLUE then _PrintMessage(sender, 3, "You can't bet while racing.") _PrintMessage(sender, 2, "You can't bet while racing.\n") return end
	money = math.floor(money)
	players[sender].money = players[sender].money-money
	_file.Write("noxiousprofiles/brbookie.txt", tonumber(_file.Read("noxiousprofiles/brbookie.txt"))-money)
	NDB.drawMoneyAmmount(sender)
	_PrintMessage(sender, 3, "You bet $"..money.." on ".._PlayerInfo(userid,"name").." to win.")
	_PrintMessage(sender, 2, "You bet $"..money.." on ".._PlayerInfo(userid,"name").." to win.\n")
	players[sender].Bet = money
	players[sender].BetOn = userid
end

function FinishRace(winner)
	local winnings = NumOfRacers*200
	if IsPlayer(winner) then
		if players[winner].GoldMember then
			winnings = winnings*1.25
		end
	end
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "connected") then
			if players[i].BetOn > 0 then
				if winner == players[i].BetOn then
					players[i].money = players[i].money+(players[i].Bet*2)
					_PrintMessage(i, 3, (players[i].Bet*2).." has been deposited to you for winning the bet.")
					_PrintMessage(i, 2, (players[i].Bet*2).." has been deposited to you for winning the bet.\n")
					drawMoneyAmmount(i)
					_PlaySoundPlayer(i, "ambient/levels/labs/coinslot1.wav")
					_EntEmitSound(i, "ambient/levels/labs/coinslot1.wav")
				else
					_PrintMessage(i, 3, "You have lost the money wagered in the bet.")
					_PrintMessage(i, 2, "You have lost the money wagered in the bet.\n")
					_file.Write("noxiousprofiles/brbookie.txt", tonumber(_file.Read("noxiousprofiles/brbookie.txt"))+(players[i].Bet*2))
					local mm = math.random(1, 2)
					if mm < 2 then _EntEmitSound(i, "vo/npc/barney/ba_ohshit03.wav") else _EntEmitSound(i, "vo/citadel/br_ohshit.wav") end
				end
				players[i].BetOn = 0
				players[i].Bet = 0
			end
		end
	end
	_GModText_Start("ImpactMassive")
	 _GModText_SetColor(255, 0, 0, 255)
	 _GModText_SetTime(6, 0, 1)
	 _GModText_SetPos(-1, 0.7)
	 if winner > 0 then
		_GModText_SetText(_PlayerInfo(winner, "name").." has won $"..winnings.."!!")
	 else
		_GModText_SetText("YOU GET NOTHING! YOU LOSE!\nGOOD DAY SIR!!")
		_PlaySound("youlose2.wav")
	 end
	 _GModText_Send(0, 911)
	 _GModRect_Start( "gmod/white" )
	 _GModRect_SetPos( 0, 0, 1, 1 )
	 _GModRect_SetColor( 255, 255, 255, 255 )
	 _GModRect_SetTime( 1, 0.1, 0.5 )
	_GModRect_Send( 0, 22 )
	 if winner > 0 then players[winner].money = players[winner].money+winnings NDB.drawMoneyAmmount(winner) end
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "connected") then
			if _PlayerInfo(i, "team") == TEAM_BLUE then
				_TraceAttack(i, i, i, 1001)
				for x=1, table.getn(RacerQueue) do
					if RacerQueue[x] == i then
						table.remove(RacerQueue, x)
						break
					end
				end
			end
		end
	end
	HaltTimer(RaceTimer)
	SetNotRacing()
	PreRaceTimer = -1
	CountDownTime = 10
	NumOfRacers = 0
	GlobalSave()
end

function CheckHaltRace()
	if Racing then
		if _TeamNumPlayers(TEAM_BLUE) < 1 then
			FinishRace(0)
		end
	end
end
AddTimer(1, 0, CheckHaltRace)

function SetNotRacing()
	Racing = false
end

function PickDefaultSpawnTeam(userid)
	_PlayerChangeTeam(userid, TEAM_RED)
	return true
end

function BookieRegenerate()
	_file.Write("noxiousprofiles/brbookie.txt", tonumber(_file.Read("noxiousprofiles/brbookie.txt"))+100)
end

function onTakeDamage(ent, inflictor, attacker, damage)
	if IsPlayer(ent) then
		if damage >= _PlayerInfo(ent, "health")+30 then
			Gib(ent)
		end
	end
end

TorsoModels = {}
TorsoModels[1] = "models/Zombie/Classic_torso.mdl"
TorsoModels[2] = "models/Humans/Charple03.mdl"
_EntPrecacheModel("models/Zombie/Classic_torso.mdl")
_EntPrecacheModel("models/Humans/Charple03.mdl")

LegModels = {}
LegModels[1] = "models/Zombie/Classic_legs.mdl"
LegModels[2] = "models/Gibs/Fast_Zombie_Legs.mdl"
_EntPrecacheModel("models/Zombie/Classic_legs.mdl")
_EntPrecacheModel("models/Gibs/Fast_Zombie_Legs.mdl")

GibModels = {}
GibModels[1]="models/Gibs/Antlion_gib_medium_1.mdl"
GibModels[2]="models/Gibs/Antlion_gib_small_1.mdl"
GibModels[3]="models/Gibs/Antlion_gib_medium_2.mdl"
GibModels[4]="models/Gibs/Antlion_gib_medium_3.mdl"
GibModels[5]="models/Gibs/Antlion_gib_small_1.mdl"
GibModels[6]="models/Gibs/Antlion_gib_small_2.mdl"

_EntPrecacheModel("models/Gibs/Antlion_gib_medium_1.mdl")
_EntPrecacheModel("models/Gibs/Antlion_gib_small_1.mdl")
_EntPrecacheModel("models/Gibs/Antlion_gib_medium_2.mdl")
_EntPrecacheModel("models/Gibs/Antlion_gib_medium_3.mdl")
_EntPrecacheModel("models/Gibs/Antlion_gib_small_1.mdl")
_EntPrecacheModel("models/Gibs/Antlion_gib_small_2.mdl")
_EntPrecacheModel("models/gibs/HGIBS.mdl")
_EntPrecacheModel("models/gibs/HGIBS_rib.mdl")
_EntPrecacheModel("models/gibs/HGIBS_rib.mdl")
_EntPrecacheModel("models/gibs/HGIBS_rib.mdl")
_EntPrecacheModel("models/gibs/HGIBS_scapula.mdl")
_EntPrecacheModel("models/gibs/HGIBS_spine.mdl")

Gibbed = {}
for i=1, _MaxPlayers() do
	Gibbed[i] = false
end

function Gib(killed)
	if Gibbed[killed] then return end
	Gibbed[killed] = true
	_TraceLine(_EntGetPos(killed), vector3(0,0,-1), 100, killed)
	if _TraceHit() then
		_MakeDecal(math.random(46,51))
	end
	local velocity = vecLength(_EntGetVelocity(killed)) + 30
	Gibbed[killed] = true
	local ent = _EntCreate("env_shooter")
	if ent > 0 then
		_EntSetPos(ent, _EntGetPos(killed))
		_EntSetKeyValue(ent, "m_iGibs", "1")
		_EntSetKeyValue(ent, "m_flVelocity", velocity)
		_EntSetKeyValue(ent, "shootmodel", LegModels[math.random(1,2)])
		_EntSetKeyValue(ent, "m_flVariance", "5.0")
		_EntSetKeyValue(ent, "simulation", "2")
		_EntSpawn(ent)
		_EntFire(ent, "shoot", "", 0)
		_EntFire(ent, "kill", "", 1)
	end
	local ent = _EntCreate("env_shooter")
	if ent > 0 then
		_EntSetPos(ent, _EntGetPos(killed))
		_EntSetKeyValue(ent, "m_iGibs", "1")
		_EntSetKeyValue(ent, "m_flVelocity", velocity)
		_EntSetKeyValue(ent, "shootmodel", TorsoModels[math.random(1,2)])
		_EntSetKeyValue(ent, "m_flVariance", "5.0")
		_EntSetKeyValue(ent, "simulation", "2")
		_EntSpawn(ent)
		_EntFire(ent, "shoot", "", 0)
		_EntFire(ent, "kill", "", 1)
	end
	_EffectInit()
	_EffectSetOrigin(_EntGetPos(killed))
	_EffectSetScale(8)
	_EffectSetFlags(9)
	_EffectDispatch("bloodspray")
	_EffectDispatch("bloodspray")
	_EffectDispatch("bloodspray")
	local gibstospawn = {}
	for i=1, 3 do
		 gibstospawn[table.getn(gibstospawn)+1] = GibModels[math.random(1, table.getn(GibModels))]
	end
	for i in gibstospawn do
		local gib = _EntCreate("prop_physics")
		if gib > 0 then
			_EntSetModel(gib, gibstospawn[i])
			_EntSetKeyValue(gib, "spawnflags", "4")
			_EntSetPos(gib, vecAdd(_EntGetPos(killed), vector3(math.random(-10,10),math.random(-10,10),math.random(10,30))))
			_EntSetAngAngle(gib, vector3(math.random(0,359), math.random(0,359), math.random(0,359)))
			_EntSetKeyValue(gib, "physdamagescale", "1500")
			_EntSpawn(gib)
			_EntFire(gib, "AddOutput", "onhealthchanged GibHitWall,RunScript,,0,3", 0)
			_phys.ApplyForceCenter(gib, vecAdd(vecMul(_EntGetVelocity(killed), 12), vector3(math.random(-2000, 2000), math.random(-2000, 2000), math.random(0, 2000))))
			_phys.ApplyTorqueCenter(gib, vector3(math.random(-10500, 10500), math.random(-10500, 10500), math.random(-3000, 13000)))
			_EntFire(gib, "kill", "", 7.5)
			local trail = _EntCreate("env_smoketrail")
			if trail > 0 then
				_EntSetPos(trail, _EntGetPos(gib))
				_EntSetKeyValue(trail, "spawnrate", "22")
				_EntSetKeyValue(trail, "lifetime", "1.2")
				_EntSetKeyValue(trail, "startcolor", "255 0 0")
				_EntSetKeyValue(trail, "endcolor", "255 0 0")
				_EntSetKeyValue(trail, "minspeed", "0")
				_EntSetKeyValue(trail, "maxspeed", "0")
				_EntSetKeyValue(trail, "startsize", "6")
				_EntSetKeyValue(trail, "endsize", "9")
				_EntSetKeyValue(trail, "spawnradius", "2")
				_EntSetKeyValue(trail, "firesprite", "sprites/redglow3.spr")
				_EntSetKeyValue(trail, "smokesprite", "sprites/redglow3.spr")
				_EntSpawn(trail)
				_EntSetParent(trail, gib)
				_EntFire(trail, "kill", "", 4.0)
			end
		end
	end
	_EntEmitSoundEx(killed, "physics/flesh/flesh_bloody_break.wav", 1.0, 0.75)
	AddTimer(0.1, 1, _PlayerSilentKill, killed, 1.5, true)
end

function GibHitWall(hit, gib)
	_TraceLine(_EntGetPos(gib), vector3(0,0,-1), 32, gib)
	if _TraceHit() then
		_MakeDecal(math.random(46,51))
		_EffectInit()
		 _EffectSetOrigin(_EntGetPos(gib))
		 _EffectSetNormal(vector3(0,0,1))
		 _EffectSetScale(7)
		 _EffectSetFlags(9)
		_EffectDispatch("bloodspray")
		_EffectDispatch("bloodspray")
	end
	_TraceLine(_EntGetPos(gib), vector3(0,0,1), 32, gib)
	if _TraceHit() then
		_MakeDecal(math.random(46,51))
		_EffectInit()
		 _EffectSetOrigin(_EntGetPos(gib))
		 _EffectSetNormal(vector3(0,0,-1))
		 _EffectSetScale(7)
		 _EffectSetFlags(9)
		_EffectDispatch("bloodspray")
		_EffectDispatch("bloodspray")
	end
	_TraceLine(_EntGetPos(gib), vector3(1,0,0), 32, gib)
	if _TraceHit() then
		_MakeDecal(math.random(46,51))
		_EffectInit()
		 _EffectSetOrigin(_EntGetPos(gib))
		 _EffectSetNormal(vector3(-1,0,0))
		 _EffectSetScale(7)
		 _EffectSetFlags(9)
		_EffectDispatch("bloodspray")
		_EffectDispatch("bloodspray")
	end
	_TraceLine(_EntGetPos(gib), vector3(-1,0,0), 32, gib)
	if _TraceHit() then
		_MakeDecal(math.random(46,51))
		_EffectInit()
		 _EffectSetOrigin(_EntGetPos(gib))
		 _EffectSetNormal(vector3(1,0,0))
		 _EffectSetScale(7)
		 _EffectSetFlags(9)
		_EffectDispatch("bloodspray")
		_EffectDispatch("bloodspray")
	end
	_TraceLine(_EntGetPos(gib), vector3(0,1,0), 32, gib)
	if _TraceHit() then
		_MakeDecal(math.random(46,51))
		_EffectInit()
		 _EffectSetOrigin(_EntGetPos(gib))
		 _EffectSetNormal(vector3(0,-1,0))
		 _EffectSetScale(7)
		 _EffectSetFlags(9)
		_EffectDispatch("bloodspray")
		_EffectDispatch("bloodspray")
	end
	_TraceLine(_EntGetPos(gib), vector3(0,-1,0), 32, gib)
	if _TraceHit() then
		_MakeDecal(math.random(46,51))
		_EffectInit()
		 _EffectSetOrigin(_EntGetPos(gib))
		 _EffectSetNormal(vector3(0,1,0))
		 _EffectSetScale(7)
		 _EffectSetFlags(9)
		_EffectDispatch("bloodspray")
		_EffectDispatch("bloodspray")
	end
	_EntEmitSound(gib, "physics/flesh/flesh_bloody_impact_hard1.wav")
end
MakeFunction("GibHitWall")

function eventPlayerSpawn(userid)
	Gibbed[userid] = false
	players[userid].Checkpoint = 0
	players[userid].LapTime = _CurTime()
	players[userid].Battery = MAXBATTERY
	_GModText_Hide(userid, 1111, 0, 0)
	_GModText_Hide(userid, 5019, 0, 0)
	if _PlayerInfo(userid, "team") == TEAM_RED then
		_GModRect_Hide(userid, 5000, 0, 0)
		_GModRect_Hide(userid, 5109, 0, 0)
		HideLaps(userid)
		if not IsGoingToRace(userid) then
			_GModText_Start("Default")
			 _GModText_SetColor(255, 0, 0, 255)
			 _GModText_SetTime(9999, 0, 5)
			 _GModText_SetText("F2 = Enter Race Queue")
			 _GModText_SetPos(-1, 0.025)
			_GModText_Send( userid, 1111)
		end
		return
	end
	if not airboats then
		if _PlayerInfo(userid, "team") == TEAM_BLUE then
			_PlayerSetHealth(userid, 1000)
			players[userid].Battery = MAXBATTERY
			local ent = _EntCreate("prop_vehicle_jeep")
			if ent > 0 then
				_EntSetPos(ent, _EntGetPos(userid))
				PlayerMove(userid, vector3(0,0,72))
				if not absoluteangles then
					local angs = _PlayerGetShootAng(userid)
					_EntSetAng(ent, vector3(angs.y, angs.x, angs.z))
				else
					_EntSetAng(ent, absoluteangles)
				end
				_EntSetKeyValue(ent, "model", "models/buggy.mdl")
				_EntSetKeyValue(ent, "vehiclescript", "scripts/vehicles/buggyracer.txt")
				_EntSetKeyValue(ent, "solid", "6")
				_EntSpawn(ent)
				_EntFire(ent, "AddOutput", "PressedAttack !self,TurnOff,,0,-1", 0)
				_EntFire(ent, "AddOutput", "PressedAttack2 !self,TurnOff,,0,-1", 0)
				_EntFire(ent, "AddOutput", "PressedAttack !self,TurnOn,,5,-1", 0)
				_EntFire(ent, "AddOutput", "PressedAttack2 !self,TurnOn,,5,-1", 0)
				players[userid].Vehicle = ent
				_GModText_Start("BrandingSmall")
				 _GModText_SetColor(math.random(75, 255), math.random(75, 255), math.random(75, 255), 255)
				 _GModText_SetTime(9999, 0, 5)
				 _GModText_SetEntityOffset(vector3(-5, -5, 24 ))
				 _GModText_SetEntity(players[userid].Vehicle)
				 _GModText_SetText(_PlayerInfo(userid, "name"))
				_GModText_Send( 0, 750+userid)
				if players[userid].BRWheels == "fire" then
					local ang = _EntGetForwardVector(ent)
					local rightang = _EntGetRightVector(ent)
					local pos = _EntGetPos(ent)
					local fire = _EntCreate("env_fire_trail")
					if fire > 0 then
						_EntSetPos(fire, vecAdd(vecAdd(pos, vecMul(ang, -88)), vecMul(rightang, 45)))
						_EntSpawn(fire)
						_EntSetParent(fire, ent)
					end
					fire = _EntCreate("env_fire_trail")
					if fire > 0 then
						_EntSetPos(fire, vecAdd(vecAdd(pos, vecMul(ang, -88)), vecMul(rightang, -45)))
						_EntSpawn(fire)
						_EntSetParent(fire, ent)
					end
				end
				if USEBATTERY then
					_GModRect_Start("gmod/white")
					 _GModRect_SetPos(0.4, 0.9, 0.2, 0.1)
					 _GModRect_SetColor(0, 0, 0, 200)
					 _GModRect_SetTime(9999, 0, 0)
					_GModRect_Send(userid, 5000)
					_GModText_Start("Default")
					 _GModText_SetColor(255, 0, 0, 255)
					 _GModText_SetTime(9999, 0, 0)
					 _GModText_SetText("Battery")
					 _GModText_SetPos(-1, 0.88)
					_GModText_Send( userid, 5019)
				end
				DrawLaps(userid)
			end
		end
	else
		if _PlayerInfo(userid, "team") == TEAM_BLUE then
			_PlayerSetHealth(userid, 1000)
			players[userid].Battery = MAXBATTERY
			local ent = _EntCreate("prop_vehicle_airboat")
			if ent > 0 then
				_EntSetKeyValue(ent, "origin", vecString(_EntGetPos(userid)))
				local airangle = vecAdd(_PlayerGetShootAng(userid), vector3(0,-0.25,0))
				_EntSetKeyValue(ent, "angles", airangle.y.." "..airangle.x.." "..airangle.z)
				PlayerMove(userid, vector3(0,0,72))
				_EntSetKeyValue(ent, "model", "models/airboat.mdl")
				_EntSetKeyValue(ent, "vehiclescript", "scripts/vehicles/buggyracerairboat.txt")
				_EntSetKeyValue(ent, "solid", "6")
				_EntSpawn(ent)
				players[userid].Vehicle = ent
				_GModText_Start("BrandingSmall")
				 _GModText_SetColor(math.random(75, 255), math.random(75, 255), math.random(75, 255), 255)
				 _GModText_SetTime(9999, 0, 5)
				 _GModText_SetEntityOffset(vector3(-5, -5, 24 ))
				 _GModText_SetEntity(players[userid].Vehicle)
				 _GModText_SetText(_PlayerInfo(userid, "name"))
				_GModText_Send( 0, 750+userid)
				if USEBATTERY then
					_GModRect_Start("gmod/white")
					 _GModRect_SetPos(0.4, 0.9, 0.2, 0.1)
					 _GModRect_SetColor(0, 0, 0, 200)
					 _GModRect_SetTime(9999, 0, 0)
					_GModRect_Send(userid, 5000)
					_GModText_Start("Default")
					 _GModText_SetColor(255, 0, 0, 255)
					 _GModText_SetTime(9999, 0, 0)
					 _GModText_SetText("Battery")
					 _GModText_SetPos(-1, 0.88)
					_GModText_Send( userid, 5019)
				end
				DrawLaps(userid)
			end
		end
	end
end

function eventPlayerUseEntity(userid, entity)
	if IsVehicle(entity) then
		if players[userid].Vehicle == entity or _EntGetName(entity) == "spectatorvehicle" then
			return false
		end
		return true
	elseif _EntGetName(entity) == "moneybag" and IsInRadius(_PlayerGetShootPos(userid), _EntGetPos(entity), 110) then
		NDB.AddMoney(userid, 20, true)
		_PrintMessage(userid, 4, "^_^")
		_EntEmitSound(userid, "ambient/levels/labs/coinslot1.wav")
		_EntFire(entity, "kill", "", 0)
	end
	return false
end

function eventPlayerDisconnect(name, userid, address, steamid, reason)
	if not IsPlayerOnline(userid) then return end
	if players[userid].Vehicle ~= nil then
		if string.find(_EntGetType(players[userid].Vehicle), "vehicle") ~= nil then
			_EntRemove(players[userid].Vehicle)
			_GModText_Hide(0, 750+userid, 0, 0)
		end
	end
	for i=1, table.getn(RacerQueue) do
		if RacerQueue[i] == userid then
			table.remove(RacerQueue, i)
			onShowTeam(0)
		end
	end
	players[userid].Vehicle = 0
	players[userid].Battery = MAXBATTERY
	if players[userid].Bet > 0 then
		_file.Write("noxiousprofiles/brbookie.txt", tonumber(_file.Read("noxiousprofiles/brbookie.txt"))+(players[userid].Bet*2))
		players[userid].Bet = 0
	end
	players[userid].BetOn = 0
	players[userid].LapTime = 9999
end

function eventPlayerKilled(killed, attacker, weapon)
	local count = 0
	local play = 0
	HideLaps(killed)
	if _EntExists(players[killed].Vehicle) then	
		RemoveVehicle(players[killed].Vehicle)
		_PlayerChangeTeam(killed, TEAM_RED)
		_GModText_Hide(0, 750+killed, 0, 0)
	end
	players[killed].Vehicle = 0
	players[killed].Checkpoint = 0
	_PlayerSetScore(killed, 0)
end

function RemoveVehicle(ent)
	_EntFire(ent, "kill", "", 1.0)
end

function onShowSpare2(userid)
	_PrintMessage(userid, 4, "The betting bookie has $".._file.Read("noxiousprofiles/brbookie.txt")..".")
end

function onShowTeam(userid)
	if userid > 0 then
		if _PlayerInfo(userid,"team") ~= TEAM_RED or not _PlayerInfo(userid, "alive") then return end
		if not InQueue(userid) then
			table.insert(RacerQueue, userid)
		end
	end

	for x=1, _MaxPlayers() do
		if IsPlayerOnline(x) then
			for i=1, table.getn(RacerQueue) do
				if RacerQueue[i] == x then
					_GModText_Start("DefaultShadow")
					_GModText_SetTime(9999, 0, 0)
					_GModText_SetPos(-1, 0.025)
					if i <= MAXNUMRACERS then
						_GModText_SetColor(0, 255, 0, 255)
						_GModText_SetText("Slot in Queue: "..i.."/"..table.getn(RacerQueue).."\nYou will race next round")
					else
						_GModText_SetColor(255, 0, 0, 255)
						_GModText_SetText("Slot in Queue: "..i.."/"..table.getn(RacerQueue).."\nYou will NOT race next round")
					end
					_GModText_Send( x, 1111)
				end
			end
		end
	end
end

function onShowHelp(userid)
	_GModRect_Start("gmod/white")
	 _GModRect_SetPos(0.0, 0.14, 1.0, 0.35)
	 _GModRect_SetColor(0, 0, 0, 175)
	 _GModRect_SetTime(10, 0.2, 1)
	_GModRect_Send(userid, 49)
	_GModText_Start("Trebuchet24")
	 _GModText_SetPos(-1, 0.16)
	 _GModText_SetColor(255, 255, 255, 255)
	 _GModText_SetTime(10, 0.2, 1.25)
	 _GModText_SetText("Buggy Racer\n a gamemode by JetBoom")
	_GModText_Send(userid, 50)
	_GModText_Start("Default")
	 _GModText_SetPos(-1, 0.3)
	 _GModText_SetColor(90, 90, 255, 240)
	 _GModText_SetTime(10, 0.2, 1.25)
	 _GModText_SetText( "Press F2 to enter your name into the racer queue.\nRace will begin when current one is done." )
	_GModText_Send( userid, 51 )
	_GModText_Start("Default")
	 _GModText_SetPos(-1, 0.35)
	 _GModText_SetColor(90, 90, 255, 240)
	 _GModText_SetTime(10, 0.2, 1.25)
	 _GModText_SetText( "This gamemode uses modified racing jeeps.\n Press F4 to see how much money the betting bookie has.\nSay I bet # on <name> to bet.")
	_GModText_Send( userid, 52 )
end

function eventPlayerActive(name, userid, steamid)
	AddTimer(4.0, 1, onShowHelp, userid)
	for i=1, _MaxPlayers() do
		if players[i].Vehicle > 0 then
			_GModText_Start("BrandingSmall")
			 _GModText_SetColor(math.random(75, 255), math.random(75, 255), math.random(75, 255), 255)
			 _GModText_SetTime(9999, 0, 5)
			 _GModText_SetEntityOffset(vector3(-5, -5, 24 ))
			 _GModText_SetEntity(players[i].Vehicle)
			 _GModText_SetText(_PlayerInfo(i, "name"))
			_GModText_Send( userid, 750+i)
		end
	end
	UpdateTopTimes(userid)
end

function explode(str, seperator, limit)
	local t={}
	local lim=limit or -1
	local reps=0
	local ll=0

	while true do
		local l=string.find(str,seperator,ll+1,true)
		if l~=nil then
			table.insert(t,string.sub(str,ll,l-1))
			ll=l+1
			reps=reps+1
		else
			table.insert(t,string.sub(str,ll))
			reps=reps+1
			break
		end
        if (reps>=lim and lim~=-1) or reps > 4000 then
			table.insert(t,string.sub(str,ll))
			break
		end
	end
	return t
end

function onGravGunPunt(player, entity)
	if IsVehicle(entity) then
		return players[player].Vehicle == entity
	end
	return true
end

function IsVehicle(entity)
	return string.find(_EntGetType(entity), "vehicle") ~= nil
end

function GiveDefaultItems(userid)
	_PlayerGiveItem(userid, "weapon_physcannon")
end

function eventPlayerDuplicateProp(userid, propid)
	return not IsVehicle(propid)
end

function onPlayerRemove(player, entity)
	return not IsVehicle(entity)
end

function drawMoneyAmmount(userid)
	NDB.drawMoneyAmmount(userid)
end

function GlobalSave()
	NDB.GlobalSave()
	SaveTopTimes()
end

function GiveOut(num)
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "connected") then
			players[i].money = players[i].money + num
			drawMoneyAmmount(i)
		end
	end
end
