// * AdmiralMOD by Matthias Lorenz, http://www.cod2mod.com *


/*
	Domination
	Objective: 	Score points for your team by capturing the enemy's flag and returning it to your base
	Map ends:	When one team reaches the score limit, or time limit is reached
	Respawning:	Instant / At base

	Level requirements
	------------------
		Spawnpoints:
			classname		mp_dm_spawn
			Allied players spawn from these.
			classname		mp_dm_spawn
			Axis players spawn from these.

		Spectator Spawnpoints:
			classname		mp_global_intermission
			Spectators spawn from these and intermission is viewed from these positions.
			Atleast one is required, any more and they are randomly chosen between.

	Level script requirements
	-------------------------
		Team Definitions:
			game["allies"] = "american";
			game["axis"] = "german";
			This sets the nationalities of the teams. Allies can be american, british, or russian. Axis can be german.

		If using minefields or exploders:
			maps\mp\_load::main();

	Optional level script settings
	------------------------------
		Soldier Type and Variation:
			game["american_soldiertype"] = "normandy";
			game["german_soldiertype"] = "normandy";
			This sets what character models are used for each nationality on a particular map.

			Valid settings:
				american_soldiertype	normandy
				british_soldiertype		normandy, africa
				russian_soldiertype		coats, padded
				german_soldiertype		normandy, africa, winterlight, winterdark
*/

/*QUAKED mp_dm_spawn (0.0 1.0 0.0) (-16 -16 0) (16 16 72)
Players spawn away from enemies and near their team at one of these positions.
*/

/*QUAKED mp_dm_spawn (1.0 0.0 0.0) (-16 -16 0) (16 16 72)
Players spawn away from enemies and near their team at one of these positions.
*/

main()
{

   	// * AdmiralMOD *  
    maps\mp\gametypes\_admiral_mod_vars::GetAMVars();
	
		//** Hinzugefügt für HELLZone_AM **//
	
	level.random_maplist = maps\mp\gametypes\_admiral_mod_player::ForAllPlayersRandomMaps();
	
	//** ---Ende für HELLZone_AM--- **//



	level.callbackStartGameType = ::Callback_StartGameType;
	level.callbackPlayerConnect = ::Callback_PlayerConnect;
	level.callbackPlayerDisconnect = ::Callback_PlayerDisconnect;
	level.callbackPlayerDamage = ::Callback_PlayerDamage;
	level.callbackPlayerKilled = ::Callback_PlayerKilled;
	maps\mp\gametypes\_callbacksetup::SetupCallbacks();

	level.autoassign = ::menuAutoAssign;
	level.allies = ::menuAllies;
	level.axis = ::menuAxis;
	level.spectator = ::menuSpectator;
	level.weapon = ::menuWeapon;
	level.endgameconfirmed = ::endMap;


	
	game["dom_language"] = "english";
	
	if(!isDefined(game["roundsplayed"])) game["roundsplayed"] = 0;
	
}

Callback_StartGameType()
{
	level.splitscreen = isSplitScreen();

	// defaults if not defined in level script
	if(!isDefined(game["allies"]))
		game["allies"] = "american";
	if(!isDefined(game["axis"]))
		game["axis"] = "german";

	// server cvar overrides
	if(getCvar("scr_allies") != "")
		game["allies"] = getCvar("scr_allies");
	if(getCvar("scr_axis") != "")
		game["axis"] = getCvar("scr_axis");
	
	
	if(!isDefined(game["alliedscore"]))	game["alliedscore"] = 0;
	if(!isDefined(game["axisscore"]))	game["axisscore"] = 0;
	
	

	level.compassflag_allies 	= "compass_flag_" + game["allies"];
	level.compassflag_axis 		= "compass_flag_" + game["axis"];
	level.compassflag_empty 	= "gfx/custom/objective_empty.tga";
	
	level.objpointflag_allies 	= "objpoint_flagpatch1_" + game["allies"];
	level.objpointflag_axis 	= "objpoint_flagpatch1_" + game["axis"];	
	level.objpointflag_empty 	= "gfx/custom/objpoint_empty.tga";

	level.hudicon_empty 		= "gfx/custom/headicon_empty.tga";
	

	precacheStatusIcon("hud_status_dead");
	precacheRumble("damage_heavy");
	precacheShader(level.compassflag_allies);
	precacheShader(level.compassflag_axis);
	precacheShader(level.objpointflag_allies);
	precacheShader(level.objpointflag_axis);
	
	precacheShader(level.compassflag_empty);
	precacheShader(level.objpointflag_empty);
	precacheShader(level.hudicon_empty);
	
	precacheShader("gfx/custom/flagge_german.tga");
	precacheShader("gfx/custom/flagge_" + game["allies"] + ".tga");
		
	
	
	precacheModel("xmodel/prop_flag_" + game["allies"]);
	precacheModel("xmodel/prop_flag_" + game["axis"]);
	precacheString(&"MP_TIME_TILL_SPAWN");
	precacheString(&"PLATFORM_PRESS_TO_SPAWN");



	level.fahne[0] = "xmodel/fahne";
	level.fahne[1] = "xmodel/fahne";
	level.fahne[2] = "xmodel/fahne";
	level.fahne[3] = "xmodel/fahne";
	level.fahne[4] = "xmodel/fahne";

	
	precacheModel("xmodel/fahne");

	


	// * AdmiralMOD *  
	if(game["am_enabled"] == 1) maps\mp\gametypes\_admiral_mod_precache::Precache();


	thread maps\mp\gametypes\_menus::init();
	thread maps\mp\gametypes\_serversettings::init();
	thread maps\mp\gametypes\_clientids::init();
	thread maps\mp\gametypes\_teams::init();
	thread maps\mp\gametypes\_weapons::init();
	thread maps\mp\gametypes\_scoreboard::init();
	thread maps\mp\gametypes\_killcam::init();
	thread maps\mp\gametypes\_shellshock::init();
	thread maps\mp\gametypes\_hud_teamscore::init();
	thread maps\mp\gametypes\_deathicons::init();
	thread maps\mp\gametypes\_hearticons::init();
	thread maps\mp\gametypes\_tnticons::init();
	thread maps\mp\gametypes\_damagefeedback::init();
	thread maps\mp\gametypes\_healthoverlay::init();
	thread maps\mp\gametypes\_objpoints::init();
	thread maps\mp\gametypes\_friendicons::init();
	thread maps\mp\gametypes\_spectating::init();
	thread maps\mp\gametypes\_grenadeindicators::init();
	
	level.xenon = (getcvar("xenonGame") == "true");
	if(level.xenon) // Xenon only
		thread maps\mp\gametypes\_richpresence::init();
	else // PC only
		thread maps\mp\gametypes\_quickmessages::init();

	setClientNameMode("auto_change");

	spawnpointname = "mp_dm_spawn";
	spawnpoints = getentarray(spawnpointname, "classname");

	if(!spawnpoints.size)
	{
		maps\mp\gametypes\_callbacksetup::AbortLevel();
		return;
	}

	for(i = 0; i < spawnpoints.size; i++)
		spawnpoints[i] placeSpawnpoint();

	spawnpointname = "mp_dm_spawn";
	spawnpoints = getentarray(spawnpointname, "classname");

	if(!spawnpoints.size)
	{
		maps\mp\gametypes\_callbacksetup::AbortLevel();
		return;
	}

	for(i = 0; i < spawnpoints.size; i++)
		spawnpoints[i] PlaceSpawnpoint();


	allowed[0] = "ctf"; // Das muß so bleiben
	maps\mp\gametypes\_gameobjects::main(allowed);



	// Time limit per map
	if(getCvar("scr_dom_timelimit") == "")
		setCvar("scr_dom_timelimit", "30");
	else if(getCvarFloat("scr_dom_timelimit") > 1440)
		setCvar("scr_dom_timelimit", "1440");
	level.timelimit = getCvarFloat("scr_dom_timelimit");
	setCvar("ui_dom_timelimit", level.timelimit);
	makeCvarServerInfo("ui_dom_timelimit", "30");


	// Round limit per map
	if(getCvar("scr_dom_roundlimit") == "")
		setCvar("scr_dom_roundlimit", "0");
	level.roundlimit = getCvarInt("scr_dom_roundlimit");
	setCvar("ui_dom_roundlimit", level.roundlimit);
	makeCvarServerInfo("ui_dom_roundlimit", "0");


	// Force respawning
	if(getCvar("scr_forcerespawn") == "")
		setCvar("scr_forcerespawn", "0");

	if(!isDefined(game["state"]))
		game["state"] = "playing";

	level.mapended = false;
	
//** hinzugefügt für HELLZone_AM **//

	level.teamplay = 1;

//** ---Ende für HELLZone_AM--- **//

	level.team["allies"] = 0;
	level.team["axis"] = 0;

	if(isDefined(game["am_dom_respawn_delay"])) level.respawndelay = game["am_dom_respawn_delay"];
	else										level.respawndelay = 10;

	minefields = [];
	minefields = getentarray("minefield", "targetname");
	trigger_hurts = [];
	trigger_hurts = getentarray("trigger_hurt", "classname");

	level.flag_returners = minefields;
	for(i = 0; i < trigger_hurts.size; i++)
		level.flag_returners[level.flag_returners.size] = trigger_hurts[i];

	thread initFlags();
	thread startGame();
	thread updateGametypeCvars();
	//thread maps\mp\gametypes\_teams::addTestClients();
	
	
	level.winning_team = "none";
	
	
}

dummy()
{
	waittillframeend;

	if(isdefined(self))
		level notify("connecting", self);
}

Callback_PlayerConnect()
{
	thread dummy();

	self.statusicon = "";
	self waittill("begin");
	self.statusicon = "";

	level notify("connected", self);

	if(!level.splitscreen)
		iprintln(&"MP_CONNECTED", self.name);

	lpselfnum = self getEntityNumber();
	lpGuid = self getGuid();
	logPrint("J;" + lpGuid + ";" + lpselfnum + ";" + self.name + "\n");


	
	// * AdmiralMOD *  
	if(game["am_enabled"] == 1){
	
		self maps\mp\gametypes\_admiral_mod_player::PlayerConnect(level.random_maplist);
	}




	if(game["state"] == "intermission")
	{
		spawnIntermission();
		return;
	}

	level endon("intermission");

	if(level.splitscreen)
		scriptMainMenu = game["menu_ingame_spectator"];
	else
		scriptMainMenu = game["menu_ingame"];

	if(isDefined(self.pers["team"]) && self.pers["team"] != "spectator")
	{
		self setClientCvar("ui_allow_weaponchange", "1");

		if(self.pers["team"] == "allies")
			self.sessionteam = "allies";
		else
			self.sessionteam = "axis";

		if(isDefined(self.pers["weapon"]))
			spawnPlayer();
		else
		{
			spawnSpectator();

			scriptMainMenu = self maps\mp\gametypes\_menus::am_menuSelection();
		}
	}
	else
	{
		self setClientCvar("ui_allow_weaponchange", "0");

		if(!level.xenon)
		{
			if(!isdefined(self.pers["skipserverinfo"])) self openMenu(game["menu_serverinfo"]);
			else self openMenu(game["menu_team"]);
		}
		else
			self openMenu(game["menu_team"]);

		self.pers["team"] = "spectator";
		self.sessionteam = "spectator";

		spawnSpectator();
	}

	self setClientCvar("g_scriptMainMenu", scriptMainMenu);
}

Callback_PlayerDisconnect()
{
	
	if(!level.splitscreen)
		iprintln(&"MP_DISCONNECTED", self.name);

	if(isdefined(self.pers["team"]))
	{
		if(self.pers["team"] == "allies")
			setplayerteamrank(self, 0, 0);
		else if(self.pers["team"] == "axis")
			setplayerteamrank(self, 1, 0);
		else if(self.pers["team"] == "spectator")
			setplayerteamrank(self, 2, 0);
	}

	lpselfnum = self getEntityNumber();
	lpGuid = self getGuid();
	logPrint("Q;" + lpGuid + ";" + lpselfnum + ";" + self.name + "\n");


	// * AdmiralMOD *  
	if(game["am_enabled"] == 1) self maps\mp\gametypes\_admiral_mod_player::PlayerDisconnect();

}

Callback_PlayerDamage(eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, psOffsetTime)
{
	if(self.sessionteam == "spectator")
		return;

	// Don't do knockback if the damage direction was not specified
	if(!isDefined(vDir))
		iDFlags |= level.iDFLAGS_NO_KNOCKBACK;

	friendly = undefined;


	// * Wenn Vote, dann kein Damage mehr *
	if(isDefined(level.vote_starting)) return;

	
	// * Weapon Damage Modifier *
	if(game["am_weapon_damage_modifiers"] == 1) {
	
		if(isDefined(sWeapon) && isDefined(sMeansOfDeath) && sMeansOfDeath != "MOD_MELEE") {
		
			iDamage = maps\mp\gametypes\_admiral_mod_weapons::ModifyWeaponDamage(iDamage,sWeapon);			
		}
	}



	// * Spawn Protection *
	if(game["am_enabled"] == 1 && game["am_player_spawn_protect"] == 1) {
	
		// * Spawn Protect hier nur wenn nicht Gas/Fire *
		if(!isDefined(sWeapon) || (isDefined(sWeapon) && sWeapon != "gas_grenade_mp" && sWeapon != "fire_grenade_mp")) {
	
			// * Gegner anzeigen das Spawn Protected *
			if(isPlayer(eAttacker) && isDefined(self.spawnProtection)) {

				self thread maps\mp\gametypes\_admiral_mod_player::PlayerSpawnProtection();	
			}

			// * Wenn getroffener Spieler Spawn Prodtected, dann kein Damage *
			if(isDefined(self.spawnProtection)) return;		
		}
	}

	if(sMeansOfDeath == "MOD_FALLING" && game["am_fall_damage_modifier"] > -1) iDamage = game["am_fall_damage_modifier"];


	// * AdmiralMOD *  
	if(game["am_enabled"] == 1) {
			
		if(isPlayer(eAttacker) && (self != eAttacker) && (self.pers["team"] == eAttacker.pers["team"]) ) {
			
			if(level.friendlyfire == "2")	eAttacker maps\mp\gametypes\_admiral_mod_player::PlayerDamage(eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, psOffsetTime);
			else							self maps\mp\gametypes\_admiral_mod_player::PlayerDamage(eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, psOffsetTime);	

		}
		else self maps\mp\gametypes\_admiral_mod_player::PlayerDamage(eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, psOffsetTime);
	}



	if(isDefined(sWeapon) && (sWeapon == "gas_grenade_mp" || sWeapon == "fire_grenade_mp")) return;


	// check for completely getting out of the damage
	if(!(iDFlags & level.iDFLAGS_NO_PROTECTION))
	{
		if(isPlayer(eAttacker) && (self != eAttacker) && (self.pers["team"] == eAttacker.pers["team"]))
		{
			if(level.friendlyfire == "0")
			{
				return;
			}
			else if(level.friendlyfire == "1")
			{
				// Make sure at least one point of damage is done
				if(iDamage < 1)
					iDamage = 1;

				self finishPlayerDamage(eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, psOffsetTime);

				// Shellshock/Rumble
				self thread maps\mp\gametypes\_shellshock::shellshockOnDamage(sMeansOfDeath, iDamage);
				self playrumble("damage_heavy");
			}
			else if(level.friendlyfire == "2")
			{
				eAttacker.friendlydamage = true;

				iDamage = int(iDamage * .5);

				// Make sure at least one point of damage is done
				if(iDamage < 1)
					iDamage = 1;

				eAttacker finishPlayerDamage(eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, psOffsetTime);
				eAttacker.friendlydamage = undefined;

				friendly = true;
			}
			else if(level.friendlyfire == "3")
			{
				eAttacker.friendlydamage = true;

				iDamage = int(iDamage * .5);

				// Make sure at least one point of damage is done
				if(iDamage < 1)
					iDamage = 1;

				self finishPlayerDamage(eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, psOffsetTime);
				eAttacker finishPlayerDamage(eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, psOffsetTime);
				eAttacker.friendlydamage = undefined;

				friendly = true;

				// Shellshock/Rumble
				self thread maps\mp\gametypes\_shellshock::shellshockOnDamage(sMeansOfDeath, iDamage);
				self playrumble("damage_heavy");
			}
		}
		else
		{
			// Make sure at least one point of damage is done
			if(iDamage < 1)
				iDamage = 1;

			self finishPlayerDamage(eInflictor, eAttacker, iDamage, iDFlags, sMeansOfDeath, sWeapon, vPoint, vDir, sHitLoc, psOffsetTime);

			// Shellshock/Rumble
			self thread maps\mp\gametypes\_shellshock::shellshockOnDamage(sMeansOfDeath, iDamage);
			self playrumble("damage_heavy");
		}

		if(isdefined(eAttacker) && eAttacker != self)
			eAttacker thread maps\mp\gametypes\_damagefeedback::updateDamageFeedback();
	}

	// Do debug print if it's enabled
	if(getCvarInt("g_debugDamage"))
	{
		println("client:" + self getEntityNumber() + " health:" + self.health +
			" damage:" + iDamage + " hitLoc:" + sHitLoc);
	}

	if(self.sessionstate != "dead")
	{
		lpselfnum = self getEntityNumber();
		lpselfname = self.name;
		lpselfteam = self.pers["team"];
		lpselfGuid = self getGuid();
		lpattackerteam = "";

		if(isPlayer(eAttacker))
		{
			lpattacknum = eAttacker getEntityNumber();
			lpattackGuid = eAttacker getGuid();
			lpattackname = eAttacker.name;
			lpattackerteam = eAttacker.pers["team"];
		}
		else
		{
			lpattacknum = -1;
			lpattackGuid = "";
			lpattackname = "";
			lpattackerteam = "world";
		}

		if(isDefined(friendly))
		{
			lpattacknum = lpselfnum;
			lpattackname = lpselfname;
			lpattackGuid = lpselfGuid;
		}

		logPrint("D;" + lpselfGuid + ";" + lpselfnum + ";" + lpselfteam + ";" + lpselfname + ";" + lpattackGuid + ";" + lpattacknum + ";" + lpattackerteam + ";" + lpattackname + ";" + sWeapon + ";" + iDamage + ";" + sMeansOfDeath + ";" + sHitLoc + "\n");
	}
}

Callback_PlayerKilled(eInflictor, attacker, iDamage, sMeansOfDeath, sWeapon, vDir, sHitLoc, psOffsetTime, deathAnimDuration)
{
	self endon("spawned");
	self notify("killed_player");

	if(self.sessionteam == "spectator")
		return;

	// If the player was killed by a head shot, let players know it was a head shot kill
	if(sHitLoc == "head" && sMeansOfDeath != "MOD_MELEE")
		sMeansOfDeath = "MOD_HEAD_SHOT";

	// send out an obituary message to all clients about the kill
	if(game["am_squads"] != 1) obituary(self, attacker, sWeapon, sMeansOfDeath);




	// * AdmiralMOD *
	if(game["am_weapon_drop"] == 1) {
	
		self maps\mp\gametypes\_weapons::dropWeapon();
		self maps\mp\gametypes\_weapons::dropOffhand();
	}
	

	self.sessionstate = "dead";
	self.statusicon = "hud_status_dead";
	self.dead_origin = self.origin;
	self.dead_angles = self.angles;


	// * AdmiralMOD *
	if(game["am_enabled"] == 1) self maps\mp\gametypes\_admiral_mod_player::PlayerKilled(eInflictor, attacker, iDamage, sMeansOfDeath, sWeapon, vDir, sHitLoc, psOffsetTime, deathAnimDuration);




	if(!isdefined(self.switching_teams))
		self.deaths++;

	lpselfnum = self getEntityNumber();
	lpselfname = self.name;
	lpselfguid = self getGuid();
	lpselfteam = self.pers["team"];
	lpattackerteam = "";

	attackerNum = -1;
	if(isPlayer(attacker))
	{
		if(attacker == self) // killed himself
		{
			doKillcam = false;

			// switching teams
			if(isdefined(self.switching_teams))
			{
				if((self.leaving_team == "allies" && self.joining_team == "axis") || (self.leaving_team == "axis" && self.joining_team == "allies"))
				{
					players = maps\mp\gametypes\_teams::CountPlayers();
					players[self.leaving_team]--;
					players[self.joining_team]++;

					if((players[self.joining_team] - players[self.leaving_team]) > 1)
						attacker.score--;
				}
			}

			if(isdefined(attacker.friendlydamage))
				attacker iprintln(&"MP_FRIENDLY_FIRE_WILL_NOT");
		}
		else
		{
			attackerNum = attacker getEntityNumber();
			doKillcam = true;

			if(self.pers["team"] == attacker.pers["team"]) // killed by a friendly
				attacker.score--;
			else
				attacker.score++;
		}

		lpattacknum = attacker getEntityNumber();
		lpattackguid = attacker getGuid();
		lpattackname = attacker.name;
		lpattackerteam = attacker.pers["team"];
	}
	else // If you weren't killed by a player, you were in the wrong place at the wrong time
	{
		doKillcam = false;

		self.score--;

		lpattacknum = -1;
		lpattackname = "";
		lpattackguid = "";
		lpattackerteam = "world";
	}

	logPrint("K;" + lpselfguid + ";" + lpselfnum + ";" + lpselfteam + ";" + lpselfname + ";" + lpattackguid + ";" + lpattacknum + ";" + lpattackerteam + ";" + lpattackname + ";" + sWeapon + ";" + iDamage + ";" + sMeansOfDeath + ";" + sHitLoc + "\n");

	// Stop thread if map ended on this death
	if(level.mapended)
		return;

	self.switching_teams = undefined;
	self.joining_team = undefined;
	self.leaving_team = undefined;

	body = self cloneplayer(deathAnimDuration);
	
	
	// * AdmiralMOD *
	if(game["am_deathicons"] == 1) 	thread maps\mp\gametypes\_deathicons::addDeathicon(body, self.clientid, self.pers["team"], 5);


	delay = 2;	// Delay the player becoming a spectator till after he's done dying


	// * AdmiralMOD *
	if(game["am_squads"] != 1) 	self thread respawn_timer(delay);
	else						self thread maps\mp\gametypes\_admiral_mod_squad::SquadRespawnTimer();

	wait delay;	// ?? Also required for Callback_PlayerKilled to complete before respawn/killcam can execute

	if(doKillcam && level.killcam)
		self maps\mp\gametypes\_killcam::killcam(attackerNum, delay, psOffsetTime);

	self thread respawn();
}

spawnPlayer()
{
	self endon("disconnect");
	self notify("spawned");
	self notify("end_respawn");

	resettimeout();

	// Stop shellshock and rumble
	self stopShellshock();
	self stoprumble("damage_heavy");


	// * AdmiralMOD *
	if(isDefined(self.pers["teamkiller"])) return;
	if(game["am_enabled"] == 1) self maps\mp\gametypes\_admiral_mod_player::SpawnPlayerPre();


	self.sessionteam = self.pers["team"];
	self.sessionstate = "playing";
	self.spectatorclient = -1;
	self.archivetime = 0;
	self.psoffsettime = 0;
	self.friendlydamage = undefined;
	self.statusicon = "";
	self.maxhealth = 100;
	self.health = self.maxhealth;
	self.dead_origin = undefined;
	self.dead_angles = undefined;

	
	spawnpointname = "mp_dm_spawn";
	
	

	spawnpoints = getentarray(spawnpointname, "classname");
	spawnpoint = maps\mp\gametypes\_spawnlogic::getSpawnpoint_NearTeam(spawnpoints);

	if(isDefined(spawnpoint))
		self spawn(spawnpoint.origin, spawnpoint.angles);
	else
		maps\mp\_utility::error("NO " + spawnpointname + " SPAWNPOINTS IN MAP");

	if(!isDefined(self.pers["savedmodel"]))
		maps\mp\gametypes\_teams::model();
	else
		maps\mp\_utility::loadModel(self.pers["savedmodel"]);

	
	self maps\mp\gametypes\_weapons::clearWeaponSlots();

	self maps\mp\gametypes\_weapons::givePistol();
	self maps\mp\gametypes\_weapons::giveGrenades();
	self maps\mp\gametypes\_weapons::giveBinoculars();

	if(!isdefined(self))
		return;

	if(maps\mp\gametypes\_weapons::checkFreeSlotA() && isDefined(self.pers["weapon"]) && self.pers["weapon"] != "" && self.pers["weapon"] != "none") {
	
	 	self setWeaponSlotWeapon("primary", self.pers["weapon"]);
		self setWeaponSlotAmmo("primary", 999);
		self setWeaponSlotClipAmmo("primary", 999);		
		self setSpawnWeapon(self.pers["weapon"]);
	}

	if(!level.splitscreen)
	{
		self setClientCvar("cg_objectiveText", &"AM_MP_DOM_OBJ_TEXT_NOSCORE");
	}
	else
		self setClientCvar("cg_objectiveText", &"MP_CAPTURE_THE_ENEMY_FLAG");

	self thread updateTimer();

	waittillframeend;
	self notify("spawned_player");
	

	// * AdmiralMOD *
	if(game["am_enabled"] == 1) self maps\mp\gametypes\_admiral_mod_player::SpawnPlayerPost();
	

}

spawnSpectator(origin, angles)
{
	self notify("spawned");
	self notify("end_respawn");

	resettimeout();

	// Stop shellshock and rumble
	self stopShellshock();
	self stoprumble("damage_heavy");



	// * AdmiralMOD *
	if(isDefined(self.pers["teamkiller"])) return;
	if(game["am_enabled"] == 1) self maps\mp\gametypes\_admiral_mod_player::SpawnSpectatorPre();



	self.sessionstate = "spectator";
	self.spectatorclient = -1;
	self.archivetime = 0;
	self.psoffsettime = 0;
	self.friendlydamage = undefined;

	if(self.pers["team"] == "spectator")
		self.statusicon = "";

	maps\mp\gametypes\_spectating::setSpectatePermissions();

	if(isDefined(origin) && isDefined(angles))
		self spawn(origin, angles);
	else
	{
		spawnpointname = "mp_global_intermission";
		spawnpoints = getentarray(spawnpointname, "classname");
		spawnpoint = maps\mp\gametypes\_spawnlogic::getSpawnpoint_Random(spawnpoints);

		if(isDefined(spawnpoint))
			self spawn(spawnpoint.origin, spawnpoint.angles);
		else
			maps\mp\_utility::error("NO " + spawnpointname + " SPAWNPOINTS IN MAP");
	}

	self setClientCvar("cg_objectiveText", "");


	// * AdmiralMOD *
	if(game["am_enabled"] == 1) self maps\mp\gametypes\_admiral_mod_player::SpawnSpectatorPost();

}

spawnIntermission()
{
	self notify("spawned");
	self notify("end_respawn");

	resettimeout();

	// Stop shellshock and rumble
	self stopShellshock();
	self stoprumble("damage_heavy");

	self.sessionstate = "intermission";
	self.spectatorclient = -1;
	self.archivetime = 0;
	self.psoffsettime = 0;
	self.friendlydamage = undefined;

	spawnpointname = "mp_global_intermission";
	spawnpoints = getentarray(spawnpointname, "classname");
	spawnpoint = maps\mp\gametypes\_spawnlogic::getSpawnpoint_Random(spawnpoints);

	if(isDefined(spawnpoint))
		self spawn(spawnpoint.origin, spawnpoint.angles);
	else
		maps\mp\_utility::error("NO " + spawnpointname + " SPAWNPOINTS IN MAP");

	self thread updateTimer();
}

respawn()
{
	self endon("disconnect");
	self endon("end_respawn");

	if(!isDefined(self.pers["weapon"]))
		return;

	self.sessionteam = self.pers["team"];
	self.sessionstate = "spectator";

	if(isdefined(self.dead_origin) && isdefined(self.dead_angles))
	{
		origin = self.dead_origin + (0, 0, 16);
		angles = self.dead_angles;
	}
	else
	{
		origin = self.origin + (0, 0, 16);
		angles = self.angles;
	}

	self spawn(origin, angles);

	
	// * AdmiralMOD *
	// * Wenn Waiting Timer bei Squad noch läuft, dann anzeigen *
	if(game["am_squads"] == 1 && isDefined(self.WaitingToSpawn)) {

		// * Respawn Timer anzeigen *
		self maps\mp\gametypes\_admiral_mod_hud::changePlayerTimerHudElementByName("squad_respawn_timer",1);
	}

	
	while(isdefined(self.WaitingToSpawn)) wait .05;



	if(getCvarInt("scr_forcerespawn") <= 0)
	{
		self thread waitRespawnButton();
		self waittill("respawn");
	}

	self thread spawnPlayer();
}

waitRespawnButton()
{
	self endon("disconnect");
	self endon("end_respawn");
	self endon("respawn");

	wait 0; // Required or the "respawn" notify could happen before it's waittill has begun

	if(!isdefined(self.respawntext))
	{
		self.respawntext = newClientHudElem(self);
		self.respawntext.horzAlign = "center_safearea";
		self.respawntext.vertAlign = "center_safearea";
		self.respawntext.alignX = "center";
		self.respawntext.alignY = "middle";
		self.respawntext.x = 0;
		self.respawntext.y = -50;
		self.respawntext.archived = false;
		self.respawntext.font = "default";
		self.respawntext.fontscale = 2;
		self.respawntext setText(&"PLATFORM_PRESS_TO_SPAWN");
	}

	thread removeRespawnText();
	thread waitRemoveRespawnText("end_respawn");
	thread waitRemoveRespawnText("respawn");

	while(self useButtonPressed() != true)
		wait .05;

	self notify("remove_respawntext");

	self notify("respawn");
}

removeRespawnText()
{
	self waittill("remove_respawntext");

	if(isDefined(self.respawntext))
		self.respawntext destroy();
}

waitRemoveRespawnText(message)
{
	self endon("remove_respawntext");

	self waittill(message);
	self notify("remove_respawntext");
}

startGame()
{

	setTeamScore("allies", game["alliedscore"]);
	setTeamScore("axis", game["axisscore"]);


	level.starttime = getTime();


	if(level.timelimit > 0)
	{
		level.clock = newHudElem();
		level.clock.horzAlign = "left";
		level.clock.vertAlign = "top";
		level.clock.x = 8;
		level.clock.y = 2;
		level.clock.font = "default";
		level.clock.fontscale = 2;
		level.clock setTimer(level.timelimit * 60);
		
		if(isDefined(game["am_show_time"]) && game["am_show_time"] == 0) level.clock.alpha = 0;
	
		// * AdmiralMOD *
		level.clock.sort = 50;
		
//** hinzugefügt für HELLZone_AM **//

	level.firstblood = 0;	//** Variabel für ersten Kill -FIRST BLOOD- **//

	thread maps\mp\gametypes\_myaddon::Timeannouncer();
	level.clock.color = (0,0,1); //** Farbe Clock **//
	
//** ---Ende für HELLZone_AM--- **//
		
	}

	for(;;)
	{
		checkTimeLimit();
		wait 1;
	}
}

endMap()
{
	
	game["state"] = "intermission";
	level notify("intermission");

	level notify("end_map");
	
	
	if(isDefined(level.clock))		level.clock destroy();			
	
	


	winningteam = "tie";
	losingteam = "tie";
	text = &"MP_THE_GAME_IS_A_TIE";
		
	
	if(level.winning_team == "allies")
	{
		game["alliedscore"]++;
		setTeamScore("allies", game["alliedscore"]);
		
		winningteam = "allies";
		losingteam = "axis";
		text = &"MP_ALLIES_WIN";
		
		level maps\mp\gametypes\_admiral_mod_hud::createLevelHudElement("flag_winner", 320,110, "center","middle","fullscreen","fullscreen",false,"gfx/custom/flagge_" + game["allies"] + ".tga",128,128,1,0.9,1,1,1);

	}
	
	if(level.winning_team == "axis")
	{
		game["axisscore"]++;
		setTeamScore("axis", game["axisscore"]);
		
		winningteam = "axis";
		losingteam = "allies";
		text = &"MP_AXIS_WIN";
		
		level maps\mp\gametypes\_admiral_mod_hud::createLevelHudElement("flag_winner", 320,110, "center","middle","fullscreen","fullscreen",false,"gfx/custom/flagge_german.tga",128,128,1,0.9,1,1,1);
	}

	level notify("update_allhud_score");

	iprintlnbold(text);
	



	winners = "";
	losers = "";

	if(winningteam == "allies")
		level thread playSoundOnPlayers("am_victory_allies");
	else if(winningteam == "axis")
		level thread playSoundOnPlayers("am_victory_axis");
	else
		level thread playSoundOnPlayers("MP_announcer_round_draw");


	// * AdmiralMOD *
	if(game["am_enabled"] == 1) maps\mp\gametypes\_admiral_mod::EndMapPre();



	wait 10;

	level maps\mp\gametypes\_admiral_mod_hud::deleteLevelHudElementByName("flag_winner");
	wait 4;
	

	// * Rounds Check * 
	game["roundsplayed"]++;
	if(game["roundsplayed"] < level.roundlimit) {
				
		iprintlnbold(&"AM_MP_START_NEXT_ROUND");
		wait 9;
	
	
		players = getentarray("player", "classname");
		for(i = 0; i < players.size; i++) {
		
			players[i].pers["rank"] = 1;
		}
			
	
	
		level.mapended = false;
		
		game["state"] = "playing";
		level notify("restarting");
	
			
		map_restart(true);		
	}
	else {



		if(game["alliedscore"] == game["axisscore"]) {
		
			text = &"MP_THE_GAME_IS_A_TIE";
		}
		else if(game["alliedscore"] > game["axisscore"]) {
		
			text = &"MP_ALLIES_WIN";
			winningteam = "axis";
			losingteam = "allies";
		}
		else {
		
			text = &"MP_AXIS_WIN";
			winningteam = "allies";
			winningteam = "axis";
		}



		players = getentarray("player", "classname");
		for(i = 0; i < players.size; i++)
		{
			player = players[i];

			if((winningteam == "allies") || (winningteam == "axis"))
			{
				lpGuid = player getGuid();
				if((isDefined(player.pers["team"])) && (player.pers["team"] == winningteam))
					winners = (winners + ";" + lpGuid + ";" + player.name);
				else if((isDefined(player.pers["team"])) && (player.pers["team"] == losingteam))
					losers = (losers + ";" + lpGuid + ";" + player.name);
			}

			player closeMenu();
			player closeInGameMenu();
			player setClientCvar("cg_objectiveText", text);

			player spawnIntermission();
		}

		if((winningteam == "allies") || (winningteam == "axis"))
		{
			logPrint("W;" + winningteam + winners + "\n");
			logPrint("L;" + losingteam + losers + "\n");
		}

		// set everyone's rank on xenon
		if(level.xenon)
		{
			players = getentarray("player", "classname");
			highscore = undefined;

			for(i = 0; i < players.size; i++)
			{
				player = players[i];

				if(!isdefined(player.score))
					continue;

				if(!isdefined(highscore) || player.score > highscore)
					highscore = player.score;
			}

			for(i = 0; i < players.size; i++)
			{
				player = players[i];

				if(!isdefined(player.score))
					continue;

				if(highscore <= 0)
					rank = 0;
				else
				{
					rank = int(player.score * 10 / highscore);
					if(rank < 0)
						rank = 0;
				}

				if(player.pers["team"] == "allies")
					setplayerteamrank(player, 0, rank);
				else if(player.pers["team"] == "axis")
					setplayerteamrank(player, 1, rank);
				else if(player.pers["team"] == "spectator")
					setplayerteamrank(player, 2, rank);
			}
			sendranks();
		}

		wait 10;


		// * AdmiralMOD *
		if(game["am_enabled"] == 1) maps\mp\gametypes\_admiral_mod::EndMap();


		exitLevel(false);
	}
}

checkTimeLimit()
{
	if(level.timelimit <= 0)
		return;

	timepassed = (getTime() - level.starttime) / 1000;
	timepassed = timepassed / 60.0;

	if(timepassed < level.timelimit)
		return;

	if(level.mapended)
		return;
	level.mapended = true;

	if(!level.splitscreen)
		iprintln(&"MP_TIME_LIMIT_REACHED");

	level thread endMap();
}




updateGametypeCvars()
{
	for(;;)
	{
		timelimit = getCvarFloat("scr_dom_timelimit");
		if(level.timelimit != timelimit)
		{
			if(timelimit > 1440)
			{
				timelimit = 1440;
				setCvar("scr_dom_timelimit", "1440");
			}

			level.timelimit = timelimit;
			setCvar("ui_dom_timelimit", level.timelimit);
			level.starttime = getTime();

			if(level.timelimit > 0)
			{
				if(!isDefined(level.clock))
				{
					level.clock = newHudElem();
					level.clock.horzAlign = "left";
					level.clock.vertAlign = "top";
					level.clock.x = 8;
					level.clock.y = 2;
					level.clock.font = "default";
					level.clock.fontscale = 2;
				}
				level.clock setTimer(level.timelimit * 60);
			}
			else
			{
				if(isDefined(level.clock))
					level.clock destroy();
			}

			checkTimeLimit();
		}

		roundlimit = getCvarInt("scr_dom_roundlimit");
		if(level.roundlimit != roundlimit)
		{
			level.roundlimit = roundlimit;
			setCvar("ui_dom_roundlimit", level.roundlimit);			
		}


	

		wait 1;
	}
}

printJoinedTeam(team)
{
	if(!level.splitscreen)
	{
	    if(team == "allies")
		    iprintln(&"MP_JOINED_ALLIES", self.name);
	    else if(team == "axis")
		    iprintln(&"MP_JOINED_AXIS", self.name);
	}
}



initFlags()
{
	level.hud_dom_pos_y = 455;
	level.flag_radius 	= 120;
	level.flag_time 	= game["am_dom_flag_capture_time"];

	flags = [];
	
	
	spawnpoints = getentarray("mp_dm_spawn", "classname");
	
	j = randomInt(spawnpoints.size);
	
	flags[0] = spawnpoints[j];	
	//logprint("Flag "+flags.size+ " : " + spawnpoints[j].origin + "\n");
	
	
	trys = 0;
	while(flags.size < 5) {
	
		trys++;
		if(trys > 100) break;
	
		j = randomInt(spawnpoints.size);
	
		
		near = false;
		for(i=0;i<flags.size;i++) {
	
			if(distance(spawnpoints[j].origin,flags[i].origin) < 1000) {
			
				near = true;
				break;
			}
		}	
		if(near == true) continue;
		
		flags[flags.size] = spawnpoints[j];			
		//logprint("Flag "+flags.size+ " : " + spawnpoints[j].origin + "\n");		
	}
	
	//logprint("Trys: " + trys + "\n");		



	for(i=0;i<flags.size;i++) {
	
		
		team 							= "none";			
			
		flags[i].home_origin 			= flags[i].origin;
		flags[i].home_angles 			= flags[i].angles;
		
		flags[i].flagmodel 	= spawn("script_model", flags[i].home_origin);
		flags[i].flagmodel.angles 		= flags[i].home_angles;
		flags[i].flagmodel setmodel("xmodel/fahne");
	
		flags[i].team 					= team;
		flags[i].objective 				= i;
		flags[i].compassflag 			= level.compassflag_empty;
		flags[i].objpointflag 			= level.objpointflag_empty;
		
		flags[i] thread flag();		


		level maps\mp\gametypes\_admiral_mod_hud::createLevelHudElement("flag_" + flags[i].objective, 255 + i*35,455, "center","middle","fullscreen","fullscreen",false,level.hudicon_empty,32,32,1,0.5,1,1,1);

	}	
	
	level.flags = flags;
	
	level thread checkWin(level.flags);
	
}



flag()
{

	level endon("end_map");



	objective_add(self.objective, "current", self.origin, self.compassflag);
	self createFlagWaypoint();

	
	for(;;)
	{
		other = maps\mp\gametypes\_admiral_mod_player::WaitForRadius(self.origin, level.flag_radius, 50);
				
		if(isPlayer(other) && isAlive(other) && (other.pers["team"] != "spectator")) {
		
			if(maps\mp\gametypes\_admiral_mod_utils::check_teams_exist()) {
			
				// Touched by enemy
				if(other.pers["team"] != self.team) {
				
					//println("PICKED UP THE FLAG!");


					self startCaptureProgress(other.clientid, other.pers["team"]);	
				}
			}
			else {
			
				other iprintlnbold(&"AM_MP_DOM_WAIT_FOR_TEAM");				
				wait 7;
			}
		}
		
		wait 0.5;
	}
}


startCaptureProgress(clientid, team) {

	

	helper = spawn("script_model",self.origin);			
	helper playloopsound("am_start_flag_capture");


	
	origin 	= self.origin;
	time 	= 0;
	swatch 	= 0;
	

	
	if(team == "axis")
		enemy_team = "allies";
	else
		enemy_team = "axis";	
	
	
	self.blink = true;
	
	
	// * Flagge Neutralizieren *	
	if(self.team != "none") {
	
		time_neutral = int(level.flag_time/2);
		
	
		while(isDefined(self) && time < time_neutral) {

			// * abfragen ob sich der Player noch im Radius der Flag befindet *
			origin = maps\mp\gametypes\_admiral_mod_player::getPlayerOrigin(clientid);


			// * Abbruch *
			if(!isDefined(origin) || (isDefined(origin) && distance(origin, self.origin) > level.flag_radius) || maps\mp\gametypes\_admiral_mod_player::checkOtherPlayerInRange(clientid, origin, enemy_team, level.flag_radius) > -1) {

				level maps\mp\gametypes\_admiral_mod_hud::changeLevelHudElementByName("flag_" + self.objective,0.5);

				if(isDefined(helper)) {

					helper stoploopsound();
					helper delete();
				}

				self.blink = undefined;

				return;
			}


			alpha = 0.5 - ((0.5/time_neutral) * time);


			if(swatch == 0) level maps\mp\gametypes\_admiral_mod_hud::changeLevelHudElementByName("flag_" + self.objective,0);
			if(swatch == 1) level maps\mp\gametypes\_admiral_mod_hud::changeLevelHudElementByName("flag_" + self.objective,alpha);

			swatch++;
			if(swatch > 1) swatch = 0;

			time++;
			wait 0.5;			
		}
	}


	// * Neutral anzeigen *
	self.flagmodel setmodel("xmodel/fahne");
	self.team 					= "none";
	self.compassflag 			= level.compassflag_empty;
	self.objpointflag 			= level.objpointflag_empty;
	objective_icon(self.objective, self.compassflag);  

	level maps\mp\gametypes\_admiral_mod_hud::deleteLevelHudElementByName("flag_" + self.objective);
	level maps\mp\gametypes\_admiral_mod_hud::createLevelHudElement("flag_" + self.objective, 255 + self.objective*35,level.hud_dom_pos_y, "center","middle","fullscreen","fullscreen",false,level.hudicon_empty,32,32,1,0.5,1,1,1);
			
	self createFlagWaypoint();	
	
	
	
	
	
	// * Dem anderen Team mitteilen das Ihre Flagge neutralisiert wurde, und im Begriff ist übernommen zu werden *
	if(self.team == "allies" || self.team == "axis")  {
	
		kurz = "GE";
	
		if(self.team == "allies")
		{
			switch(game["allies"]) {

			case "american":
				kurz = "US";			
				break;
			case "british":
				kurz = "UK";			
				break;		
			case "russian":
				kurz = "RU";			
				break;
			}
		}

		if(self.team == "allies") 	level thread playSoundOnPlayers("am_dom_" + kurz + "_losing_ground_" + game["dom_language"], "allies");	
		else						level thread playSoundOnPlayers("am_dom_" + kurz + "_losing_ground_" + game["dom_language"], "axis");	
	}
	
	
	
	
	self.blink = true;
	

	// * Flagge Capturen *	
	while(isDefined(self) && time < level.flag_time) {
	
		// * abfragen ob sich der Player noch im Radius der Flag befindet *
		origin = maps\mp\gametypes\_admiral_mod_player::getPlayerOrigin(clientid);
	
	
		// * Abbruch *
		if(!isDefined(origin) || (isDefined(origin) && distance(origin, self.origin) > level.flag_radius) || maps\mp\gametypes\_admiral_mod_player::checkOtherPlayerInRange(clientid, origin, enemy_team, level.flag_radius) > -1) {
			
			level maps\mp\gametypes\_admiral_mod_hud::changeLevelHudElementByName("flag_" + self.objective,0.5);
			
			if(isDefined(helper)) {
								
				helper stoploopsound();
				helper delete();
			}
			
			self.blink = undefined;
			
			return;
		}
	
		
		alpha = 0.5 - ((0.5/level.flag_time) * time);
	
	
		if(swatch == 0) level maps\mp\gametypes\_admiral_mod_hud::changeLevelHudElementByName("flag_" + self.objective,0);
		if(swatch == 1) level maps\mp\gametypes\_admiral_mod_hud::changeLevelHudElementByName("flag_" + self.objective,alpha);
		
		swatch++;
		if(swatch > 1) swatch = 0;
		
		time++;
		wait 0.5;			
	}

	
	if(isDefined(helper)) helper delete();

	other = maps\mp\gametypes\_admiral_mod_player::getPlayerPlaying(clientid,team);
	if(isDefined(other)) other GetFlag(self); // Getting flag
	
	self.blink = undefined;
}




GetFlag(flag) {

	self endon("disconnect");


	if(self.pers["team"] == "axis")		enemy = "allies";
	else								enemy = "axis";



	// * Punkte vergeben *
	if(game["am_dom_points_capture_flag"] > 0) {

		maps\mp\gametypes\_admiral_mod_player::givePlayerPoints(self.clientid,self.pers["team"],game["am_dom_points_capture_flag"]);				
	}
				
				

	
	if(self.pers["team"] == "allies") {

		flag.team = "allies";	// Muß hier oben stehen		


		kurz = self maps\mp\gametypes\_admiral_mod_player::GetTeamKurz();
		
		// * nur wenn nicht letzte Flag *
		if(!checkAllFlagsCaptured()) {
		
			if(flag.team != "axis") 	level thread playSoundOnPlayers("am_dom_" + kurz + "_area_secured_" + game["dom_language"], "allies");	
			else						level thread playSoundOnPlayers("am_dom_" + kurz + "_ground_taken_" + game["dom_language"], "allies");	
			level thread playSoundOnPlayers("am_dom_GE_lost_ground_" + game["dom_language"], "axis");
		}

	
		flagModel = "xmodel/prop_flag_" + game["allies"];
		flag.flagmodel setmodel(flagModel);	
		
		flag.compassflag = level.compassflag_allies;
		objective_icon(flag.objective, flag.compassflag);  
		flag.objpointflag = level.objpointflag_allies;
		
		level maps\mp\gametypes\_admiral_mod_hud::deleteLevelHudElementByName("flag_" + flag.objective);
		level maps\mp\gametypes\_admiral_mod_hud::createLevelHudElement("flag_" + flag.objective, 255 + flag.objective*35,level.hud_dom_pos_y, "center","middle","fullscreen","fullscreen",false,game["hudicon_allies"],32,32,1,0.5,1,1,1);
		
	}
	else {

		flag.team = "axis";	  // Muß hier oben stehen	


		kurz = maps\mp\gametypes\_admiral_mod_player::GetKurzAllies();

		// * nur wenn nicht letzte Flag *
		if(!checkAllFlagsCaptured()) {
	
			if(flag.team != "allies")	level thread playSoundOnPlayers("am_dom_GE_area_secured_" + game["dom_language"], "axis");
			else						level thread playSoundOnPlayers("am_dom_GE_ground_taken_" + game["dom_language"], "axis");

			level thread playSoundOnPlayers("am_dom_" + kurz + "_lost_ground_" + game["dom_language"], "allies");	
		}

		flagModel = "xmodel/prop_flag_" + game["axis"];
		flag.flagmodel setmodel(flagModel);	
		
		
		flag.compassflag = level.compassflag_axis;
		objective_icon(flag.objective, flag.compassflag);  
		flag.objpointflag = level.objpointflag_axis;


		level maps\mp\gametypes\_admiral_mod_hud::deleteLevelHudElementByName("flag_" + flag.objective);
		level maps\mp\gametypes\_admiral_mod_hud::createLevelHudElement("flag_" + flag.objective, 255 + flag.objective*35,level.hud_dom_pos_y, "center","middle","fullscreen","fullscreen",false,game["hudicon_axis"],32,32,1,0.5,1,1,1);


	}		


	
	

		
	self.dont_auto_balance = true;

	flag createFlagWaypoint();	
	
}


createFlagWaypoint()
{
	self deleteFlagWaypoint();

	waypoint = newHudElem();
	waypoint.x = self.origin[0];
	waypoint.y = self.origin[1];
	waypoint.z = self.origin[2] + 100;
	waypoint.alpha = .61;
	waypoint.archived = true;

	if(level.splitscreen)
		waypoint setShader(self.objpointflag, 14, 14);
	else
		waypoint setShader(self.objpointflag, 7, 7);

	waypoint setwaypoint(true);
	self.waypoint_flag = waypoint;

}

deleteFlagWaypoint()
{
	if(isdefined(self.waypoint_flag))
		self.waypoint_flag destroy();
}



checkWin(flags) {

	level notify("checkWin");
	level endon("checkWin");
	
	
	while(isDefined(flags)) {
				
		if(checkAllFlagsCaptured()) {
	
			
			if(flags[0].team == "allies")	level.winning_team = "allies";
			else							level.winning_team = "axis";
	
	
			level.mapended = true;

		
			level thread endMap();
		
			break;
		}		
		
		wait 0.5;
	}
}


checkAllFlagsCaptured() {

	flags = level.flags;
	
	team = flags[0].team;



	if(!isDefined(team)) return false;
	if(team != "axis" && team != "allies") return false;


	// * Wenn alle Flaggen einem Team gehören... *
	if(flags[0].team == team && flags[0].team == team && flags[1].team == team && flags[2].team == team && flags[3].team == team && flags[4].team == team) {
	
		return true;
	
		/*
		
		// * ... und keine Flagge blinkt! *
		if(!isDefined(flags[0].blink) && !isDefined(flags[1].blink) && !isDefined(flags[2].blink) && !isDefined(flags[3].blink) && !isDefined(flags[4].blink)) {
			
			return true;
		}
		
		*/
	}
		
	
	return false;

}




playSoundOnPlayers(sound, team)
{
	players = getentarray("player", "classname");

	if(level.splitscreen)
	{
		if(isdefined(players[0]))
			players[0] playLocalSound(sound);
	}
	else
	{
		if(isdefined(team))
		{
			for(i = 0; i < players.size; i++)
			{
				if((isdefined(players[i].pers["team"])) && (players[i].pers["team"] == team))
					players[i] playLocalSound(sound);
			}
		}
		else
		{
			for(i = 0; i < players.size; i++)
				players[i] playLocalSound(sound);
		}
	}
}

printOnTeam(text, team, playername)
{
	players = getentarray("player", "classname");
	for(i = 0; i < players.size; i++)
	{
		if((isdefined(players[i].pers["team"])) && (players[i].pers["team"] == team))
			players[i] iprintln(text,playername);
	}
}

menuAutoAssign()
{
	if(!level.xenon && isdefined(self.pers["team"]) && (self.pers["team"] == "allies" || self.pers["team"] == "axis"))
	{
		self openMenu(game["menu_team"]);
		return;
	}

	numonteam["allies"] = 0;
	numonteam["axis"] = 0;

	players = getentarray("player", "classname");
	for(i = 0; i < players.size; i++)
	{
		player = players[i];

		if(!isDefined(player.pers["team"]) || player.pers["team"] == "spectator" || player == self)
			continue;

		numonteam[player.pers["team"]]++;
	}

	// if teams are equal return the team with the lowest score
	if(numonteam["allies"] == numonteam["axis"])
	{
		if(getTeamScore("allies") == getTeamScore("axis"))
		{
			teams[0] = "allies";
			teams[1] = "axis";
			assignment = teams[randomInt(2)];
		}
		else if(getTeamScore("allies") < getTeamScore("axis"))
			assignment = "allies";
		else
			assignment = "axis";
	}
	else if(numonteam["allies"] < numonteam["axis"])
		assignment = "allies";
	else
		assignment = "axis";

	if(assignment == self.pers["team"] && (self.sessionstate == "playing" || self.sessionstate == "dead"))
	{
	    if(!isdefined(self.pers["weapon"]))
	    {
		    if(self.pers["team"] == "allies")
			    self openMenu(game["menu_weapon_allies"]);
		    else
			    self openMenu(game["menu_weapon_axis"]);
	    }

		return;
	}

	if(assignment != self.pers["team"] && (self.sessionstate == "playing" || self.sessionstate == "dead"))
	{
		self.switching_teams = true;
		self.joining_team = assignment;
		self.leaving_team = self.pers["team"];
		self suicide();
	}

	self.pers["team"] = assignment;
	self.pers["weapon"] = undefined;
	self.pers["savedmodel"] = undefined;


	self.pers["remember_player_class"] 		= -1;
	self.pers["preselected_player_class"] 	= -1;
	self.pers["player_class"] 				= -1;	

	self setClientCvar("ui_allow_weaponchange", "1");

	if(self.pers["team"] == "allies")
	{
		scriptMainMenu = self maps\mp\gametypes\_menus::am_menuSelection();
		//self openMenu(game["menu_weapon_allies"]);
		//self setClientCvar("g_scriptMainMenu", game["menu_weapon_allies"]);
	}
	else
	{
		scriptMainMenu = self maps\mp\gametypes\_menus::am_menuSelection();
		//self openMenu(game["menu_weapon_axis"]);
		//self setClientCvar("g_scriptMainMenu", game["menu_weapon_axis"]);
	}

	self notify("joined_team");
	self notify("end_respawn");
}

menuAllies()
{
	if(self.pers["team"] != "allies")
	{
		if(!level.xenon && !maps\mp\gametypes\_teams::getJoinTeamPermissions("allies"))
		{
			self openMenu(game["menu_team"]);
			return;
		}

		if(self.sessionstate == "playing")
		{
			self.switching_teams = true;
			self.joining_team = "allies";
			self.leaving_team = self.pers["team"];
			self suicide();
		}

		self.pers["team"] = "allies";
		self.pers["weapon"] = undefined;
		self.pers["savedmodel"] = undefined;


		self.pers["remember_player_class"] 		= -1;
		self.pers["preselected_player_class"] 	= -1;
		self.pers["player_class"] 				= -1;	

		self setClientCvar("ui_allow_weaponchange", "1");
		scriptMainMenu = self maps\mp\gametypes\_menus::am_menuSelection();
		//self setClientCvar("g_scriptMainMenu", scriptMainMenu);

		self notify("joined_team");
		self notify("end_respawn");
	}

	if(!isdefined(self.pers["weapon"])) {
	
		scriptMainMenu = self maps\mp\gametypes\_menus::am_menuSelection();
	}
}

menuAxis()
{
	if(self.pers["team"] != "axis")
	{
		if(!level.xenon && !maps\mp\gametypes\_teams::getJoinTeamPermissions("axis"))
		{
			self openMenu(game["menu_team"]);
			return;
		}

		if(self.sessionstate == "playing")
		{
			self.switching_teams = true;
			self.joining_team = "axis";
			self.leaving_team = self.pers["team"];
			self suicide();
		}

		self.pers["team"] = "axis";
		self.pers["weapon"] = undefined;
		self.pers["savedmodel"] = undefined;


		self.pers["remember_player_class"] 		= -1;
		self.pers["preselected_player_class"] 	= -1;
		self.pers["player_class"] 				= -1;	


		self setClientCvar("ui_allow_weaponchange", "1");
		scriptMainMenu = self maps\mp\gametypes\_menus::am_menuSelection();
		//self setClientCvar("g_scriptMainMenu", scriptMainMenu);


		self notify("joined_team");
		self notify("end_respawn");
	}

	if(!isdefined(self.pers["weapon"])) {
		
		scriptMainMenu = self maps\mp\gametypes\_menus::am_menuSelection();
	}
}

menuSpectator()
{
	if(self.pers["team"] != "spectator")
	{
		if(isAlive(self))
		{
			self.switching_teams = true;
			self.joining_team = "spectator";
			self.leaving_team = self.pers["team"];
			self suicide();
		}

		self.pers["team"] = "spectator";
		self.pers["weapon"] = undefined;
		self.pers["savedmodel"] = undefined;

		self.sessionteam = "spectator";
		self setClientCvar("ui_allow_weaponchange", "0");


		self.pers["remember_player_class"] 		= -1;
		self.pers["preselected_player_class"] 	= -1;
		self.pers["player_class"] 				= -1;	

		self thread updateTimer();

		spawnSpectator();

		if(level.splitscreen)
			self setClientCvar("g_scriptMainMenu", game["menu_ingame_spectator"]);
		else
			self setClientCvar("g_scriptMainMenu", game["menu_ingame"]);

		self notify("joined_spectators");
		self notify("end_respawn");
	}
}

menuWeapon(response)
{
	self endon("disconnect");


	if(!isDefined(self.pers["team"]) || (self.pers["team"] != "allies" && self.pers["team"] != "axis"))
		return;

	weapon = self maps\mp\gametypes\_weapons::restrictWeaponByServerCvars(response);

	if(weapon == "restricted")
	{
		if(self.pers["team"] == "allies")
			self openMenu(game["menu_weapon_allies"]);
		else if(self.pers["team"] == "axis")
			self openMenu(game["menu_weapon_axis"]);

		return;
	}

	if(level.splitscreen)
		self setClientCvar("g_scriptMainMenu", game["menu_ingame_onteam"]);
	else
		self setClientCvar("g_scriptMainMenu", game["menu_ingame"]);

	if(isDefined(self.pers["weapon"]) && self.pers["weapon"] == weapon)
		return;

	if(!isDefined(self.pers["weapon"]))
	{
		self.pers["weapon"] = weapon;

		if(isdefined(self.WaitingToSpawn))
		{
			self thread respawn();
			self thread updateTimer();
		}
		else
			spawnPlayer();

		self thread printJoinedTeam(self.pers["team"]);
	}
	else
	{
		self.pers["next_spawn_weapon"] = weapon;
		
		self.pers["weapon"] = weapon;

		weaponname = maps\mp\gametypes\_weapons::getWeaponName(self.pers["weapon"]);
	
		if(maps\mp\gametypes\_weapons::useAn(self.pers["weapon"]))
			self iprintln(&"MP_YOU_WILL_RESPAWN_WITH_AN", weaponname);
		else
			self iprintln(&"MP_YOU_WILL_RESPAWN_WITH_A", weaponname);
	}

	self thread maps\mp\gametypes\_spectating::setSpectatePermissions();
}

respawn_timer(delay)
{
	self endon("disconnect");

	self.WaitingToSpawn = true;

	if(level.respawndelay > 0)
	{
		if(!isdefined(self.respawntimer))
		{
			self.respawntimer = newClientHudElem(self);
			self.respawntimer.x = 0;
			self.respawntimer.y = -50;
			self.respawntimer.alignX = "center";
			self.respawntimer.alignY = "middle";
			self.respawntimer.horzAlign = "center_safearea";
			self.respawntimer.vertAlign = "center_safearea";
			self.respawntimer.alpha = 0;
			self.respawntimer.archived = false;
			self.respawntimer.font = "default";
			self.respawntimer.fontscale = 2;
			self.respawntimer.label = (&"MP_TIME_TILL_SPAWN");
			self.respawntimer setTimer (level.respawndelay + delay);
		}

		wait delay;
		self thread updateTimer();

		wait level.respawndelay;

		if(isdefined(self.respawntimer))
			self.respawntimer destroy();
	}

	self.WaitingToSpawn = undefined;
}

updateTimer()
{
	if(isdefined(self.respawntimer))
	{
		if(isdefined(self.pers["team"]) && (self.pers["team"] == "allies" || self.pers["team"] == "axis") && isdefined(self.pers["weapon"]))
			self.respawntimer.alpha = 1;
		else
			self.respawntimer.alpha = 0;
	}
	
	
	// * AdmiralMOD *
	if(game["am_squads"] == 1) self thread maps\mp\gametypes\_admiral_mod_squad::SquadRespawnTimerUpdate();
	
}
