//ispaused()
//IsPlayingBack()
//EstimateLength()

//debug stuff
debug <- false	//Set true to enable debug block during think function
debugInterval <- 10.00

lastthink <- Time()
startBlock <- 0

//Queue of scenes started with GladosPlayVcd()
scenequeue <- {}
firedfromqueue <- false

//Map Name
curMapName <- GetMapName()

//PitchShifting stuff
pitchShifting <- false
pitchShiftLastThink <- Time()
pitchShiftInterval <- 1.0
pitchShiftValue <- 1.0
pitchOverride <- null

//State Flags
stateSlowFieldTraining <- false


//jailbreak specific stuff
if (curMapName=="sp_sabotage_jailbreak_01" || curMapName=="sp_sabotage_jailbreak" || curMapName=="sp_a2_bts1")
{
	jailbreakpos <- 0
}


//sp_catapult_fling_sphere_peek specific stuff
if (curMapName=="sp_a2_sphere_peek")
{
	peekctr <- 0
}


//Dings
sceneDingOn  <- CreateSceneEntity("scenes/npc/glados_manual/ding_on.vcd")
sceneDingOff <- CreateSceneEntity("scenes/npc/glados_manual/ding_off.vcd")


//Include the autogenerated scene table
DoIncludeScript( "choreo/glados_scenetable_include", self.GetScriptScope() )

//Include the manual scene table
DoIncludeScript( "choreo/glados_scenetable_include_manual", self.GetScriptScope() )

//include the manual scene table for act 3
DoIncludeScript( "choreo/glados_scenetable_include_manual_act3", self.GetScriptScope() )

//include the manual scene table for act 3
DoIncludeScript( "choreo/glados_scenetable_include_manual_cave", self.GetScriptScope() )

//include the manual scene table for act 4
DoIncludeScript( "choreo/glados_scenetable_include_manual_act4", self.GetScriptScope() )


function printldebug(arg)
{
	if (debug)
	{
		printl(arg)
	}
}


// -------------------------------------------------------------------
// Precache sounds we will emit
// Define like this: self.PrecacheSoundScript( "Your.SoundName" )
//
// Then you call the sound like so:
// self.EmitSound("Your.SoundName")
// -------------------------------------------------------------------
function Precache()
{              
	if (curMapName=="sp_a4_tb_trust_drop")
	{
		self.PrecacheSoundScript( "World.WheatleyZap" )
	}
	if (curMapName=="sp_a1_wakeup")
	{
		self.PrecacheSoundScript( "World.HackBuzzer" )
	}
	if (curMapName=="sp_a3_speed_ramp")
	{
		self.PrecacheSoundScript( "World.WheatleyZap" )
		self.PrecacheSoundScript( "World.GladosPotatoZap" )
	}
	if (curMapName=="sp_a3_transition01")
	{
		self.PrecacheSoundScript( "World.GladosPotatoZap" )
	}

	
}

//function testemito()
//{
//	self.EmitSound("World.Electrocution")
//}




// OnPostSpawn - this is all the initial setup stuff
function OnPostSpawn()
{
		local i = 0
		//assign a unique id to each scene entity (uses SetTeam because that's the only thing available)
		foreach (val in SceneTable)
		{
			i+=1
			val.vcd.ValidateScriptScope()
			val.vcd.SetTeam(i)
			val.index <- i
		}		
		//Initialize the deferred scene queue
		QueueInitialize()
		PuzzlePreStart()
		
		//Map specific Spawn stuff
		switch (curMapName)
		{
			case "sp_a1_wakeup":
				EntFire("@glados","runscriptcode","sp_a1_wakeup_start_map()",1.0)
				break
		}
}



//Passed the unique team id associated with a scene entity defined in SceneTable, this function returns the correct SceneTable index for that entry
//ex: SceneTableInst = SceneTable[findIndex(team)]
function findIndex(team)
{
		local idx, val
		foreach (idx, val in SceneTable)
		{
			if (val.index == team)
			{
				return idx
			}
		}
		return null
}

//Passed the unique team id associated with a scene entity defined in SceneTable, this function returns the scene instance that originally fired it.
//Unfortunately, if multiple scene instances fire the same vcd, this isn't reliable. Hopefully we can either a) fix that 
//or b) not have multiple scene instances use the same vcd (which is currently the case as of 07/19/2010 - efw)
function FindSceneInstanceByTeam(team)
{
	local idx, val
	local idx2, val2
	local inst = null
	foreach (idx, val in scenequeue)
	{
		foreach (idx2, val2 in val.waitFiredVcds)
		{
			if (val2 == team)
			{
				inst = val
				break
			}
		}
		if (inst != null)
			break
	}
	return inst
}


function SceneCanceled()
{
	printldebug("========SCENE CANCELLED - CALLING ENTITY: "+findIndex(owninginstance.GetTeam()))
}

//If a vcd is tagged to "exit early" (by setting postdelay < 0), this event fires rather than PlayNextScene() when the vcd finishes.
//SkipOnCompletion() has all the functionality of PlayNextScene(), except it doesn't actually play the next scene, because the next scene presumably
//already started playing when the vcd exited early.
//SkipOnCompletion does, however, evaluate the vcd's SceneTable entry to see if any EntFires need to happen.
function SkipOnCompletion()
{
	printldebug("========SKIPONCOMPLETION CALLING ENTITY: "+findIndex(owninginstance.GetTeam())+" : TIME "+Time())
	local team = owninginstance.GetTeam()
	local inst = FindSceneInstanceByTeam(team)
	if (inst != null)
	{
		inst.deleteFiredVcd(team)
		inst.waitVcdCurrent = findIndex(team)
		//Are there any EntFires associated with this vcd?
		if (inst.waitVcdCurrent != null)
		{
			if ("fires" in SceneTable[inst.waitVcdCurrent])
			{
				local idx, val
				foreach (idx, val in SceneTable[inst.waitVcdCurrent].fires)
				{
					if (!("fireatstart" in val))
					{
						printldebug(">>>>>>ENT FIRE AT (SKIPCOMPLETION) END: "+val.entity+":"+val.input)
						EntFire(val.entity,val.input,val.parameter,val.delay)
					}
				}
			}
		}
	}
}	


function PlayNextScene()
{
	local team = owninginstance.GetTeam()
	local inst = FindSceneInstanceByTeam(team)
	if (inst != null)
	{
		printldebug("========PLAYNEXTSCENE CALLING ENTITY: "+findIndex(owninginstance.GetTeam())+" : TIME "+Time())
		inst.deleteFiredVcd(team)
		inst.waitVcdCurrent = findIndex(team)
		PlayNextSceneInternal(inst)
	}	
	else
	{
		printldebug("========PLAYNEXTSCENE CALLING ENTITY NO LONGER EXISTS: CHECKING QUEUE...")
		QueueCheck()
	}
}	



function PlayNextSceneInternal(inst = null)
//inst = just completed scene
{
	local i = 0
	local tmp = 0

	//Set the ducking back to the default value
	SendToConsole( "snd_ducktovolume 0.55" )
	
	//Are there any "fire at the end" triggers associated with the just completed?
	if (inst.waitVcdCurrent != null)
	{
		if ("fires" in SceneTable[inst.waitVcdCurrent])
		{
			local idx, val
			foreach (idx, val in SceneTable[inst.waitVcdCurrent].fires)
			{
				if (!("fireatstart" in val))
				{
					printldebug(">>>>>>ENT FIRE AT END: "+val.entity+":"+val.input)
					EntFire(val.entity,val.input,val.parameter,val.delay)
				}
			}
		}
	}
	
	//If the vcd that's ending is part of a nag cycle, check to see if there are any queued
	//scenes for the primary nag character. If so, abandon the nag and start the queued scene.
	if (inst.isNag) 
	{
		if (QueueLen(inst.currentCharacter)>0)
		{
			printldebug("========ABANDONING NAG CYCLE TO PLAY QUEUED SCENE")
			scenequeue_DeleteScene(inst.index)
			QueueCheck()
			return
		}	
	}
	
	//Is there another vcd in the scene chain?
	if (inst.waitNext != null)
	{
		printldebug("=====There is a next scene: "+inst.waitNext)
		if (inst.waitLength == null)
		{
			i+=1
			printldebug("===================Ready to play:" + i)
			GladosPlayVcd(inst)
 		}	
		else
		{
			inst.waitStartTime = Time()
			inst.waiting = 1
		}	
	}
	else
	{
		printldebug("=====No next scene!")
		//Remove the instance from the scene list
		scenequeue_DeleteScene(inst.index)
		//The current scene is over. Check to see if there are any queued scenes.
		if (QueueCheck())
			return
		//Do the ding if nothing's queued and the previous scene requires a ding
		if (!inst.waitNoDingOff)
			EntFireByHandle( sceneDingOff, "Start", "", 0.1, null, null )
	}
}


//Think function
function GladosThink()
{
	//Put debug stuff here!
	if (debug)
	{
		if (Time()-lastthink>debugInterval)
		{
			printldebug("===================GladosThink-> " + lastthink)
			lastthink = Time()
			QueueDebug()
		}
	}	
	//Is GLaDOS gibbering
	//if (glados_gibbering)
	//{
		//sp_sabotage_glados_gibberish()
	//}
	//Are we PitchShifting?
	if (pitchShifting)
	{
		if (Time()-pitchShiftLastThink>pitchShiftInterval)
		{
			local curscene = self.GetCurrentScene()
			if ( curscene != null )
			{ 
				local shiftAmount = RandomFloat( -0.10, 0.10)
				if (shiftAmount<0.00)
					shiftAmount=shiftAmount*1.5
				pitchShiftValue += shiftAmount
				if ((pitchShiftValue <= 0.0) || (pitchShiftValue >= 1.7) )
					pitchShiftValue -= (shiftAmount*2)
				EntFireByHandle( curscene, "PitchShift", pitchShiftValue.tostring(), 0, null, null )
				pitchShiftInterval = RandomFloat( 0.1, 0.2)
			}
			//Set Lastthink
			pitchShiftLastThink = Time()
		}
	}	
	
	
	local idx, val
	//scan the list of currently playing scenes.
	foreach (idx,val in scenequeue)
	{
		//Check if the current vcd is scheduled to exit early
		if (val.waitPreDelayed)
		{
			if (Time()>=val.waitDelayingUntil)
			{
				printldebug("*******LAUNCHING PREDELAYED SCENE")
				GladosPlayVcd(val)
			}
		}
		if (val.waitExitingEarly)
		{
			if (Time()-val.waitExitingEarlyStartTime >= val.waitExitingEarlyThreshold)
			{
				local team
				val.waitExitingEarly=false
				local curscene = characterCurscene(val.currentCharacter)
				if (curscene!=null)
				{
					curscene.ValidateScriptScope()
					curscene.GetScriptScope().SkipOnCompletion <- SkipOnCompletion.bindenv(this)
					curscene.DisconnectOutput("OnCompletion", "PlayNextScene")
					curscene.DisconnectOutput("OnCompletion", "SkipOnCompletion")
					curscene.ConnectOutput( "OnCompletion", "SkipOnCompletion" )
					team = curscene.GetTeam()
					val.waitVcdCurrent = findIndex(team)
				}
				printldebug("====Scene "+val.index+" EXITING EARLY")
				PlayNextSceneInternal(val)
				return
			}
		}
	}
	
	local tmp
	//Check the deferred scene queue
	tmp = QueueThink()
	//Is a queued scene ready to fire?
	if (tmp != null)
	{
			printldebug("===========FORCING QUEUED SCENE: "+tmp)
			GladosPlayVcd(tmp,true)
			return
	}

	foreach (idx,val in scenequeue)
	{
		//Are we waiting to play another vcd?
		if (val.waiting == 1)
		{
			if (Time()-val.waitStartTime >= val.waitLength)
			{
				val.waiting = 0
				GladosPlayVcd(val)
			}
		}
	}
}


//Play a vcd from the SceneTable, plus set up next line (if any).
//This is the function that should be used to start a scene from inside a map.
function GladosPlayVcd(arg,IgnoreQueue = null, caller = null)
//arg==instance	-> Continue playing scene defined by scene class instance arg
//arg==integer	-> Start playing new scene (scene being a chain of vcds) from SceneTable[SceneTableLookup[arg]]
//arg==string		-> Start playing new scene (scene being a chain of vcds) from SceneTable[arg]
//arg==null			-> Continue playing current scene with next vcd in current chain
//IgnoreQueue		-> true == don't check for queue status (this is used to force a queued vcd to play)
//caller				-> If passed as an entity, the vcd will have its "target1" set to caller.GetName()
{
	printldebug("=========GladosPlayVcd Called!========="+arg)	
	local dingon = false
	
	local inst
	local fromqueue = firedfromqueue
	firedfromqueue = false
	
	if (typeof arg == "instance")
	{
		//if this is a vcd that was being held for predelay, play it
		if (arg.waitPreDelayed)
		{
			inst = arg
			arg = inst.waitPreDelayedEntry
		}
		//otherwise, play the next vcd in the chain
		else
		{
			inst = arg
			arg=inst.waitNext
		}	
	}
	else
	{
		//If this is a call from the map, look up the integer arg in the scene lookup table.
		//We need to do this because hammer/the engine can't pass a squirrel script a string, just an integer.
		//In other words, from a map, @glados.GladosPlayVcd("MyVcd") crashes the game. GladosPlayVcd(16) doesn't.
		local sceneStart = 0
		if (typeof arg == "integer")
		{
			if (arg == 407 || arg == 43) //remove this line without changing map (12/21/2010)
			{
				return
			}
			sceneStart = arg
			printldebug("{}{}{}{}{}{}{}{}{}GladosPlayVcd: "+arg)	
			arg = SceneTableLookup[arg]
		}
		else
		{
			sceneStart = 0
		}
		//if SkipIfBusy is present & we're already playing a scene, skip this new scene
		if ("skipifbusy" in SceneTable[arg])
		{
			if (characterCurscene(SceneTable[arg].char)!=null)
			{
				return
			}
		}
		//if queue is present & we're already playing a scene, add scene to queue
 		if ("queue" in SceneTable[arg])
	 	{
	 		if (IgnoreQueue == null)
			{
				//queue if a specific character is talking 
		 		if ("queuecharacter" in SceneTable[arg])
		 		{
					if (characterCurscene(SceneTable[arg].queuecharacter)!=null)
					{
				 		QueueAdd(arg)
			 			return
			 		}
				}
				//otherwise, queue if the character associated with the vcd is talking
				else
				{
					if (characterCurscene(SceneTable[arg].char)!=null)
					{
				 		QueueAdd(arg)
			 			return
			 		}
			 	}	
			}		
	  }
	  
		if (scenequeue_AddScene(arg,SceneTable[arg].char) == null)
			return
		inst = scenequeue[arg]
		inst.waitSceneStart = sceneStart
		
		if ("idle" in SceneTable[arg])
		{
			nags_init(inst,arg)
		}

		//This is a new dialog block, so turn off special processing
		dingon=true
		pitchShifting = false
		//startBlock = Time()
		if ("noDingOff" in SceneTable[arg])
			inst.waitNoDingOff = true
		else
			inst.waitNoDingOff = false	
		if ("noDingOn" in SceneTable[arg])
			inst.waitNoDingOn = true
		else
			inst.waitNoDingOn = false	
	}
	
	local preDelay = 0.00
	//If this vcd wasn't called after a predelay (meaning the predelay already happened), see if there is a predelay
	if (!inst.waitPreDelayed)
	{
		preDelay = EvaluateTimeKey("predelay", SceneTable[arg])
		if (fromqueue && "queuepredelay" in SceneTable[arg])
		{
			preDelay = EvaluateTimeKey("queuepredelay", SceneTable[arg])
		}
		//If there is a predelay, set it and then GladosThink() will fire it after predelay seconds.
		if (preDelay > 0.00)
		{
			inst.waitPreDelayed = true
			inst.waitDelayingUntil = Time()+preDelay
			inst.waitPreDelayedEntry = arg
			printldebug("======= "+arg+" PREDELAYED FOR "+preDelay+" SECONDS")
			return
		}
	}
	//Otherwise, set the PreDelayed flag to false	
	else
	{
		inst.waitPreDelayed = false
		inst.waitPreDelayedEntry = null
	}
	
	//If this scene is a nag/idle cycle, grab the next line off the stack
	if (inst.isNag)
	{
		//If we're not in a vcd chain, grab the next vcd from the randomized pool
		if (!inst.naginchain)
		{
			arg = nags_fetch(inst)
		}	
		//if nothing fetched (because the nag has used all the lines and isn't marked as "repeat"), remove this scene
		if (arg == null)
		{
			scenequeue_DeleteScene(inst.index)
			return
		}
	}
	
	//Set ducking volume correctly for booming glados audio
	SendToConsole( "snd_ducktovolume 0.2" )
	
  //SetDucking( "announcerVOLayer", "announcerVO", 0.01 ) 
  //SetDucking( "gladosVOLayer", "gladosVO", 0.1 ) 

	if ( arg != null )
	{

		local ltalkover
		ltalkover =  "talkover" in SceneTable[arg]

		//Cancel any vcd that's already playing
		if (!ltalkover)
		{
			GladosAllCharactersStopScene()
		}	
		else
		{
			//characters can't currently talk over themselves
			GladosCharacterStopScene(SceneTable[arg].char)
		}
		
		//Play the initial ding (unless the scene specifically requests no ding)
		if (dingon && !inst.waitNoDingOn)
			EntFireByHandle( sceneDingOn, "Start", "", 0.00, null, null )

		
		//Start the new vcd	
		printldebug("===================Playing:" + arg)
		inst.currentCharacter = SceneTable[arg].char
		
		//Bind the OnCompletion Event
		SceneTable[arg].vcd.ValidateScriptScope()
		SceneTable[arg].vcd.GetScriptScope().PlayNextScene <- PlayNextScene.bindenv(this)
		SceneTable[arg].vcd.DisconnectOutput( "OnCompletion", "PlayNextScene" )
		SceneTable[arg].vcd.ConnectOutput( "OnCompletion", "PlayNextScene" )
		SceneTable[arg].vcd.ConnectOutput( "OnCanceled", "SceneCanceled" )
		
		//Set the target1 if necessary
		if (caller != null)
		{
			if (typeof caller == "string")
			{
				EntFireByHandle( SceneTable[arg].vcd, "SetTarget1", caller, 0, null, null )
				printldebug("++++++++++++SETTING TARGET: "+caller)
			}	
			else
			{
				EntFireByHandle( SceneTable[arg].vcd, "SetTarget1", caller.GetName(), 0, null, null )
			}
		}	
		if ("settarget1" in SceneTable[arg])
		{
			printldebug("++++++++++++ "+arg+"SETTING TARGET: "+SceneTable[arg].settarget1)
			EntFireByHandle( SceneTable[arg].vcd, "SetTarget1", SceneTable[arg].settarget1 , 0, null, null )
		}

		inst.waitVcdTeam = SceneTable[arg].index
		inst.waitVcdCurrent = arg
		
		inst.addFiredVcd(SceneTable[arg].index)
				
		if (dingon && !inst.waitNoDingOn)
			EntFireByHandle( SceneTable[arg].vcd, "Start", "", 0.00+0.18, null, null )
		else	
			EntFireByHandle( SceneTable[arg].vcd, "Start", "", 0.00, null, null )

		
		//Does this vcd have a "fire into entities" array?
		if ("fires" in SceneTable[arg])
		{
			local idx, val
			foreach (idx, val in SceneTable[arg].fires)
			{
				if ("fireatstart" in val)
				{
					printldebug(">>>>>>ENT FIRE AT START: "+val.entity+":"+val.input)
					EntFire(val.entity,val.input,val.parameter, val.delay)
				}
			}
		}

		if ("special" in SceneTable[arg])
		{
			switch (SceneTable[arg].special)
			{
				case 1: //Block-wide pitch shifting
					pitchShifting = true
					break
				case 2: //Speed up
					if (pitchOverride == null)	
						EntFireByHandle( SceneTable[arg].vcd, "PitchShift", "2.5", 0, null, null )
					break
				case 3: //Slow down a bit	
					EntFireByHandle( SceneTable[arg].vcd, "PitchShift", "0.9", 0, null, null )
					break
			}
		}
		if (pitchOverride!=null)
			EntFireByHandle( SceneTable[arg].vcd, "PitchShift", pitchOverride.tostring(), 0, null, null )

    //Setup next line (if there is one)
    if (SceneTable[arg].next != null || inst.isNag)
    {
    	local pdelay = EvaluateTimeKey("postdelay",SceneTable[arg])
    	
    	//if this is a nag, use min/max defined in the first entry in the scene
    	if (inst.isNag)
    	{
    		pdelay = RandomFloat(inst.nagminsecs,inst.nagmaxsecs)
    	}

    	if (pdelay<0.00)
    	{
    		if (inst.isNag)
    			//If the "next" key != null, it means we're in a vcd chain
    			if (SceneTable[arg].next != null)
    			{
    				inst.waitNext = SceneTable[arg].next
    				inst.naginchain = true
    			}
    			else
    			{
    				//Otherwise, just slug in the same index (any non-null value would work here, however)
						inst.waitNext = arg
    				inst.naginchain = false
					}
    		else
					inst.waitNext = SceneTable[arg].next 
 				inst.waitExitingEarly=true
 				inst.waitLength=null
 				inst.waitExitingEarlyStartTime=Time()
				//If we're in a nag vcd chain, use the vcds postdelay rather than the nag-wide delay
				//This is because vcd chains generally need to be explicitly timed at the chain level
				//since the vcds are grouped together as a block
 				if (inst.naginchain)
 					pdelay = EvaluateTimeKey("postdelay",SceneTable[arg])
 				inst.waitExitingEarlyThreshold=pdelay*-1
			}
			else
			{
 				inst.waitExitingEarly=false
    		if (inst.isNag)
    		{
    			//If the "next" key != null, it means we're in a vcd chain
    			if (SceneTable[arg].next != null)
    			{
    				inst.waitNext = SceneTable[arg].next
    				inst.naginchain = true
    			}
    			else
    			{
    				//Otherwise, just slug in the same index (any non-null value would work here, however)
						inst.waitNext = arg
    				inst.naginchain = false
					}
				}
    		else
    		{
					inst.waitNext = SceneTable[arg].next 
				}	
				//If we're in a nag vcd chain, use the vcds postdelay rather than the nag-wide delay
				//This is because vcd chains generally need to be explicitly timed at the chain level
				//since the vcds are grouped together as a block
 				if (inst.naginchain)
 					pdelay = EvaluateTimeKey("postdelay",SceneTable[arg])
			}	
   		inst.waitLength = pdelay
    }	
		else
		{
			inst.waitNext = null
			printldebug("===================SCENE END")
		}
	}	
}

function EvaluateTimeKey(keyname, keytable)
{
	local ret = null

 	if (keyname in keytable)
 	{
 		local typ = typeof keytable[keyname]
 		if (typ == "array")
 		{
 			if (keytable[keyname].len() != 2)
 			{
				printldebug("!!!!!!!!!!!!EVALUATE TIME KEY ERROR: "+keyname+" is an array with a length != 2") 		
				return 0.00
 			}
	 		ret = RandomFloat(keytable[keyname][0],keytable[keyname][1])
	 	}
	 	else
	 	{
	 		ret = keytable[keyname]
	 	}	
 	}
 	if (ret == null)
 		ret = 0.00
	printldebug(">>>>>>>>>EVALUATE TIME KEY: "+keyname+" : "+ret) 		
 	return ret
}


function GladosToggleDebug(arg = null)
{
	debug = !debug
	if (debug)
		printl("======================GLaDOS debug ON")
	else
		printl("======================GLaDOS debug OFF")
	if (arg!=null)
		debugInterval = arg
}

function GladosSetPitch(arg)
{
	pitchOverride = arg
	local curscene = self.GetCurrentScene()
	if ( curscene != null )	
		EntFireByHandle( curscene, "PitchShift", pitchOverride.tostring(), 0, null, null )
}


//Nukes Everything. Delete all currently playing & queued scenes.
function nuke()
{
	scenequeue = {}
	Queue.clear()
	GladosAllCharactersStopScene()
	StopAllCaveSpeakers()
	
}

//Checks each cave speaker actor to see if it's playing a vcd and stops it if it is.
function StopAllCaveSpeakers()
{
	local caveactors = array(27),ent,val,sc
	caveactors[0] = "@cave_exit_lift"
	caveactors[1] = "cave_a3_03_dummy"
	caveactors[2] = "cave_a3_03_dummy2"
	caveactors[3] = "cave_a3_03_dummy3"
	caveactors[4] = "cave_a3_03_exit"
	caveactors[5] = "cave_a3_03_lift_shaft"
	caveactors[6] = "cave_a3_03_waiting_room"
	caveactors[7] = "cave_a3_jump_intro_entrance"
	caveactors[8] = "cave_a3_jump_intro_interchamber"
	caveactors[9] = "cave_a3_jump_intro_second_chamber"
	caveactors[10] = "cave_a3_transition01_dummy"
	caveactors[11] = "cave_a3_transition01_dummy2"
	caveactors[12] = "cave_a3_transition01_dummy3"
	caveactors[13] = "cave_bomb_flings_chamber"
	caveactors[14] = "cave_bomb_flings_entrance"
	caveactors[15] = "cave_crazy_box_2nd_chamber"
	caveactors[16] = "cave_crazy_box_dummy_chamber"
	caveactors[17] = "cave_crazy_box_entrance"
	caveactors[18] = "cave_portal_intro_entrance"
	caveactors[19] = "cave_portal_intro_exit"
	caveactors[20] = "cave_portal_intro_office"
	caveactors[21] = "cave_portal_intro_whitepaint"
	caveactors[22] = "cave_speed_flings_entrance"
	caveactors[23] = "cave_speed_ramp_entrance"
	caveactors[24] = "cave_speed_ramp_inter_chamber"
	caveactors[25] = "cave_transition01_dummy_exit"
	caveactors[26] = "cave_transition01_welcome"

	foreach (val in caveactors)
	{
			ent=null
			ent = Entities.FindByName(ent, val)
			if (ent != null)
			{
				sc = ent.GetCurrentScene()
				if ( sc != null )	
				{
					EntFireByHandle( sc, "Cancel", "", 0, null, null )
				}	
			}
	}
}


//Stops a scene for all characters
function GladosAllCharactersStopScene()
{
	GladosCharacterStopScene("glados")
	GladosCharacterStopScene("wheatley")
	GladosCharacterStopScene("cave_body")
	GladosCharacterStopScene("core01")
	GladosCharacterStopScene("core02")
	GladosCharacterStopScene("core03")
}

function characterCurscene(arg)
{
	local ret = null, ent = null
	switch (arg)
	{
		case "bossannouncer":
			ent = Entities.FindByName(ent, "@actor_announcer")
			break
		case "announcerglados":
			ent = Entities.FindByName(ent, "@glados")
			break
		case "glados":
		case "@glados":
			ent = Entities.FindByName(ent, "@glados")
			break
		case "cave":
		case "@cave":
			ent = Entities.FindByName(ent, "@cave")
			break
		case "@sphere":
		case "wheatley":	
		case "sphere":
			ent = Entities.FindByName(ent, "@sphere")
			break
		case "core01":	
		case "@core01":	
			ent = Entities.FindByName(ent, "@core01")
			break
		case "core02":	
		case "@core02":	
			ent = Entities.FindByName(ent, "@core02")
			break
		case "core03":	
		case "@core03":	
			ent = Entities.FindByName(ent, "@core03")
			break
		case "cave_body":	
		case "cavebody":	
			ent = Entities.FindByName(ent, "@cave_body")
			break
		case "conveyor_turret":	
			ent = Entities.FindByName(ent, "conveyor_turret_body")
			break
	}
	if (ent != null)
	{
		printldebug("&&&&&&FOUND ENTITY: "+arg)
		ret = ent.GetCurrentScene()
	}	
	return ret
}

//Stops a scene for a particular character
function GladosCharacterStopScene(arg)
{
	local ent = null
	local curscene = characterCurscene(arg)
	if ( curscene != null )
	{
		printldebug("&&&&&&STOP SCENE: "+arg+" FOUND SCENE TO DELETE!!!!!!!!!")
		EntFireByHandle( curscene, "Cancel", "", 0, null, null )
	}
	else
	{
		printldebug("&&&&&&STOP SCENE: NO SCENE TO DELETE FOR " + arg)
	}
}

//Turns off current Glados speech
function GladosStopTalking()
{
	local curscene = self.GetCurrentScene()
	pitchOverride = null
	waitNext = null
	waitLength = null
	if ( curscene != null )	
			EntFireByHandle( curscene, "Cancel", "", 0, null, null )
}

//Turns off current Glados speech if the scene # passed as arg is currently playing
function GladosStopScene(arg)
{
	if (waitSceneStart == arg)
	{ 
		local curscene = self.GetCurrentScene()
		pitchOverride = null
		waiting = 0
		waitNext = null
		waitLength = null
		if ( curscene != null )	
			EntFireByHandle( curscene, "Cancel", "", 0, null, null )
	}		
}

//Slowfield functions
function GladosEndSlowFieldTraining()
{
	stateSlowFieldTraining = false
	GladosStopTalking()
}

function GladosStartSlowFieldTraining()
{
	stateSlowFieldTraining = true
	GladosPlayVcd(40)
}

function GladosSlowFieldOn()
{
	if (stateSlowFieldTraining)
		GladosPlayVcd(41)
}

function GladosSlowFieldOff()
{
	if (stateSlowFieldTraining)
		GladosPlayVcd(40)
}
//End of Slowfield functions

//Special Chamber Processing
function GladosRelaxationVaultPowerUp()
{
	EntFire("open_portal_relay","Trigger","", 0.00)
}

//----------------------------------------------------------------------------------------------------------------
// Automated dialog lookup
//----------------------------------------------------------------------------------------------------------------

function MapNameConversion(orgname)
{
	if (orgname in MapBspConversion)
	{
		return  MapBspConversion[orgname]
	}
	else
	{
		return orgname
	}
}


GladosDialog <- 
[
	{ map = "sp_a1_intro2", prestart = "PreHub01PortalCarouselEntry01" completed = "PreHub01PortalCarouselSuccess01" },
	{ map = "sp_a1_intro3", prestart = "sp_intro_03Start01"  completed = "sp_intro_03MindTheGapFinish01"},
	{ map = "sp_a1_intro4", start = "PreHub01BoxDropperEntry01" completed = "sp_a1_intro4End01" },
	//{ map = "sp_a1_intro5", start = "PreHub01DualButtonOnePortalEntry01" completed = "PreHub01DualButtonOnePortalSuccessB01" },
	{ map = "sp_a1_intro5", start = "sp_a1_intro5Start01" completed = "PreHub01DualButtonOnePortalSuccessB01" },
	{ map = "sp_a1_intro6", start = "sp_a1_intro6Start01" completed = "sp_a1_intro6End01" },
	{ map = "sp_a1_intro7", prestart = "sp_a1_intro7Start01" },
	//{ map = "sp_incinerator_01", exitstarted = "sp_incinerator_01Elevator01" },
	{ map = "sp_laser_redirect_intro", start = "sp_laser_redirect_introStart01" completed = "sp_laser_redirect_introEnd01" },
	{ map = "sp_laser_stairs", start = "sp_laser_stairsStart01" completed = "sp_laser_stairsEnd01" },
	{ map = "sp_laser_dual_lasers", prestart = "sp_laser_dual_lasersStart01" completed = "sp_laser_dual_lasersEnd01" },
	{ map = "sp_laser_over_goo", start = "sp_laser_over_gooStart01" completed = "sp_laser_over_gooEnd01" },
	{ map = "sp_catapult_intro", completed = "sp_catapult_introEnd01" },
	{ map = "sp_trust_fling", prestart = "sp_trust_flingStart01" completed = "sp_trust_flingEnd01" },
	{ map = "sp_a2_pit_flings", prestart = "sp_a2_pit_flingsStart01" completed = "sp_a2_pit_flingsCubeSmuggleEnding01" },
	{ map = "sp_a2_fizzler_intro" start = "sp_a2_fizzler_introStart01" },
	{ map = "sp_catapult_fling_sphere_peek",  completed = "sp_catapult_fling_sphere_peekEnd01" },
	{ map = "sp_a2_ricochet", prestart = "sp_a2_ricochetStart01" completed = "sp_a2_ricochetEnd01"},
	{ map = "sp_bridge_intro", completed = "sp_bridge_introEnd01" },
	{ map = "sp_bridge_the_gap", prestart = "sp_bridge_the_gapStart01" completed = "sp_bridge_the_gapEnd01" },
	{ map = "sp_turret_training_advanced", prestart = "sp_turret_training_advancedStart01" },
	{ map = "sp_laser_relays",  prestart = "sp_laser_relaysStart01" completed = "sp_laser_relaysEnd01" },
	{ map = "sp_a2_turret_blocker", prestart = "sp_turret_blocker_introStart01" completed = "sp_turret_blocker_introEnd01" },
	{ map = "sp_laser_vs_turret_intro", prestart = "sp_laser_vs_turret_introStart01" completed = "sp_laser_vs_turret_introEnd01" },
	{ map = "sp_a2_pull_the_rug", prestart = "sp_a2_pull_the_rugStart01" completed = "sp_a2_pull_the_rugEnd01" },
	//RING AROUND THE TURRETS NO LONGER IN THE TRACK
	//{ map = "sp_ring_around_the_turrets",  completed = "sp_ring_around_the_turretsEnd01" }, **
	{ map = "sp_column_blocker", completed = "sp_column_blockerEnd01" },
	{ map = "sp_a2_laser_chaining" prestart = "sp_a2_laser_chainingStart01" completed = "sp_a2_laser_chainingEnd01"},
	//Turret Tower no longer in track
	//{ map = "sp_turret_tower" prestart = "sp_turret_towerStart01" completed = "sp_turret_towerEnd01"},
	{ map = "sp_a2_triple_laser" start = "sp_a2_triple_laserStart01" completed = "sp_a2_triple_laserEnd01"},
	{ map = "sp_sabotage_jailbreak" prestart = "sp_sabotage_jailbreakStart01" },
	{ map = "sp_a3_speed_ramp", prestart = "-3150_01" },
	{ map = "sp_a4_finale3", prestart = "-4849_01" },
]

//Generic glados dialog functions.
//PuzzleStart fires automatically as the player moves out of the level transition area
function PuzzleStart()
{
	printldebug( "===============In Puzzle Start" + GetMapName())
	local mpco
	foreach (index, level in GladosDialog)
	{
		mpco=MapNameConversion(level.map)
		if ((level.map == GetMapName() || mpco == GetMapName()) && ("start" in level) )
		{
			printldebug( "===============PuzzleStart: playing scene " + level.start )
			GladosPlayVcd(level.start)
		}
	}
}

//PuzzlePreStart fires just after the level load
function PuzzlePreStart()
{
	printldebug( "===============In Puzzle PreStart")
	local mpco
	foreach (index, level in GladosDialog)
	{
		mpco=MapNameConversion(level.map)
		if ((level.map == GetMapName() || mpco == GetMapName()) && ("prestart" in level) )
		{
			printldebug( "===============PuzzlePreStart: playing scene " + level.prestart )
			GladosPlayVcd(level.prestart)
		}
	}
}

didLeftElevatorChamber <- false

function LeftElevatorChamber()
{
	if (!didLeftElevatorChamber)
	{
		didLeftElevatorChamber = true
		local mpco
		foreach (index, level in GladosDialog)
		{
			mpco=MapNameConversion(level.map)
			if ((level.map == GetMapName() || mpco == GetMapName()) && ("leftelevatorchamber" in level) )
			{
				printldebug( "===============LeftElevatorChamber: playing scene " + level.leftelevatorchamber )
				GladosPlayVcd(level.leftelevatorchamber)
			}
		}
	}
}

//ExitStarted fires when the exit elevator doors close
function ExitStarted()
{
	printldebug( "===============In Puzzle ExitStarted")
	local mpco
	foreach (index, level in GladosDialog)
	{
		mpco=MapNameConversion(level.map)
		if ((level.map == GetMapName() || mpco == GetMapName()) && ("exitstarted" in level) )
		{
			printldebug( "===============ExitStarted: playing scene " + level.exitstarted )
			GladosPlayVcd(level.exitstarted)
		}
	}
}

//PuzzleCompleted fires when the glados exit speech is supposed to trigger. It isn't fired automatically from an instance.
//It needs to fire from a trigger in the map
function PuzzleCompleted()
{
	local mpco
	foreach (index, level in GladosDialog)
	{
		mpco=MapNameConversion(level.map)
		if ((level.map == GetMapName() || mpco==GetMapName()) && ("completed" in level) )
		{
			printldebug( "===============PuzzleCompleted: playing scene " + level.completed )
			GladosPlayVcd(level.completed)
		}
	}
}

//--------------------------------------------------------------------------------------------------------------
//Queue Functions
//	-This is the queue of scenes delayed by another scene
//--------------------------------------------------------------------------------------------------------------

Queue <- []

//Initialize the queue
function QueueInitialize()
{
	Queue.clear()
}

//Add a scene to the queue
//Queue table structure:
//	item 						= index in SceneTable (ie: SceneTable[Queue[index].item])
//	added						= time added to queue
//	queueforcesecs	= (from SceneTable) force item to play after queueforcesecs seconds in queue
//	queuetimeout		= (from SceneTable) delete item if it sits in queue for queuetimeout seconds
//	queuepredelay		= (from SceneTable) wait queuepredelay seconds to fire the scene if it sat in the queue for any amount of time
function QueueAdd(arg)
{
	Queue.append( { item = arg added = Time() })
	if (arg in SceneTable)
	{
 		if ("queueforcesecs" in SceneTable[arg])
 		{
 			Queue[Queue.len()-1].queueforcesecs <- SceneTable[arg].queueforcesecs
 		}
 		else
 		{
 			Queue[Queue.len()-1].queueforcesecs <- 45.0
 		}
 		if ("queuetimeout" in SceneTable[arg])
 		{
 			Queue[Queue.len()-1].queuetimeout <- SceneTable[arg].queuetimeout
 		}
 		if ("queuepredelay" in SceneTable[arg])
 		{
 			Queue[Queue.len()-1].queuepredelay <- SceneTable[arg].queuepredelay
 		}

	}
}

//Returns number of items in the queue
function QueueLen(char = null)
{
	local i = 0
	if (char == null)
	{
		return Queue.len()
	}	
	else
	{
		foreach (index, scene in Queue)
		{
			if (SceneTable[scene.item].char == char)
			{
				i+=1
			}
		}
		return i
	}
}

//Fetch the next scene in the queue
function QueueGetNext()
{
	local ret,l
	ret = null
	l=QueueLen()
	if (l>0)
	{
		ret = Queue[l-1].item
		Queue.remove(l-1)
	}
	return ret
}

function QueueDebug()
{
	printldebug("===================  items in queue-> " + Queue.len())
	foreach (index, scene in Queue)
	{
		printldebug("========= queue item "+index+"("+scene.item+"): character "+SceneTable[scene.item].char)
	}
}

//General stuff called from GladosThink()
function QueueThink()
{
	local ret,t,index
	if (QueueLen()==0)
	{
		return null
	}	
	
	t=Time()
	//Check to see if any queued scenes timed out
	for (index = QueueLen(); index > 0; index -= 1)
	{
 		if ("queuetimeout" in Queue[index-1])
 		{
 			if (t-Queue[index-1].added > Queue[index-1].queuetimeout)
 			{
 				Queue.remove(index-1)
 			}
 		}
	}

	//Check to see if any queued scenes should force fire
	foreach (index, scene in Queue)
	{
 		if ("queueforcesecs" in scene)
 		{
 			if (t-scene.added >scene.queueforcesecs)
 			{
 				ret = scene.item
 				Queue.remove(index)
 				return ret
 			}
 		}
	}
	return null
}

//Debug testbed function
function QueueTest()
{
	local a = []
	for(local i=0;i<10;i+=1)
	{
		a.append(RandomInt(1,100))
		printl(">>>>>> " + i + " : " + a[i])
	}
	for (local i = a.len(); i>0; i-=1)
	{
		if (a[i-1]<50)
			a.remove(i-1)
	}
	foreach (index, n in a)
	{
		printl(">>>>>> " + index + " : " + a[index])
	}
}

//Delete a single item from the queue
function QueueDeleteItem(item)
{
	if (QueueLen()==0)
	{
		return false
	}	
	foreach (index, scene in Queue)
	{
		if (scene.item == item)
		{
 				Queue.remove(index)
 				return true
 		}
	}
	return false
}


//Check to see if there's a Queued scene ready to go. If so, fire it! (and return true)
function QueueCheck()
{
	local tmp
	if (QueueLen()>0)
	{
		printldebug("===QUEUE LEN IS "+QueueLen())
		tmp=QueueGetNext()
		if (tmp != null)
		{
			firedfromqueue = true
			GladosPlayVcd(tmp,true)
			//GladosPlayVcd(tmp)
			return true
		}
	}
	return false
}

//--------------------------------------------------------------------------------------------------------------
//End of Queue Functions
//--------------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------------
//sp_sabotage_jailbreak specific functions 
//--------------------------------------------------------------------------------------------------------------

function jailbreak_alert(arg)
{
	jailbreakpos =arg
	printldebug("==========JAILBREAK ALERT "+arg)
}

function jailbreak_whoah_speech()
{
	if (jailbreakpos == 0)
	{
		GladosPlayVcd(303)
	}
	else
	{
		GladosPlayVcd(302)
	}
}


//--------------------------------------------------------------------------------------------------------------
//sp_sabotage_darkness specific functions 
//--------------------------------------------------------------------------------------------------------------


function PlayGhostStory()
{
	GladosPlayVcd(445)
}

function PlaySmellyHumansOne()
{
	GladosPlayVcd(446)
}

function PlaySmellyHumansTwo()
{
	GladosPlayVcd(447)
}
 
function PlaySmellyHumansThree()
{
	GladosPlayVcd(448)
}

function PlaySmellyHumansFour()
{
	GladosPlayVcd(449)
}


//--------------------------------------------------------------------------------------------------------------
//Glados Battle specific functions 
//--------------------------------------------------------------------------------------------------------------

glados_gibbering <- false
glados_gibbering_start <- Time()
glados_gibbering_next <- 0.00
glados_gibbering_times <- {}

glados_gibbering_times[1] <- 0.7
glados_gibbering_times[2] <- 1.37
glados_gibbering_times[3] <- 1.22
glados_gibbering_times[4] <- 1.27
glados_gibbering_times[5] <- 5.29
glados_gibbering_times[6] <- 4.15
glados_gibbering_times[7] <- 3.35



if (curMapName=="sp_a2_core" )
{
	sp_a2_core_xfer_left_annex <- false
}



function sp_sabotage_glados_start_gibberish()
{
	//gibberish is off for now
	//glados_gibbering = true
	glados_gibbering_start = Time()
	glados_gibbering_next = 0.00
}

function sp_sabotage_glados_stop_gibberish()
{
	glados_gibbering = false
}

function sp_sabotage_glados_gibberish()
{
	local i = RandomInt(1,7)
	if (Time() - glados_gibbering_start > glados_gibbering_next)
	{
		SendToConsole( "scene_playvcd npc/glados/sp_sabotage_glados_gibberish0"+i)
		glados_gibbering_start = Time()
		//glados_gibbering_next = RandomFloat(3.5, 5.0)
		glados_gibbering_next = glados_gibbering_times[i]
	}	
}



// ==============================
// player starts vault trap
// ==============================
function VaultTrapStart()
{
	GladosPlayVcd(-50)
}

// ==============================
// player begins moving in relaxation vault
// ==============================
function VaultTrapStartMoving() 
{
	GladosPlayVcd(-53)
}

// ==============================
// turrets are on the ground and begin their scene
// ==============================
function TurretScene()
{
	GladosPlayVcd(-700)
}
 
// ==============================
// ==============================
function TurretDeathReactionDialog()
{
	GladosPlayVcd(-57)
	//gladosbattle_pre_05 // my turrets!
	//gladosbattle_pre_06 // oh, you were busy back there
	//gladosbattle_pre_17 // i suppose we could just sit here and glare ... but i have a better idea
}



// ==============================
// ==============================
function WheatleyBouncingDownTubeDialog()
{
	// play various "ouch.. oof... ow..." lines here
	// play glados dialog responding to wheatley falling.  "...sigh..."
}


// ==============================
// ==============================
function WheatleyLandsInChamberDialog()
{
	GladosPlayVcd(-61)
	printldebug("==========HELLO!!!!!!!!!!!!!!!!!!!!!")
	//wheatley - gladosbattle_pre01 // Hello!
	//gladosbattle_pre_09 // i hate you so much
}

// ==============================
// ==============================
function CoreDetectedDialog()
{
	//announcer - gladosbattle02 // warning: core corrupted
	//glados - gladosbattle_xfer04 // that's funny i don't feel corrupted. in fact i feel pretty good
	//announcer - gladosbattle03 // alternate core detected
	//wheatley pre05  // ah that's me they're talking about!
	//announcer - gladosbattle03 // to initiate a core transfer deposit core in receptacle
	//ent_fire "deploy_core_receptacle_relay" trigger // deploys the core receptacle
	//glados - gladosbattle_xfer05 // core transfer?
	//glados - gladosbattle_xfer06 // oh you are kidding me
	
}


// ==============================
// ==============================
function WheatleyCoreSocketed()
{

	StopWheatleyPluginNag()
	GladosPlayVcd(-71) // announcer - substitute core accepted.  core, are you willing to start the procedure?
	
}

// ==============================
//	called when the player reaches a catapult or enters the room to press stalemate button
// ==============================
function StalemateAssociateNotSoFast()
{
	StopWheatleyPluginNag()
	GladosPlayVcd(-84)
}


// ==============================
// ==============================
function CoreTransferInitiated()
{
	// start the core particle system
	nuke()
	EntFire("glados_shutdown_particles_relay", "trigger", 0, 0 )
	GladosPlayVcd(-88) //Stalemate Resolved. Core Transfer Initiated.
}

// ==============================
// ==============================
function WheatleyCoreTransferStart()
{
	sp_a2_core_xfer_left_annex = true
	//nuke()
	GladosPlayVcd(-4) // Here I go!
}

function sp_a2_core_leave_annex_nag()
{
	if (!sp_a2_core_xfer_left_annex)
	{
		GladosPlayVcd(-45)
	}
}

// ==============================
// ==============================
function PitHandsGrabGladosHead()
{
	GladosPlayVcd(-89) // Get your hands off me!
}

// ==============================
// ==============================
function PullGladosIntoPit()
{
	GladosPlayVcd(-90) // CHELL! STOP THIS! I AM YOUR MOTHER!
}

// ==============================
// ==============================
function CoreTransferCompleted()
{
	GladosPlayVcd(-9)  // Wow! Check ME out, Partner! .. Look how small you are!
} 

// ==============================
// ==============================
function PlayerEnteredElevator()
{
	StopWheatleyElevatorNag()
	CorePlayerInElevator = 1 // this will prevent the elevator nag from being triggered by subsequent IO
	EntFire("@exit_elevator_music_relay","trigger", 0, 0 )
	GladosPlayVcd(-13) // I knew it was going to be cool being in charge..
	
	// delete many of the small_pos arms
	EntFire("small_pos1", "kill", 0, 0 )
	EntFire("small_pos3", "kill", 0, 0 )
	EntFire("small_pos4", "kill", 0, 0 )
	EntFire("small_pos7", "kill", 0, 0 )
	EntFire("small_pos9", "kill", 0, 0 )
	EntFire("small_pos10", "kill", 0, 0 )
}


// ==============================
// ==============================
function DialogDuringPotatosManufacture()
{
	GladosPlayVcd(-33)
}

// ==============================
// ==============================
function PotatosPresentation()
{
	GladosPlayVcd(-34)
}

// ==============================
// ==============================
function ElevatorMoronScene()
{
	GladosPlayVcd(-37)
}

// ==============================
// ==============================
function ElevatorConclusion()
{
	GladosPlayVcd(-44)
}


//--------------------------------------------------------------------------------------------------------------
//sp_sabotage_factory functions 
//--------------------------------------------------------------------------------------------------------------

function sabotage_factory_WatchTheLine()
{
	GladosPlayVcd(441)
}

function sabotage_factory_ReachedHackingSpot()
{
	GladosPlayVcd(442)
}

function sabotage_factory_PlayerReachedWheatley()
{
	WheatleyStopNag()
	GladosPlayVcd(443)
}

function sabotage_factory_PlayerReachedExitDoor()
{
	WheatleyStopNag()
	GladosPlayVcd(444)
}	


//--------------------------------------------------------------------------------------------------------------
//sp_sabotage_factory - Science Fair functions 
//--------------------------------------------------------------------------------------------------------------
function ScienceFairGoingTheRightWay()
{
	GladosPlayVcd( -100 )
}

function ScienceFairBringDaughter()
{
	GladosPlayVcd( -101 )
}

function JustToReassureYou()
{
	GladosPlayVcd( -102 )
}

function DefinitelySureThisWay()
{
	GladosPlayVcd( -103 )
}


//--------------------------------------------------------------------------------------------------------------
//sp_catapult_fling_sphere_peek functions 
//--------------------------------------------------------------------------------------------------------------

function sp_catapult_fling_sphere_peek()
{
		switch (peekctr)
		{
			case 0:
				GladosPlayVcd(335)
				break
			case 2:
				GladosPlayVcd(362)
				break
			case 4:
				GladosPlayVcd(363)
				break
		}	
		peekctr+=1
}


//--------------------------------------------------------------------------------------------------------------
//New test functions 
//--------------------------------------------------------------------------------------------------------------
function GladosTest1(arg)
{
	foreach (index, scene in arg)
	{
		if (scene.item)
		{
			arg.remove(index)
		}
	}
}


//--------------------------------------------------------------------------------------------------------------
//Scenes List Functions START
//	-This is the list of currently playing scenes
//--------------------------------------------------------------------------------------------------------------

class scene {
	//constructor
	constructor(a, caller)
	{
		index = a
		owner = caller
		currentCharacter = ""
		waitSceneStart = 0 //1 means we're waiting for the current vcd to finish so we can play the next vcd in the chain
		waiting = 0  
		waitVcdCurrent = null
		waitStartTime = Time()
		waitLength = Time()
		waitNext = null 
		waitExitingEarly = false 
		waitExitingEarlyStartTime = Time() 
		waitExitingEarlyThreshold = 0.00 //How many seconds sould the VCD play before moving on to the next one
		waitDelayingUntil = null
		waitPreDelayed = false
		waitPreDelayedEntry = null
		waitNoDingOff = false
		waitNoDingOn = false
		waitVcdTeam = -1
		waitFiredVcds = []
		nagminsecs = 0
		nagmaxsecs = 0
		nags = []
		isNag = false
		nagpool = []
		naglastfetched = null
		nagrandom = false
		nagrandomonrepeat = false
		nagtimeslistcompleted = 0
		nagrepeat = false
		naginchain = false
	}
	
	function nagsClear()
	{
		naglastfetched = null
		nags.clear()
	}
	
	function nagpoolClear()
	{
		nagpool.clear()
	}


	function addFiredVcd(team)
	{
		waitFiredVcds.append(team)
	}

	function deleteFiredVcd(team)
	{
		local idx, val
		local fnd = null
		foreach (idx, val in waitFiredVcds)
		{
			if (val == team)
			{
				fnd = idx
				break
			}
		}	
		if (fnd != null)
		{
			waitFiredVcds.remove(fnd)
		}
	}

	
	//property
	index = 0;
	owner = null;
	currentCharacter = "";
	waitSceneStart = 0; //1 means we're waiting for the current vcd to finish so we can play the next vcd in the chain
	waiting = 0;  
	waitVcdCurrent = null; //SceneTable index of last launched vcd
	waitStartTime = 0;
	waitLength = 0;
	waitNext = null; 
	waitExitingEarly = false; 
	waitExitingEarlyStartTime = 0; 
	waitExitingEarlyThreshold = 0.00; //How many seconds sould the VCD play before moving on to the next one
	waitDelayingUntil = null;
	waitPreDelayed = false;
	waitPreDelayedEntry = null;
	waitNoDingOff = false;
	waitNoDingOn = false;
	waitFires = [];
	waitVcdTeam = -1;
	waitFiredVcds = [];
	isNag = false;
	nags = [];
	nagpool = [];
	nagminsecs = 0;
	nagmaxsecs = 0;
	naglastfetched = null;
	nagrandom = false;
	nagrandomonrepeat = false;
	nagtimeslistcompleted = 0;
	nagrepeat = false;
	naginchain = false;
}


function scenequeue_AddScene(arg,char)
{
	local idx, val,delme
	delme=null
	foreach (idx, val in scenequeue)
	{
		if (SceneTable[idx].char==char)
		{
			delme = idx
		}
		if (idx == arg)
		{
			printldebug(">>>>>>>>>>Scene "+arg+" is already in the queue")
			return null
		}
	}
	if (delme != null)
	{
		printldebug(">>>>>>>>>>DELETING SCENE "+delme)
		scenequeue_DeleteScene(delme)
	}
	scenequeue[arg] <- scene(arg, this)
	scenequeue_Dump()
	return scenequeue[arg]
}

function scenequeue_DeleteScene(arg)
{
	local idx, val
	foreach (idx, val in scenequeue)
	{
		if (idx == arg)
		{
			printldebug(">>>>>>>>>>Scene "+arg+" deleted!")
			delete scenequeue[arg]
			return true
		}
	}
	return null
}

function scenequeue_Dump()
{
	
	printldebug(">>>>>>>>>>Scene Dump at "+Time())
	foreach (idx, val in scenequeue)
	{
		printldebug(">>>>>>>>>>Scene "+idx+" ADDED at "+val.waitStartTime+" Type "+ typeof val)
	}	
}

//--------------------------------------------------------------------------------------------------------------
//Scene Queue Functions END
//--------------------------------------------------------------------------------------------------------------

//--------------------------------------------------------------------------------------------------------------
//Nag Table Functions START
//--------------------------------------------------------------------------------------------------------------

function nags_init(inst,scenetableentry)
{
	local i = 0
	inst.nagsClear()
	if ("idleminsecs" in SceneTable[scenetableentry])
	{
		inst.nagminsecs = SceneTable[scenetableentry].idleminsecs
		if ("idlemaxsecs" in SceneTable[scenetableentry])
		{
			inst.nagmaxsecs = SceneTable[scenetableentry].idlemaxsecs
		}
		else
		{
			inst.nagmaxsecs = inst.nagminsecs
		}
	}
	
	if ("idlerandomonrepeat" in SceneTable[scenetableentry])
	{
		inst.nagrandomonrepeat = true
	}
	
	if ("idlerepeat" in SceneTable[scenetableentry])
	{
		inst.nagrepeat = true
	}

	if ("idlerandom" in SceneTable[scenetableentry])
	{
		inst.nagrandom = true
	}

	local igroup = SceneTable[scenetableentry].idlegroup
	local idx, val,oig=0
	foreach (idx, val in SceneTable)
	{
		if (!("idlegroup" in val))
			continue
		if (val.idlegroup != igroup)
			continue
		local rar = 101, mnum = 0
		if ("idlerarity" in val)
		{
			rar = val.idlerarity
		}
		if ("idlemaxplays" in val)
		{
			mnum = val.idlemaxplays
		}
		//Skip vcds that are part of a chain (and not the first link in the chain)
		if ("idleunder" in val)
		{
			continue
		}
		if ("idleorderingroup" in val)
		{
			oig=val.idleorderingroup
		}
		else
		{
			oig=0
		}
		inst.nags.append({SceneTableIndex=idx, rarity = rar, maxplays = mnum, totplays = 0,orderingroup = oig})
	}
	inst.nags.sort(nag_array_compare)
	inst.isNag = true
	inst.nagtimeslistcompleted = 0
	nags_createpool(inst)
}

function nags_createpool(inst)
{
	inst.nagpoolClear()
	local idx, val
	local takeit = false
	local tempa = []
	foreach (idx, val in inst.nags)
	{
		takeit=false
		if (val.totplays >= val.maxplays && val.maxplays>0)
		{
			continue
		}
		if (RandomInt(1,100)<val.rarity)
		{
			takeit=true
		}	
		if (takeit)
		{
			tempa.append(val)
		}
	}
	local r
	//The pool can still be empty at this point if only rare lines were available and none of them "made their roll".
	if (tempa.len() == 0)
		return
	
	if (inst.nagrandom || (inst.nagrandomonrepeat && inst.nagtimeslistcompleted > 0))
	{
		//Make sure the first entry in the new list isn't the same as the last vcd played.
		//This ensures no repeats.
		if (tempa.len()>1 && inst.naglastfetched!=null)
		{
			while (true) 
			{
				r=RandomInt(0,tempa.len()-1)
				if (tempa[r].SceneTableIndex != inst.naglastfetched)
				{
					inst.nagpool.append(tempa[r])
					tempa.remove(r)
					break
				}
			}
		}
		//Now build the rest of the pool
		while (tempa.len()>0)
		{
			r=RandomInt(0,tempa.len()-1)
			inst.nagpool.append(tempa[r])
			tempa.remove(r)
		}
	}
	else
	{
		foreach(idx, val in tempa)
		{
			inst.nagpool.append(val)
		}
	}	
}

function nags_nagpooldump(inst)
{
	local idx, val
	foreach (idx, val in inst.nagpool)
		printldebug("*********NAG "+idx+" : "+val.SceneTableIndex)
}

function nags_fetch(inst)
{
	if (inst.nagpool.len() == 0)
	{
		if (inst.nagrepeat)
		{
			inst.nagtimeslistcompleted += 1
			nags_createpool(inst)
			if (inst.nagpool.len() == 0)
				return null
		}
		else
		{
			return null
		}	
	}
	local ret = inst.nagpool[0].SceneTableIndex
	foreach( idx, val in inst.nags)
	{
		if (val.SceneTableIndex == ret)
		{
			val.totplays+=1
			break
		}
	}
	//nags_nagpooldump(inst)
	inst.nagpool.remove(0)
	inst.naglastfetched = ret
	return ret
}

function GladosStopNag(arg = 0)
{
	nag_stop("glados",arg)
}

function WheatleyStopNag(arg = 0)
{
	nag_stop("wheatley",arg)
}

function Core01StopNag(arg = 0)
{
	nag_stop("core01",arg)
}

function Core02StopNag(arg = 0)
{
	nag_stop("core02",arg)
}

function Core03StopNag(arg = 0)
{
	nag_stop("core03",arg)
}


function nag_stop(char, stoptype)
{
	local idx, val
	local todel = null
	foreach (idx, val in scenequeue)
	{
		if (val.isNag && val.currentCharacter == char)
		{
			todel=idx
			break
		}
	}
	if (todel != null)
	{
		scenequeue_DeleteScene(todel)	
	}
}

function nag_array_compare(a,b)
{
	if(a.orderingroup>b.orderingroup) return 1
	else if(a.orderingroup<b.orderingroup) return -1
	return 0;
}


//--------------------------------------------------------------------------------------------------------------
//Nag Table Functions END
//--------------------------------------------------------------------------------------------------------------


function TrustFlingCatapultTurretNoticesPlayer()
{
	GladosPlayVcd(439, null, "catapulted_turret")
}

//--------------------------------------------------------------------------------------------------------------
//Elevator Stoppage in bridge over goo
//--------------------------------------------------------------------------------------------------------------

function sp_a2_laser_over_goo_elevator_stoppage()
{
	GladosPlayVcd(465)
	// @trigger_this_to_stop_elevator
	// @trigger_this_to_start_elevator
}


//--------------------------------------------------------------------------------------------------------------
//sp_a1_intro7 functions
//--------------------------------------------------------------------------------------------------------------
if (curMapName=="sp_a1_intro7")
{
	sp_a1_intro7_popped <- false
	sp_a1_intro7_camethrough <- false
	sp_a1_intro7_pickedup <- false
	sp_a1_intro7_pickedupcount <- 0
	sp_a1_intro7_pluggedin <- false
	sp_a1_intro7_turnedaway <- false
	sp_a1_intro7_sayingnotdead <- false
	sp_a1_intro7_saidnotdead <- false
}	

function sp_a1_intro7_HeyUpHere()
{
	GladosPlayVcd(466)
}

function sp_a1_intro7_YouFoundIt()
{
	EntFire("spherebot_train_1_chassis_1","MoveToPathNode","spherebot_train_1_path_11",8.5)
	GladosPlayVcd(467)
}

function sp_a1_intro7_PopPortal()
{
	if (!sp_a1_intro7_popped)
	{
		GladosPlayVcd(469)
	}	
}


function sp_a1_intro7_PopPortalNag()
{
	if (!sp_a1_intro7_popped)
	{
		GladosPlayVcd(468)
	}
}

function sp_a1_intro7_ComeThroughNag()
{
	if (!sp_a1_intro7_camethrough)
	{
		GladosPlayVcd(470)
	}
}


function sp_a1_intro7_PoppedAPortal()
{
	EntFire("portal_detector","Disable","",0.0)
	EntFire("@glados","runscriptcode","sp_a1_intro7_ComeThroughNag()",4.0)
	WheatleyStopNag()
	sp_a1_intro7_popped = true
}

function sp_a1_intro7_JumpToOtherSide()
{
	WheatleyStopNag()
	sp_a1_intro7_camethrough = true
}

function sp_a1_intro7_ManagementRail()
{
	//WheatleyStopNag()
	GladosPlayVcd(471)
}

function sp_a1_intro7_OnThree()
{
	GladosPlayVcd(472)
}

function sp_a1_intro7_Impact()
{
	GladosPlayVcd(473)
}


function sp_a1_intro7_NotDeadStart()
{
	sp_a1_intro7_sayingnotdead = true
}

function sp_a1_intro7_NotDeadEnd()
{
	sp_a1_intro7_sayingnotdead = false
	sp_a1_intro7_saidnotdead = true
	if (sp_a1_intro7_pickedup)
	{
		nuke()
		GladosPlayVcd(572)
	}
}


function sp_a1_intro7_PickMeUpNag()
{
	if (!sp_a1_intro7_pickedup)
	{
		GladosPlayVcd(474)
	}
}

function sp_a1_intro7_PickUp()
{
	sp_a1_intro7_pickedup = true
	switch (sp_a1_intro7_pickedupcount)
	{
		case 0:
			sp_a1_intro7_pickedupcount += 1
			//before the "I'm not dead!" line has started playing
			if ((!sp_a1_intro7_sayingnotdead) && (!sp_a1_intro7_saidnotdead))
			{
				nuke()
				GladosPlayVcd(571)
			}
			else
			{
				//the "I'm not dead!" line finished playing before the pickup happened
				if ( !((!sp_a1_intro7_saidnotdead) && sp_a1_intro7_sayingnotdead))
				{
					WheatleyStopNag()
					GladosPlayVcd(475)
				}	
			}	
			break
		case 1:
			sp_a1_intro7_pickedupcount += 1
			nuke()
			GladosPlayVcd(577)
			break
	}	
}

function sp_a1_intro7_PlugMeInNag()
{
	if (!sp_a1_intro7_pluggedin)
	{
		GladosPlayVcd(476)
	}
}

function sp_a1_intro7_NoWatching()
{
	sp_a1_intro7_pluggedin = true
	WheatleyStopNag()
	GladosPlayVcd(477)
}

function sp_a1_intro7_NoWatchingNag()
{
	if (!sp_a1_intro7_turnedaway)
	{
		GladosPlayVcd(481)
	}
}

function sp_a1_intro7_TurnAroundNow()
{
	sp_a1_intro7_turnedaway = true
	WheatleyStopNag()
	GladosPlayVcd(478)
}

function sp_a1_intro7_BamSecretPanel()
{
	sp_a1_intro7_turnedaway = true
	WheatleyStopNag()
	GladosPlayVcd(479)
}

function sp_a1_intro7_GloriousFreedom()
{
	GladosPlayVcd(480)
}

function sp_a1_intro7_DontLeaveMeNag()
{
}



//--------------------------------------------------------------------------------------------------------------
//sp_a1_wakeup functions
//--------------------------------------------------------------------------------------------------------------

if (curMapName=="sp_a1_wakeup")
{
	sp_a1_wakeup_gantryexpositionover <- false
	sp_a1_wakeup_gantryexpositioncounter <- 0
	sp_a1_wakeup_humanexpositionover <- false
	sp_a1_wakeup_In_Breaker_Room <- false
	sp_a1_wakeup_Looked_Down <- false
}	

function sp_a1_wakeup_start_map()    
{
	GladosPlayVcd(482)
}

function sp_a1_wakeup_gantry_exposition_end()
{
	sp_a1_wakeup_gantryexpositionover = true
}

function sp_a1_wakeup_inside_observation()    
{
	if (sp_a1_wakeup_gantryexpositionover)
	{
		sp_a1_wakeup_gantryexpositionover = false
		switch (sp_a1_wakeup_gantryexpositioncounter)
		{
			case 0:
				sp_a1_wakeup_gantryexpositioncounter+=1
				GladosPlayVcd(483)
				break
			case 1:
				sp_a1_wakeup_gantryexpositioncounter+=1
				GladosPlayVcd(484)
				break
			case 2:
				sp_a1_wakeup_gantryexpositioncounter+=1
				GladosPlayVcd(485)
				break
			case 3:
				sp_a1_wakeup_gantryexpositioncounter+=1
				GladosPlayVcd(486)
				break
		}		
	}
}

function sp_a1_wakeup_gantry_door_open()    
{
	GladosPlayVcd(487)
}

function sp_a1_wakeup_there_she_is()
{
		GladosPlayVcd(488)
}

function sp_a1_wakeup_human_exposition_end()
{
	sp_a1_wakeup_gantryexpositionend = true
}

function sp_a1_wakeup_down_the_stairs()
{
		GladosPlayVcd(489)
}

function sp_a1_wakeup_JumpNags()
{
	GladosPlayVcd(581)
}

function sp_a1_wakeup_Falling()
{
	nuke()
	GladosPlayVcd(579)
}

function sp_a1_wakeup_Landed()
{
	GladosPlayVcd(580)
}

function sp_a1_wakeup_come_through_here()
{
		if (sp_a1_wakeup_Looked_Down)
		{
			GladosPlayVcd(586)
		}
}

function sp_a1_wakeup_Do_Not_Look_Down()
{
		GladosPlayVcd(491)
}

function sp_a1_wakeup_Do_Not_Look_Down_Over()
{
	sp_a1_wakeup_Looked_Down = true
	EntFire("@ComeThroughHereTrigger","enable","",0.2)
}


function sp_a1_wakeup_This_Is_Breaker_Room()
{
		GladosPlayVcd(492)
}

function sp_a1_wakeup_Lets_Go_In()
{
		if (!sp_a1_wakeup_In_Breaker_Room)
		{
			GladosPlayVcd(585)
		}	
}

function sp_a1_wakeup_Do_Not_Touch()
{
		sp_a1_wakeup_In_Breaker_Room = true
		GladosPlayVcd(493)
}

function sp_a1_wakeup_Lights_On()
{
		GladosPlayVcd(494)
}

function sp_a1_wakeup_Oops()
{
	GladosPlayVcd(542)
}

//--------------------------------------------------------------------------------------------------------------
//Wheatley Elevator Scene (currently after sp_a2_column_blocker)
//--------------------------------------------------------------------------------------------------------------


function Wheatley_Elevator_Scene_Start()
{
		GladosPlayVcd(495)
}

function Wheatley_Elevator_Scene_Ow()
{
		GladosPlayVcd(496)
}

//--------------------------------------------------------------------------------------------------------------
//Jailbreak - sp_a2_bts1 & bts2
//--------------------------------------------------------------------------------------------------------------

if (curMapName=="sp_a2_bts1")
{
	sp_a2_bts1_FakeEntered <- false
}	



function JailbreakGladosSomethingWrong()
{
	GladosPlayVcd(301)
}

function JailbreakWheatleyHeyLady()
{
	GladosPlayVcd(497)
}

function JailbreakICanHearYou()
{
	nuke()
	EntFire( "@sphere", "SetIdleSequence", "sphere_damaged_glance_concerned", 0 )
	GladosPlayVcd(498)
}

function JailbreakWheatleyCloseChamber()
{
	WheatleyStopNag()	
	GladosPlayVcd(500)
}

function WheatleyKeepMoving()
{
	//WheatleyStopNag()	
	//GladosPlayVcd(501)
}

function WheatleyGoGoGoNag()
{
	GladosPlayVcd(502)
}

function JailbreakLastTestIntro()
{
	WheatleyStopNag()	
	GladosPlayVcd(503)
}

function JailbreakLastChamberMain()
{
	WheatleyStopNag()	
	GladosPlayVcd(504)
}

function JailbreakLastTestDeer()
{
	sp_a2_bts1_FakeEntered = true
	WheatleyStopNag()	
	GladosPlayVcd(505)
}

function JailBreakHowStupid()
{
	if (!sp_a2_bts1_FakeEntered)
	{
		WheatleyStopNag()	
		GladosPlayVcd(506)
	}	
}

function JailbreakBridgeDisappear()
{
	WheatleyStopNag()	
	GladosPlayVcd(507)
}

function JailbreakLookOutTurrets()
{
	WheatleyStopNag()	
	GladosPlayVcd(508)
}

function JailBreak2Trapped()
{
	WheatleyStopNag()	
	GladosPlayVcd(573)
	
}

function JailBreak2Gunfire()
{
	GladosPlayVcd(574)
}

function bts2_wheatley_comeon_prompt()
{
	GladosPlayVcd(587)
}

function JailBreak2AlmostOut()
{
	GladosPlayVcd(575)
}

function JailBreak2BringingDown()
{
	GladosPlayVcd(576)
}

function JailbreakHurryHurry()
{
	WheatleyStopNag()	
	GladosPlayVcd(509)
}

function JailbreakGetInTheLift()
{
	WheatleyStopNag()	
	GladosPlayVcd(510)
}

function jailbreak_player_in_exit_elevator()
{
	WheatleyStopNag()	
	GladosPlayVcd(511)
}

function Jailbreak2ThisWay()
{
	WheatleyStopNag()	
	GladosPlayVcd(512)
}

function JailbreakGoGo()
{
	WheatleyStopNag()	
	GladosPlayVcd(513)
}

function JailbreakComeOnComeOn()
{
	WheatleyStopNag()	
	GladosPlayVcd(514)
}


//--------------------------------------------------------------------------------------------------------------
//Turret Factory -- sp_a2_bts4
//--------------------------------------------------------------------------------------------------------------

if (curMapName=="sp_a2_bts4")
{
	sp_a2_bts4_StillThinkingNagStage <- 0
	sp_a2_bts4_StillThinkingNagOK <- false
	sp_a2_bts4_StillThinkingNagIdx <- 0
	sp_a2_bts4_StillThinkingNagTime <- 0
	sp_a2_bts4_MentionedSwap <- false
	sp_a2_bts4_At_Window <- false
	sp_a2_bts4_At_Big_Potato <- false
	sp_a2_bts4_At_Volcano <- false
	sp_a2_bts4_Intro_Talking <- false
	sp_a2_bts4_Science_Fair_Busy <- false
	sp_a2_bts4_Did_Big_Potato <- false
	sp_a2_bts4_Did_Volcano <- 0
	
}	


function FactoryWheatleyHey()
{
	GladosPlayVcd(515)
}

function FactoryFollowMe()
{
	GladosPlayVcd(516)
}

function FactoryAlmostThere()
{
	GladosPlayVcd(518)
}


function FactoryTahDah()
{
	GladosPlayVcd(517)
}

function FactoryScannerIntro()
{
	sp_a2_bts4_At_Window = true
	if (!sp_a2_bts4_Intro_Talking)
	{
		GladosPlayVcd(519)
	}
}

function FactoryScannerSpeech()
{
	GladosPlayVcd(519)
}

function FactoryCheckAtWindowEnd()
{
	sp_a2_bts4_Intro_Talking = false
	if (sp_a2_bts4_At_Window)
	{
		FactoryScannerSpeech()
	}
}

function FactoryCheckAtWindowStart()
{
	sp_a2_bts4_Intro_Talking = true
	if (sp_a2_bts4_At_Window)
	{
		FactoryScannerSpeech()
	}
}


function FactoryControlDoorHackIntro()
{
	GladosPlayVcd(520)
}

function FactoryControlRoomHackSuccess()
{
	WheatleyStopNag()	
	GladosPlayVcd(521)
}

function FactoryFirstTurretTaken()
{
	WheatleyStopNag()	
	GladosPlayVcd(522)
}

function FactoryFirstTurretPulled()
{
	//WheatleyStopNag()	
	//GladosPlayVcd(522)
}


function FactoryEnableThinkingNag()
{
	printldebug("%%%%%%%%%%%%%%%%ENABLE STILL THINKING NAG")
	sp_a2_bts4_StillThinkingNagOK = true
}

function FactoryDisableThinkingNag()
{
	printldebug("%%%%%%%%%%%%%%%%DISABLE STILL THINKING NAG")
	sp_a2_bts4_StillThinkingNagOK = false
}

function FactoryStillThinkingNag()
{
	printldebug("%%%%%%%%%%%%%%%%STILL THINKING NAG")
	switch (sp_a2_bts4_StillThinkingNagStage)
	{
		case 0:
			if (!sp_a2_bts4_StillThinkingNagOK)
			{
				return
			}
			if (!(characterCurscene("wheatley")==null))
			{
				sp_a2_bts4_StillThinkingNagTime = Time()
				return
			}	
			if (Time()-sp_a2_bts4_StillThinkingNagTime > 5 && RandomInt(1,100) > 50)
			{
				sp_a2_bts4_StillThinkingNagIdx+=1
				sp_a2_bts4_StillThinkingNagTime=Time()
				switch (sp_a2_bts4_StillThinkingNagIdx)
				{
					case 1:
						GladosPlayVcd(523)
						break
					case 2:
						GladosPlayVcd(524)
						break
					case 3:
						GladosPlayVcd(525)
						break
					case 4:
						GladosPlayVcd(526)
						break
					case 5:
						GladosPlayVcd(527)
						break
					case 6:
						GladosPlayVcd(528)
						break
					case 7:
						sp_a2_bts4_MentionedSwap = true
						GladosPlayVcd(529)
						break
					case 8:
						sp_a2_bts4_MentionedSwap = true
						GladosPlayVcd(530)
						break
					default:
						sp_a2_bts4_MentionedSwap = true
						GladosPlayVcd(531)
						break
				}
			}
			break
		case 1:
	}
}	


function FactoryWhereAreYouGoing()
{
	if (!sp_a2_bts4_MentionedSwap)
	{
		GladosPlayVcd(532)
	}
}

function FactoryWhereAreYouGoingTwo()
{
	if (!sp_a2_bts4_MentionedSwap)
	{
		GladosPlayVcd(533)
	}	
}


function FactoryBroughtBackDefectiveTurret()
{
	printldebug("$$$$$$$$$$$$$CRAP TURRET TRIGGER")
	sp_a2_bts4_StillThinkingNagStage = 2
	if (sp_a2_bts4_MentionedSwap)
	{
		GladosPlayVcd(535)
	}
	else
	{
		GladosPlayVcd(534)
	}
}

function FactoryWheatleyShoutout()
{
	if (!sp_a2_bts4_MentionedSwap)
	{
		GladosPlayVcd(541)
	}
}

function FactoryEnterScannerRoomWithTurret()
{
	if (!sp_a2_bts4_MentionedSwap)
	{
		GladosPlayVcd(540)
	}
}

function FactorySuccess()
{
	sp_a2_bts4_StillThinkingNagStage = 2
	if (sp_a2_bts4_MentionedSwap)
	{
		GladosPlayVcd(539)
	}
	else
	{
		GladosPlayVcd(538)
	}
}


function ScienceFairBusy()
{
	sp_a2_bts4_Science_Fair_Busy = true
}

function ScienceFairNotBusy()
{
	sp_a2_bts4_Science_Fair_Busy = false
	if (sp_a2_bts4_At_Volcano)
	{
		PlayerNearScienceFairVolcano()
		return
	}
	if (sp_a2_bts4_At_Big_Potato)
	{
		PlayerLookingAtScienceFairPotato()
		return
	}
}


function PlayerNearScienceFairVolcano()
{
	sp_a2_bts4_At_Volcano = true
	if (!sp_a2_bts4_Science_Fair_Busy)
	{
		switch (sp_a2_bts4_Did_Volcano)
		{
			case 0:
				sp_a2_bts4_Did_Volcano = 1
				GladosPlayVcd(583)
				break
			case 1:
				sp_a2_bts4_Did_Volcano = 2
				GladosPlayVcd(584)
				break
		}		
	}	
}	

function PlayerLeavingScienceFairVolcano()
{
	sp_a2_bts4_At_Volcano = false
}


function PlayerLookingAtScienceFairPotato() // fires once player looks at potato plant
{
	sp_a2_bts4_At_Big_Potato = true
	if (!sp_a2_bts4_Science_Fair_Busy)
	{
		if (!sp_a2_bts4_Did_Big_Potato)
		{
			sp_a2_bts4_Did_Big_Potato = true
			GladosPlayVcd(582)
		}	
	}	
}


function PlayerNotLookingAtScienceFairPotato() // fires if player looks away from plant after looking at it
{
		sp_a2_bts4_At_Big_Potato = false
}


//--------------------------------------------------------------------------------------------------------------
// BTS4 conveyor turret functions
//--------------------------------------------------------------------------------------------------------------

// ========================================================
// Called when the player gets near the turret for the first time
// ========================================================

if (curMapName=="sp_a2_bts4")
{
	sp_a2_bts4_redemption_turret_held <- false
	sp_a2_bts4_redemption_turret_babble_index <- 0
	sp_a2_bts4_redemption_turret_babbling <- false
}	


function SabotageFactoryRecycledTurretNoticesPlayer()
{
	GladosPlayVcd(439, null, "conveyor_turret_body")
}


// ========================================================
// SP_A2_BTS4 ACHIEVEMENT - ACH.SAVE_REDEMPTION_TURRET
// ========================================================
function bts4_redemption_line_turret_achievement()
{	
	// award achievement after turret is done speaking
	EntFire("achievement_redemption_line", "fireevent", 0, 0 )
}

// ========================================================
// Called every time the turret is picked up
// ========================================================
function bts4_redemption_line_turret_pickup()
{
	sp_a2_bts4_redemption_turret_held = true
	if (!sp_a2_bts4_redemption_turret_babbling)
	{
		GladosPlayVcd(614, null, "conveyor_turret_body")
	}	
}

// ========================================================
// Called every time the turret is dropped
// NOTE: when turret gets fizzled it is also dropped
// so this function will get called
// ========================================================
function bts4_redemption_line_turret_drop()
{
	sp_a2_bts4_redemption_turret_held = false
}

function bts4_redemption_line_turret_babble_start()
{
	sp_a2_bts4_redemption_turret_babbling = true
}

function bts4_redemption_line_turret_babble_end()
{
	local dly = RandomInt(2,5)
	sp_a2_bts4_redemption_turret_babbling = false
	if (sp_a2_bts4_redemption_turret_held)
	{
		EntFire("@glados","runscriptcode","bts4_redemption_line_turret_babble()",dly)
	}
}


function bts4_redemption_line_turret_babble()
{
	if (!sp_a2_bts4_redemption_turret_babbling)
	{
		if (sp_a2_bts4_redemption_turret_held)
		{
			if (sp_a2_bts4_redemption_turret_babble_index < 8)
			{
				sp_a2_bts4_redemption_turret_babble_index+=1
				GladosPlayVcd(614+sp_a2_bts4_redemption_turret_babble_index, null, "conveyor_turret_body")
			}	
		}
	}	
}


// ========================================================
// Called if turret is not saved and goes through conveyor exit
// ========================================================
function bts4_redemption_line_turret_not_saved()
{
	GladosCharacterStopScene("conveyor_turret_body")
	GladosPlayVcd(613, null, "conveyor_turret_body")
}

// ========================================================
// Called if player and turret are approaching the fizzler
// NOTE: if the player leaves and comes back this could be triggered
// again!
// ========================================================
function bts4_redemption_line_fizzler_approach()
{
	
}

// ========================================================
// Called if turret gets fizzled
// ========================================================
function bts4_redemption_line_turret_fizzled()	
{
	GladosCharacterStopScene("conveyor_turret_body")
	GladosPlayVcd(613, null, "conveyor_turret_body")
}

// ========================================================
// Called when player gets into dummy shoot area
// ========================================================
function bts4_redemption_line_turret_safe()
{
	
}



//--------------------------------------------------------------------------------------------------------------
//Turret Factory -- sp_a2_intro - incinerator
//--------------------------------------------------------------------------------------------------------------

function sp_a2_intro_SecondSpeech()
{
	if (characterCurscene("glados")==null)
	{
		GladosPlayVcd(206)
	}
	else
	{
		GladosPlayVcd(543)
	}
}

function sp_a2_intro_ClearArms()
{
	if (characterCurscene("glados")==null)
	{
		GladosPlayVcd(208)
	}
	else
	{
		GladosPlayVcd(544)
	}
}




//--------------------------------------------------------------------------------------------------------------
//sp_a1_intro1
//--------------------------------------------------------------------------------------------------------------

if (curMapName=="sp_a1_intro1")
{
	sp_a1_intro1_fizzler_triggered <- false
	sp_a1_intro1_fizzler_said <- false
	sp_a1_intro1_fizzler_passed <- false
}

function sp_a1_intro1_fizzler_intro()
{
	sp_a1_intro1_fizzler_triggered = true
	if (characterCurscene("glados")==null)
	{
		sp_a1_intro1_fizzler_said = true
		GladosPlayVcd(553)
	}
}

function sp_a1_intro1_fizzler_passed()
{
	if (!sp_a1_intro1_fizzler_said)
	{
		sp_a1_intro1_fizzler_passed = true
		if (characterCurscene("glados")==null)
		{
			sp_a1_intro1_fizzler_said = true
			GladosPlayVcd(630)
		}
	}
}

function sp_a1_intro1_fizzler_test()
{
	if (sp_a1_intro1_fizzler_triggered && !sp_a1_intro1_fizzler_said)
	{
		sp_a1_intro1_fizzler_said = true
		if (sp_a1_intro1_fizzler_passed)
		{
			GladosPlayVcd(630)
		}
		else
		{
			GladosPlayVcd(553)
		}	
	}
}

//--------------------------------------------------------------------------------------------------------------
//sp_a1_intro3
//--------------------------------------------------------------------------------------------------------------

//Triggers when you drop into the "Mind the Gap" puzzle
function sp_a1_intro3_turret_live_fire()
{
	GladosPlayVcd(623)
}


//--------------------------------------------------------------------------------------------------------------
//sp_a1_intro6
//--------------------------------------------------------------------------------------------------------------

function sp_a1_intro6_PuzzleOneCompleted()
{
	printldebug("Insert puzzle 1 completed dialog here.")
}



//--------------------------------------------------------------------------------------------------------------
//sp_a2_fizzler_training
//--------------------------------------------------------------------------------------------------------------
function sp_a2_fizzler_training_Have_To_Go()
{
	GladosPlayVcd(546)
}

//--------------------------------------------------------------------------------------------------------------
//sp_a4_turret_tbeam functions
//--------------------------------------------------------------------------------------------------------------

function Finale02_turret_tbeam_abort1()
{
	GladosPlayVcd(556)
}

function Finale02_turret_tbeam_2()
{
	GladosPlayVcd(557)
}

function Finale02_turret_tbeam_abort2()
{
	GladosPlayVcd(558)
}

function Finale02_turret_tbeam_3()
{
	GladosPlayVcd(559)
}

function Finale02_turret_tbeam_abort3()
{
	GladosPlayVcd(560)
}

//stub function from co-op
function BotDeath(arg,arg2)
{
}

//sp_a1_intro6_first half of chamber
function MidpointPuzzleCompleted()
{
	GladosPlayVcd(626)
}



//--------------------------------------------------------------------------------------------------------------
// Control Potatos light
//--------------------------------------------------------------------------------------------------------------

function PotatosTurnOff()
{
	GetPlayer().TurnOffPotatos();
}

function PotatosTurnOn()
{
	GetPlayer().TurnOnPotatos();
}


