-- NoXious CTF
-- by JetBoom

BUILD_LENGTH = 13
CTF_LENGTH = 20
STARTING_MONEY = 200
MONEY_KILL_AMOUNT = 35
FLAG_SCORE_MONEY = 1000
GLOBALMAXPROPS = 280
BONUS_WIN = 750
SCORELIMIT = 3
ROUND = 2
RETRO = false
NEXTMAP = 99999

--=======================================================================================
if string.find(_GetCurrentMap(), "noxctfnb") ~= nil or string.find(_GetCurrentMap(), "nobuild_noxctf") ~= nil then
	CTF_LENGTH = 900
end

votedskip = {}
SKIPVOTES = 0
for i=1, _MaxPlayers() do
	votedskip[i] = false
end

teams = {}
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}}

for i in teams do
	teams[i].props=0
	teams[i].flag=0
	teams[i].flagCarrier=0
	teams[i].flagpoint=0
end

function eventPlayerChangeTeam(name, userid, new_team, old_team)
	_EntSetName(userid, TeamString(new_team))
end

PropSpawn = {}
PropSpawn[1] = {Name="Metal Wall", Model="models/props_lab/blastdoor001a.mdl", Price=15}
PropSpawn[2] = {Name="Wooden Pallet [Breakable]", Model="models/props_junk/wood_pallet001a.mdl", Price=0}
PropSpawn[3] = {Name="Wooden Plank [Breakable]", Model="models/props_wasteland/dockplank01b.mdl", Price=0}
PropSpawn[4] = {Name="Wooden Log", Model="models/props_docks/dock01_pole01a_128.mdl", Price=1}
PropSpawn[5] = {Name="Metal Barrel", Model="models/props_c17/oildrum001.mdl", Price=1}
PropSpawn[6] = {Name="Short Metal Panel", Model="models/props_debris/metal_panel02a.mdl", Price=2}
PropSpawn[7] = {Name="Long Metal Panel", Model="models/props_debris/metal_panel01a.mdl", Price=3}
PropSpawn[8] = {Name="Combine Barricade", Model="models/props_combine/combine_barricade_short01a.mdl", Price=3}
PropSpawn[9] = {Name="Concrete Tube", Model="models/props_pipes/concrete_pipe001a.mdl", Price=15}
PropSpawn[10] = {Name="Booth", Model="models/props_combine/combine_booth_short01a.mdl", Price=25}
PropSpawn[11] = {Name="Dumpster", Model="models/props_junk/trashdumpster02.mdl", Price=30}
PropSpawn[12] = {Name="Roof", Model="models/props_rooftop/dome005.mdl", Price=30}
PropSpawn[13] = {Name="Big Column 1", Model="models/props_c17/column02a.mdl", Price=30}
PropSpawn[14] = {Name="Big Column 2", Model="models/props_c17/support01.mdl", Price=30}
PropSpawn[15] = {Name="Metal Bars", Model="models/props_wasteland/prison_gate001b.mdl", Price=12}
PropSpawn[16] = {Name="Cargo Container", Model="models/props_wasteland/cargo_container01.mdl", Price=35}
PropSpawn[17] = {Name="Concrete Barrier", Model="models/props_c17/concrete_barrier001a.mdl", Price=15}
PropSpawn[18] = {Name="Arch-Gate", Model="models/props_wasteland/prison_archgate001.mdl", Price=20}
PropSpawn[19] = {Name="C. Window", Model="models/props_combine/combine_window001.mdl", Price=5}
PropSpawn[20] = {Name="C. Wall 1", Model="models/props_combine/combine_barricade_tall01a.mdl", Price=20}
PropSpawn[21] = {Name="C. Wall 2", Model="models/props_combine/combine_barricade_med03b.mdl", Price=20}

function VoteSkip(userid)
	if not VOTEENABLED then _PrintMessage(userid, 3, "Voting is disabled at this time.\n") return end
	if FightMode then _PrintMessage(userid, 3, "You can not vote during CTF!\n") return end
	if votedskip[userid] then _PrintMessage(userid, 3, "You or a person in this player slot already voted for a build mode skip.\n") return end
	votedskip[userid] = true
	SKIPVOTES = SKIPVOTES + 1
	_PrintMessageAll(3, _PlayerInfo(userid,"name").." voted to skip build mode. ("..SKIPVOTES.."/"..GetNumPlayers()*0.65..")")
	if SKIPVOTES >= GetNumPlayers()*0.65 then
		_PrintMessageAll(3, "Build Mode ending early due to vote.")
		StartCTF()
	end
end

function RetroMode()
	PropSpawn = {}
	PropSpawn[1] = {Name="Small Box", Model="models/props_junk/wood_crate001a.mdl", Price=0}
	PropSpawn[2] = {Name="Large Box", Model="models/props_junk/wood_crate002a.mdl", Price=0}
	PropSpawn[3] = {Name="Wooden Pallet", Model="models/props_junk/wood_pallet001a.mdl", Price=0}
	for i=1, _MaxPlayers() do
		if IsPlayerOnline(i) then
			players[i].Class = 1
			_PlayerRespawn(i)
			LoadSpawnMenu(i)
		end
	end
	_PrintMessageAll(3, "RETRO MODE ENABLED!")
	_PrintMessageAll(4, "RETRO MODE ENABLED!")
	RETRO = true
end

TimeTrack = -1
fCTF_time = 0
sCTF_time = BUILD_LENGTH * 60
fCTF_len = 0
sCTF_len = CTF_LENGTH * 60

function StartBuild()
	fCTF_time = _CurTime() + (sCTF_time*0.5)
	HaltTimer(TimeTrack)
	TimeTrack = AddTimer(5, 0, doCountCTF)
	UpdateScores(0)
	for i in teams do
		_GModRect_Hide(0, 97+i, 0, 0)
		if _EntGetName(teams[i].flag) == "flag" then
			_EntRemove(teams[i].flag)
			_GModRect_Hide(0, 97+i, 0, 0)
		end
		teams[i].flag=0
		teams[i].flagCarrier=0
	end
	NDB.GlobalSave()
	AllPlayers(_PlayerRespawn)
	for i=1, 4000 do
		if PhysProps[i] and _EntGetName(i) == "unfrozenprop" then
			_EntRemove(i)
			PhysProps[i] = nil
			if PlasmaTurrets[i] then
				PlasmaTurrets[i] = nil
				teams[PlasmaTurrets[i].Team].PlasmaTurrets = teams[PlasmaTurrets[i].Team].PlasmaTurrets-1
			end
			if Mway[i] then
				for	k, x in Mway[i].Children do
					_EntRemove(x)
				end
				Mway[i] = nil
			end
		end
	end
	toggleWalls()
end

FightMode = true
PhysProps = {}
players = {}

for i=1, _MaxPlayers() do
	players[i] = {}
	players[i].spawn = vector3(0, 0, 0)
	players[i].money = 0
	players[i].Invisible = false
	players[i].Class = 1
	players[i].lastmine = 0
	players[i].ore = 0
	players[i].LASTPROP = 0
	players[i].PropSelection = 1
	players[i].Certifications = "gunslinger"
	players[i].LastSpawn = 0
	--players[i].Mana = 100
	--players[i].Magery = 0
end

local result = _file.Find( "lua/gamemodes/noxctf/specialprops/*.lua" )
for i=1, table.getn(result) do
    if result[i] ~= "." and result[i] ~= ".." then
		if _file.Exists( "lua/gamemodes/noxctf/specialprops/"..result[i]) then
			_Msg("Opening special prop "..result[i].."\n")
			_OpenScript("gamemodes/noxctf/specialprops/"..result[i])
		end
    end
end
result = nil

local result = _file.Find( "lua/gamemodes/noxctf/init/*.lua" )
for i=1, table.getn(result) do
    if result[i] ~= "." and result[i] ~= ".." then
		if _file.Exists( "lua/gamemodes/noxctf/init/"..result[i]) then
			_OpenScript("gamemodes/noxctf/init/"..result[i])
		end
    end
end
result = nil

oldTraceAttack = _TraceAttack
function newTraceAttack(ent, inflictor, attacker, damage, damagetype)
	if Vehicles[ent] then
		if damagetype then
			if damagetype == "bullet" then
				ProcessVehicleDamage(ent, attacker, math.ceil(damage*0.75))
			elseif damagetype == "antivehicle" then
				ProcessVehicleDamage(ent, attacker, math.ceil(damage*3))
			elseif damagetype == "weak" then
				ProcessVehicleDamage(ent, attacker, math.ceil(damage*0.5))
			else
				ProcessVehicleDamage(ent, attacker, math.ceil(damage))
			end
		else
			ProcessVehicleDamage(ent, attacker, math.ceil(damage))
		end
	elseif PlasmaTurrets[ent] then
		ProcessPlasmaTurretDamaged(ent, attacker, math.ceil(damage))
	else
		oldTraceAttack(ent, inflictor, attacker, damage)
	end
end
_TraceAttack = newTraceAttack

function OverDrive()
	_PrintMessageAll(4, "OverDrive")
	for i=1, _MaxPlayers() do
		if IsPlayerOnline(i) then
			_SWEPRunString(_PlayerGetActiveWeapon(i), "OverDrive=true")
			_PlayerSetHealth(i, 1250)
			_EntSetMaxHealth(i, 1250)
		end
	end
end

function TeamToString(team)
	return teams[team].name
end

function eventPropBreak(breakerid, propid)
	if PhysProps[propid] then
		PhysProps[propid] = nil
	end
end

function CheckIllegalProp(entity)
	if IsInRadius(entity, teams[PhysProps[entity].Team].flagpoint, 125) then
		_EntSetPos(entity, vecAdd(_EntGetPos(teams[PhysProps[entity].Team].flagpoint), vector3(0,0,145)))
		return
	end
	_TraceLine(_EntGetPos(teams[PhysProps[entity].Team].flagpoint), vector3(0,0,1), 125, 0)
	if _TraceHitNonWorld() then
		if _TraceGetEnt() == entity then 
			_EntSetPos(entity, vecAdd(_EntGetPos(teams[PhysProps[entity].Team].flagpoint), vector3(0,0,250)))
		end
	end
end

function StartDragoonTransSequence(userid)
	_PlayerLockInPlace(userid, true)
	_PlayerDisableAttack(userid, true)
	_EntEmitSoundEx(userid, "ambient/energy/whiteflash.wav", 1.0, 1.5)
	AddTimer(0.75, 5, _EntEmitSound, userid, "ambient/energy/zap"..math.random(5,9)..".wav")
	local ent = _EntCreate("env_sprite")
	if ent > 0 then
		_EntSetKeyValue(ent, "model", "sprites/splodesprite.spr")
		_EntSetKeyValue(ent, "rendermode", "5")
		_EntSetKeyValue(ent, "scale", "0.8")
		_EntSetKeyValue(ent, "spawnflags", "1")
		_EntSetPos(ent, _EntGetPos(userid))
		_EntSpawn(ent)
		_EntFire(ent, "showsprite", "", 1)
		_EntFire(ent, "setscale", "0.8", 1.25)
		_EntFire(ent, "setscale", "1.25", 1.5)
		_EntFire(ent, "setscale", "1.55", 1.75)
		_EntFire(ent, "setscale", "2.8", 1.0)
		_EntFire(ent, "setscale", "1.85", 2.5)
		_EntFire(ent, "setscale", "1.25", 3.0)
		_EntFire(ent, "setscale", "0.5", 4.25)
		_EntFire(ent, "hidesprite", "", 5.25)
		_EntFire(ent, "kill", "", 5.5)
	end

	_util.ScreenShake(_EntGetPos(userid), math.random(15,35), 160.0, 3.0, 140)
	AddTimer(5.0, 1, EndDragoonTransSequence, userid)
end

function EndDragoonTransSequence(userid)
	_PlayerLockInPlace(userid, false)
	_PlayerDisableAttack(userid, false)
	_EntEmitSoundEx(userid, "weapons/rpg/rocketfire1.wav", 1.0, 0.8)
	_EntEmitSoundEx(userid, "ambient/explosions/explode_6.wav", 1.0, 1.1)
	_EntSetVelocity(userid, vector3(0,0,0))
end

ateamwon = false
function FlagCapture(otherteam, team)
	if teams[team] == nil or teams[otherteam] == nil then return end
	PrintMessageAll("The "..TeamToString(team).." captured the "..TeamToString(otherteam).." flag!", 255, 255, 255, 255)
	_PlaySound("jbb/allyscore.mp3")
	_TeamAddScore(team, 1)
	if teams[otherteam].flagCarrier > 0 then
		local mon = FLAG_SCORE_MONEY
		if players[teams[otherteam].flagCarrier].GoldMember then mon = math.ceil(mon*1.25) end
		players[teams[otherteam].flagCarrier].money = players[teams[otherteam].flagCarrier].money + mon
		drawMoneyAmmount(teams[otherteam].flagCarrier)
		teams[otherteam].flagCarrier = 0
	end
	_EntSetPos(teams[team].flag, _EntGetPos(teams[team].flagpoint))
	_EntSetPos(teams[otherteam].flag, _EntGetPos(teams[otherteam].flagpoint))
	UpdateScores(0)
	for i in teams do
		if _TeamScore(i) >= SCORELIMIT then
			ateamwon = true
			messageInfo(0, 67, 0.3, "Game over.\n Score limit has been reached...\nNext map in 10 seconds...")
			displayWhoWon()
			EndCTF()
			return
		end
	end
	NDB.GlobalSave()
end

function SetTimeToCTF(sender, args)
	if not IsJetAdmin(sender) then return end
	if FightMode then return end
	args = tonumber(args)
	if args == nil or args<0 then return end
	fCTF_time = _CurTime() + args*60
	_PrintMessageAll(3, _PlayerInfo(sender,"name").." set remaining build time to "..math.time(args*60)..".")
	_PrintMessageAll(4, _PlayerInfo(sender,"name").." set remaining build time to "..math.time(args*60)..".")
end
CONCOMMAND("buildtime", SetTimeToCTF)

function SetTeam(sender, args)
	if not IsJetAdmin(sender) then return end
	local targs = explode(string.lower(args), " ")
	if table.getn(targs) ~= 2 then return end
	if tonumber(targs[2]) == nil then
		for i in teams do
			if string.lower(TeamString(i)) == targs[2] then
				targs[2] = i
			end
		end
	end
	if tonumber(targs[2]) == nil then return end
	for i=1, _MaxPlayers() do
		if IsPlayerOnline(i) then
			if string.find(string.lower(_PlayerInfo(i, "name")), targs[1]) then
				if IsJetAdmin(i) and i ~= sender then return end
				_PlayerChangeTeam(i, tonumber(targs[2]))
				players[i].spawn = vector3(0,0,0)
				_PlayerRespawn(i)
				if i ~= sender then
					_PrintMessage(sender, 3, "Their team has been set.")
					_PrintMessage(i, 3, _PlayerInfo(sender,"name").." set your team.")
				else
					_PrintMessage(sender, 3, "Your team has been set.")
				end
				return
			end
		end
	end
end
CONCOMMAND("setteam", SetTeam)

function SetTimeToEnd(sender, args)
	if not IsJetAdmin(sender) then return end
	if not FightMode then return end
	args = tonumber(args)
	if args == nil or args<0 then return end
	fCTF_len = _CurTime() + args*60
	_PrintMessageAll(3, _PlayerInfo(sender,"name").." set remaining fight time to "..math.time(args*60)..".")
	_PrintMessageAll(4, _PlayerInfo(sender,"name").." set remaining fight time to "..math.time(args*60)..".")
end
CONCOMMAND("fighttime", SetTimeToEnd)

function gamerulesThink()
	if _CurTime() > NEXTMAP then
		_ServerCommand("changelevel "..GetNextMap().."\n")
	end
	if fCTF_time <= _CurTime() and not FightMode then
		messageInfo(0, 67, 0.5, "Capture the enemy flags!!")
		StartCTF()
	elseif fCTF_len <= _CurTime() and FightMode then
		removeAllPlayersWeapons()
		for i in teams do
			if _TeamScore(i) >= SCORELIMIT then
				messageInfo(0, 67, 0.3, "Game over.\n Score limit has been reached...")
				displayWhoWon()
				EndCTF()
				return
			end
		end
		messageInfo(0, 67, 0.3, "CTF is over.\n Starting new round...")
		EndCTF()
	end
	if FightMode then
		for x in teams do
			for y in teams do
				if x ~= y then
					if IsInRadius(teams[x].flag, teams[y].flagpoint, 50) then
						if IsInRadius(teams[y].flag, teams[y].flagpoint, 100) then
							if teams[x].flagCarrier > 0 then
								FlagCapture(x, y)
							end
						end
					end
				end
			end
		end
	end
	--thinkDrawMana()
end

function GetPlayerDamageScale(hitgroup)
	if hitgroup == HITGROUP_HEAD then
		return 3.0
	end
	return 1.0
end

MAXPROPS=50
START = false
function gamerulesStartMap()
	if START then return end
	START = true
	PlayerFreezeAll(false)
	_GameSetTargetIDRules(TRGTID_TEAMONLY)
	for i in teams do
		_TeamSetName(i, teams[i].name)
	end
	_ServerCommand("sk_zombie_health 400\n")
	_ServerCommand("sk_zombie_dmg_both_slash 50\n")
	_ServerCommand("sk_zombie_dmg_one_slash 35\n")

	_EntPrecacheModel("models/weapons/v_smg_mac10.mdl")
	_EntPrecacheModel("models/weapons/w_smg_mac10.mdl")
	_EntPrecacheModel("models/weapons/w_shot_m3super90.mdl")
	_EntPrecacheModel("models/weapons/v_shot_m3super90.mdl")
	_EntPrecacheModel("models/weapons/w_pist_deagle.mdl")
	_EntPrecacheModel("models/weapons/v_pist_deagle.mdl")
	_EntPrecacheModel("models/peanut/conansword.mdl")
	_EntPrecacheModel("models/weapons/v_stunbaton.mdl")
	_EntPrecacheModel("models/weapons/w_stunbaton.mdl")
	_EntPrecacheModel("models/mixerman3d/weapons/axe01.mdl")
	_EntPrecacheModel("models/weapons/w_rif_ak47.mdl")
	_EntPrecacheModel("models/weapons/v_rif_ak47.mdl")
	_EntPrecacheModel("models/weapons/w_pist_p228.mdl")
	_EntPrecacheModel("models/weapons/v_pist_p228.mdl")
	_EntPrecacheModel("models/weapons/w_knife_ct.mdl")
	_EntPrecacheModel("models/weapons/v_knife_t.mdl")

	_EntPrecacheModel("models/Roller_Spikes.mdl")
	_EntPrecacheModel("models/player/gman_high.mdl")
	_EntPrecacheModel("models/player/barney.mdl")
	_EntPrecacheModel("models/player/alyx.mdl")
	_EntPrecacheModel("models/player/breen.mdl")
	_EntPrecacheModel("models/player/combine_soldier.mdl")
	_EntPrecacheModel("models/player/combine_soldier_prisonguard.mdl")
	_EntPrecacheModel("models/player/combine_super_soldier.mdl")
	_EntPrecacheModel("models/player/eli.mdl")
	_EntPrecacheModel("models/player/classic.mdl")
	_EntPrecacheModel("models/player/corpse1.mdl")
	_EntPrecacheModel("models/player/female_04.mdl")
	_EntPrecacheModel("models/player/female_06.mdl")
	_EntPrecacheModel("models/player/male_02.mdl")
	_EntPrecacheModel("models/player/male_03.mdl")
	_EntPrecacheModel("models/player/male_08.mdl")
	_EntPrecacheModel("models/player/monk.mdl")
	_EntPrecacheModel("models/player/mossman.mdl")
	_EntPrecacheModel("models/player/odessa.mdl")
	_EntPrecacheModel("models/player/stripped.mdl")
	_EntPrecacheModel("models/player/stalker.mdl")
	_EntPrecacheModel("models/player/kleiner.mdl")
	_EntPrecacheModel("models/player/female_07.mdl")
	_EntPrecacheModel("models/player/charple01.mdl")
	_EntPrecacheModel("models/headcrabclassic.mdl")
	_EntPrecacheModel("models/player/Police.mdl")
	_EntPrecacheModel("models/Player/gordon_classic.mdl")
	_EntPrecacheModel("models/headcrabblack.mdl")
	_EntPrecacheModel("models/headcrab.mdl")

	for i in PropSpawn do
		_EntPrecacheModel(PropSpawn[i].Model)
	end
	UpdateScores(0)

	FightMode = false
	fCTF_time = _CurTime() + sCTF_time
	TimeTrack = AddTimer(5, 0, doCountCTF)
	
	local teamcount = 0
	for i in teams do
		if _EntGetByName(string.lower(TeamString(i)).."flagpoint") > 0 then
			teams[i].flagpoint = _EntGetByName(string.lower(TeamString(i)).."flagpoint")
			teamcount = teamcount+1
		else
			teams[i] = nil
		end
	end
	MAXPROPS = math.ceil(GLOBALMAXPROPS/teamcount)
	if string.find(_GetCurrentMap(), "noxctfnb") ~= nil or string.find(_GetCurrentMap(), "nobuild_noxctf") ~= nil then
		StartCTF()
	end
end

function EndCTF()
	_GModRect_Hide(0, 99, 0, 0)
	_GModRect_Hide(0, 727, 0, 0)
	FightMode = false
	fCTF_time = _CurTime() + sCTF_time
	for i in teams do
		if _EntGetName(teams[i].flag) == "flag" then
			_EntRemove(teams[i].flag)
			teams[i].flag = 0
		end
	end

	NDB.GlobalSave()
	if ateamwon then
		_Msg(GetNextMap().." has won the vote.\n")
		_PrintMessageAll(3, GetNextMap().." has won the vote.\n")
		NEXTMAP = _CurTime()+10
	else
		if string.find(_GetCurrentMap(), "noxctfnb") ~= nil or string.find(_GetCurrentMap(), "nobuild_noxctf") ~= nil then
			AddTimer(10, 1, StartCTF)
		else
			ROUND = ROUND-1
			if ROUND <= 0 then
				AddTimer(1, 1, StartCTF)
				_GModText_Start( "ImpactMassive" )
				 _GModText_SetPos( -1, 0.65 )
				 _GModText_SetColor( 255, 0, 0, 255 )
				 _GModText_SetTime( 6, 0.5, 0.5 )
				 _GModText_SetText( "-: SUDDEN DEATH ROUND :-" )
				_GModText_Send( 0, 5555 )
				local maxscore = 0
				for i in teams do
					if _TeamScore(i) > maxscore then maxscore = _TeamScore(i) end
				end
				SCORELIMIT=maxscore+1
				CTF_LENGTH = 60
				toggleWalls()
				UpdateScores(0)
				removeAllProps()
			else
				AddTimer(1, 1, StartBuild)
				_GModText_Start( "ImpactMassive" )
				 _GModText_SetPos( -1, 0.65 )
				 _GModText_SetColor( 255, 0, 0, 255 )
				 _GModText_SetTime( 6, 0.5, 0.5 )
				 _GModText_SetText( "Rounds Before SD: "..ROUND )
				_GModText_Send( 0, 5555 )
			end
		end
		for i in Vehicles do
			if string.find(_EntGetName(i), "scriptedvehicle:") ~= nil then
				local vehicle = i
				if Vehicles[vehicle].Driver > 0 then
					local driver = Vehicles[vehicle].Driver
					_PlayerSpectatorEnd(driver)
					_PlayerRespawn(driver)
					_EntSetPos(driver, _EntGetPos(vehicle))
					if VehicleTypes[Vehicles[vehicle].Type].HideHUD ~= nil then
						VehicleTypes[Vehicles[vehicle].Type].HideHUD(driver)
					end
			end
			if VehicleTypes[Vehicles[vehicle].Type].PassengerSlots > 0 then
				for i=1, table.getn(Vehicles[vehicle].Passenger) do
					if Vehicles[vehicle].Passenger[i] > 0 then
						local passenger = Vehicles[vehicle].Passenger[i]
						_PlayerSpectatorEnd(passenger)
						_PlayerRespawn(passenger)
						_EntSetPos(passenger, _EntGetPos(vehicle))
						if VehicleTypes[Vehicles[vehicle].Type].HideHUD ~= nil then
							VehicleTypes[Vehicles[vehicle].Type].HideHUD(passenger)
						end
					end
				end
			end
				if VehicleTypes[Vehicles[vehicle].Type].onRemoved ~= nil then
					VehicleTypes[Vehicles[vehicle].Type].onRemoved(vehicle)
				end
				Vehicles[i] = nil
				_EntRemove(i)
				--VehicleDestroyed(Vehicles[i].Owner, i)
			end
		end
	end
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

function KillUnfrozen(sender, args)
	if not IsJetAdmin(sender) then return end
	for i=1, 4000 do
		if _EntGetName(i) == "unfrozenprop" then
			_EntRemove(i)
			PhysProps[i] = nil
			if PlasmaTurrets[i] then
				PlasmaTurrets[i] = nil
				teams[PlasmaTurrets[i].Team].PlasmaTurrets = teams[PlasmaTurrets[i].Team].PlasmaTurrets-1
			end
			if Mway[i] then
				for	k, x in Mway[i].Children do
					_EntRemove(x)
				end
				Mway[i] = nil
			end
		end
	end
end
CONCOMMAND("killunfrozen", KillUnfrozen)

function fixthefuckingwalls(sender, args)
	if FightMode then
		PlayerLookTrace(sender, 9999)
		if _TraceHitNonWorld() then
			if _EntGetType(_TraceGetEnt()) == "func_wall_toggle" then
				_PrintMessage(sender, 2, "Walls fixed!\n")
				toggleWalls()
			else
				_PrintMessage(sender, 2, "Must be pointing at the dividing walls.\n")
			end
		else
			_PrintMessage(sender, 2, "Must be pointing at the dividing walls.\n")
		end
	else
		_PrintMessage(sender, 2, "Can only use this to debug in CTF Mode.\n")
	end
end
CONCOMMAND("fixthefuckingwalls", fixthefuckingwalls)

function StartCTF()
	for i=1, 4000 do
		if PhysProps[i] and _EntGetName(i) == "unfrozenprop" then
			_EntRemove(i)
			PhysProps[i] = nil
			if PlasmaTurrets[i] then
				PlasmaTurrets[i] = nil
				teams[PlasmaTurrets[i].Team].PlasmaTurrets = teams[PlasmaTurrets[i].Team].PlasmaTurrets-1
			end
			if Mway[i] then
				for	k, x in Mway[i].Children do
					_EntRemove(x)
				end
				Mway[i] = nil
			end
		end
	end
	for entity in PlasmaTurrets do
		_EntFire(entity, "alpha", "255", 0)
		PlasmaTurrets[entity].Health = PLASMATURRETMAXHEALTH
		_TraceLine(_EntGetPos(entity), vecMul(_EntGetUpVector(entity), -1), 14, entity)
		if not _TraceHit() then
			PlasmaTurrets[entity] = nil
			teams[PlasmaTurrets[entity].Team].PlasmaTurrets = teams[PlasmaTurrets[entity].Team].PlasmaTurrets-1
			_EntRemove(entity)
		elseif _TraceHitNonWorld() then
			if _EntGetName(_TraceGetEnt()) ~= "frozenprop" then
				PlasmaTurrets[entity] = nil
				teams[PlasmaTurrets[entity].Team].PlasmaTurrets = teams[PlasmaTurrets[entity].Team].PlasmaTurrets-1
				_EntRemove(entity)	
			end
		end
	end
	toggleWalls()

	HaltTimer(TimeTrack)

	FightMode = true
	CreateFlags()
	fCTF_len = _CurTime() + sCTF_len

	TimeTrack = AddTimer(5, 0, doCountDMLen)

	for i=1, _MaxPlayers() do
		votedskip[i] = false
		if _PlayerInfo(i, "connected") then
			SaveInfo(i)
			if _PlayerInfo(i, "alive") then
				_PlayerRespawn(i)
			end
		end
	end
	SKIPVOTES=0
end

function doCountCTF()
	if CTF_LENGTH < 900 then
		UpdateDMTime(0, math.time(fCTF_time - _CurTime()))
	end
end

function doCountDMLen()
	if CTF_LENGTH < 900 then
		UpdateDMTime(0, math.time(fCTF_len - _CurTime()))
	end
end

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

function GiveDefaultItems(userid)
	if _PlayerInfo(userid, "team") == TEAM_SPECTATOR then return end
	if FightMode then
		_PlayerGiveItem(userid, "weapon_physcannon")
		for i=1, table.getn(Classes[players[userid].Class].SWEPs) do
			_PlayerGiveSWEP(userid, Classes[players[userid].Class].SWEPs[i])
		end
	else
		_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_propmaker2.lua")
		_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_spawn.lua")
		_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_remover.lua")
		_PlayerGiveItem(userid, "weapon_physcannon")
		_PlayerGiveItem(userid, "weapon_physgun")
	end
end

function displayWhoWon()
	local maxpoints = 0
	local winners = {}
	for i in teams do
		if _TeamScore(i) > maxpoints then
			maxpoints = _TeamScore(i)
		end
	end
	for i in teams do
		if _TeamScore(i) >= maxpoints then
			winners[table.getn(winners)+1] = i
		end
	end
	if table.getn(winners) ~= 1 then
		messageInfo(0, 68, 0.2, "It was a tie game")
		return
	end
	if winners[1] == nil then return end
	local winner = winners[1]
	messageInfo(0, 368, 0.2, "The "..TeamToString(winner).." won the game!")
	for i=1, _MaxPlayers() do
		if IsPlayerOnline(i) then
			if _PlayerInfo(i, "team") == winner then
				players[i].money = players[i].money + BONUS_WIN
				drawMoneyAmmount(i)
				_PrintMessage(i, 3, "Your team was given $"..BONUS_WIN.." for winning the match!\n")
			end
		end
	end
end

function EnergyGrenade(prop, userid)
	AddTimer(2.5, 1, EnergyGrenadeExplode, prop, userid)
end

function EnergyGrenadeExplode(prop, userid)
	local ents = _EntitiesFindInSphere(_EntGetPos(prop), 250)
	for i=1, table.getn(ents) do
		if Vehicles[ents[i]] then
			_TraceAttack(ents[i], userid, userid, 310)
		elseif _EntGetType(ents[i]) == "prop_physics" then
			_TraceAttack(ents[i], userid, userid, 200)
		elseif IsPlayer(ents[i]) then
			_TraceAttack(ents[i], userid, userid, _EntGetMaxHealth(ents[i])*0.75 or 75)
		else
			_TraceAttack(ents[i], userid, userid, 75)
		end
	end
	local exp = _EntCreate("env_ar2explosion")
	if exp > 0 then
		_EntSetPos(exp, vecAdd(_EntGetPos(prop), vector3(0, 0, 50)))
		_EntSpawn(exp)
		_EntFire(exp, "explode", "", 0.1)
		_EntEmitSound(exp, "weapons/physcannon/energy_disintegrate5.wav")
		_EntEmitSound(exp, "weapons/mortar/mortar_explode1.wav")
	end
	_EntRemove(prop)
end

function SummonZombie(prop, userid)
	AddTimer(2.5, 1, DoSummonZombie, prop, userid)
end

function DoSummonZombie(prop, userid)
	local exp2 = _EntCreate("npc_zombie")
	if exp2 > 0 then
		_EntSetPos(exp2, vecAdd(_EntGetPos(prop), vector3(0, 0, 20)))
		_EntSpawn(exp2)
		_EntEmitSound(exp2, "ambient/creatures/town_zombie_call1.wav")
		local n = _PlayerInfo(userid, "team")
		_EntFire(exp2, "color", teams[n].color.r.." "..teams[n].color.g.." "..teams[n].color.b, 0)
		_EntFire(exp2, "sethealth", "250", 0)
	end
	_EntRemove(prop)
end

function Certified(userid, name)
	return string.find(players[userid].Certifications, name) ~= nil
end

function SaveInfo(userid)
	NDB.SaveInfo(userid)
end

function ConvertNet(str)
	if str == "UNKNOWN" or str == "STEAM_ID_PENDING" or str == "STEAM_ID_LAN" then return "admin"
	else
		return string.sub(str, 11)
	end
end

function vecAngAngle(v1)
	return vecMul(vecAdd(v1, vector3(1.0, 1.0, 1.0)), vector3(180,180,180))
end

function eventPlayerSpawn(userid)
	Gibbed[userid] = false
	--players[userid].Mana = 100
	_PlayerSetDrawViewModel(userid, true)
	_PlayerGod(userid, not FightMode)
	if players[userid].spawn.x ~= 0 then _EntSetPos(userid, players[userid].spawn) end
	_player.ShouldDropWeapon(userid, RETRO)
	_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
	if RETRO then
		if players[userid].Class ~= 1 then
			players[userid].Class = 1
			_PlayerRespawn(userid)
		end
	end
end

function TeamColor(num)
	if num ~= TEAM_SPECTATOR then
		return teams[num].color.r.." "..teams[num].color.g.." "..teams[num].color.b
	else
		return "255 255 255"
	end
end

function eventPlayerUseEntity(userid, entity)
	if Mouse[userid].On then return true end
	if _EntGetModel(entity) == "models/props_combine/health_charger001.mdl" and _PlayerInfo(userid,"alive") then
		Doheal(userid)
		return true
	elseif _EntGetName(entity) == "mine" and _PlayerInfo(userid,"alive") then
		if _CurTime() < players[userid].lastmine + 0.5 then return false end
		if players[userid].ore < 50 then
			local chance = math.random(1, 10)
			if chance > 6 then
				players[userid].ore = players[userid].ore + 1
				_PrintMessage(userid, 4, "You extract some Jetanium.")
				DrawOre(userid)
			else
				_PrintMessage(userid, 4, "You fail to find any Jetanium.")
			end
			players[userid].lastmine = _CurTime()
		else
			_PrintMessage(userid, 4, "You cannot mine anymore Jetanium.\nPress USE on your flag stand for a reward!")
		end
		return true
	elseif string.sub(_EntGetName(entity), 1, 7) == "orebag:"  and _PlayerInfo(userid,"alive") then
		local num = tonumber(string.sub(_EntGetName(entity), 8))
		if num == nil then return false end
		if players[userid].ore >= 50 then
			_PrintMessage(userid, 4, "You cannot take anymore Jetanium.\nPress USE on your flag stand for a reward!")
		else
			players[userid].ore = players[userid].ore+num
			if players[userid].ore > 50 then
				players[userid].ore = 50
				DrawOre(userid)
			end
			_PrintMessage(userid, 4, "You pick up an ore bag worth "..num.." Jetanium.")
			_EntEmitSound(userid, "ambient/levels/labs/coinslot1.wav")
			_EntRemove(entity)
		end
		return true
	elseif _EntGetName(entity) == string.lower(TeamString(_PlayerInfo(userid,"team"))).."factionstone" and _PlayerInfo(userid,"alive") then
		if players[userid].ore > 0 then
			local oremoney = math.ceil(players[userid].ore*(math.random(375, 575)*0.01))
			if players[userid].GoldMember then oremoney = math.ceil(oremoney*1.25) end
			_PrintMessage(userid, 3, "The quality of the Jetanium yielded $"..oremoney..".")
			players[userid].money = players[userid].money+oremoney
			players[userid].ore = 0
			drawMoneyAmmount(userid)
			_EntEmitSound(userid, "ambient/levels/labs/coinslot1.wav")
		end
		return true
	elseif _EntGetModel(entity) == TELEPORTPADMODEL then
		if TeleportPads[entity] ~= nil then
			if _EntGetModel(TeleportPads[entity]) == TELEPORTPADMODEL then
				if FightMode then
					_TraceLine(_EntGetPos(entity), _EntGetUpVector(entity), 64, entity)
					if _TraceHitNonWorld() then
						if _TraceGetEnt() == userid then
							_EntSetPos(userid, vecAdd(_EntGetPos(TeleportPads[entity]), vecMul(_EntGetUpVector(TeleportPads[entity]), vector3(64,64,80))))
							_EntEmitSoundEx(userid, "ambient/energy/whiteflash.wav", 0.5, 1)
							_EntEmitSoundEx(entity, "ambient/energy/whiteflash.wav", 0.5, 1)
							local effect2 = _EntCreate("point_tesla")
							if effect2 > 0 then
								_EntSetKeyValue(effect2, "m_flRadius", "50")
								_EntSetKeyValue(effect2, "m_SoundName", "DoSpark")
								_EntSetKeyValue(effect2, "m_Color", "255 255 255")
								_EntSetKeyValue(effect2, "texture", "effects/laser1.vmt")
								_EntSetKeyValue(effect2, "beamcount_min", "8")
								_EntSetKeyValue(effect2, "beamcount_max", "12")
								_EntSetKeyValue(effect2, "thick_min", "2")
								_EntSetKeyValue(effect2, "thick_max", "12")
								_EntSetKeyValue(effect2, "lifetime_min", "0.3")
								_EntSetKeyValue(effect2, "lifetime_max", "0.9")
								_EntSetKeyValue(effect2, "interval_min", "0.1")
								_EntSetKeyValue(effect2, "interval_max", "0.25")
								_EntSetPos(effect2, _EntGetPos(entity))
								_EntSpawn(effect2)
								_EntActivate(effect2)
								_EntFire(effect2, "DoSpark", "", 0.1)
								_EntFire(effect2, "kill", "", 0.3)
							end
							local effect2 = _EntCreate("point_tesla")
							if effect2 > 0 then
								_EntSetKeyValue(effect2, "m_flRadius", "50")
								_EntSetKeyValue(effect2, "m_SoundName", "DoSpark")
								_EntSetKeyValue(effect2, "m_Color", "255 255 255")
								_EntSetKeyValue(effect2, "texture", "effects/laser1.vmt")
								_EntSetKeyValue(effect2, "beamcount_min", "8")
								_EntSetKeyValue(effect2, "beamcount_max", "12")
								_EntSetKeyValue(effect2, "thick_min", "2")
								_EntSetKeyValue(effect2, "thick_max", "12")
								_EntSetKeyValue(effect2, "lifetime_min", "0.3")
								_EntSetKeyValue(effect2, "lifetime_max", "0.9")
								_EntSetKeyValue(effect2, "interval_min", "0.1")
								_EntSetKeyValue(effect2, "interval_max", "0.25")
								_EntSetPos(effect2, _EntGetPos(TeleportPads[entity]))
								_EntSpawn(effect2)
								_EntActivate(effect2)
								_EntFire(effect2, "DoSpark", "", 0.1)
								_EntFire(effect2, "kill", "", 0.3)
							end
						end
					end
				else
					_PrintMessage(userid, 4, "You can't use this during build mode.")
				end
			end
		end
		return false
	elseif _EntGetModel(entity) == DOORMODEL2 then
		if PhysProps[entity].Team == _PlayerInfo(userid,"team") or Classes[players[userid].Class].Name == "assassin" then
			_EntEmitSound(entity, "buttons/lever4.wav")
			_EntSetModel(entity, DOORMODEL1)
		else
			_PlaySoundPlayer(userid, "buttons/button8.wav")
		end
	elseif _EntGetModel(entity) == DOORMODEL1 then
		if PhysProps[entity].Team == _PlayerInfo(userid,"team") or Classes[players[userid].Class].Name == "assassin" then
			_EntEmitSound(entity, "buttons/lever4.wav")
			_EntSetModel(entity, DOORMODEL2)
		else
			_PlaySoundPlayer(userid, "buttons/button8.wav")
		end
	elseif _EntGetModel(entity) == VEHICLEPADMODEL then
		if not FightMode then
			_PlaySoundPlayer(userid, "buttons/button8.wav")
			_PrintMessage(userid, 4, "You can't use this during building mode.")
			return false
		end
		if not PhysProps[entity] then return false end
		if PhysProps[entity].Team == _PlayerInfo(userid,"team") or string.find(_EntGetName(entity), "vehiclepad") ~= nil then
			for i in Vehicles do
				if Vehicles[i].Owner == userid then
					_PlaySoundPlayer(userid, "buttons/button8.wav")
					_PrintMessage(userid, 4, "You already have a vehicle spawned.")
					return
				end
			end
			VehiclePadMenu(userid, entity)
		else
			_PlaySoundPlayer(userid, "buttons/button8.wav")
			_PrintMessage(userid, 4, "You can't use another team's vehicle pad.")
		end
	elseif Vehicles[entity] ~= nil then
		ProcessVehicleEntry(userid, entity)
	elseif Mway[entity] then
		_TraceLine(_PlayerGetShootPos(userid), _PlayerGetShootAng(userid), 90, {userid, Mway[entity].Children[1]})
		if _TraceGetEnt() == entity then
			if Mway[entity].State == true then
				MwayRetract(entity)
			else
				MwayExtend(entity)
			end
		end
	end
end

function eventKeyPressed(userid, in_key)
	if players[userid].Invisible then
		if in_key == IN_ATTACK then
			local unin = false
			if Classes[players[userid].Class].Name == "mage" then
				unin = not _PlayerIsKeyDown(userid, IN_ATTACK2)
			else
				unin = true
			end
			for i in teams do
				if teams[i] ~= nil then
					if teams[i].flagCarrier == userid then unin = true break end
				end
			end
			if unin then
				players[userid].Invisible = false
				_EntEmitSound(userid, "nox/invisoff.wav")
				_EntSetMaterial(userid, "")
				_EntFire(userid, "alpha", "255", 0)
				_PlayerSetDrawWorldModel(userid, true)
			end
		end
	end
end

function onTakeDamage(ent, inflictor, attacker, damage)
	if IsPlayer(ent) then
		if players[ent].Invisible then
			players[ent].Invisible = false
			_EntFire(ent, "alpha", "255", 0)
			_EntEmitSound(ent, "nox/invisoff.wav")
			_EntSetMaterial(ent, "")
			_PlayerSetDrawWorldModel(ent, true)
		end
		if damage >= _PlayerInfo(ent, "health")+30 then
			if _PlayerInfo(ent, "armor") < 10 then
				if IsPlayer(attacker) then
					if _PlayerInfo(attacker, "team") ~= _PlayerInfo(ent, "team") or ent == attacker then
						Gib(ent)
					end
				else
					Gib(ent)
				end
			end
		end
	end
end

function math.frandom(minn, maxn)
	minn = minn * 100
	maxn = maxn * 100
	return math.random(minn, maxn)*0.01
end

function CreateOreBag(num, vec)
	_EntPrecacheModel("models/props_junk/garbage_bag001a.mdl")
	local prop = _EntCreate("prop_physics")
	if prop > 0 then
		_EntSetPos(prop, vecAdd(vec, vector3(0,0,10)))
		_EntSetName(prop, "orebag:"..num)
		_EntSetModel(prop, "models/props_junk/garbage_bag001a.mdl")
		_EntSetMaterial(prop, "gmod/shiny")
		_EntSetCollisionGroup(prop, 4)
		_EntSpawn(prop)
		_EntFire(prop, "color", "255 0 0", 0)
		_EntFire(prop, "kill", "", 30)
	end
end

function DrawOre(userid)
	_GModRect_Start( "gmod/white" )
	 _GModRect_SetPos( 0.75, 0.53, 0.18, 0.05 )
	 _GModRect_SetColor( 0, 0, 0, 100 )
	 _GModRect_SetTime( 3, 0.4, 0.4 )
	_GModRect_Send( userid, 9877 )
	_GModText_Start( "Default" )
	 _GModText_SetPos( 0.785, 0.55 )
	 _GModText_SetColor( 255, 0, 0, 255 )
	 _GModText_SetTime( 3, 0.4, 0.4 )
	 _GModText_SetText( "Jetanium: "..players[userid].ore.."/50")
	_GModText_Send( userid, 9878 )
end

function eventPlayerKilled(killed, attacker, weapon)
	if FightMode then
		_PlayerAddDeath(killed, 1)
		if killed == attacker then
			_PlayerAddScore(killed, -1)
		elseif IsPlayer(attacker) then
			_file.Write("noxiousprofiles/"..TeamString(_PlayerInfo(attacker,"team")).."totalkills.txt", tonumber(_file.Read("noxiousprofiles/"..TeamString(_PlayerInfo(attacker,"team")).."totalkills.txt"))+1)
			local moneytoadd = MONEY_KILL_AMOUNT + Classes[players[killed].Class].KillBonus
			if players[attacker].GoldMember then moneytoadd = math.ceil(moneytoadd*1.25) end
			players[attacker].money = players[attacker].money + moneytoadd
			drawMoneyAmmount(attacker)
			_PlayerAddScore(attacker, 1)
		end
		if players[killed].ore > 0 then
			CreateOreBag(players[killed].ore, _EntGetPos(killed))
			players[killed].ore = 0
			_PrintMessage(killed, 3, "You dropped all of your ore.")
		end

		for i in teams do
			if teams[i] ~= nil then
				if teams[i].flagCarrier == killed then teams[i].flagCarrier = 0 break end
			end
		end
	end
	--_EntEmitSound(killed, "ambient/voices/citizen_beaten"..math.random(1,5)..".wav")
	if Mouse[killed].On then eventMouseClicked(killed, 100, 100) end
	_EntEmitSoundEx(killed, "nox/player_death.wav", 1.3, 1.0)
end

function onPhysFreeze(player, entity)
	if not playerCanUse(player, entity) then _PrintMessage(player, 4, "You can't freeze another person's prop!\n") return false end
	if _EntGetType(entity) == "func_wall_toggle" then return false end
	if _EntGetType(entity) == "prop_physics" then
		for i in teams do
			if teams[i] ~= nil then
				if IsInRadius(entity, teams[i].flagpoint, 125) then
					_PrintMessage(player, 4, "Too close to flag stand to freeze.\n")
					return false
				end
			end
		end
		_TraceLine(_EntGetPos(teams[_PlayerInfo(player,"team")].flagpoint), vector3(0,0,1), 125, player)
		if _TraceHitNonWorld() then
			if _TraceGetEnt() == entity then 
				_PrintMessage(player, 4, "Too close to flag stand to freeze.\n")
				return false
			end
		end
		if PlasmaTurrets[entity] then
			_TraceLine(_EntGetPos(entity), vecMul(_EntGetUpVector(entity), -1), 14, entity)
			if not _TraceHit() then
				_PrintMessage(player, 4, "The turret's base must be fixed to something solid.\n")
				return false
			elseif _TraceHitNonWorld() then
				if _EntGetName(_TraceGetEnt()) ~= "frozenprop" then
					_PrintMessage(player, 4, "The turret's base must be fixed to something solid.\n")
					return false
				end
			end
		end
		_EntSetName(entity, "frozenprop")
		local n = _PlayerInfo(player, "team")
		_EntFire(entity, "color", teams[n].color.r.." "..teams[n].color.g.." "..teams[n].color.b, 0)
	end
	return true
end

function onPhysPickup( player, entity )
	if FightMode then return false end
	if not playerCanUse(player, entity) then _PrintMessage(player, 4, "You can't move another person's prop!\n") return false end
	_EntSetName(entity, "unfrozenprop")
	_EntFire(entity, "color", "255 255 255", 0)
	return true
end

function onPhysUpright(player, entity)
	if FightMode then return false end
	if _EntGetName(entity) == "frozenprop" then return false end
	if not playerCanUse(player, entity) then return false end
	local mytype = _EntGetType(entity)
	if string.find(mytype, "prop_") ~= nil
		and mytype ~= "prop_detail"
		and mytype ~= "prop_static"
		and mytype ~= "prop_thumper" then
		return true
	end
	return false
end

function onGravGunPunt(player, entity)
	if FightMode then
		return _EntGetName(entity) ~= "flag" and _EntGetName(entity) ~= "frozenprop"
	end
	return playerCanUse(player, entity) and _EntGetName(entity) ~= "frozenprop" and not Vehicles[entity]
end

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

function onGravGunPickup(player, entity)
	if Vehicles[entity] then return false end
	if FightMode then
		if _EntGetName(entity) ~= "frozenprop" and _EntGetName(entity) ~= "flag" then
			return true
		elseif _EntGetName(entity) == "flag" then
			for i in teams do
				if teams[i] ~= nil then
					if entity == teams[i].flag then
						if _PlayerInfo(player, "team") ~= i then
							if _TeamNumPlayers(i) > 0 then
								teams[i].flagCarrier = player
								_PlaySound("jbb/ballsnatch.mp3")
								PrintMessageAll(_PlayerInfo(player, "name").." took the "..teams[i].name.." flag.", teams[i].color.r, teams[i].color.g, teams[i].color.b, 255)
								return true
							else
								_PrintMessage(player, 4, "You can't take the flag of an unrepresented team!")
								return false
							end
						else
							if IsInRadius(teams[i].flag, teams[i].flagpoint, 100) then return false end
							teams[i].flagCarrier = 0
							_PlaySound("weapons/physcannon/energy_bounce1.wav")
							if IsInRadius(teams[i].flag, teams[i].flagpoint, 1024) then
								PrintMessageAll(_PlayerInfo(player, "name").." gently put the "..teams[i].name.." flag back on the stand.", teams[i].color.r, teams[i].color.g, teams[i].color.b, 255)
							else
								PrintMessageAll(_PlayerInfo(player, "name").." returned the "..teams[i].name.." flag.", teams[i].color.r, teams[i].color.g, teams[i].color.b, 255)
								NDB.AddMoney(player, 250, false)
							end
							_EntSetPos(teams[i].flag, _EntGetPos(teams[i].flagpoint))
							return false						
						end
					end
				end
			end
		end
		return false
	end
	if not playerCanUse(player, entity) then return false end
	
	_EntSetName(entity, "unfrozenprop")
	_EntFire(entity, "color", "255 255 255", 0)
	return true
end

function onGravGunDrop(player, entity)
	for i in teams do
		if teams[i].flag == entity then
			teams[i].flagCarrier = 0
			_PlaySound("weapons/physcannon/energy_sing_flyby1.wav")
			PrintMessageAll("Team "..TeamString(_PlayerInfo(player, "team")).." dropped the "..teams[i].name.." flag.", teams[i].color.r, teams[i].color.g, teams[i].color.b, 255)
			return true
		end
	end
	return true
end

function onGravGunLaunch(player, entity)
	return _EntGetName(entity) ~= "flag"
end

function TeamString(intt)
	if intt == TEAM_RED then return "Red"
	elseif intt == TEAM_BLUE then return "Blue"
	elseif intt == TEAM_GREEN then return "Green"
	elseif intt == TEAM_YELLOW then return "Yellow"
	else return "Spectator" 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 PrintMessageAll(msg, r, g, b, a)
	PrintMessage(0, msg, r, g, b, a)
end

function canPlayerHaveItem(playerid, itemname)
	return _PlayerInfo(playerid, "team") > 1
end

function eventPlayerActive(name, userid, steamid)
	LoadSpawnMenu(userid)
	_EntSetKeyValue(userid, "rendermode", "1")
	players[userid].spawn = vector3(0, 0, 0)
	players[userid].money = STARTING_MONEY
	players[userid].Class = 1
	players[userid].LASTPROP = 0
	players[userid].lastmine = 0
	players[userid].ore = 0
	players[userid].PropSelection = 1
	players[userid].Certifications = "gunslinger"
	_PlayerSetDrawTeamCircle(userid, false)
	AddTimer(1, 1, onShowTeam, userid)
	InitialScores(userid)
	UpdateScores(userid)
	if FightMode then
		for i in teams do
			_GModRect_Start( "noxctf/flagicon")
			 _GModRect_SetPos(0, 0, 0.035, 0.035)
			 _GModRect_SetTime(99999, 0, 0)
			 _GModRect_SetColor(teams[i].color.r, teams[i].color.g, teams[i].color.b, 230)
			 _GModRect_SetDelay(0)
			 _GModRect_SetEntityOffset(vector3(0, 0, 16))
			 _GModRect_SetEntity(teams[i].flag)
			_GModRect_Send(userid, 99+i)
		end
	end
	AddTimer(45, 1, AutoChooseTeam, userid)
end

function toggleWalls()
	local walls = _EntitiesFindByClass("func_wall_toggle")
	for i,v in walls do
		_EntFire(v, "toggle", 0, 0)
	end
end

function setSpawnPoint(Owner)
	if FightMode then return end
	players[Owner].spawn = _EntGetPos(Owner)
	message(Owner, 98, -1, 0.3, 4, "Your spawn point has been set")
end

function resetSpawnPoint(userid)
	if userid > 0 and userid <= _MaxPlayers() then
		players[userid].spawn = vector3(0,0,0)		
		message(userid, 98, -1, 0.3, 4, "Your spawn point has been reset")
	end
end

function ResetSpawn(sender, args)
	resetSpawnPoint(sender)
end
CONCOMMAND("resetspawn", ResetSpawn)

function CreateFlags()
	for i in teams do
		local prop = _EntCreate("prop_physics")
		if prop > 0 then
			_EntSetKeyValue(prop, "model", "models/Roller_Spikes.mdl")
			_EntSetPos(prop, _EntGetPos(teams[i].flagpoint))
			_EntSpawn(prop)
			_EntFire(prop, "Color", teams[i].color.r.." "..teams[i].color.g.." "..teams[i].color.b, 0)
			local fire = _EntCreate("env_smoketrail")
			_EntSetKeyValue(fire, "firesprite", "sprites/glow02.spr")
			_EntSetKeyValue(fire, "smokesprite", "sprites/physcannon_blueflare1.spr")
			_EntSetPos(fire, _EntGetPos(prop))
			_EntSpawn(fire)
			_EntSetName(prop, "flag")
			_EntSetParent(fire, prop)
			_GModRect_Start( "noxctf/flagicon")
			_GModRect_SetPos(0, 0, 0.035, 0.035)
			_GModRect_SetTime(99999, 0, 0)
			_GModRect_SetColor(teams[i].color.r, teams[i].color.g, teams[i].color.b, 230)
			_GModRect_SetDelay(0)
			_GModRect_SetEntityOffset(vector3(0, 0, 16))
			_GModRect_SetEntity(prop)
			_GModRect_Send(0, 97+i)
			_phys.SetMass(prop, 250)
			teams[i].flag = prop
			AttatchTrail(prop, teams[i].color.r.." "..teams[i].color.g.." "..teams[i].color.b)
		end
	end
end

function isFlagCarrier(userid)
	for i in teams do
		if teams[i].flagcarrier == userid then return true end
	end
	return false
end

function playerCanUse(player, entity)
	if PhysProps[entity] then
		return ((PhysProps[entity].Team == _PlayerInfo(player, "team") and PhysProps[entity].Owner == player) or IsJetAdmin(player)) or _PlayerInfo(PhysProps[entity].Owner, "team") ~= PhysProps[entity].Team
	end
	return false
end

function SM_MakeProp(sender, args)
	if FightMode then return end
	if _CurTime() < players[sender].LastSpawn+0.5 then return end
	args = tonumber(args) if args == nil then return end
	if args < 0 or args > table.getn(PropSpawn) then return end
	if _PlayerInfo(sender, "team") < TEAM_BLUE then return end
	players[sender].PropSelection = args
	PlayerLookTrace(sender, 200)
	local hitpos = vecAdd(_TraceEndPos(), vector3(0, 0, 40))
	players[sender].LastSpawn = _CurTime()
	MakeProp(sender, hitpos.x, hitpos.y, hitpos.z)
end
CONCOMMAND("makeprop", SM_MakeProp)

function LoadSpawnMenu(userid)
	_spawnmenu.RemoveAll(userid)
	_spawnmenu.AddItem(userid, "Quick Menu", "@Props", "")
	for i=1, table.getn(PropSpawn) do
		_spawnmenu.AddItem(userid, "Quick Menu", "+"..PropSpawn[i].Name.." - $"..PropSpawn[i].Price, "makeprop "..i)
	end
end

function MakeProp(Owner, posx, posy, posz)
	if FightMode then return end
	if players[Owner].PropSelection <= 0 or players[Owner].PropSelection > table.getn(PropSpawn) then players[Owner].PropSelection = 1 end
	if teams[_PlayerInfo(Owner, "team")].props >= MAXPROPS then
		_PrintMessage(Owner, 4, "Your team's prop limit has been reached.\nRemove some props to make room for more.")
		DrawCurrentTeamProps(Owner)
		return
	end
	if _EntExists(players[Owner].LASTPROP) then
		if _EntGetType(players[Owner].LASTPROP) == "prop_physics" then
			if _EntGetName(players[Owner].LASTPROP) == "unfrozenprop" and PhysProps[players[Owner].LASTPROP].Owner == Owner then
				removeProp(Owner, players[Owner].LASTPROP)
			end
		end
	end
	if players[Owner].money >= PropSpawn[players[Owner].PropSelection].Price then
		players[Owner].money = players[Owner].money - PropSpawn[players[Owner].PropSelection].Price
		drawMoneyAmmount(Owner)
	else
		_PrintMessage(Owner, 4, "Not enough money to create this!")
		return
	end
	_EntPrecacheModel(PropSpawn[players[Owner].PropSelection].Model)
	local prop = _EntCreate("prop_dynamic_override")
	if prop > 0 then
		_EntSetModel(prop, PropSpawn[players[Owner].PropSelection].Model)
		_EntSetKeyValue(prop, "solid", "6")
		local plyang = _EntGetAng(Owner)
		_EntSetPos(prop, vector3(posx, posy, posz))
		_EntSetAng(prop, vector3(plyang.x, plyang.y, 0))
		_EntSpawn(prop)
		_EntSetName(prop, "unfrozenprop")
		teams[_PlayerInfo(Owner, "team")].props = teams[_PlayerInfo(Owner, "team")].props+1
		PhysProps[prop] = {}
		PhysProps[prop].Team = _PlayerInfo(Owner, "team")
		PhysProps[prop].Owner = Owner
		if PropSpawn[players[Owner].PropSelection].Price <= 0 then
			if RETRO then
				_EntFire(prop, "SetHealth", "5000", 0)
			else
				_EntFire(prop, "SetHealth", "1000", 0)
			end
		end
		DrawCurrentTeamProps(Owner)
		players[Owner].LASTPROP = prop
	end
end

function CycleProp(userid)
	local num = players[userid].PropSelection
	if num < table.getn(PropSpawn) then
		num = players[userid].PropSelection+1
	else
		num = 1
	end
	_PrintMessage(userid, 4, "Prop selection: "..PropSpawn[num].Name.."\n        Price: $"..PropSpawn[num].Price)
	players[userid].PropSelection = num
end

function DrawCurrentTeamProps(userid)
	_GModRect_Start( "gmod/white" )
	 _GModRect_SetPos( 0.435, 0.83, 0.13, 0.05 )
	 _GModRect_SetColor( 0, 0, 0, 100 )
	 _GModRect_SetTime( 3, 0.4, 0.4 )
	_GModRect_Send( userid, 9875 )
	_GModText_Start( "Default" )
	 _GModText_SetPos( 0.45, 0.85 )
	 _GModText_SetColor( 0, 255, 0, 255 )
	 _GModText_SetTime( 3, 0.4, 0.4 )
	 _GModText_SetText( "Props: "..teams[_PlayerInfo(userid, "team")].props.."/"..MAXPROPS)
	_GModText_Send( userid, 9876 )
end

function moveProp(Owner, entity, vector)
	if not PhysProps[entity] then return end
	if not players[PhysProps[entity].Owner] then return end
	local prevmoney = players[PhysProps[entity].Owner].money
	if playerCanUse(Owner, entity) or not IsPlayerOnline(Owner) then
		if _EntGetType(entity) == "prop_dynamic" then
			PlayerMove(entity, vector)
		end
	else
		_PrintMessage(Owner, 4, "You can't move another person's prop!\n")
	end
end

function rotateProp(Owner, entity, vector)
	if not PhysProps[entity] then return end
	if not players[PhysProps[entity].Owner] then return end
	local prevmoney = players[PhysProps[entity].Owner].money
	if playerCanUse(Owner, entity) or not IsPlayerOnline(Owner) then
		if _EntGetType(entity) == "prop_dynamic" then
			_EntSetAng(entity, vecAdd(_EntGetAng(entity), vector))
		end
	else
		_PrintMessage(Owner, 4, "You can't rotate another person's prop!\n")
	end
end

function selectProp(Owner, entity)
	if not PhysProps[entity] then return end
	if not players[PhysProps[entity].Owner] then return end
	local prevmoney = players[PhysProps[entity].Owner].money
	if playerCanUse(Owner, entity) or not IsPlayerOnline(Owner) then
		if _EntGetType(entity) == "prop_dynamic" then
			_SWEPRunString(_PlayerGetActiveWeapon(Owner), "myEntity="..entity)
			_PlayerLockInPlace(Owner, false)
			_GModText_Start("BrandingSmall")
			 _GModText_SetColor(255, 0, 0, 255)
			 _GModText_SetTime(30, 0.25, 0.25)
			 _GModText_SetEntityOffset(vector3(0, 0, 16 ))
			 _GModText_SetEntity(entity)
			 _GModText_SetText("[ Selection ]")
			_GModText_Send( 0, 6668)
		end
	else
		_PrintMessage(Owner, 4, "This isn't your prop!\n")
	end
end

function removeProp(Owner, entity)
	if not PhysProps[entity] then return end
	if not players[PhysProps[entity].Owner] then return end
	local prevmoney = players[PhysProps[entity].Owner].money
	if playerCanUse(Owner, entity) or not IsPlayerOnline(Owner) then
		if _EntGetType(entity) == "prop_physics" then
			for i=1, table.getn(PropSpawn) do
				if _EntGetModel(entity) == PropSpawn[i].Model then
					players[PhysProps[entity].Owner].money = players[PhysProps[entity].Owner].money + PropSpawn[i].Price
					if players[PhysProps[entity].Owner].money > prevmoney then
						drawMoneyAmmount(PhysProps[entity].Owner)
					end
					_EntRemove(entity)
					teams[PhysProps[entity].Team].props = teams[PhysProps[entity].Team].props-1
					PhysProps[entity] = nil
					DrawCurrentTeamProps(Owner)
					return
				end
			end
		end
		if _EntGetModel(entity) == TELEPORTPADMODEL then
			players[PhysProps[entity].Owner].money = players[PhysProps[entity].Owner].money + TELEPORTPADPRICE
			if players[PhysProps[entity].Owner].money > prevmoney then
				NDB.drawMoneyAmmount(PhysProps[entity].Owner)
			end
			local entity2 = TeleportPads[entity]
			_EntRemove(entity2)
			_EntRemove(entity)
			TeleportPads[entity] = nil
			TeleportPads[entity2] = nil
			teams[PhysProps[entity].Team].props = teams[PhysProps[entity].Team].props-2
			PhysProps[entity] = nil
			PhysProps[entity2] = nil
			DrawCurrentTeamProps(Owner)
		elseif _EntGetModel(entity) == DOORMODEL1 or _EntGetModel(entity) == DOORMODEL2 then
			players[PhysProps[entity].Owner].money = players[PhysProps[entity].Owner].money + DOORPRICE
			if players[PhysProps[entity].Owner].money > prevmoney then
				NDB.drawMoneyAmmount(PhysProps[entity].Owner)
			end
			_EntRemove(entity)
			teams[PhysProps[entity].Team].props = teams[PhysProps[entity].Team].props-1
			PhysProps[entity] = nil
			DrawCurrentTeamProps(Owner)
		elseif _EntGetModel(entity) == HEALINGPADMODEL then
			players[PhysProps[entity].Owner].money = players[PhysProps[entity].Owner].money + HEALINGPADPRICE
			if players[PhysProps[entity].Owner].money > prevmoney then
				NDB.drawMoneyAmmount(PhysProps[entity].Owner)
			end
			_EntRemove(entity)
			teams[PhysProps[entity].Team].props = teams[PhysProps[entity].Team].props-1
			PhysProps[entity] = nil
			DrawCurrentTeamProps(Owner)
		elseif _EntGetModel(entity) == VEHICLEPADMODEL then
			players[PhysProps[entity].Owner].money = players[PhysProps[entity].Owner].money + VEHICLEPADPRICE
			if players[PhysProps[entity].Owner].money > prevmoney then
				NDB.drawMoneyAmmount(PhysProps[entity].Owner)
			end
			_EntRemove(entity)
			teams[PhysProps[entity].Team].props = teams[PhysProps[entity].Team].props-1
			PhysProps[entity] = nil
			DrawCurrentTeamProps(Owner)
		elseif _EntGetModel(entity) == PLASMATURRETMODEL then
			players[PhysProps[entity].Owner].money = players[PhysProps[entity].Owner].money + PLASMATURRETPRICE
			if players[PhysProps[entity].Owner].money > prevmoney then
				NDB.drawMoneyAmmount(PhysProps[entity].Owner)
			end
			_EntRemove(entity)
			teams[PhysProps[entity].Team].props = teams[PhysProps[entity].Team].props-1
			teams[PhysProps[entity].Team].PlasmaTurrets = teams[PhysProps[entity].Team].PlasmaTurrets - 1
			PhysProps[entity] = nil
			DrawCurrentTeamProps(Owner)
			PlasmaTurrets[entity] = nil
		elseif Mway[entity] then
			players[PhysProps[entity].Owner].money = players[PhysProps[entity].Owner].money + EXTENDINGBRIDGEPRICE
			if players[PhysProps[entity].Owner].money > prevmoney then
				NDB.drawMoneyAmmount(PhysProps[entity].Owner)
			end
			for k, i in Mway[entity].Children do
				_EntRemove(i)
			end
			_EntRemove(entity)
			teams[PhysProps[entity].Team].props = teams[PhysProps[entity].Team].props-1
			PhysProps[entity] = nil
			DrawCurrentTeamProps(Owner)
			Mway[entity] = nil
		end
	else
		_PrintMessage(Owner, 4, "You can't delete another person's prop!\n")
	end
end

function sendmessage(userid, key, posx, posy, r, g, b, stime, text)
	_GModText_Start("HudHintTextLarge")
		_GModText_SetPos(posx, posy)
		_GModText_SetColor(r, g, b, 255)
		_GModText_SetTime(stime, 0.5, 1.5)
		_GModText_SetText(text)
		_GModText_SetDelay(0)
	_GModText_Send(userid, key)
end

function message(userid, key, posx, posy, stime, text)
	sendmessage(userid, key, posx, posy, 255, 255, 255, stime, text)
end

function messageMenu(userid, key, posx, posy, stime, text)
	sendmessage(userid, key, posx, posy, 255, 200, 50, stime, text)
end

function messageAttn(userid, key, posx, posy, stime, text)
	sendmessage(userid, key, posx, posy, 255, 0, 0, stime, text)
end

function messageInfo(userid, key, posy, text)
	_GModText_Start("TargetID")
		_GModText_SetPos(-1, posy)
		_GModText_SetColor(255, 255, 255, 255)
		_GModText_SetTime(8, 0.5, 1.5)
		_GModText_SetText(text)
		_GModText_SetDelay(0)
	_GModText_Send(userid, key)
end

function stopPlayer (userid, stop)
	if stop then
		_PlayerSetMaxSpeed(userid, 1)
	else
		_PlayerSetMaxSpeed(userid, 200)
	end
	_PlayerEnableSprint(userid, not stop)
end

function stopPlayersAll (stop)
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "alive") and _PlayerInfo(i, "connected") then
			stopPlayer(i, stop)
		end
	end
end

function removeAllPlayersWeapons ()
	for i=1, _MaxPlayers() do
		if _PlayerInfo(i, "alive") and _PlayerInfo(i, "connected") then
			_PlayerRemoveAllWeapons(i)
		end
	end
end

function removeAllProps()
	local props = _EntitiesFindByClass("prop_physics")
	for i, v in props do
		if PhysProps[v] then
			_EntRemove(v)
		end
	end
	PlasmaTurrets = {}
	Mway = {}
	PhysProps = {}
end

function math.round( num, idp )
	return tonumber( string.format("%."..idp.."f", num ) )
end

function math.time( num )
	if num then
		if num <= 0 then return "00:00" end
		
		local minutes = (num / 60)
		local mins = string.format("%.2i",math.floor(minutes))
		local secs = string.format("%.2i",math.floor ((minutes - mins) * 60))
		return mins .. ":" .. secs
	else
		return "error"
	end
end

function PrestigeClassesMenu(playerid, num)
	for i=109, table.getn(Classes)+111 do
		_GModText_Hide(playerid, i, 0.9)
	end
	if num <= table.getn(Classes) and num > 0 then
		Mouse[playerid].Data = num
		_GModText_Start("TargetID")
		 _GModText_SetPos(-1.0, 0.5)
		 _GModText_SetColor(255, 50, 0, 255)
		 _GModText_SetTime(99999, 0, 0)
		 if Certified(playerid, Classes[num].Name) then
			_GModText_SetText("Switch class to a "..Classes[num].DisplayName.."?\n[1] Yes      [2] No")
		 else
			_GModText_SetText("Buy a "..Classes[num].DisplayName.." for $"..Classes[num].Value.."?\n[1] Yes      [2] No")
		 end
		_GModText_Send(playerid, 31000)
		_PlayerOption(playerid, "AreYouSure", 9999)
	end
end

function AreYouSure(userid, num, seconds)
	_GModText_Hide(userid, 31000, 0.1)
	if num == 1 then
		if players[userid].Class == tonumber(Mouse[userid].Data) then
			_PrintMessage(userid, 4, "You are already a "..Classes[tonumber(Mouse[userid].Data)].DisplayName.."!")
		elseif Certified(userid, Classes[tonumber(Mouse[userid].Data)].Name) then
			players[userid].Class = tonumber(Mouse[userid].Data)
			_PlayerRespawn(userid)
			_PrintMessage(userid, 4, "You are now a "..Classes[tonumber(Mouse[userid].Data)].DisplayName.."!")
		elseif players[userid].money >= Classes[tonumber(Mouse[userid].Data)].Value then
			players[userid].money = players[userid].money-Classes[tonumber(Mouse[userid].Data)].Value
			players[userid].Class = tonumber(Mouse[userid].Data)
			players[userid].Certifications = players[userid].Certifications..Classes[tonumber(Mouse[userid].Data)].Name
			SaveInfo(userid)
			_PlayerRespawn(userid)
			_PrintMessage(userid, 4, "You are now a certified "..Classes[tonumber(Mouse[userid].Data)].DisplayName.."!")
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough cash.")
		end
	else
		_PrintMessage(userid, 4, "Canceled.")
	end
end

function onShowSpare1(userid)
	if teams[_PlayerInfo(userid,"team")] == nil then return end
	if RETRO then _PrintMessage(userid, 3, "Disabled during Retro mode.") return end
	if FightMode then
		if not IsInRadius(userid, teams[_PlayerInfo(userid,"team")].flagpoint, 200) then
			_PrintMessage(userid, 4, "You must be near your flag\n during CTF to switch classes!")
			return
		end
	end
	local xpos = 0.2
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.2)
		_GModText_SetColor(255, 50, 0, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("Prestige Classes + Certifications")
	_GModText_Send(userid, 109)

	local x = 1
	for i=1, table.getn(Classes) do
		_GModText_Start("DefaultShadow")
		 _GModText_SetPos(xpos, 0.27+(x*0.03))
		 if Certified(userid, Classes[i].Name) then
			_GModText_SetColor(255, 255, 255, 255)
		 elseif players[userid].money >= Classes[i].Value then
			_GModText_SetColor(0, 255, 0, 255)
		 else
			_GModText_SetColor(255, 30, 0, 255)
		 end
		 _GModText_SetTime(99999, 0, 0)
		 if Certified(userid, Classes[i].Name) then
			_GModText_SetText("[ ] "..x..". (CERTIFIED) - "..Classes[i].DisplayName)
		 else
			_GModText_SetText("[ ] "..x..". ("..Classes[i].Value..") "..Classes[i].DisplayName..": "..Classes[i].Desc)
		 end
		_GModText_Send(userid, 109+x)
		x = x+1
	end
		
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.75)
		_GModText_SetColor(255, 0, 0, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("[ ] Exit Menu")
	_GModText_Send(userid, table.getn(Classes)+110)
	MouseOn(userid, xpos, 0.9)
	Mouse[userid].Data = "classmenu"
end

function eventMouseClicked(userid, x, y)
	if Mouse[userid].Data == "classmenu" then
		for i=1, table.getn(Classes) do
			if MouseNear(userid, 0.05, 0.195, 0.25+(i*0.029)) then
				MouseOff(userid)
				PrestigeClassesMenu(userid, i)
				return
			end
		end
		MouseOff(userid)
	elseif string.find(Mouse[userid].Data, "vehiclemenu:") ~= nil then
		local vehiclepad = tonumber(string.sub(Mouse[userid].Data, 13))
		local x = 0
		for i in VehicleTypes do
			x = x+1
			if MouseNear(userid, 0.05, 0.045, 0.25+(x*0.029)) then
				MouseOff(userid)
				VehicleSelect(userid, i)
				return
			end
		end
		MouseOff(userid)
	end
	for i=109, table.getn(Classes)+111 do
		_GModText_Hide(userid, i, 0.9)
	end
end

function onShowSpare2 (userid)
	if _PlayerInfo(userid, "team") == TEAM_SPECTATOR or not _PlayerInfo(userid, "alive") then return end
	--[[if Classes[players[userid].Class].Name ~= "gunslinger" and FightMode then return end
	if FightMode then
		if not IsInRadius(userid, teams[_PlayerInfo(userid, "team")].flagpoint, 350) then
			_PrintMessage(userid, 4, "Too far away from flag stand to buy.")
			return
		end
		buyMenu(userid)
		]]
	if not FightMode then
		buildbuyMenu(userid)
	end
end

function onShowHelp(userid)
	_GModText_Hide( userid, 0, 0.5 )
	_GModRect_Hide( userid, 0, 0.5 )
	_GModText_Hide( userid, 1, 0.5 )
	_GModText_Hide( userid, 2, 0.5 )
	_GModRect_Hide( userid, 2, 0.5 )

	messageMenu(userid,50, 0.30, 0.30, 20, "[HELP]")
	message(userid,51, 0.35, 0.35, 15, "  [ BUILD ]")
	message(userid,52, 0.35, 0.38, 16, "Build your forts by utilizing the available props with the spawn menu.")
	message(userid,53, 0.35, 0.41, 17, "Freeze props with the physgun. USE to rotate while holding. Sprint to upright.")
	message(userid,54, 0.35, 0.44, 18, "  [ CTF ]")
	message(userid,55, 0.35, 0.47, 19, "Use vehicles, combat, stealth, and sheer power to capture the enemy flags.")
	message(userid,56, 0.35, 0.50, 20, "Be sure to watch your neighbors flags during 3 and 4 way CTF!")
	message(userid,57, 0.35, 0.53, 21, "  [ REPEAT ]")
	message(userid,58, 0.35, 0.56, 22, "Game ends when any team reaches 3 points or sudden death. Until then, Build and CTF will repeat.")
	message(userid,60, 0.35, 0.60, 23, "  [ INVEST ]")
	message(userid,61, 0.35, 0.63, 24, "Kills range from $50 - $100 and captures are $1000. Save up and buy classes.")
	message(userid,62, 0.35, 0.67, 25, "  [ DRIVE ]")
	message(userid,63, 0.35, 0.70, 26, "Vehicles allow quick deployment and armored assault. Inpenetrable by normal bullets.")
	message(userid,64, 0.35, 0.73, 27, "Use the vehicle pads to create and press USE to enter. Secondary fire to exit.")
	message(userid,65, 0.35, 0.81, 28, "ALL CLASSES, MONEY, TEAMS, AND CERTIFICATIONS ARE SAVED BY STEAMID.")
	
	messageAttn(userid,66, 0.30, 0.84, 25, "F3 - Prestige Classes    F4 - Elite props buy menu")
	
	_GModRect_Start( "gmod/white" )
		_GModRect_SetPos(0.2, 0.2, 0.7, 0.7)
		_GModRect_SetColor(0, 0, 0, 150)
		_GModRect_SetTime(25, 0.5, 1.5)
		_GModRect_SetDelay(0)
	_GModRect_Send(userid, 69)
	_PlayerOption( userid, "CloseHelp", 25 )
end

function CloseHelp(playerid, num, seconds)
	for i=50, 66 do
		_GModText_Hide(playerid, i, (i-49)*0.1)
	end
	_GModRect_Hide(playerid, 69, 1.2)
end

function onShowTeam(userid)
	_GModText_Start( "ImpactMassive" )
	 _GModText_SetPos( -1, 0.1 )
	 _GModText_SetColor( 0, 0, 255, 100 )
	 _GModText_SetTime( 10, 1.5, 0 )
	 if RETRO then
	 _GModText_SetText( "NoXious CTF: Retro" )
	 else
	 _GModText_SetText( "NoXious CTF" )
	 end
	 _GModText_SetDelay( 1.5 )
	 _GModText_AllowOffscreen( true )
	_GModText_Send( userid, 0 )
	
	_GModText_Start( "ImpactMassive" )
	 _GModText_SetPos( -1, 0.3 )
	 _GModText_SetColor( 255, 0, 0, 205 )
	 _GModText_SetDelay( 1.0 )
	_GModText_SendAnimate( userid, 0, 1.5, 0.7 )

	_GModText_Start( "HudHintTextLarge" )
	 _GModText_SetPos( 0.5, 0.37 )
	 _GModText_SetColor( 255, 0, 0, 255 )
	 _GModText_SetTime( 10, 0.5, 1.5 )
	 local totalkills = _file.Read("noxiousprofiles/"..TeamString(TEAM_RED).."totalkills.txt")+_file.Read("noxiousprofiles/"..TeamString(TEAM_GREEN).."totalkills.txt")+_file.Read("noxiousprofiles/"..TeamString(TEAM_BLUE).."totalkills.txt")+_file.Read("noxiousprofiles/"..TeamString(TEAM_YELLOW).."totalkills.txt")
	 _GModText_SetText( "by JetBoom\nThere have been "..totalkills.." people killed since 4/21/06!")
	 _GModText_SetDelay( 1.0 )
	_GModText_Send( userid, 1 )
	
	_GModRect_Start( "VGUI/screens/vgui_bg" )
	 _GModRect_SetPos( 0.0, 0.0, 1, 1 )
	 _GModRect_SetColor( 255, 255, 255, 255 )
	 _GModRect_SetTime( 10, 0.5, 2 )
	 _GModRect_SetDelay( 1 )
	_GModRect_Send( userid, 0 )

	_GModRect_Start( "VGUI/screens/vgui_bg" )
	 _GModRect_SetPos( 0.0, 0.3, 1.0, 0.25 )
	 _GModRect_SetColor( 200, 200, 200, 240 )
	 _GModRect_SetDelay( 1 )
	_GModRect_SendAnimate(userid, 0, 0.5, 0.5)
	if _PlayerInfo(userid, "team") == TEAM_SPECTATOR then
	_PlayerOption( userid, "ChooseTeam", 99999 )
	_GModText_Start("Default")
	 _GModText_SetPos(0.01, 0.4)
	 _GModText_SetColor(255, 0, 0, 255) 
	 _GModText_SetTime(99999, 3, 1.0)
	 _GModText_SetText("PRESS F1 FOR THE HELP MENU!\nvotemap, maplist, and givemoney are chat commands.")
	 _GModText_SetDelay(1.5)
	_GModText_Send(userid, 2)

	_GModText_Start("Default")
	 _GModText_SetPos(0.01, 0.3)
	 _GModText_SetColor(255, 0, 0, 255) 
	 _GModText_SetTime(99999, 3, 1.0)
	 local n = 1
	 local str = "Choose your alliegence:\n"
	 for i=1, 5 do
		if teams[i] ~= nil then
			str = str..n..") "..teams[i].name.." (Deaths: ".._file.Read("noxiousprofiles/"..TeamString(i).."totalkills.txt")..")\n"
			n = n+1
		end
	 end
	 _GModText_SetText(str)
	 _GModText_SetDelay(1.5)
	_GModText_Send(userid, 4)
	end
end

function ChooseTeam(playerid, num, seconds)
	players[playerid].spawn = vector3(0, 0, 0)
	
	local choices = {}
	for i=1, 5 do
		if teams[i] ~= nil then
			choices[table.getn(choices)+1] = i
		end
	end
	_GModText_Hide( playerid, 0, 0.5 )
	_GModRect_Hide( playerid, 0, 0.5 )
	_GModRect_Hide( playerid, 1, 0.5 )
	_GModText_Hide( playerid, 1, 0.5 )
	_GModText_Hide( playerid, 2, 0.5 )
	_GModText_Hide( playerid, 4, 0.9 )
	if choices[num] ~= nil then
		local team = choices[num]
		for i in teams do
			if team ~= i then
				if _TeamNumPlayers(i) < _TeamNumPlayers(team) and _TeamNumPlayers(i) > 0 then
					_GModText_Start("ImpactMassive")
					 _GModText_SetColor(255, 255, 255, 255)
					 _GModText_SetTime(3, 0, 1)
					 _GModText_SetPos(-1, 0.2)
					 _GModText_SetText("That would make teams uneven!")
					_GModText_Send(playerid, 9021)
					onShowTeam(playerid)
					return
				end
			end
		end
		_PlayerChangeTeam(playerid, team)
		_PlayerRespawn(playerid)
	end
end

function AutoChooseTeam(userid)
	if _PlayerInfo(userid, "team") ~= TEAM_SPECTATOR or not _PlayerInfo(userid, "active") then return end
	_GModText_Hide( userid, 0, 0.5 )
	_GModRect_Hide( userid, 0, 0.5 )
	_GModRect_Hide( userid, 1, 0.5 )
	_GModText_Hide( userid, 1, 0.5 )
	_GModText_Hide( userid, 2, 0.5 )
	_GModText_Hide( userid, 4, 0.9 )
	local team = 2
	for i=2, 5 do
		if teams[i] ~= nil and teams[team] == nil then
			team = i
		end
	end
	for i=team, 5 do
		if _TeamNumPlayers(i) < _TeamNumPlayers(team) and _TeamNumPlayers(i) > 0 and teams[i] ~= nil then
			team = i
		end
	end
	_PlayerChangeTeam(userid, team)
	_PlayerRespawn(userid)
	_PlayerOption( userid, "ChooseTeam", 0.01 )
	_GModText_Start("ImpactMassive")
	 _GModText_SetColor(255, 255, 255, 255)
	 _GModText_SetTime(5, 0.5, 0.5)
	 _GModText_SetPos(-1, 0.2)
	 _GModText_SetText("You have been auto-assigned\nfor not picking a team.")
	_GModText_Send(userid, 9021)
end

function InitialScores(UserID)
	_GModText_Start( "DefaultShadow" )
	 _GModText_SetPos(0.1, 0.03)
	 _GModText_SetColor( 255, 255, 255, 255 )
	 _GModText_SetTime( 99999, 0, 0 )
	 _GModText_SetText( "Captures" )
	_GModText_Send( UserID, 5 )
	_GModRect_Start( "gmod/white" )
	 _GModRect_SetPos( 0.0, 0.0, 0.25, 0.2 )
	 _GModRect_SetColor( 0, 0, 0, 150 )
	 _GModRect_SetTime( 99999, 0, 0 )
	 _GModRect_SetDelay( 0 )
	_GModRect_Send( UserID, 17 )
end

function UpdateScores(UserID)
	local COLUMN1, COLUMN2, COLUMN3, COLUMN4, COLUMN5 = 0.03, 0.14, 0.19, 0.24, 0.27
	local TOP_MARGIN, LINE_SPACING, COL_SPACING = 0.06, 0.025, 0.05

	local marg_multi = 0
	for iTeam in teams do
		_GModText_Start("DefaultShadow")
			_GModText_SetPos(COLUMN1, TOP_MARGIN + (marg_multi * LINE_SPACING))
			_GModText_SetColor(teams[iTeam].color.r, teams[iTeam].color.g, teams[iTeam].color.b, 255)
			_GModText_SetTime(99999, 0, 0)
			_GModText_SetText(teams[iTeam].name .. ": ")
		_GModText_Send(UserID, 10 + marg_multi)

		_GModText_Start("DefaultShadow")
			_GModText_SetPos(COLUMN2+0.055, TOP_MARGIN + (marg_multi * LINE_SPACING))
			_GModText_SetColor(teams[iTeam].color.r, teams[iTeam].color.g, teams[iTeam].color.b, 255)
			_GModText_SetTime(99999, 0, 0)
			_GModText_SetText(_TeamScore(iTeam).."/"..SCORELIMIT)
		_GModText_Send(UserID, 14 + marg_multi)

		marg_multi = marg_multi + 1
	end
end

function UpdateDMTime(UserID, rTime)
	_GModText_Start("DefaultShadow")
	 _GModText_SetPos(0.075, 0.17)
	 _GModText_SetColor(255, 0, 0, 255)
	 _GModText_SetTime(99999, 0, 0)
	 if not FightMode then
	 	_GModText_SetText("Build Bases: "..rTime)
	 else
		_GModText_SetText("CTF: "..rTime)
	 end
	_GModText_Send(UserID, 19)
end

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

function buyMenu(userid)
	_PlayerOption(userid, "BuyItem", 99999)
	
	local xpos = 0.04
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.25)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("1. Weapon List One")
	_GModText_Send(userid, 110)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.29)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("2. Weapon List Two")
	_GModText_Send(userid, 111)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.33)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("3. Buy Ammo")
	_GModText_Send(userid, 112)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.37)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("4. Exit Menu")
	_GModText_Send(userid, 113)	
end

function buildbuyMenu(userid)
	if FightMode then return end
	if RETRO then _PrintMessage(userid, 3, "Disabled in Retro mode.") return end
	_PlayerOption(userid, "BuyBuildItem", 99999)
	
	local xpos = 0.04
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.25)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("1. Healing Pad - $"..HEALINGPADPRICE)
	_GModText_Send(userid, 110)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.29)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("2. Teleporter - $"..TELEPORTPADPRICE)
	_GModText_Send(userid, 111)

	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.33)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("3. Door - $"..DOORPRICE)
	_GModText_Send(userid, 112)

	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.37)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("4. Vehicle Pad - $"..VEHICLEPADPRICE)
	_GModText_Send(userid, 113)

	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.41)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("5. Plasma Turret - $"..PLASMATURRETPRICE)
	_GModText_Send(userid, 114)

	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.45)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("6. Extending Bridge - $"..EXTENDINGBRIDGEPRICE)
	_GModText_Send(userid, 115)

	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.49)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("7. Exit Menu")
	_GModText_Send(userid, 116)
end

function WeaponMenuOne(userid)
	_PlayerOption(userid, "BuyWeaponOne", 99999)
	
	local xpos = 0.04
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.25)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("1. Sweeper Shotgun - $175")
	_GModText_Send(userid, 110)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.29)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("2. Desert Eagle - $150")
	_GModText_Send(userid, 111)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.33)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("3. UZI 9mm - $100")
	_GModText_Send(userid, 112)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.37)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("4. Sniper Rifle - $200")
	_GModText_Send(userid, 113)	

	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.41)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("5. AK47 Assault Rifle - $250")
	_GModText_Send(userid, 114)

	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.47)
		_GModText_SetColor(255, 0, 0, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("6. Previous Menu")
	_GModText_Send(userid, 115)
end

function BuyWeaponOne(userid, num, seconds)
	if _PlayerInfo(userid, "team") == TEAM_SPECTATOR or not _PlayerInfo(userid, "alive") then HideBuyMenu(userid) return end
	if num == 1 then
		if players[userid].money >= 175 then
			_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_sweepershotgun.lua")
			players[userid].money = players[userid].money - 175
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		HideBuyMenu(userid)
		return
		
	elseif num == 2 then
		if players[userid].money >= 150 then
			_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_deagle.lua")
			players[userid].money = players[userid].money - 150
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		HideBuyMenu(userid)
		return
	elseif num == 3 then
	if players[userid].money >= 100 then
			_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_uzi.lua")
			players[userid].money = players[userid].money - 100
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		HideBuyMenu(userid)
		return
	elseif num == 4 then
		if RETRO then _PrintMessage(userid, 3, "Disabled in Retro mode.") HideBuyMenu(userid) return end
		if players[userid].money >= 200 then
			_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_sniperrifle.lua")
			players[userid].money = players[userid].money - 200
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		HideBuyMenu(userid)
		return
	elseif num == 5 then
		if RETRO then _PrintMessage(userid, 3, "Disabled in Retro mode.") HideBuyMenu(userid) return end
		if players[userid].money >= 250 then
			_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_ak47.lua")
			players[userid].money = players[userid].money - 250
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		HideBuyMenu(userid)
		return
	else
		HideBuyMenu(userid)
	end
	HideBuyMenu(userid)
	buyMenu(userid)
	return
end

function WeaponMenuTwo(userid)
	_PlayerOption(userid, "BuyWeaponTwo", 99999)
	
	local xpos = 0.04
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.25)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("1. Hunting Rifle - $175")
	_GModText_Send(userid, 110)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.3)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("2. Energy Grenade - $50")
	_GModText_Send(userid, 111)

	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.35)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("3. Crowbarang - $75")
	_GModText_Send(userid, 112)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.4)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("4. Zombie Summon Ball - $200")
	_GModText_Send(userid, 114)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.45)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("5. Combat Shield - $100")
	_GModText_Send(userid, 115)
		
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.62)
		_GModText_SetColor(255, 0, 0, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("6. Previous Menu")
	_GModText_Send(userid, 116)
end

function BuyBuildItem(userid, num, seconds)
	if _PlayerInfo(userid, "team") == TEAM_SPECTATOR or FightMode or not _PlayerInfo(userid, "alive") then HideBuyMenu(userid) return end
	if num == 1 then
		if players[userid].money >= HEALINGPADPRICE then
			CreateHealPad(userid)
			players[userid].money = players[userid].money - HEALINGPADPRICE
			NDB.drawMoneyAmmount(userid)
			_PrintMessage(userid, 4, "A healing pad appears over your head.")
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
	elseif num == 2 then
		if players[userid].money >= TELEPORTPADPRICE then
			CreateTeleportPad(userid)
			players[userid].money = players[userid].money - TELEPORTPADPRICE
			NDB.drawMoneyAmmount(userid)
			_PrintMessage(userid, 4, "A pair of teleport pads appear.")
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
	elseif num == 3 then
		if players[userid].money >= DOORPRICE then
			CreateDoor(userid)
			players[userid].money = players[userid].money - DOORPRICE
			NDB.drawMoneyAmmount(userid)
			_PrintMessage(userid, 4, "The door appears.")
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
	elseif num == 4 then
		if players[userid].money >= VEHICLEPADPRICE then
			CreateVehiclePad(userid)
			players[userid].money = players[userid].money - VEHICLEPADPRICE
			NDB.drawMoneyAmmount(userid)
			_PrintMessage(userid, 4, "The vehicle pad appears.")
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
	elseif num == 5 then
		if players[userid].money >= PLASMATURRETPRICE then
			if teams[_PlayerInfo(userid, "team")].PlasmaTurrets < PLASMATURRETMAX then
				CreatePlasmaTurret(userid)
				players[userid].money = players[userid].money - PLASMATURRETPRICE
				NDB.drawMoneyAmmount(userid)
				_PrintMessage(userid, 4, "The turret appears.")
				_PrintMessage(userid, 4, "Plasma Turrets: "..teams[_PlayerInfo(userid, "team")].PlasmaTurrets.."/"..PLASMATURRETMAX)
			else
				_PrintMessage(userid, 4, "Your team has reached the max amount of plasma turrets.")
			end
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
	elseif num == 6 then
		if players[userid].money >= EXTENDINGBRIDGEPRICE then
			MakeMway(userid)
			players[userid].money = players[userid].money - EXTENDINGBRIDGEPRICE
			NDB.drawMoneyAmmount(userid)
			_PrintMessage(userid, 4, "The bridge appears.")
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
	end
	HideBuyMenu(userid)
end

function BuyWeaponTwo(userid, num, seconds)
	if _PlayerInfo(userid, "team") == TEAM_SPECTATOR or not _PlayerInfo(userid, "alive") then HideBuyMenu(userid) end
	if num == 1 then
		if RETRO then _PrintMessage(userid, 3, "Disabled in Retro mode.") HideBuyMenu(userid) return end
		if players[userid].money >= 175 then
			_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_rifle.lua")
			players[userid].money = players[userid].money - 175
			NDB.drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		HideBuyMenu(userid)
		return
	elseif num == 2 then
		if RETRO then _PrintMessage(userid, 3, "Disabled in Retro mode.") HideBuyMenu(userid) return end
		if players[userid].money >= 50 then
			if _PlayerHasWeapon(userid, "weapon_energygrenade") then
				_PlayerGiveAmmo(userid, 1, "Grenade", true)
			else
				_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_energygrenade.lua")
			end
			players[userid].money = players[userid].money - 50
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		HideBuyMenu(userid)
		return
	elseif num == 3 then
		if players[userid].money >= 75 then
			_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_crowbarang.lua")
			players[userid].money = players[userid].money - 75
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		HideBuyMenu(userid)
		return
	elseif num == 4 then
		if players[userid].money >= 200 then
			if _PlayerHasWeapon(userid, "weapon_summonzombie") then
				_PlayerGiveAmmo(userid, 1, "GaussEnergy", true)
			else
				_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_summonzombie.lua")
			end
			players[userid].money = players[userid].money - 200
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		HideBuyMenu(userid)
		return
	elseif num == 5 then
		if players[userid].money >= 100 then
			_PlayerGiveSWEP(userid, "weapons/noxctf/weapon_combatshield.lua")
			players[userid].money = players[userid].money - 100
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		HideBuyMenu(userid)
		return
	else
		HideBuyMenu(userid)
	end
	HideBuyMenu(userid)
	buyMenu(userid)
	return
end


function BuyItem(userid, num, seconds)
	if num == 1 then
		HideBuyMenu(userid)
		WeaponMenuOne(userid)
		return
	elseif num == 2 then
		HideBuyMenu(userid)
		WeaponMenuTwo(userid)
		return
	elseif num == 3 then
		HideBuyMenu(userid)
		AmmoMenu(userid)
		return
	else
		HideBuyMenu(userid)
	end
	HideBuyMenu(userid)
	return
end

function HideBuyMenu(userid)
	for i=110, 120 do
		_GModText_Hide(userid, i, 0.5, 0)
	end
end

function AmmoMenu(userid)
	_PlayerOption(userid, "BuyAmmo", 99999)
	
	local xpos = 0.04
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.25)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("1. Buckshot (10 rounds): $5")
	_GModText_Send(userid, 120)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.29)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("2. Pistol/.45 Bullets (16 rounds): $5")
	_GModText_Send(userid, 121)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.33)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("3. UZI 9mm (60 rounds): $5")
	_GModText_Send(userid, 122)
	
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.37)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("4. Sniper/Slug Rifle Bullets (5 rounds): $15")
	_GModText_Send(userid, 123)

	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.41)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("5. AK-47 Clip (30 rounds): $15")
	_GModText_Send(userid, 124)

	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.45)
		_GModText_SetColor(255, 200, 50, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("6. Rocket (1 round): $50")
	_GModText_Send(userid, 125)
		
	_GModText_Start("TargetID")
		_GModText_SetPos(xpos, 0.57)
		_GModText_SetColor(255, 0, 0, 255)
		_GModText_SetTime(99999, 0, 0)
		_GModText_SetText("7. Previous Menu")
	_GModText_Send(userid, 126)
end

function HideAmmoMenu(userid)
	_GModText_Hide(userid, 120, 0.5, 0)
	_GModText_Hide(userid, 121, 0.5, 0)
	_GModText_Hide(userid, 122, 0.5, 0)
	_GModText_Hide(userid, 123, 0.5, 0)
	_GModText_Hide(userid, 124, 0.5, 0)
	_GModText_Hide(userid, 125, 0.5, 0)
	_GModText_Hide(userid, 126, 0.5, 0)
end

function BuyAmmo(userid, num, seconds)
	if _PlayerInfo(userid, "team") == TEAM_SPECTATOR or not _PlayerInfo(userid, "alive") then HideAmmoMenu(userid) end
	if num == 1 then
		if players[userid].money >= 15 then
			_PlayerGiveAmmo(userid, 10, "Buckshot", true)
			players[userid].money = players[userid].money - 5
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		AmmoMenu(userid)
		return
		
	elseif num == 2 then
		if players[userid].money >= 10 then
			_PlayerGiveAmmo(userid, 16, "Pistol", true)
			players[userid].money = players[userid].money - 5
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		AmmoMenu(userid)
		return
	
	elseif num == 3 then
		if players[userid].money >= 20 then
			_PlayerGiveAmmo(userid, 60, "SMG1", true)
			players[userid].money = players[userid].money - 5
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		AmmoMenu(userid)
		return
	
	elseif num == 4 then
		if players[userid].money >= 30 then
			_PlayerGiveAmmo(userid, 5, "357", true)
			players[userid].money = players[userid].money - 15
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		AmmoMenu(userid)
		return

	elseif num == 5 then
		if players[userid].money >= 30 then
			_PlayerGiveAmmo(userid, 30, "AR2", true)
			players[userid].money = players[userid].money - 15
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		AmmoMenu(userid)
		return

	elseif num == 6 then
		if players[userid].money >= 75 then
			_PlayerGiveAmmo(userid, 1, "RPG_Round", true)
			players[userid].money = players[userid].money - 50
			drawMoneyAmmount(userid)
		else
			_PrintMessage(userid, 4, "You don't have enough money for this item")
		end
		AmmoMenu(userid)
		return

	else
		HideAmmoMenu(userid)
		buyMenu(userid)
		return
	end
	
	return
end

ArrowTimers = {}

function CreateArrow(userid, arrowtype)
	if not _PlayerInfo(userid, "alive") or not _PlayerInfo(userid, "connected") then return end
		local Bolt = _EntCreate( "physics_prop" )
		_EntPrecacheModel( "models/mixerman3d/other/arrow.mdl" )
	if Bolt > 0 then
		_EntSetModel(Bolt, "models/mixerman3d/other/arrow.mdl")
		_EntSetPos(Bolt, vecAdd(_PlayerGetShootPos(userid), vecMul(_PlayerGetShootAng( userid ),vector3(30,30,30))))
		_EntSetAng(Bolt, _PlayerGetShootAng(userid))
		_EntSetOwner(Bolt, userid)
		_EntSetAng(Bolt, _PlayerGetShootAng(userid))
		_EntSpawn(Bolt)
		_phys.ApplyForceCenter(Bolt, vecMul(_PlayerGetShootAng(userid), vector3(250000, 250000, 250000)))
		_EntEmitSound(Bolt, "weapons/crossbow/bolt_fly4.wav")
		_EntitySetPhysicsAttacker(Bolt, userid)
		_EntFire(Bolt, "kill", "", 15)

		if arrowtype < 2 then
			_EntSetName(Bolt, "normal")
			AttatchTrail(Bolt, "255 0 0")
		elseif arrowtype < 3 then
			_EntFire(Bolt, "color", "255 25 0", 0)
			_EntSetName(Bolt, "explode")
			local firetrail = _EntCreate("env_fire_trail")
			if firetrail > 0 then
				_EntSetPos(firetrail, _EntGetPos(Bolt))
				_EntSetParent(firetrail, Bolt)
			end
		elseif arrowtype < 4 then
			_EntFire(Bolt, "color", "0 25 255", 0)
			_EntSetName(Bolt, "cold")
			AttatchTrail(Bolt, "0 50 255")
		elseif arrowtype < 5 then
			_EntSetMaterial(Bolt, "gmod/shiny")
			_EntSetName(Bolt, "rope")
			AttatchTrail(Bolt, "255 255 255")
		end
		ArrowTimers[Bolt] = AddTimer(0.05, 120, ArrowCheckHit, Bolt, userid)
	end
end

function ArrowCheckHit(prop, userid)
	if not _EntExists(prop) or _EntGetType(prop) ~= "prop_physics" or prop <= 0 then HaltTimer(ArrowTimers[prop]) return end
	_TraceLine(_EntGetPos(prop), _EntGetForwardVector(prop), 75, prop)
	if _TraceHit() then
		if _TraceHitNonWorld() then
			ArrowProcessHit(_TraceGetEnt(), prop, userid)
			return
		else
			ArrowProcessHit(0, prop, userid)
			return
		end
	end
	local tab = _EntitiesFindInSphere(_EntGetPos(prop), 30)
	for i=1, table.getn(tab) do
		if tab[i] ~= userid and tab[i] ~= prop and ValidFireBall(tab[i]) and Vehicles[tab[i]] == nil then
			ArrowProcessHit(tab[i], prop, userid)
			return
		end
	end
end

function ArrowFreeze(userid)
	AddTimer(4, 1, ArrowUnfreeze, userid)
	_PlayerFreeze(userid, true)
	_EntSetMaterial(userid, "gmod/shiny")
end

function ArrowUnfreeze(userid)
	_PlayerFreeze(userid, false)
	_EntSetMaterial(userid, "")
end

function ArrowProcessHit(targ, prop, userid)
	if _EntGetType(prop) ~= "prop_physics" or prop <= 0 then HaltTimer(ArrowTimers[prop]) return end
	local arrowtype = _EntGetName(prop)
	if arrowtype == "normal" then
		if targ == 0 then _EntFire(prop, "kill", "", 5) HaltTimer(ArrowTimers[prop]) return end
		_TraceAttack(targ, userid, userid, math.random(25, 40))
		if targ <= _MaxPlayers() then
			_EntEmitSound(targ, "weapons/crossbow/hitbod"..math.random(1,2)..".wav")
			_EntEmitSoundEx(targ, "player/pl_pain5.wav", 1.1, 1)
		end
		HaltTimer(ArrowTimers[prop])
		_EntFire(prop, "kill", "", 0)
	elseif arrowtype == "cold" then
		if targ == 0 then _EntFire(prop, "kill", "", 5) HaltTimer(ArrowTimers[prop]) return end
		if targ <= _MaxPlayers() then
			_EntEmitSound(targ, "weapons/crossbow/hitbod"..math.random(1,2)..".wav")
			if _PlayerInfo(targ,"team") ~= _PlayerInfo(userid,"team") then
				_EntEmitSoundEx(targ, "ambient/creatures/town_muffled_cry1.wav", 1, 0.8)
				ArrowFreeze(targ)
			end
		end
		HaltTimer(ArrowTimers[prop])
		_EntFire(prop, "kill", "", 0)
	elseif arrowtype == "explode" then
		ArrowExplode(prop, userid)
		if targ > 0 then
			_EntEmitSound(targ, "weapons/crossbow/hitbod"..math.random(1,2)..".wav")
		end
	elseif arrowtype == "rope" then
		HaltTimer(ArrowTimers[prop])
		if targ > 0 then
			_EntEmitSound(targ, "weapons/crossbow/hitbod"..math.random(1,2)..".wav")
			_EntFire(prop, "kill", "", 0)
			AddTimer(0.05, 70, DoHook, targ, userid)
		else
			_EntFire(prop, "kill", "", 3.6)
			_phys.EnableMotion(prop, false)
			AddTimer(0.05, 70, DoHook, userid, prop)
		end
	end
end

function DoHook(userid, prop)
	if not _EntExists(prop) or not _PlayerInfo(userid, "alive") then return end
	if _EntGetType(prop) == "prop_physics" then
		if _PlayerIsKeyDown(userid, IN_ATTACK2) then
			_EntSetVelocity(userid, vecAdd(_EntGetVelocity(userid), vecMul(vecNormalize(vecSub(_EntGetPos(prop), _EntGetPos(userid))),vector3(75,75,75))))
		end
	else
		if not IsInRadius(userid, prop, 220) then		
			_EntSetVelocity(userid, vecAdd(_EntGetVelocity(userid), vecMul(vecNormalize(vecSub(_EntGetPos(prop), _EntGetPos(userid))),vector3(75,75,75))))
		end
	end
	_EffectInit()
	_EffectSetEnt(userid)
	if prop <= _MaxPlayers() then
		_EffectSetStart(_PlayerGetShootPos(prop))
	else
		_EffectSetOrigin(_EntGetPos(prop))
	end
	if userid <= _MaxPlayers() then
		_EffectSetStart(_PlayerGetShootPos(userid))
	else
		_EffectSetStart(_EntGetPos(userid))
	end
	_EffectSetScale(4)
	_EffectSetMagnitude(2)
	_EffectSetRadius(70)
	_EffectDispatch("FadingLineTeam")
end

function ArrowExplode(prop, userid)
	local ents = _EntitiesFindInSphere(_EntGetPos(prop), 165)
	for i=1, table.getn(ents) do
		if _phys.HasPhysics(ents[i]) and ents[i] ~= prop then
			_TraceAttack(ents[i], userid, userid, (90-(math.abs(vecLength(vecSub(_EntGetPos(prop),_EntGetPos(ents[i])))))*0.4)*0.75)
		end
	end

	local exp = _EntCreate("env_explosion")
	if exp > 0 then
		_EntSetKeyValue(exp, "spawnflags", "17")
		_EntSetPos(exp, _EntGetPos(prop))
		_EntSpawn(exp)
		_EntFire(exp, "explode", "", 0)
		_EntFire(exp, "kill", "", 0.1)
	end
	_util.ScreenShake(_EntGetPos(prop), math.random(15,35), 160.0, 1.15, 140)
	if _EntGetType(prop) == "prop_physics" then
		_EntRemove(prop)
	end
	HaltTimer(ArrowTimers[prop])
end

function DamagelessExplosion(targ, tim)
	local ent = _EntCreate("env_explosion")
	if ent > 0 then
		_EntSetPos(ent, _EntGetPos(targ))
		_EntSetKeyValue(ent, "spawnflags", "65")
		_EntSpawn(ent)
		_EntFire(ent, "explode", "", tim)
		_EntFire(ent, "kill", "", tim+0.05)
	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 FlagHit(Activator, Caller, Num)
	-- Obsolete, but can prevent console errors.
end

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"

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 gibstospawn = {}
	gibstospawn[1] = "models/gibs/HGIBS.mdl"
	gibstospawn[2] = "models/gibs/HGIBS_rib.mdl"
	gibstospawn[3] = "models/gibs/HGIBS_rib.mdl"
	gibstospawn[4] = "models/gibs/HGIBS_rib.mdl"
	gibstospawn[5] = "models/gibs/HGIBS_scapula.mdl"
	gibstospawn[6] = "models/gibs/HGIBS_spine.mdl"
	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_multiplayer")
		if gib > 0 then
			_EntPrecacheModel(gibstospawn[i])
			_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)))
			_EntSpawn(gib)
			_phys.ApplyForceCenter(gib, vecMul(_EntGetVelocity(killed), vector3(8,8,8)))
			_phys.ApplyTorqueCenter(gib, vector3(math.random(-10500, 10500), math.random(-10500, 10500), math.random(-3000, 13000)))
			_phys.ApplyForceCenter(gib, vector3(math.random(-8000, 8000), math.random(-8000, 8000), math.random(-3000, 8500)))
			_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

WraithPortals = {}
for i=1, _MaxPlayers() do
	WraithPortals[i] = {}
	WraithPortals[i].Entry = vector3(0,0,0)
	WraithPortals[i].Exit = vector3(0,0,0)
end

function WraithTick()
	for i=1, table.getn(WraithPortals) do
		if WraithPortals[i].Entry.x ~= 0 then
			if WraithPortals[i].ActiveTime > 30 then
				if _EntGetType(WraithPortals[i].EntrySprite) == "env_sprite" then
					_EntFire(WraithPortals[i].EntrySprite, "kill", "", 1)
					for y=0, 10 do
						_EntFire(WraithPortals[i].EntrySprite, "setscale", tostring(y-(y*0.2)), y*0.1)
					end
				end
				if _EntGetType(WraithPortals[i].ExitSprite) == "env_sprite" then
					_EntFire(WraithPortals[i].ExitSprite, "kill", "", 1)
					for y=0, 10 do
						_EntFire(WraithPortals[i].ExitSprite, "setscale", tostring(y-(y*0.2)), y*0.1)
					end
				end
				WraithPortals[i] = nil
				WraithPortals[i] = {}
				WraithPortals[i].Entry = vector3(0,0,0)
				WraithPortals[i].Exit = vector3(0,0,0)
				return
			else
				WraithPortals[i].ActiveTime = WraithPortals[i].ActiveTime + 0.25
			end
			if WraithPortals[i].Exit.x ~= 0 then
				local ents = _EntitiesFindInSphere(WraithPortals[i].Entry, 64)
				for x=1, table.getn(ents) do
					if IsPlayer(ents[x]) then
						_EntSetPos(ents[x], WraithPortals[i].Exit)
						local ran = math.random(2, 4)
						if ran < 3 then ran = 1 end
						_EntEmitSound(ents[x], "ambient/machines/teleport"..ran..".wav")
					end
				end
			end
		end
	end
end
AddTimer(0.25, 0, WraithTick)

function CreateWraithPortalEntry(userid)
	if WraithPortals[userid].ActiveTime ~= nil then
		if WraithPortals[userid].ActiveTime < 15 then
			return
		end
	end
	if WraithPortals[userid].EntrySprite ~= nil then
		if _EntGetType(WraithPortals[userid].EntrySprite) == "env_sprite" then
			_EntFire(WraithPortals[userid].EntrySprite, "kill", "", 1)
			for y=0, 10 do
				_EntFire(WraithPortals[userid].EntrySprite, "setscale", tostring(y-(y*0.2)), y*0.1)
			end
		end
	end
	_TraceLine(_PlayerGetShootPos(userid), _PlayerGetShootAng(userid), 500, userid)
	WraithPortals[userid].Entry = _TraceEndPos()
	local ent = _EntCreate("env_sprite")
	if ent > 0 then
		_EntSetKeyValue(ent, "model", "sprites/strider_blackball.spr")
		_EntSetKeyValue(ent, "rendermode", "5")
		_EntSetKeyValue(ent, "scale", "0.1")
		_EntSetKeyValue(ent, "spawnflags", "1")
		_EntSetPos(ent, _TraceEndPos())
		_EntSpawn(ent)
		_EntFire(ent, "showsprite", "", 0)
		for i=1, 10 do
			_EntFire(ent, "setscale", tostring(i*0.2), i*0.1)
		end
		_EntEmitSound(ent, "weapons/stunstick/alyx_stunner"..math.random(1,2)..".wav")
		WraithPortals[userid].EntrySprite = ent
	end
	if WraithPortals[userid].Exit.x ~= 0 then
		WraithPortals[userid].ActiveTime = 0
	end
end

function CreateWraithPortalExit(userid)
	if WraithPortals[userid].ActiveTime ~= nil then
		if WraithPortals[userid].ActiveTime < 15 then
			return
		end
	end
	if WraithPortals[userid].ExitSprite ~= nil then
		if _EntGetType(WraithPortals[userid].ExitSprite) == "env_sprite" then
			_EntFire(WraithPortals[userid].ExitSprite, "kill", "", 1)
			for y=0, 10 do
				_EntFire(WraithPortals[userid].ExitSprite, "setscale", tostring(y-(y*0.2)), y*0.1)
			end
		end
	end
	_TraceLine(_PlayerGetShootPos(userid), _PlayerGetShootAng(userid), 500, userid)
	WraithPortals[userid].Exit = _TraceEndPos()
	local ent = _EntCreate("env_sprite")
	if ent > 0 then
		_EntSetKeyValue(ent, "model", "sprites/strider_blackball.spr")
		_EntSetKeyValue(ent, "rendermode", "5")
		_EntSetKeyValue(ent, "scale", "0.1")
		_EntSetKeyValue(ent, "spawnflags", "1")
		_EntSetPos(ent, _TraceEndPos())
		_EntSpawn(ent)
		_EntFire(ent, "color", "255 0 0", 0.1)
		_EntFire(ent, "showsprite", "", 0)
		for i=1, 10 do
			_EntFire(ent, "setscale", tostring(i*0.2), i*0.1)
		end
		_EntEmitSound(ent, "weapons/stunstick/alyx_stunner"..math.random(1,2)..".wav")
		WraithPortals[userid].ExitSprite = ent
	end
	if WraithPortals[userid].Entry.x ~= 0 then
		WraithPortals[userid].ActiveTime = 0
	end
end

function DoExplode(Owner)
	if not _PlayerInfo(Owner, "alive") then return end
	_EntEmitSoundEx(Owner, "ambient/explosions/explode_"..math.random(1,9)..".wav", 1.5, 0.9)
	_EntEmitSoundEx(Owner, "ambient/explosions/explode_"..math.random(1,9)..".wav", 1.0, 1.1)
	_util.ScreenShake(_EntGetPos(Owner), 50, 475, 3, 550)
	local ents = _EntitiesFindInSphere(_EntGetPos(Owner), 330)
	local damage = 0
	for i=1, table.getn(ents) do
		if _phys.HasPhysics(ents[i]) then
			if IsPlayer(ents[i]) then
				if _PlayerInfo(ents[i], "connected") then
					if _PlayerInfo(ents[i], "team") ~= _PlayerInfo(Owner, "team") then
						_EntSetVelocity(ents[i], vecAdd(vector3(math.random(-1000, 1000), math.random(-1000, 1000), math.random(500, 1500)), _EntGetVelocity(ents[i])))
					end
					damage = 355-(math.abs(vecLength(vecSub(_EntGetPos(Owner),_EntGetPos(ents[i])))))
					if damage >= _PlayerInfo(ents[i], "health") then damage = 2000 end
					_RunString("_TraceAttack("..ents[i]..", "..Owner..", "..Owner..", "..damage..")")
				end
			else
				damage = 355-(math.abs(vecLength(vecSub(_EntGetPos(Owner),_EntGetPos(ents[i])))))
				_RunString("_TraceAttack("..ents[i]..", "..Owner..", "..Owner..", "..damage..")")
			end
		end
	end
	local x = -90
	local y = -90
	local ent = 0
	for i=1, 3 do
		if x ~= 0 then
			ent = 0
			ent = _EntCreate("env_explosion")
			if ent > 0 then
				_EntSetPos(ent, vecAdd(vector3(x, 0, 0), _EntGetPos(Owner)))
				_EntSetKeyValue(ent, "spawnflags", "65")
				_EntSpawn(ent)
				_EntFire(ent, "explode", "", 0)
				_EntFire(ent, "kill", "", 0.15)
			end
		end
		x = x + 90
	end
	for ii=1, 3 do
		if y ~= 0 then
			ent = 0
			ent = _EntCreate("env_explosion")
			if ent > 0 then
				_EntSetPos(ent, vecAdd(vector3(0, y, 0), _EntGetPos(Owner)))
				_EntSetKeyValue(ent, "spawnflags", "65")
				_EntSpawn(ent)
				_EntFire(ent, "explode", "", 0)
				_EntFire(ent, "kill", "", 0.15)
			end
		end
		y = y + 90
	end
	Gib(Owner)
end

--[[
function ShockBeam(userid)
	if not _PlayerInfo(userid, "alive") then return end
	PlayerLookTrace(userid, 4096)
	if _TraceHitNonWorld() then
		local traced = _TraceGetEnt()
		if _EntGetName(traced) == "shockball" then
			ShockExplosion(userid, traced)
		else
			_TraceAttack(traced, userid, userid, 25)
		end
	end
end

function ShockBall(userid)
	if not _PlayerInfo(userid, "alive") then return end
	
end

function ShockExplosion(userid, prop)
	local tabs = _EntitiesFindInSphere(_EntGetPos(prop), 180)
	for x in tabs do
		_TraceAttack(tabs[x], userid, userid, (190-Distance(_EntGetPos(prop), _EntGetPos(tabs[x])))*0.4)
	end
	HaltTimer(FireBallTimers[prop])
	FireBallTimers[prop] = nil
	
	_EntRemove(prop)
end

function ShockBallThink(userid, prop)
	if not _EntExists(prop) then HaltTimer(FireBallTimers[prop]) return end
	_TraceLine(_EntGetPos(prop), _EntGetForwardVector(prop), 92, prop)
	if _TraceHit() then
		local tabs = _EntitiesFindInSphere(_EntGetPos(prop), 135)
		for x in tabs do
			_TraceAttack(tabs[x], userid, userid, (140-Distance(_EntGetPos(prop), _EntGetPos(tabs[x])))*0.33)
		end
		HaltTimer(FireBallTimers[prop])
		FireBallTimers[prop] = nil
		_EntRemove(prop)
		return
	end
	local tab = _EntitiesFindInSphere(_EntGetPos(prop), 35)
	for i=1, table.getn(tab) do
		if tab[i] ~= userid and tab[i] ~= prop and ValidFireBall(tab[i]) then
			local tabs = _EntitiesFindInSphere(_EntGetPos(prop), 135)
			for x in tabs do
				_TraceAttack(tabs[x], userid, userid, (140-Distance(_EntGetPos(prop), _EntGetPos(tabs[x])))*0.33)
			end
			HaltTimer(FireBallTimers[prop])
			FireBallTimers[prop] = nil
			_EntRemove(prop)
			return
		end
	end
end
]]

Cannons = {}
function JuggernautCannon(userid)
	_EntEmitSound(userid, "weapons/stinger_fire1.wav")
	_EntEmitSound(userid, "weapons/rpg/rocketfire1.wav")
	local i = table.getn(Cannons)+1
	Cannons[i] = {}
	Cannons[i].pos = _PlayerGetShootPos(userid)
	Cannons[i].ang = _PlayerGetShootAng(userid)
	Cannons[i].owner = userid
end

function CannonsTick()
	for i in Cannons do
		_TraceLine(Cannons[i].pos, Cannons[i].ang, 9999, Cannons[i].owner)
		if not _TraceHit() then
			Cannons[i] = nil
		else
			_TraceLine(Cannons[i].pos, Cannons[i].ang, 180, Cannons[i].owner)
			if _TraceHit() then
				Cannons[i].pos = _TraceEndPos()
				local ents = _EntitiesFindInSphere(Cannons[i].pos, 250)
				for x=1, table.getn(ents) do
					if _phys.HasPhysics(ents[x]) then
						_TraceAttack(ents[x], Cannons[i].owner, Cannons[i].owner, (250-math.abs(vecLength(vecSub(Cannons[i].pos,_EntGetPos(ents[x])))))*0.33, "antivehicle")
					end
				end
				NoDamageLuaExplosion(Cannons[i].pos)
				AR2Explosion(Cannons[i].pos)
				Cannons[i] = nil
			else
				local ents = _EntitiesFindInSphere(Cannons[i].pos, 140)
				for x in ents do
					if ents[x] ~= Cannons[i].owner and not Vehicles[ents[x]] then
						_TraceAttack(ents[x], Cannons[i].owner, Cannons[i].owner, (145-Distance(Cannons[i].pos, _EntGetPos(ents[i])))*0.15)
					end
				end
				local ent = _EntCreate("env_sprite")
				if ent > 0 then
					_EntSetKeyValue(ent, "model", "sprites/muzzleflash"..math.random(1,3)..".spr")
					_EntSetKeyValue(ent, "rendermode", "5")
					_EntSetKeyValue(ent, "scale", "1.0")
					_EntSetKeyValue(ent, "spawnflags", "1")
					_EntSetPos(ent, Cannons[i].pos)
					_EntSpawn(ent)
					_EntFire(ent, "showsprite", "", 0)
					_EntFire(ent, "setscale", "0.85", 0.25)
					_EntFire(ent, "setscale", "0.55", 0.5)
					_EntFire(ent, "setscale", "0.15", 0.75)
					_EntFire(ent, "hidesprite", "", 0.9)
					_EntFire(ent, "kill", "", 1.0)
					_EntEmitSoundEx(ent, "weapons/explode"..math.random(3,5)..".wav", 1, 1.45)
				end
				--Cannons[i].ang = vecAdd(Cannons[i].ang, vector3(math.frandom(-0.06, 0.06), math.frandom(-0.06, 0.06), math.frandom(-0.06, 0.06)))
				Cannons[i].pos = vecAdd(Cannons[i].pos, vecMul(Cannons[i].ang, vector3(175,175,175)))
			end
		end
	end
end
AddTimer(0.12, 0, CannonsTick)

if _file.Exists("lua/noxctfmaps/".._GetCurrentMap()..".lua") then
	_OpenScript("noxctfmaps/".._GetCurrentMap()..".lua")
end
