EXTENDINGBRIDGEPRICE = 300
MwayModel = "models/props_rooftop/Sign_Letter_M001.mdl"
MwayDistance = 18
MwayDelay = 0.15
Mway = {}

_EntPrecacheModel(MwayModel)

function MwayUDeploy(activator,caller,num)
	MwayExtend(num)
end

function MwayURetract(activator, caller, num)
	MwayRetract(num)
end

function MakeMway(userid)
	PlayerLookTrace(userid, 128)
	local point = _EntCreate("prop_physics")
	if point > 0 then
		_EntSetPos(point, _TraceEndPos())
		_EntSetModel(point, MwayModel)
		_EntSpawn(point)
		_EntSetName(point, "unfrozenprop")
		_EntSetMaterial(point, "gmod/wireframe")
		local n = _PlayerInfo(userid, "team")
		PhysProps[point] = {}
		PhysProps[point].Owner = userid
		PhysProps[point].Team = n
		teams[n].props = teams[n].props+1
		_EntFire(point, "color", teams[n].color.r.." "..teams[n].color.g.." "..teams[n].color.b, 0)
		Mway[point] = {}
		Mway[point].State = false	
		Mway[point].Children = {}
	end
end

function MwayExtend(index)
	if Mway[index].State then return end
	MwayMakeChildren(index)
	_EntFire(index, "color", "255 255 0", 0)
	_EntEmitSound(index, "npc/dog/dog_servo12.wav")
end

function MwaySetOff(index)
	_EntFire(index, "color", "0 255 0", 0)
	Mway[index].State = false
end

function MwayMakeChildren(index)
	if not Mway[index] then return end
	if Mway[index].Children[1] ~= nil and _EntExists(Mway[index].Children[1]) then
		_TraceLine(_EntGetPos(Mway[index].Children[1]), vecMul(_EntGetUpVector(index), vector3(-1,-1,-1)), MwayDistance, {Mway[index].Children[1], index})
	else
		_TraceLine(_EntGetPos(index),vecMul(_EntGetUpVector(index),vector3(-1,-1,-1)),MwayDistance, index)
	end
	local point = _EntCreate("prop_dynamic_override")
	if point > 0 then
		_EntSetPos(point, _TraceEndPos())
		_EntSetAngAngle(point, _EntGetAngAngle(index))
		_EntSetModel(point, MwayModel)
		_EntSetParent(point, index)
		_EntSetKeyValue(point, "solid", "6")
		_EntSpawn(point)
		table.insert(Mway[index].Children, 1, point)
		_EntEmitSound(point,"npc/dog/dog_servo7.wav")
		if table.getn(Mway[index].Children) > 34 then
			_EntFire(index,"color","255 0 0",0)
			Mway[index].State = true
		elseif _TraceFraction() == 1 then
			AddTimer(MwayDelay, 1, MwayMakeChildren, index)
		else
			_EntFire(index, "color", "255 0 0", 0)
			Mway[index].State = true
		end
	end
end

function MwayRetract(index)
	if Mway[index].State == false then return end
	local childcount = 0
	for k, v in Mway[index].Children do
		AddTimer(MwayDelay + (k * MwayDelay), 1, MwayRemoveChild, v)
		childcount = childcount + 1
	end
	AddTimer(MwayDelay * childcount, 1, MwaySetOff, index)
	_EntFire(index, "color","255 255 0", 0)
	Mway[index].Children = {}
	_EntEmitSound(index, "npc/dog/dog_servo10.wav")
end

function MwayRemoveChild(entity)
	_EntEmitSound(entity, "npc/turret_floor/click1.wav")
	_EntRemove(entity)
end
