// Survivor Handler.
// Worthless Bums 2012.


// Initialize Survivor GUI.
function initializeSurvivorScreen ()
{//echo("initializeSurvivorScreen()");
	// Only have a random chance of a survivor popping up!
	if (getRandom(1, 100) > $survivorSpawnChance)
	//if (getRandom(1, 100) > 100)
	{//echo("no survivor spawn!");
		return;
	}
	
	if (!$leaderPersist		||
		!$scoutPersist		||
		!$grenadierPersist	||
		!$supportPersist)
	{
		// Check if the squad is not full in slot order.
		%slot = -1;
		if (!$leaderPersist)
		{
			$leaderPersist = true;
			%slot = 0;
		}
		else if (!$scoutPersist)
		{
			$scoutPersist = true;
			%slot = 1;
		}
		else if (!$grenadierPersist)
		{
			$grenadierPersist = true;
			%slot = 2;
		}
		else if (!$supportPersist)
		{
			$supportPersist = true;
			%slot = 3;
		}
		
		// 
		if (%slot != -1)
		{
			$survivorScreenPushed = true;
			// Generate random squad member.
			// Generate random gender and name.
			%gender = getRandom(0, 1);
			%name = "";
			switch (%gender)
			{
				case 0: // Female.
					%name = generateRandomCallsign();
					
				case 1:	// Male.
					%name = generateRandomCallsign();
			}
			// Generate survivor class.
			%survivorClass = getRandom(0, 4);
			
			// Track the generated values!
			$survivorSlot = %slot;
			$survivorName = %name;
			$survivorGender = %gender;
			$survivorClass = %survivorClass;
			// Compose gender and class strings.
			%genderString = "Female";
			%pronoun1 = "she";
			%pronoun2 = "her";
			if ($survivorGender)
			{
				%genderString = "Male";
				%pronoun1 = "he";
				%pronoun2 = "his";
			}
			%classString = "";
			switch ($survivorClass)
			{
				case 0:	%classString = "Leader";
				case 1:	%classString = "Scout";
				case 2:	%classString = "Grenadier";
				case 3:	%classString = "Support";
				case 4:	%classString = "Engineer";
			}
			
			// Generate random health and action points.
			$survivorHP = getRandom(4, 12);
			$survivorAP = getRandom(4, 6);
			%figureAdjective = "";
			if ($survivorHP <= 6)
			{
				%figureAdjective = "huddled";
			}
			else if ($survivorHP <= 9)
			{
				%figureAdjective = "crouched";
			}
			else
			{
				%figureAdjective = "standing";
			}
			%movementAdjective = "";
			if ($survivorAP <= 4)
			{
				%movementAdjective = "slow";
			}
			else if ($survivorAP <= 4)
			{
				%movementAdjective = "furtive";
			}
			else
			{
				%movementAdjective = "decisive";
			}
			// Generate random amount of ammo.
			$survivorAmmo = getRandom(1, 6);
			%ammoAdjective = "";
			if ($survivorAmmo <= 2)
			{
				%ammoAdjective = "small";
			}
			else if ($survivorAmmo <= 3)
			{
				%ammoAdjective = "decent";
			}
			else
			{
				%ammoAdjective = "large";
			}
			
			// Set survivior description!
			survivorDescription.setText("You see a " @ "" @ %figureAdjective @ "" @ " figure in the corner, " @
										/*%pronoun2 @*/ "movements " @ "" @ %movementAdjective @ "\c0" @
										//". You aren't entirely convinced that " @ %pronoun1 @ " knows how to use the " @ "\c6" @ %classString @ "\c0" @ " class weapon in " @ %pronoun2 @ " hands."	NL
										". You aren't entirely convinced the marine knows how to use that " @ "" @ %classString @ "" @ " class weapon."	NL
										"\nYou can't help but notice the " @ "" @ %ammoAdjective @ "" @ " stack of ammunition on the ground."	NL
										"\nDo you take this survivor with you?");
			
			// Push GUI.
			Canvas.pushDialog(survivorGui);
		}
	}
	else
	{
		// Instantiate non-survivor event?
		%elevatorEventRoll = getRandom(0, 5);
		switch (%elevatorEventRoll)
		{
			case 0:	// Nothing happens.
			case 1:	// Find grenades.
			case 2:	// Fine ammo crate.
			case 3:	// Find medkit.
			case 4:	//	
		}
	}
}

// Cancel Survivor button pressed
function cancelSurvivorButton ()
{//echo("cancelSurvivorButton()");
	Canvas.popDialog(survivorGui);
	$survivorScreenPushed = false;
}

// Accept Survivor button pressed
function acceptSurvivorButton ()
{//echo("acceptSurvivorButton()");
	enforceSquadPersistence();
	// Increment total Survivors Recruited!
	$GlobalStats.totalSurvivorsRecruited++;
	
	// Create random class weapon and armor.
	// Create a random weapon.
	%weaponCode = createRandomWeapon($survivorClass, 1, $weaponProjectileBallisticType);
	// Create a random armor.
	%armorCode = createRandomArmor($survivorClass, 1);
	
	// Spawn character.
	//echo("spawning survivor!");
	//$survivorClass = 1;	// For testing purposes only.
	/*%squadMember = spawnCharacterClass($survivorClass,
									   $survivorName,
									   $survivorGender,
									   "Null_Imagemap",	// Imagemap empty - dispatched internally by class!
									   0,
									   getRandom(1, $survivorHP),
									   $survivorHP,
									   0,
									   $survivorAP,
									   $survivorAP,
									   0 SPC 0 SPC 0,	// Stats.
									   0 SPC 0 SPC 0,	// Skills.
									   %weaponCode,
									   %armorCode,
									   "-1",				// Retraining.
									   $survivorAmmo,
									   0,
									   0,
									   "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0",
									   "Perkless");*/
	//%characterSprite = new Sprite();	// This doesn't crash: function spawnCharacterClass() is causing the crash!
	
	
	// TESTER
	%characterClass = $survivorClass;
	%characterName = $survivorName;
	%characterGender = $survivorGender;
	%characterImageMap = "Null_Imagemap";
	%characterExperience = 0;
	%characterCurrentHealth = getRandom(1, $survivorHP);
	%characterMaxHealth = $survivorHP;
	%characterArmorRating = 0;
	%characterCurrentActionPoints = $survivorAP;
	%characterMaxActionPoints = $survivorAP;
	%characterStats = 0 SPC 0 SPC 0;
	%characterSkills = 0 SPC 0 SPC 0;
	%characterWeapon = %weaponCode;
	%characterArmor = %armorCode;
	%characterAmmo = $survivorAmmo;
	%characterKills = 0;
	%characterTalentPoints = 0;
	%characterTalents = "0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0";
	%characterPerks = "Perkless";
	
	%characterAnimation = "Sprites:" @ getCharacterClassName (%characterClass) @ "BallisticIdleSouthAnimation";
	%sight = 4;
	switch (%characterClass)
	{
		case 0:	// Leader.
			%sight = 5;
		case 1:	// Scout.
			%sight = 5;
		case 2:	// Grenadier.
			%sight = 4;
		case 3:	// Support.
			%sight = 4;
		case 4:	// Engineer.
			%sight = 4;
	}
	%characterSprite = new Sprite();
	%characterSprite.SceneLayer = $SquadMemberLayer;
	%characterSprite.group = $SquadMemberGroup;
	%characterSprite.characterClass = %characterClass;
	%characterSprite.name = %characterName;
	%characterSprite.gender = %characterGender;
	%characterSprite.scenegraph = levelSceneGraph;
	%characterSprite.config = "";
	%characterSprite.Animation = %characterAnimation;
	%characterSprite.position = "2 2";										// Offset by 2 internal Torque units to space the character avatar on the square tilemaps properly.
	%characterSprite.size = "4 4";
	%characterSprite.visible = true;
	%characterSprite.xIndex = 0;											// By default set player on the upper left hand corner of the map!
	%characterSprite.yIndex = 0;											// By default set player on the upper left hand corner of the map!
	%characterSprite.rank = 0;
	%characterSprite.level = getLevelFromExperience(%characterExperience);
	%characterSprite.experience = %characterExperience;
	%characterSprite.currentHealth = %characterCurrentHealth;				// Character's current health.
	%characterSprite.maxHealth = %characterMaxHealth;						// Character's maximum health.
	%characterSprite.armorRating = %characterArmorRating;					// Character's armor rating.
	%characterSprite.currentActionPoints = %characterCurrentActionPoints;	// Character's current action points.
	%characterSprite.maxActionPoints = %characterMaxActionPoints;			// Character's max action points.
	%characterSprite.actionPointReduction = 0;								// Used for combat turns where squad members lose action points.
	%characterSprite.sight = %sight;
	// Statistics:
	%characterSprite.power = %characterPower;								// Increases the power of bash and charge.
	%characterSprite.speed = %characterSpeed;								// Increases movement, reload, and bomb placement speed.
	%characterSprite.endurance = %characterndurance;							// Increases health.
	// Skills:
	%characterSprite.bash = %characterBash;									// By default the only skill a starting player has. Allows character to melee monsters and bash destructible objects.
	%characterSprite.demolitions = %characterDemolitions;					// Used to activate explosives.
	%characterSprite.arms = %characterArms;									// Allows character to use better ranged weapons.
	// Retraining.
	%characterSprite.retraining = "-1";
	// Inventory:
	%characterSprite.weapon = createNewWeapon(%characterWeapon);
	%characterSprite.armor = createNewArmor(%characterArmor);
	%characterSprite.ammo = %characterammo;
	%characterSprite.kills = %characterKills;
	// Talents:
	%characterSprite.characterTalentPoints = %characterTalentPoints;
	%characterSprite.talents = %characterTalents;
	// Perks:
	%characterSprite.perks = %characterPerks;
	// Weapon attachments:
	%characterSprite.weaponAttachment = 0;		// 0 - Flashlight, 1 - Laser Sight.
	%characterSprite.weaponAttachmentSprite = null;
	%characterSprite.evasion = 0;
	%characterSprite.overkill = false;
	%characterSprite.facing = $southDirection;
	%characterSprite.vehicle = -1;
	%characterSprite.oxygen = (%characterSprite.armor).oxygen;	// Oxygen is based on armor oxygen stat!
	handleLiftedTileMarker(%characterSprite);
	// END OF TESTER
	
	// Set survivor as new squad member.
	$playerSquad[$survivorSlot] = %characterSprite;
	addObjectToScene($playerSquad[$survivorSlot]);
	// Mount squad weapons.
	mountSquadWeapons();
	enforceSquadPersistence();
	
	// Move squad member into proper position instead.
	// NOTE: This function assumes there is at least one clear spot near the squad!
	%placedSurvivor = false;
	for (%i = 0; %i < 4; %i++)
	{
		if (%i != $survivorSlot	&&
			isObject($playerSquad[%i]))
		{
			if ((%i == 0	&&	$leaderPersist)		||
				(%i == 1	&&	$scoutPersist)		||
				(%i == 2	&&	$grenadierPersist)	||
				(%i == 3	&&	$supportPersist))
			{
				for (%x = $playerSquad[%i].xIndex - 1; %x <= $playerSquad[%i].xIndex + 1; %x++)
				{
					for (%y = $playerSquad[%i].yIndex - 1; %y <= $playerSquad[%i].yIndex + 1; %y++)
					{
						if (tileIsClear(%x, %y))
						{//echo("placing squad member!");
							$playerSquad[$survivorSlot].xIndex = %x;
							$playerSquad[$survivorSlot].yIndex = %y;
							$playerSquad[$survivorSlot].setPosition(getTilePositionFromIndices($playerSquad[$survivorSlot].xIndex, $playerSquad[$survivorSlot].yIndex));
							%placedSurvivor = true;
							%x = 9999;
							%y = 9999;
							%i = 9999;
							//break;
						}
					}
				}
			}
		}
	}
	if (!%placedSurvivor)
	{//echo("moving squad to free area!");
		moveSquadToFreeArea();	// This can land the squad on enemies!
	}
	//setSquadAroundActiveCharacter();
	
	// Refresh fow.
	$fogOfWar.fullCoverFog();
	$fogOfWar.showFogOfWar();
	// Refresh squad information.
	updatePortraits();
	// Update squad info gui.
	updateSquadInfoGui();
	// Update inventory tab information.
	//updateInventoryTabInformation();
	schedule(100, 0, "updateInventoryTabInformation");
	// Save current game.
	//saveCurrentGame();
	
	// Pop GUI.
	Canvas.popDialog(survivorGui);
	$survivorScreenPushed = false;
}