-- JB Ball
-- By JetBoom

_OpenScript("noxiouscore.lua")

-- Options: --
-- The display name for team blue
BLUENAME = "Blue Butt Baboons"
-- The display name for team red
REDNAME = "Red Rhino Reavers"
-- How many points a team must have to win the round
MAXTEAMSCORE = 14
-- Rounds before map change. Set to 0 for no change.
NUMROUNDS = 0
-- Seconds that any one player can hold the ball before it drops. Leave 0 to disable.
HOTPOTATOTIME = 4
-- This greatly changes gameplay. Ball with gravity seems to be more fun.
BALLGRAVITY = true
-- This makes it so if the ball goes near the ground, it floats upwards a little.
-- It makes for interesting gameplay.
GROUNDREPELBALL = true

-- Scoring

-- Bonus point(s) for when a person blocks the ball from going in their goal.
BLOCKBONUS = 2
-- Bonus point(s) for when a person scores for their team.
SCOREBONUS = 10
MONEYSCOREBONUS=250
-- Bonus point(s) for when a person knocks out an enenmy.
KILLBONUS = 1
MONEYKILLBONUS=30
-- Point(s) taken away when a person tries to score on their own team. You can't
-- actually score on your own team, but points can be deducted if you want.
SELFSCOREPENALTY = 0

--================================================================================--
-- Don't edit below this line. kk? =)
--================================================================================--

_ServerCommand("mp_falldamage 1\n")
jetpacks = {}
ball = 0
LastBallHitter = 0
redgoal = 0
bluegoal = 0
hotpotato = nil
currentround = 1
redwins = 0
bluewins = 0

LastDeath = {}
for i=1, _MaxPlayers() do
	LastDeath[i] = vector3(0,0,0)
end

function JetPack(userid)
	if _PlayerIsKeyDown(userid, IN_JUMP) and _PlayerInfo(userid, "alive") then
		local vAim = _PlayerGetShootAng(userid)
		if  vAim == nil then return end
			vAim.x = vAim.x * 7
			vAim.y = vAim.y * 7
			--vAim.z = 12
			vAim.z = vAim.z * 15
			if vAim.z < 10 then
				vAim.z = 10
			end
		_EntSetVelocity(userid, vecAdd(vecMul(vAim, TICKRATE), _EntGetVelocity(userid)))
		if _EntGetType(jetpacks[userid]) ~= "env_smoketrail" then
			local trail = _EntCreate("env_smoketrail")
			if trail > 0 then
				_EntSetPos(trail, _EntGetPos(userid))
				_EntSetKeyValue(trail, "spawnrate", "30")
				_EntSetKeyValue(trail, "lifetime", "2.0")
				_EntSetKeyValue(trail, "startcolor", TeamColor(_PlayerInfo(userid,"team")))
				_EntSetKeyValue(trail, "endcolor", TeamColor(_PlayerInfo(userid,"team")))
				_EntSetKeyValue(trail, "minspeed", "0")
				_EntSetKeyValue(trail, "maxspeed", "6")
				_EntSetKeyValue(trail, "startsize", "9")
				_EntSetKeyValue(trail, "endsize", "15")
				_EntSetKeyValue(trail, "spawnradius", "2")
				_EntSetKeyValue(trail, "firesprite", "sprites/redglow3.spr")
				_EntSetKeyValue(trail, "smokesprite", "sprites/redglow3.spr")
				_EntSpawn(trail)
				_EntSetParent(trail, userid)
			end
			jetpacks[userid] = trail
		end
	else
		if _EntGetType(jetpacks[userid]) == "env_smoketrail" then
			_EntRemove(jetpacks[userid])
			jetpacks[userid] = 0
		end
	end
end

function gamerulesThink()
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "alive") then
			JetPack(i)
		end
	end

	if GROUNDREPELBALL then
		if _EntGetType(ball) ~= "n/a" and ball > 0 then
			_TraceLine(_EntGetPos(ball), vector3(0,0,-90), 300, ball)
			if _TraceHitWorld() then
				_phys.ApplyForceCenter(ball, vector3(0,0,475*TICKRATE))
			end
		end
	end
	
	--[[
	if LastBallHitter > 0 and ball > 0 then
		if not IsInRadius(ball, LastBallHitter, 200) then
			onGravGunDrop(LastBallHitter, ball)
		end
	end
	]]

	if redgoal > 0 then
		local inrad = _EntitiesFindInSphere(_EntGetPos(redgoal), 20)
		for i=1, table.getn(inrad) do
			if inrad[i] == ball then
				if _PlayerInfo(LastBallHitter, "team") == TEAM_BLUE then
					if _TeamNumPlayers(TEAM_RED) > 0 then
						NDB.AddMoney(LastBallHitter, MONEYSCOREBONUS, false)
						TeamScores("blue")
					else
						_PrintMessage(LastBallHitter, 4, [[Can't score on an unrepresented team]])
					end
					break
				else
					PrintMessageAll(_PlayerInfo(LastBallHitter, "name").." tried to score for the enemy team...", 255, 255, 255, 255)
					createBall()
					_PlayerAddScore(LastBallHitter, SELFSCOREPENALTY*-1)
					break
				end
			end
		end
	end
	if bluegoal > 0 then
		local inrad2 = _EntitiesFindInSphere(_EntGetPos(bluegoal), 20)
		for i=1, table.getn(inrad2) do
			if(inrad2[i] == ball) then
				if _PlayerInfo(LastBallHitter, "team") == TEAM_RED then
					if _TeamNumPlayers(TEAM_BLUE) > 0 then
						NDB.AddMoney(LastBallHitter, MONEYSCOREBONUS, false)
						TeamScores("red")
					else
						_PrintMessage(LastBallHitter, 4, [[Can't score on an unrepresented team]])
					end
					break
				else
					PrintMessageAll(_PlayerInfo(LastBallHitter, "name").." tried to score for the enemy team...", 255, 255, 255, 255)
					createBall()
					_PlayerAddScore(LastBallHitter, SELFSCOREPENALTY*-1)
					break
				end
			end
		end
	end
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 Blink(userid) return end
function Typhoon(userid) return end

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

function onShowHelp(userid)
	_GModRect_Start("gmod/white")
	 _GModRect_SetPos(0.0, 0.14, 1.0, 0.24)
	 _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("JB Ball\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( "Use your Smacker/G-gun to slap the JB Ball into the enemy goal.\nHold jump to use your jetboots.\nYou can slap enemy players and send them off course or kill them!\nSet score wins the match!")
	_GModText_Send( userid, 51 )
	if HOTPOTATOTIME > 0 then
	_GModText_Start("Default")
	 _GModText_SetPos(-1, 0.4)
	 _GModText_SetColor(255, 90, 25, 240)
	 _GModText_SetTime(10, 0.2, 1.25)
	 _GModText_SetText( "Hot Potato time: "..HOTPOTATOTIME.." seconds.")
	_GModText_Send( userid, 52 )
	else
	_GModText_Start("Default")
	 _GModText_SetPos(-1, 0.4)
	 _GModText_SetColor(255, 90, 25, 240)
	 _GModText_SetTime(10, 0.2, 1.25)
	 _GModText_SetText( "Hot Potato time: DISABLED")
	_GModText_Send( userid, 52 )
	end
end

function TeamScores(team)
	if(team == "red") then
		_TeamAddScore(TEAM_RED, 1)
		for i=1, _MaxPlayers() do
			if(_PlayerInfo(i, "connected")) then
				if(_PlayerInfo(i, "team") == TEAM_RED) then
					_PlaySoundPlayer(i, "jbb/allyscore.mp3")
				else
					_PlaySoundPlayer(i, "jbb/enemyscore.mp3")
				end
				DrawTeamScore(i)
			end
		end
	elseif(team == "blue") then
		_TeamAddScore(TEAM_BLUE, 1)
		for i=1, _MaxPlayers() do
			if(_PlayerInfo(i, "connected")) then
				if(_PlayerInfo(i, "team") == TEAM_BLUE) then
					_PlaySoundPlayer(i, "jbb/allyscore.mp3")
				else
					_PlaySoundPlayer(i, "jbb/enemyscore.mp3")
				end
				DrawTeamScore(i)
			end
		end
	end
	PrintMessageAll(_PlayerInfo(LastBallHitter, "name").." scores for the "..TeamToString(_PlayerInfo(LastBallHitter, "team")).."!", 255, 255, 255, 255)
	_PlayerAddScore(LastBallHitter, SCOREBONUS)
	if hotpotato ~= nil then HaltTimer(hotpotato) hotpotato = nil end
	if(_TeamScore(TEAM_RED) >= MAXTEAMSCORE) then
		_PrintMessageAll(HUD_PRINTCENTER, "Score limit reached!\n"..TeamToString(TEAM_RED).." WIN THE MATCH!")
		AddTimer(1.5, 1, _PrintMessageAll, HUD_PRINTCENTER, "Score limit reached!\n"..TeamToString(TEAM_RED).." WIN THE MATCH!")
		_EntRemove(ball)
		_PlaySound("weapons/physcannon/energy_disintegrate4.wav")
		AddTimer(10, 1, Restart)
		return
	elseif(_TeamScore(TEAM_BLUE) >= MAXTEAMSCORE) then
		_PrintMessageAll(HUD_PRINTCENTER, "Score limit reached!\n"..TeamToString(TEAM_BLUE).." WIN THE MATCH!")
		AddTimer(1.5, 1, _PrintMessageAll, HUD_PRINTCENTER, "Score limit reached!\n"..TeamToString(TEAM_BLUE).." WIN THE MATCH!")
		_EntRemove(ball)
		_PlaySound("weapons/physcannon/energy_disintegrate4.wav")
		AddTimer(10, 1, Restart)
		return
	end
	createBall()
end

function Restart()
	currentround = currentround+1
	if currentround > NUMROUNDS and NUMROUNDS > 0 then
		_StartNextLevel()
		return
	end
	_TeamSetScore(TEAM_RED, 0)
	_TeamSetScore(TEAM_BLUE, 0)
	createBall()
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "connected") then
			_EntSpawn(i)
			_PlayerSetScore(i, 0)
			_PlayerAddDeath(i, _PlayerInfo(i, "deaths")*-1)
		end
	end
end

function gamerulesStartMap ()	
	PlayerFreezeAll(false)
	_TeamSetName(TEAM_BLUE, BLUENAME)
	_TeamSetName(TEAM_RED, REDNAME)

	_TeamSetName(TEAM_GREEN, "Green Team")
	_TeamSetName(TEAM_YELLOW, "Yellow Team")

	_EntPrecacheModel("models/Roller.mdl")
	_EntPrecacheModel("models/Combine_Helicopter/helicopter_bomb01.mdl")
	
	redgoal = _EntGetByName("redgoal")
	bluegoal = _EntGetByName("bluegoal")
	if redgoal == 0 then
		_ALERT("No red goal detected!\n")
	end

	if bluegoal == 0 then
		_ALERT("No blue goal detected!\n")
	end
	AddTimer(5, 1, createBall)
	--AddTimer(7.5, 1, createDeathBall)
	--AddTimer(8.5, 1, createFireBall)
	--AddTimer(9.5, 1, createLightningBall)
end

function DrawTeamScore(userid)
	_GModRect_Start("gmod/white")
	 _GModRect_SetPos(0.0, 0.0, 0.21, 0.14)
	 _GModRect_SetColor(0, 200, 0, 150)
	 _GModRect_SetTime(99999, 0, 0)
	_GModRect_Send(userid, 3310)
	_GModRect_Start("gmod/white")
	 _GModRect_SetPos(0.0, 0.0, 0.2, 0.13)
	 _GModRect_SetColor(0, 0, 0, 175)
	 _GModRect_SetTime(99999, 0, 0)
	_GModRect_Send(userid, 3311)
	_GModText_Start("Default")
	 _GModText_SetPos( 0.01, 0.05 )
	 _GModText_SetColor( 255, 0, 0, 200 )
	 _GModText_SetTime( 99999, 0, 0 )
	 _GModText_SetText( TeamToString(TEAM_RED)..": ".._TeamScore(TEAM_RED).."/"..MAXTEAMSCORE)
	_GModText_Send( userid, 966 )
	_GModText_Start("Default")
	 _GModText_SetPos( 0.01, 0.09 )
	 _GModText_SetColor( 0, 0, 255, 200 )
	 _GModText_SetTime( 99999, 0, 0 )
	 _GModText_SetText( TeamToString(TEAM_BLUE)..": ".._TeamScore(TEAM_BLUE).."/"..MAXTEAMSCORE)
	_GModText_Send( userid, 967 )
	if NUMROUNDS > 0 then
		_GModText_Start("Default")
		 _GModText_SetPos( 0.01, 0.13 )
		 _GModText_SetColor( 255, 255, 255, 200 )
		 _GModText_SetTime( 99999, 0, 0 )
		 _GModText_SetText( "Round: "..currentround.."/"..NUMROUNDS)
		_GModText_Send( userid, 967 )
	end
end

function setBallHitter(userid)
	_PlaySound("weapons/physcannon/energy_sing_flyby1.wav")
	_EntitySetPhysicsAttacker(ball, userid)
	local ents = _EntitiesFindInSphere(_EntGetPos(ball), 250)
	for i=1, table.getn(ents) do
		if(_EntGetName(ents[i]) == "redgoal" and _PlayerInfo(userid, "team") == TEAM_RED and _PlayerInfo(LastBallHitter, "team") ~= TEAM_RED) then
			PrintMessageAll(_PlayerInfo(userid, "name").." blocks the ball for the "..TeamToString(_PlayerInfo(userid, "team")).."!", 255, 255, 255, 255)
			_PlaySound("weapons/physcannon/superphys_launch"..math.random(1,4)..".wav")
			LastBallHitter = userid
			return
		elseif(_EntGetName(ents[i]) == "bluegoal" and _PlayerInfo(userid, "team") == TEAM_BLUE and _PlayerInfo(LastBallHitter, "team") ~= TEAM_BLUE) then
			PrintMessageAll(_PlayerInfo(userid, "name").." blocks the ball for the "..TeamToString(_PlayerInfo(userid, "team")).."!", 255, 255, 255, 255)
			_PlaySound("weapons/physcannon/superphys_launch"..math.random(1,4)..".wav")
			LastBallHitter = userid
			return
		end
	end
	if LastBallHitter == 0 then
		PrintMessageAll(_PlayerInfo(userid, "name").." smacks the ball.", 255, 255, 255, 255)
		_PlaySound("jbb/ballsnatch.mp3")
	elseif _PlayerInfo(LastBallHitter, "team") ~= _PlayerInfo(userid, "team") then
		PrintMessageAll(_PlayerInfo(userid, "name").." bashes the ball.", 255, 255, 255, 255)
		_PlaySound("jbb/ballsnatch.mp3")
	elseif _PlayerInfo(LastBallHitter, "team") == _PlayerInfo(userid, "team") then
		PrintMessageAll(_PlayerInfo(userid, "name").." smacks the ball.", 255, 255, 255, 255)
	end
	LastBallHitter = userid
end

function TeamToString(team)
	if team == TEAM_RED then
		return REDNAME
	elseif team == TEAM_BLUE then
		return BLUENAME
	end
end

function ClassMenu(userid, class)
	if _PlayerInfo(userid, "team") == TEAM_BLUE then
		if not IsInRadius(userid, bluegoal, 250) then
			_PrintMessage(userid, 4, "You must be near your goal to switch classes.")
			return
		end
	elseif _PlayerInfo(userid, "team") == TEAM_RED then
		if not IsInRadius(userid, redgoal, 250) then
			_PrintMessage(userid, 4, "You must be near your goal to switch classes.")
			return
		end
	end
	if players[userid].Class == class then
		_PrintMessage(userid, 4, "You are already a "..Classes[class].DisplayName.."!")
	elseif Certified(userid, Classes[class].Name) then
		players[userid].Class = class
		_PlayerRespawn(userid)
		_PrintMessage(userid, 4, "You are now a "..Classes[class].DisplayName.."!")
	elseif players[userid].money >= Classes[class].Value then
		players[userid].money = players[userid].money-Classes[class].Value
		players[userid].Class = class
		players[userid].Certifications = players[userid].Certifications.." "..Classes[class].Name
		SaveInfo(userid)
		_PlayerRespawn(userid)
		_PrintMessage(userid, 4, "You are now a certified "..Classes[class].DisplayName.."!")
		NDB.drawMoneyAmmount(userid)
	else
		_PrintMessage(userid, 4, "You don't have enough cash.")
	end
end

function onShowSpare1(userid)
	if _PlayerInfo(userid, "team") == TEAM_BLUE then
		if not IsInRadius(userid, bluegoal, 200) then
			_PrintMessage(userid, 4, "You must be near your goal to switch classes.")
			return
		end
	elseif _PlayerInfo(userid, "team") == TEAM_RED then
		if not IsInRadius(userid, redgoal, 200) then
			_PrintMessage(userid, 4, "You must be near your goal to switch classes.")
			return
		end
	end
	local menu = JBMenu.CreateMenu(false, "Class Menu", "", "255 255 255", "255 255 255")
	JBMenu.AddChoice(menu, "Class Catalog", "Purchase certifications.", "0 255 0", BuyClasses, userid)
	JBMenu.AddChoice(menu, "Your Classes", "Certifications you have purchased.", "0 255 0", CurrentClasses, userid)
	JBLastExit[userid] = _CurTime()-1
	JBMenu.SendMenu(userid, menu)
end

function BuyClasses(userid)
	local menu = JBMenu.CreateMenu(false, "Buy Classes", "", "255 255 255", "255 255 255")
	for i=1, table.getn(Classes) do
		if not Certified(userid, Classes[i].Name) then
			if not Classes[i].Hidden then
				if Classes[i].Value > players[userid].money then
					JBMenu.AddChoice(menu, "($"..Classes[i].Value..") "..Classes[i].DisplayName, Classes[i].Desc, "255 0 0", ClassMenu, userid, i)
				else
					JBMenu.AddChoice(menu, "($"..Classes[i].Value..") "..Classes[i].DisplayName, Classes[i].Desc, "0 255 0", ClassMenu, userid, i)
				end
			end
		end
	end
	JBMenu.AddChoice(menu, "", "<-- Back", "255 255 255", onShowSpare1, userid)
	JBLastExit[userid] = _CurTime()-1
	JBMenu.SendMenu(userid, menu)
end

function CurrentClasses(userid)
	local menu = JBMenu.CreateMenu(false, "Your Classes", "", "255 255 255", "255 255 255")
	for i=1, table.getn(Classes) do
		if Classes[i].Hidden then
			if Certified(userid, Classes[i].Name) then
				JBMenu.AddChoice(menu, "(HIDDEN) "..Classes[i].DisplayName, Classes[i].Desc, "255 255 0", ClassMenu, userid, i)
			end
		elseif Certified(userid, Classes[i].Name) then
			JBMenu.AddChoice(menu, "(CERTIFIED) "..Classes[i].DisplayName, Classes[i].Desc, "255 255 255", ClassMenu, userid, i)
		end
	end
	JBMenu.AddChoice(menu, "", "<-- Back", "255 255 255", onShowSpare1, userid)
	JBLastExit[userid] = _CurTime()-1
	JBMenu.SendMenu(userid, menu)
end

function createBall()
	if ball > 0 then
		_EntRemove(ball)
		ball = 0
	end

	local targs = _EntitiesFindByClass("info_target")
	local ballpos = vector3(0, 0, 0)
	if targs == nil then
		_ALERT("No spawn point for ball found. Using 0,0,0\n")
	else
		for i=1, table.getn(targs) do
			if _EntGetName(targs[i]) == "ballspawn" then
				ballpos = _EntGetPos(targs[i])
			end
		end
	end

	local prop = _EntCreate("prop_physics")
	if prop > 0 then
		_EntSetKeyValue(prop, "model", "models/Roller.mdl")
		
		_EntSetPos(prop, ballpos)

		_EntSpawn(prop)
		_EntSetName(prop, "ball")
		local fire = _EntCreate("env_smoketrail")
		local fire2 = _EntCreate("env_fire_trail")
		_EntSetKeyValue(fire, "firesprite", "sprites/glow02")
		_EntSetKeyValue(fire, "smokesprite", "sprites/physcannon_blueflare1")
		_EntSetPos(fire, _EntGetPos(prop))
		_EntSetPos(fire2, _EntGetPos(prop))
		_EntSpawn(fire)
		_EntSpawn(fire2)
		_EntSetParent(fire, prop)
		_EntSetParent(fire2, prop)
		_GModRect_Start( "deathnotify/swep_default")
			_GModRect_SetPos(0, 0, 0.035, 0.035)
			_GModRect_SetColor(255, 255, 255, 255)
			_GModRect_SetTime(99999, 0, 0)
			_GModRect_SetDelay(0)
			_GModRect_SetEntityOffset(vector3(0, 0, 16))
			_GModRect_SetEntity(prop)
		_GModRect_Send(0, 884)
		
		ball = prop
		_phys.EnableGravity(ball, BALLGRAVITY)
		LastBallHitter = 0
	end
end

function PrintMessage(userid, msg, r, g, b, a)
	_GModText_Start( "Trebuchet24" )
	 _GModText_SetPos( -1.0, 0.8 )
	 _GModText_SetColor( r, g, b, a )
	 _GModText_SetTime( 5, 1, 1 )
	 _GModText_SetText( msg )
	_GModText_Send( userid, 521 )
end

function HotPotatoMessage(userid)
	_GModText_Start( "Trebuchet24" )
	 _GModText_SetPos( -1.0, 0.85 )
	 _GModText_SetColor( 255, 25, 25, 255 )
	 _GModText_SetTime( 3, 1, 1 )
	 _GModText_SetText( "They held the ball too long." )
	_GModText_Send( userid, 522 )
end

function PrintMessageAll(msg, r, g, b, a)
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "connected") then
			PrintMessage(i, msg, r, g, b, a)
		end
	end
end

function HotPotatoMessageAll()
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "connected") then
			HotPotatoMessage(i)
		end
	end
end

function canPlayerHaveItem(playerid, itemname)
	return true
end

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

function GetAutoTeam()
	local r = 0
	local b = 0
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "connected") then
			if(_PlayerInfo(i, "team") == TEAM_RED) then r=r+1; end
			if(_PlayerInfo(i, "team") == TEAM_BLUE) then b=b+1; end
		end
	end
	if r>b then
		return TEAM_BLUE
	else
		return TEAM_RED
	end
end

function onShowTeam(userid)
	if not _PlayerInfo(userid, "alive") then return end
	if GetAutoTeam() == _PlayerInfo(userid, "team") then
		_PrintMessage(userid, 3, "The teams are even enough there, buddy.\n")
		return
	end
	if _PlayerInfo(userid, "team") == TEAM_RED then
		_PlayerChangeTeam(userid, TEAM_BLUE)
	else
		_PlayerChangeTeam(userid, TEAM_RED)
	end
	_PlayerKill(userid)
end

if teams == nil then
	teams = {}
end
teams[TEAM_BLUE] = {name="Blue Butt Baboons", color={r=15,g=170,b=255}}
teams[TEAM_RED] = {name="Red Rear-end Rednecks", color={r=255,g=40,b=0}}
teams[TEAM_GREEN] = {name="Green Grime Gremlins", color={r=25,g=255,b=25}}
teams[TEAM_YELLOW] = {name="Yellow Yonkaviches", color={r=255,g=200,b=0}}

function eventPlayerActive(name, userid, steamid)
	_EntSetKeyValue(userid, "rendermode", "1")
	LastDeath[userid] = vector3(0,0,0)
	AddTimer(2.0, 1, onShowHelp, userid)
end

function eventPlayerKilled(killed, attacker, weapon)
	_PlaySound("jbb/knockout.mp3")
	_PlaySoundPlayer(killed, "jbb/respawning.mp3")
	_PlayerAddDeath(killed, 1)
	if IsPlayer(attacker) then
		if killed == attacker then
			_PlayerAddScore(killed, -1)
		else
			_PlayerAddScore(attacker, KILLBONUS)
			NDB.AddMoney(attacker, MONEYKILLBONUS, false)
		end
	end
	if _EntGetType(jetpacks[killed]) == "env_fire_trail" then
		_EntRemove(jetpacks[killed])
		jetpacks[killed] = 0
	end
end

function eventPlayerSpawn(userid)
	if _PlayerInfo(userid, "team") == TEAM_SPECTATOR then
		onShowTeam(userid)
		return
	end
	DrawTeamScore(userid)
	Gibbed[userid] = false
	_PlayerSetDrawViewModel(userid, true)
	_player.ShouldDropWeapon(userid, false)
	_EntSetMaxHealth(userid, Classes[players[userid].Class].Health)
	_PlayerSetHealth(userid, Classes[players[userid].Class].Health)
	_PlayerSetArmor(userid, Classes[players[userid].Class].Armor)
	_EntFire(userid, "color", TeamColor(_PlayerInfo(userid,"team")), 0)
	if Classes[players[userid].Class].Mana then
		_GModRect_Start("gmod/white")
		 _GModRect_SetPos(0.4, 0.95, 0.2, 0.1)
		 _GModRect_SetColor(0, 0, 0, 200)
		 _GModRect_SetTime(9999, 0, 0)
		_GModRect_Send(userid, 1800)
	else
		_GModRect_Hide(userid, 1800, 0, 0)
		_GModRect_Hide(userid, 1801, 0, 0)
	end
end

function GiveDefaultItems(userid)
	if _PlayerInfo(userid, "team") == TEAM_SPECTATOR then return end
	_PlayerGiveItem(userid, "weapon_physcannon")
	for i=1, table.getn(Classes[players[userid].Class].SWEPs) do
		_PlayerGiveSWEP(userid, Classes[players[userid].Class].SWEPs[i])
	end
end

function HotPotato(player)
	if LastBallHitter ~= player or _EntGetType(ball) == "n/a" or HOTPOTATOTIME == 0 then return end
	onGravGunDrop(player, ball)
	HotPotatoMessageAll()
	_EntSetVelocity(player, vecAdd(_EntGetVelocity(player), vector3(0,0,-4000)))
	AddTimer(1, 1, _PlayerKill, player)
end

function onGravGunPickup(player, entity)
	local ents = _EntitiesFindInSphere(_EntGetPos(ball), 250)
	for i=1, table.getn(ents) do
		if(_EntGetName(ents[i]) == "redgoal" and _PlayerInfo(player, "team") == TEAM_RED and _PlayerInfo(LastBallHitter, "team") ~= TEAM_RED) then
			PrintMessageAll(_PlayerInfo(player, "name").." blocks the ball for the "..TeamToString(_PlayerInfo(player, "team")).."!", 255, 255, 255, 255)
			_PlayerAddScore(player, BLOCKBONUS)
			_PlaySound("weapons/physcannon/superphys_launch"..math.random(1,4)..".wav")
			LastBallHitter = player
			if hotpotato ~= nil then HaltTimer(hotpotato) hotpotato = nil end
			hotpotato = AddTimer(HOTPOTATOTIME, 1, HotPotato, player)
			return true
		elseif(_EntGetName(ents[i]) == "bluegoal" and _PlayerInfo(player, "team") == TEAM_BLUE and _PlayerInfo(LastBallHitter, "team") ~= TEAM_BLUE) then
			PrintMessageAll(_PlayerInfo(player, "name").." blocks the ball for the "..TeamToString(_PlayerInfo(player, "team")).."!", 255, 255, 255, 255)
			_PlayerAddScore(player, BLOCKBONUS)
			_PlaySound("weapons/physcannon/superphys_launch"..math.random(1,4)..".wav")
			LastBallHitter = player
			if hotpotato ~= nil then HaltTimer(hotpotato) hotpotato = nil end
			hotpotato = AddTimer(HOTPOTATOTIME, 1, HotPotato, player)
			return true
		end
	end
	if entity == ball then
		if LastBallHitter == 0 or _PlayerInfo(LastBallHitter, "team") ~= _PlayerInfo(player, "team") then
			PrintMessageAll(_PlayerInfo(player, "name").." snatches the ball.", 255, 255, 255, 255)
		else
			PrintMessageAll(_PlayerInfo(player, "name").." takes the ball.", 255, 255, 255, 255)
		end
		_PlaySound("jbb/ballsnatch.mp3")
		LastBallHitter = player
		if hotpotato ~= nil then HaltTimer(hotpotato) hotpotato = nil end
		hotpotato = AddTimer(HOTPOTATOTIME, 1, HotPotato, player)
	end
	return true
end

function onGravGunPunt(player, entity)
	local ents = _EntitiesFindInSphere(_EntGetPos(ball), 250)
	for i=1, table.getn(ents) do
		if(_EntGetName(ents[i]) == "redgoal" and _PlayerInfo(player, "team") == TEAM_RED and _PlayerInfo(LastBallHitter, "team") ~= TEAM_RED) then
			PrintMessageAll(_PlayerInfo(player, "name").." blocks the ball for the "..TeamToString(_PlayerInfo(player, "team")).."!", 255, 255, 255, 255)
			_PlaySound("weapons/physcannon/superphys_launch"..math.random(1,4)..".wav")
			LastBallHitter = player
			return true
		elseif(_EntGetName(ents[i]) == "bluegoal" and _PlayerInfo(player, "team") == TEAM_BLUE and _PlayerInfo(LastBallHitter, "team") ~= TEAM_BLUE) then
			PrintMessageAll(_PlayerInfo(player, "name").." blocks the ball for the "..TeamToString(_PlayerInfo(player, "team")).."!", 255, 255, 255, 255)
			_PlaySound("weapons/physcannon/superphys_launch"..math.random(1,4)..".wav")
			LastBallHitter = player
			return true
		end
	end
	if entity == ball then
		_PlaySound("weapons/physcannon/energy_sing_flyby1.wav")
		if(LastBallHitter == 0) then
			PrintMessageAll(_PlayerInfo(player, "name").." punts the ball.", 255, 255, 255, 255)
			_PlaySound("jbb/ballsnatch.mp3")
		else
			PrintMessageAll(_PlayerInfo(player, "name").." punts the ball.", 255, 255, 255, 255)
		end
		LastBallHitter = player
	end
	return true
end

function onGravGunLaunch(player, entity)
	if entity == ball then
		PrintMessageAll(_PlayerInfo(player, "name").." throws the ball.", 255, 255, 255, 255)
		_PlaySound("weapons/physcannon/energy_sing_flyby1.wav")
		LastBallHitter = player
		if hotpotato ~= nil then HaltTimer(hotpotato) hotpotato = nil end
	end
	return true
end

function onGravGunDrop(player, entity)
	if entity == ball then
		PrintMessageAll(_PlayerInfo(player, "name").." dropped the ball.", 255, 255, 255, 255)
		_PlaySound("weapons/physcannon/energy_sing_flyby1.wav")
		LastBallHitter = player
		if hotpotato ~= nil then HaltTimer(hotpotato) hotpotato = nil end
	end
	return true
end
