"use strict";
/*

Cataclysm.js

Script for Cataclysm.oxp.


Oolite
Copyright © 2008 Giles C Williams and contributors

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA.

*/

this.name = "Cataclysm";
this.author = "Commander McLane";
this.copyright = "© 2009 Commander McLane";
this.version = "2.0";

/*variables*/

this.hiveLocations = new Array()
this.hiveLocations[0] = [134, 176, 22, 195, 4, 184, 44, 228, 48, 144, 68, 211]
this.hiveLocations[1] = [20, 63, 207, 241, 28, 177, 30, 210, 5, 229, 61, 92]
this.hiveLocations[2] = [115, 196, 13, 159, 17, 218, 219, 233, 58, 76, 65, 79]
this.hiveLocations[3] = [131, 180, 175, 225, 20, 152, 48, 167, 56, 238, 83, 114]
this.hiveLocations[4] = [158, 212, 18, 186, 187, 207, 77, 246, 78, 125, 97, 108]
this.hiveLocations[5] = [116, 221, 153, 241, 26, 169, 43, 175, 5, 194, 85, 99]
this.hiveLocations[6] = [109, 215, 12, 174, 39, 44, 40, 158, 48, 120, 85, 99, 27, 153]
this.hiveLocations[7] = [173, 179, 237, 245, 33, 78, 44, 70, 61, 138, 66, 165]

this.systemList = {
	"0": [16, 28, 36, 56, 62, 83, 91, 110, 145, 150, 179, 198, 200, 230, 237],
	"4": [24, 26, 35, 41, 111, 112, 180, 181, 183, 210, 216, 222, 231],
	"5": [33, 41, 55, 202],
	"6": [15, 17, 27, 30, 61, 79, 97, 110, 115, 125, 130, 134, 137, 139, 153, 161, 173, 178, 186, 191, 205, 214, 218, 228, 229, 237, 248],
};

this.choice = null;

this._padInfo = {};

/* functions */

//-------------------------------------------------------------------------------------------------------------
this.turnStationToPlanet = function (station) {
	var type = expandDescription("[cataclysm_stn_research]");
	if (station.name.indexOf(expandDescription("[cataclysm_stn_military]")) >= 0) type = expandDescription("[cataclysm_stn_military]");
	var targetVector = system.mainPlanet.position.subtract(station.position).direction();
	station.orientation = targetVector.rotationTo([0, 0, 1]);
	var buoy = system.addShips("cataclysm_stn_buoy", 1, station.position.add(station.vectorForward.multiply(10E3)), 0)[0];
	buoy.beaconLabel = buoy.beaconLabel.replace("Navy", type);
	buoy.displayName = buoy.displayName.replace("Navy", type);
	// TODO: work out why buoy isn't directly in line with station exit in some cases
}

//-------------------------------------------------------------------------------------------------------------
this.blockSystemRedux = function () {
	if (worldScripts["System Redux"]) {
		var sr = worldScripts["System Redux"];
		// make sure system redux startup script has been run before we try to add moon exclusions
		if (!sr.excl) {
			sr.startUp();
		}
		delete sr.startUp;
		//system_info[0 * 256 + 164] = system_info[0 * 256 + 164] & 0xFFF0
		if (sr.excl[0].indexOf(164) == -1) sr.excl[0].push(164);
		//system_info[2 * 256 + 86] = system_info[2 * 256 + 86] & 0xFFF0
		if (sr.excl[2].indexOf(86) == -1) sr.excl[2].push(86);
		//system_info[5 * 256 + 33] = system_info[5 * 256 + 33] & 0xFF00
		if (sr.excl[5].indexOf(33) == -1) sr.excl[5].push(33);
	}
}

//-------------------------------------------------------------------------------------------------------------
this.advanceJumpCounters = function () {
	if (galaxyNumber == 0) {
		if (missionVariables.cataclysm == "STAGE1")
			missionVariables.cataclysm = "STAGE1a";
		if (missionVariables.cataclysm == "STAGE1b")
			missionVariables.cataclysm = "STAGE1c";
	}
}

//-------------------------------------------------------------------------------------------------------------
this.checkForGalDriveMod = function () {
	if (player.ship.hasEquipmentProviding("EQ_GAL_DRIVE_MOD")) {
		this.defaultGalacticHyperspaceBehaviour = player.ship.galacticHyperspaceBehaviour;
		player.ship.galacticHyperspaceBehaviour = "BEHAVIOUR_ALL_SYSTEMS_REACHABLE";
	}
}

//-------------------------------------------------------------------------------------------------------------
this.resetGalHyperspaceBehaviour = function () {
	if (player.ship.hasEquipmentProviding("EQ_GAL_DRIVE_MOD")) {
		player.ship.removeEquipment("EQ_GAL_DRIVE_MOD");
		player.ship.galacticHyperspaceBehaviour = this.defaultGalacticHyperspaceBehaviour;
	}
}

//-------------------------------------------------------------------------------------------------------------
this.switchMilitaryAI = function () {
	system.shipsWithPrimaryRole("military-ship").forEach(
		function (ship) {
			ship.switchAI("route1patrolAI.plist");
			ship.fuel = 15;
		}
	)
}

//-------------------------------------------------------------------------------------------------------------
this.setupThargoidShipScript = function () {
	this.livingThargoids = system.shipsWithPrimaryRole("thargoid", system.mainStation, 60000);
	this.thargoidsKilledByPlayer = 0;
	this.livingThargoids.forEach(
		function (ship) {
			ship.script.shipDied = function (whom, why) {
				if (whom == player.ship) {
					worldScripts.Cataclysm.thargoidsKilledByPlayer++;
				}
			}
		}
	)
}

//-------------------------------------------------------------------------------------------------------------
this.startThargoidsRemainingTimer = function () {
	if (!this.thargoidsRemainingTimer)
		this.thargoidsRemainingTimer = new Timer(this, this.countRemainingThargoids, 0, 10);
	else
		this.thargoidsRemainingTimer.start();
}

//-------------------------------------------------------------------------------------------------------------
this.countRemainingThargoids = function () {
	var stn = system.mainStation;
	if (this.currentSystem == "Tetier") {
		this.tetierStation = system.shipsWithPrimaryRole("cataclysm_tetier_station")[0];
		stn = this.tetierStation;
	}
	var thargoidsNearStation = system.countShipsWithPrimaryRole("thargoid", stn, 50000);

	if (this.currentSystem == "Galaxy1") {
		if (thargoidsNearStation == 0) {
			this.$findNearestStation().commsMessage(expandDescription("[cataclysm_attack_finished]"));
			missionVariables.cataclysm = "STAGE2a";
			this.thargoidsRemainingTimer.stop();
		}
	} else if (this.currentSystem == "Ribilebi") {
		if (thargoidsNearStation < 3) {
			this.$findNearestStation().commsMessage(expandDescription("[cataclysm_battle_complete]"));
			var stn = system.shipsWithPrimaryRole("cataclysm_ribilebi_station")[0];
			// only turn the beacon on now.
			stn.beaconCode = "R";
			stn.beaconLabel = expandDescription("[cataclysm_ribilebi_name]");
			missionVariables.cataclysm = "STAGE4a";
			this.thargoidsRemainingTimer.stop();
		} else
			player.consoleMessage(expandDescription("[cataclysm_defend_Ribilebi_hail]"), 3);
	} else if (this.currentSystem == "Galaxy3") {
		if (thargoidsNearStation == 0) {
			this.$findNearestStation().commsMessage(expandDescription("[cataclysm_attack_finished]"));
			missionVariables.cataclysm_missions = "STATION_DEFENDED";
			this.thargoidsRemainingTimer.stop();
		}
	} else if (this.currentSystem == "Tetier") {
		if (thargoidsNearStation == 0) {
			this.$findNearestStation().commsMessage(expandDescription("[cataclysm_smashed_them]"));
			missionVariables.cataclysm = "STAGE11c";
			this.thargoidsRemainingTimer.stop();
			var replica = system.shipsWithRole("cataclysm_warship_replica_2")[0];
			if (replica) {
				replica.target = this.tetierStation;
				replica.setAI("dockingAI.plist");
			}
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
// returns the nearest station to the player
this.$findNearestStation = function () {
	function _stations(entity) {
		return entity.isShip && entity.isStation;
	}
	return system.filteredEntities(this, _stations, player.ship)[0];
}

//-------------------------------------------------------------------------------------------------------------
this.$findNearestGalCopShip = function () {
	function _galcop(entity) {
		return entity.isShip && (entity.isStation || entity.isPolice);
	}
	return system.filteredEntities(this, _galcop, player.ship)[0];
}

//-------------------------------------------------------------------------------------------------------------
// I'm not sure why we're doing these next two functions
// basically, we're removing three pieces of equipment when the system is populated
// and then giving them back once you dock at a station.
// in the case of the cloak, it's only removed if you haven't completed the mission, so an anti-cheat?
// or is this to make the missions harder because with these items the missions would be super easy? not sure.
this.dealWithIllicitEquipment1 = function () {
	if (player.ship.hasEquipmentProviding("EQ_CLOAKING_DEVICE") && missionVariables.cloak != "COMPLETE") {
		player.ship.removeEquipment("EQ_CLOAKING_DEVICE");
		this.illicitEquipment |= 1;
	}
	if (player.ship.hasEquipmentProviding("EQ_MILITARY_JAMMER") && !this.MJlegal) {
		player.ship.removeEquipment("EQ_MILITARY_JAMMER");
		this.illicitEquipment |= 2;
	}
	if (player.ship.hasEquipmentProviding("EQ_MILITARY_SCANNER_FILTER") && !this.MSFlegal) {
		player.ship.removeEquipment("EQ_MILITARY_SCANNER_FILTER");
		this.illicitEquipment |= 4;
	}
}

//-------------------------------------------------------------------------------------------------------------
this.dealWithIllicitEquipment2 = function () {
	if ((this.illicitEquipment & 1) == 1) {
		player.ship.awardEquipment("EQ_CLOAKING_DEVICE");
		this.illicitEquipment -= 1;
	}
	if ((this.illicitEquipment & 2) == 2) {
		player.ship.awardEquipment("EQ_MILITARY_JAMMER");
		this.illicitEquipment -= 2;
	}
	if ((this.illicitEquipment & 4) == 4) {
		player.ship.awardEquipment("EQ_MILITARY_SCANNER_FILTER");
		this.illicitEquipment -= 4;
	}
}

//-------------------------------------------------------------------------------------------------------------
this.stopWaiting = function () {
	missionVariables.cataclysm_hivemission = "WAIT_ENDED";
	delete this.waitTimer;
	this.missionScreens();
}

//-------------------------------------------------------------------------------------------------------------
this.wormholeCollapsed = function () {
	if (missionVariables.cataclysm == "STAGE7") {
		var commsSrc = this.$findNearestGalCopShip();
		if (!commsSrc) commsSrc = player;
		commsSrc.commsMessage(expandDescription("[cataclysm_crew_escaped]"));
		mission.setInstructionsKey("cataclysm_search_for_warship");
		this.searchWarshipTimer = new Timer(this, this.warshipSearchOver, 360);
	}
	delete this.wormholeCollapseTimer;
}

//-------------------------------------------------------------------------------------------------------------
this.warshipSearchOver = function () {
	missionVariables.cataclysm = "STAGE7c";
	delete this.searchWarshipTimer;
}

//-------------------------------------------------------------------------------------------------------------
this.missionScreens = function () {
	if (guiScreen == "GUI_SCREEN_MISSION" || !player.ship.docked) return;

	if (galaxyNumber == 0) {
		if (player.ship.dockedStation.isMainStation) {
			if (!missionVariables.cataclysm &&
				player.score > 5119 &&
				missionVariables.thargplans == "MISSION_COMPLETE" && this.systemList["0"].indexOf(system.ID) >= 0
				&& !missionVariables.offering) {
				this.runMissionScreen("cataclysm_intro_inews", "iNews.png");
				missionVariables.cataclysm = "STAGE1";
			}
			else if (missionVariables.cataclysm == "STAGE1a") {
				missionVariables.cataclysm = "STAGE1b";
			}
			else if (missionVariables.cataclysm == "STAGE1c" && player.ship.bounty == 0 && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_station_attack", null, "cataclysm_launch", null, "siren.ogg");
				mission.setInstructionsKey("cataclysm_defend_station");
				//system.legacy_addSystemShips("thargoid", 6, 0.98);
				system.addShips("thargoid", 6, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.98), 10000);
				//system.legacy_addSystemShips("trader", 4, 0.985);
				system.addShips("trader", 4, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.985), 10000);
				//system.legacy_addSystemShips("police", 3, 0.985);
				system.addShips("police", 3, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.985), 10000);
				this.setupThargoidShipScript();
				this.currentSystem = "Galaxy1";
				this.startThargoidsRemainingTimer();
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm = "STAGE1d";
			}
			else if (missionVariables.cataclysm == "STAGE1d" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_LAUNCH") {
				this.choice = null;
				player.ship.launch();
				delete missionVariables.offering;
				missionVariables.cataclysm = "STAGE2";
			}
			else if (missionVariables.cataclysm == "STAGE2a" && !missionVariables.offering) {
				this.$addPadLogEntry(expandDescription("[cataclysm_defended_station]"));
				if (this.thargoidsKilledByPlayer > 2) {
					this.runMissionScreen("cataclysm_station_attack_debrief", { name: "cataclysm_navy_star.png", height: 546 });
					this.$updateCurruthers();
					mission.setInstructionsKey("cataclysm_goto_Ribilebi");
					mission.markSystem({ system: 164, name: this.name });
					player.credits += 2000;
					missionVariables.cataclysm = "STAGE3";
				}
				else {
					this.runMissionScreen("cataclysm_station_attack_debrief_alt");
					mission.setInstructionsKey(null);
					player.credits += 500;
					missionVariables.cataclysm = "STAGE1";
				}
				delete this.livingThargoids;
				delete this.thargoidsKilledByPlayer;
			}
			else if (missionVariables.cataclysm == "STAGE3" && system.ID == 164 && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_ribilebi_brief_1", { name: "cataclysm_navy_star.png", height: 546 }, "cataclysm_continue");
				mission.unmarkSystem({ system: 164, name: this.name });
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm = "STAGE3a";
			}
			else if (missionVariables.cataclysm == "STAGE3a" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.choice = null;
				this.runMissionScreen("cataclysm_ribilebi_brief_2", null, "cataclysm_continue", "cataclysm_disabled_warship_1");
				missionVariables.cataclysm = "STAGE3b";
			}
			else if (missionVariables.cataclysm == "STAGE3b" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.choice = null;
				this.runMissionScreen("cataclysm_ribilebi_attack", null, "cataclysm_launch", null, "siren.ogg");
				mission.setInstructionsKey("cataclysm_defend_Ribilebi");
				var pos = Vector3D(86294, -48749, 73138).fromCoordinateSystem("pwm");
				//system.legacy_addShipsWithinRadius("thargoid", 8, "pwm", [86294, -48749, 73138], 25000);
				system.addShips("thargoid", 8, pos, 25000);
				//system.legacy_addShipsWithinRadius("trader", 5, "pwm", [86294, -48749, 73138], 25000);
				system.addShips("trader", 5, pos, 25000);
				//system.legacy_addShipsWithinRadius("police", 4, "pwm", [86294, -48749, 73138], 25000);
				system.addShips("police", 4, pos, 25000);
				missionVariables.cataclysm = "STAGE3c";
			}
			else if (missionVariables.cataclysm == "STAGE3c" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_LAUNCH") {
				player.ship.fuel += 3;
				this.currentSystem = expandDescription("[cataclysm_system_ribilebi]");
				this.startThargoidsRemainingTimer();
				player.ship.launch();
				delete missionVariables.offering;
				this.choice = null;
				missionVariables.cataclysm = "STAGE4";
			}
		}
		else if (player.ship.dockedStation.name == "Ribilebi Research Station") {
			if (missionVariables.cataclysm == "STAGE4a" && !missionVariables.offering) {
				this.$addPadLogEntry(expandDescription("[cataclysm_defended_station]"));
				this.runMissionScreen("cataclysm_ribilebi_brief_3", null, "cataclysm_continue", "cataclysm_disabled_warship_1");
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm = "STAGE4b";
			}
			else if (missionVariables.cataclysm == "STAGE4b" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runMissionScreen("cataclysm_ribilebi_brief_4", null, null, "cataclysm_disabled_warship_1");
				this.choice = 0;
				if (player.ship.hasEquipmentProviding("EQ_GAL_DRIVE")) {
					mission.addMessageTextKey("cataclysm_ribilebi_brief_4a");
					player.credits += 5000;
				}
				else {
					mission.addMessageTextKey("cataclysm_ribilebi_brief_4b");
					player.ship.awardEquipment("EQ_GAL_DRIVE");
				}
				mission.addMessageTextKey("cataclysm_ribilebi_brief_4c");
				mission.setInstructionsKey("cataclysm_goto_Galaxy3");
				delete missionVariables.offering;
				missionVariables.cataclysm = "STAGE5";
			}
		}
	}
	else if (galaxyNumber == 2) {
		if (player.ship.dockedStation.isMainStation) {
			if (missionVariables.cataclysm == "STAGE5" && system.ID != 36 && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_galaxy3_brief", { name: "cataclysm_navy_star.png", height: 546 });
				mission.setInstructionsKey("cataclysm_meet_Agent_Blake");
				mission.markSystem({ system: 36, name: this.name });
				missionVariables.cataclysm = "STAGE6";
			}
			else if (missionVariables.cataclysm == "STAGE6" &&
				system.ID != 36 &&
				!missionVariables.cataclysm_missions &&
				!missionVariables.offering) {
				if (missionVariables.cataclysm_trigger > 11 && missionVariables.cataclysm_trigger < 20) {
					this.runMissionScreen("cataclysm_defector_brief", null, null, "[ferdelance]");
					mission.setInstructionsKey("cataclysm_kill_defector");
					//system.legacy_addShipsAt("cataclysm_defector", 1, "pwm", [1000, -1000, 150000]);
					system.addShips("cataclysm_defector", 1, Vector3D(1000, -1000, 150000).fromCoordinateSystem("pwm"));
					//system.legacy_addShipsAt("police", 2, "pwm", [1000, -1000, 145000]);
					system.addShips("police", 2, Vector3D(1000, -1000, 145000).fromCoordinateSystem("pwm"));
					//system.legacy_addSystemShips("thargoid", 2, 0.95);
					system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.95));
					missionVariables.cataclysm_missions = "DEFECTOR_HUNT";
				}
				else if (missionVariables.cataclysm_trigger > 88 && missionVariables.cataclysm_trigger < 98) {
					missionVariables.cataclysm_ambassador_name = expandDescription("[nom11]");
					this.runMissionScreen("cataclysm_ambassador_brief", null, null, "[boa-mk2]");
					mission.setInstructionsKey("cataclysm_escort_ambassador");
					//system.legacy_addSystemShips("cataclysm_ambassador", 1, 0.8);
					system.addShips("cataclysm_ambassador", 1, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.8));
					//system.legacy_addSystemShips("thargoid", 2, 0.92);
					system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.92));
					//system.legacy_addSystemShips("thargoid", 2, 0.85);
					system.addShips("thargoid", 1, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.85));
					missionVariables.cataclysm_missions = "ESCORT_AMBASSADOR";
				}
				else if (missionVariables.cataclysm_trigger > 33 && missionVariables.cataclysm_trigger < 49) {
					this.runMissionScreen("cataclysm_station_attack", null, "cataclysm_launch", null, "siren.ogg");
					mission.setInstructionsKey("cataclysm_defend_station_2");
					//system.legacy_addSystemShips("thargoid", 6, 0.98);
					system.addShips("thargoid", 6, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.98), 10000);
					//system.legacy_addSystemShips("trader", 4, 0.985);
					system.addShips("trader", 4, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.985), 10000);
					//system.legacy_addSystemShips("police", 3, 0.985);
					system.addShips("police", 3, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.985), 10000);
					this.currentSystem = "Galaxy3";
					this.startThargoidsRemainingTimer();
					missionVariables.offering = "CATACLYSM";
					missionVariables.cataclysm_missions = "STATION_ATTACK";
				}
				else if (missionVariables.cataclysm_trigger > 55 && missionVariables.cataclysm_trigger < 71) {
					this.runMissionScreen("cataclysm_evacuation_brief");
					player.ship.removeAllCargo();
					missionVariables.cataclysm_sourceplanet = expandDescription("%I");
					player.ship.useSpecialCargo(expandDescription("[cataclysm_refugees]"));
					mission.setInstructionsKey("cataclysm_evacuation");
					missionVariables.cataclysm_sourceplanet_nr = system.ID;
					missionVariables.cataclysm_missions = "EVACUATION";
				}
			}
			else if (missionVariables.cataclysm_missions == "DEFECTOR_KILLED" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_defector_debrief");
				this.$addPadLogEntry(expandDescription("[cataclysm_killed_defector]"));
				player.credits += 1250;
				mission.setInstructionsKey("cataclysm_meet_Agent_Blake");
				missionVariables.cataclysm_missions = "DONE";
			}
			else if (missionVariables.cataclysm_missions == "DEFECTOR_ESCAPED" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_defector_escaped");
				this.$addPadLogEntry(expandDescription("[cataclysm_defector_escaped]"));
				mission.setInstructionsKey("cataclysm_meet_Agent_Blake");
				missionVariables.cataclysm_missions = "DONE";
			}
			else if (missionVariables.cataclysm_missions == "AMBASSADOR_SUCCESS" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_ambassador_success");
				this.$addPadCharacter("ambassador", expandDescription("%N") + " " + missionVariables.cataclysm_ambassador_name);
				this.$addPadLogEntry(expandDescription("[cataclysm_rescued_ambassador]"));
				player.credits += 1000;
				if (worldScripts.GalCopBB_Reputation) {
					var rep = worldScripts.GalCopBB_Reputation;
					rep.$adjustReputationForEntity(expandDescription("[gcm_reputation_galcop]"), system.ID, "Success", 1, 1);
					rep.$adjustReputationForEntity(expandDescription("[gcm_reputation_localgov]"), system.ID, "Success", 1, 1);
					rep.$adjustReputationForEntity(expandDescription("[gcm_reputation_navy]"), system.ID, "Success", 1, 1);
				}
				mission.setInstructionsKey("cataclysm_meet_Agent_Blake");
				delete missionVariables.cataclysm_ambassador_name;
				missionVariables.cataclysm_missions = "DONE";
			}
			else if (missionVariables.cataclysm_missions == "AMBASSADOR_FAILURE" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_ambassador_failure");
				this.$addPadCharacter("ambassador", expandDescription("%N") + " " + missionVariables.cataclysm_ambassador_name, null, null, expandDescription("[cataclysm_died_report]", { time: clock.clockStringForTime(clock.adjustedSeconds) }));
				this.$addPadLogEntry(expandDescription("[cataclysm_ambassador_failed]"));
				mission.setInstructionsKey("cataclysm_meet_Agent_Blake");
				delete missionVariables.cataclysm_ambassador_name;
				missionVariables.cataclysm_missions = "DONE";
			}
			else if (missionVariables.cataclysm_missions == "AMBASSADOR_FAILURE2" && !missionVariables.offering) {
				this.$addPadLogEntry(expandDescription("[cataclysm_ambassador_piloterror]"));
				this.$addPadCharacter("ambassador", expandDescription("%N") + " " + missionVariables.cataclysm_ambassador_name, null, null, expandDescription("[cataclysm_died_report]", { time: clock.clockStringForTime(clock.adjustedSeconds) }));
				this.runMissionScreen("cataclysm_ambassador_failure2");
				mission.setInstructionsKey("cataclysm_meet_Agent_Blake");
				delete missionVariables.cataclysm_ambassador_name;
				missionVariables.cataclysm_missions = "DONE";
			}
			else if (missionVariables.cataclysm_missions == "STATION_ATTACK" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_LAUNCH") {
				this.choice = null;
				player.ship.launch();
				delete missionVariables.offering;
				missionVariables.cataclysm_missions = "DEFEND_STATION";
			}
			else if (missionVariables.cataclysm_missions == "DEFEND_STATION" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_station_attack_continues", null, "cataclysm_launch", null, "siren.ogg");
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm_missions = "STATION_ATTACK";
			}
			else if (missionVariables.cataclysm_missions == "STATION_DEFENDED" && !missionVariables.offering) {
				missionVariables.clockDays = clock.days;
				this.runMissionScreen("cataclysm_station_attack_thanks");
				this.$addPadLogEntry(expandDescription("[cataclysm_station_defended]"));

				if (worldScripts.GalCopBB_Reputation) {
					var rep = worldScripts.GalCopBB_Reputation;
					rep.$addAward({
						title: expandMissionText("cataclysm_award_medal_title"),
						entity: expandDescription("[gcm_reputation_galcop]"),
						worldScript: this.name,
						description: expandMissionText("cataclysm_award_medal_info"),
						source: system.name,
						galaxy: galaxyNumber,
						received: clock.adjustedSeconds,
						imageType: Math.floor(Math.random() * 6) + 5 // pick one of the badges or medals from the available options
					});
					rep.$adjustReputationForEntity(expandDescription("[gcm_reputation_galcop]"), system.ID, "Success", 2, 1);
					rep.$adjustReputationForEntity(expandDescription("[gcm_reputation_navy]"), system.ID, "Success", 2, 1);
				}

				delete missionVariables.clockDays;
				mission.setInstructionsKey("cataclysm_meet_Agent_Blake");
				missionVariables.cataclysm_missions = "DONE";
			}
			else if (missionVariables.cataclysm_missions == "EVACUATION" && system.ID != missionVariables.cataclysm_sourceplanet_nr && !missionVariables.offering) {
				this.$addPadLogEntry(expandDescription("[cataclysm_delivered_refugees]", { sys: System.systemNameForID(missionVariables.cataclysm_sourceplanet_nr) }));
				this.runMissionScreen("cataclysm_evacuation_debrief");
				mission.setInstructionsKey("cataclysm_meet_Agent_Blake");
				player.ship.removeAllCargo();
				player.credits += 1000;
				delete missionVariables.cataclysm_sourceplanet;
				delete missionVariables.cataclysm_sourceplanet_nr;
				missionVariables.cataclysm_missions = "DONE";
			}
			else if (missionVariables.cataclysm == "STAGE6" && system.ID == 36 && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_birera_brief", null, null, "cataclysm_disabled_warship_1");
				mission.unmarkSystem({ system: 36, name: this.name });
				delete missionVariables.cataclysm_trigger;
				mission.markSystem({ system: 86, name: this.name });
				mission.setInstructionsKey("cataclysm_goto_Enrece");
				missionVariables.cataclysm = "STAGE6a";
			}
			else if (missionVariables.cataclysm == "STAGE7a" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_post_enrece_brief_1", null, "cataclysm_wait", "cataclysm_disabled_warship_1");
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm = "STAGE7b";
			}
			else if (missionVariables.cataclysm == "STAGE7b" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_WAIT") {
				this.runMissionScreen("cataclysm_post_enrece_brief_2", null, null, "cataclysm_disabled_warship_1");
				this.$addPadLogEntry(expandDescription("[cataclysm_stopped_steal]"));
				player.credits += 5000;
				mission.setInstructionsKey("cataclysm_goto_Aquxein");
				this.choice = null;
				delete missionVariables.offering;
				missionVariables.cataclysm_hivemission = "WAITING";
				missionVariables.cataclysm = "STAGE8A";
			}
			else if (missionVariables.cataclysm == "STAGE7c" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_post_enrece_brief_3", null, null, "cataclysm_disabled_warship_1");
				this.$addPadLogEntry(expandDescription("[cataclysm_stopped_steal]"));
				player.credits += 5000;
				mission.setInstructionsKey("cataclysm_goto_Aquxein");
				this.choice = null;
				delete missionVariables.offering;
				missionVariables.cataclysm_hivemission = "WAITING";
				missionVariables.cataclysm = "STAGE8A";
			}
			else if (missionVariables.cataclysm == "DESTROYED" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_warship_destroyed_brief_1", null, null, "cataclysm_disabled_warship_1");
				this.$addPadLogEntry(expandDescription("[cataclysm_warship_failed]"));
				player.credits += 5000;
				mission.setInstructionsKey(null);
				missionVariables.cataclysm_delay_counter = 0;
				missionVariables.cataclysm = "DELAY";
			}
			else if (missionVariables.cataclysm == "E_RESCUED" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_engineer_rescued_brief", null, null, "[escape-capsule]");
				this.$addPadLogEntry(expandDescription("[cataclysm_warship_failed]"));
				this.$addPadLogEntry(expandDescription("[cataclysm_did_save_one]"));
				player.credits += 5000;
				mission.setInstructionsKey(null);
				missionVariables.cataclysm_engineer = "RESCUED";
				missionVariables.cataclysm_delay_counter = 6;
				missionVariables.cataclysm = "DELAY";
			}
		}
		else if (player.ship.dockedStation.name == "Enrece Research Station") {
			if (missionVariables.cataclysm == "STAGE6a" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_enrece_brief", null, null, "[thargoid]");
				mission.unmarkSystem({ system: 86, name: this.name });
				mission.setInstructionsKey("cataclysm_pursue_Thargoids");
				//system.legacy_addShips("thargoid", 5);
				system.addShips("thargoid", 5);
				//system.legacy_addShips("trader", 2);
				system.addShips("trader", 2);
				//system.legacy_addShips("cataclysm_disabled_warship_1", 1);
				system.addShips("cataclysm_disabled_warship_1", 1);
				missionVariables.cataclysm = "STAGE7";
			}
			else if (missionVariables.cataclysm == "DESTROYED" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_warship_destroyed_brief_2", null, null, "cataclysm_disabled_warship_1");
				this.$addPadLogEntry(expandDescription("[cataclysm_warship_failed]"));
				player.credits += 5000;
				mission.setInstructionsKey(null);
				missionVariables.cataclysm_delay_counter = 0;
				missionVariables.cataclysm = "DELAY";
			}
		}
	}
	else if (player.ship.dockedStation.isMainStation && missionVariables.cataclysm == "DELAY" &&
		system.ID != 216 && missionVariables.cataclysm_delay_counter > 18 && !missionVariables.offering) {
		this.runMissionScreen("cataclysm_delay_end_brief_1", null, null, "[thargoid]");
		if (missionVariables.cataclysm_engineer == "RESCUED") {
			mission.addMessageTextKey("cataclysm_delay_end_brief_2");
			missionVariables.cataclysm_engineer = "YES";
		}
		if (galaxyNumber == 4)
			missionVariables.cataclysm_aquxein_string = expandDescription("[cataclysm_report_aquxein1]");
		else
			missionVariables.cataclysm_aquxein_string = expandDescription("[cataclysm_report_aquxein2]");
		if (galaxyNumber < 4) {
			missionVariables.cataclysm_galdrive_string = expandDescription("[cataclysm_report_galdrive1]");
			player.credits += 5000;
		}
		else if (galaxyNumber > 4) {
			missionVariables.cataclysm_galdrive_string = expandDescription("[cataclysm_report_galdrive2]");
			player.credits += 20000;
		}
		mission.addMessageTextKey("cataclysm_delay_end_brief_3");
		delete missionVariables.cataclysm_delay_counter;
		delete missionVariables.cataclysm_aquxein_string;
		delete missionVariables.cataclysm_galdrive_string;
		mission.setInstructionsKey("cataclysm_goto_Aquxein");
		missionVariables.cataclysm_hivemission = "WAITING";
		missionVariables.cataclysm = "STAGE8B";
	}
	else if (galaxyNumber == 4) {
		if (player.ship.dockedStation.isMainStation) {
			if ((missionVariables.cataclysm == "STAGE8A" || missionVariables.cataclysm == "STAGE8B") &&
				missionVariables.cataclysm_hivemission == "WAITING" && this.systemList["4"].indexOf(system.ID) >= 0 &&
				!missionVariables.offering) {
				missionVariables.cataclysm_species = expandDescription("[cataclysm_species]");
				this.runMissionScreen("cataclysm_hive_brief_1", "cataclysm_blurry_scan.png", "cataclysm_continue");
				this.$addPadCharacter("urquhart", expandDescription("%N") + " " + expandDescription("[cataclysm_urquhart_name]"), null, missionVariables.cataclysm_species);
				delete missionVariables.cataclysm_species;
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm_hivemission = "WAITING1";
			}
			else if (missionVariables.cataclysm_hivemission == "WAITING1" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runMissionScreen("cataclysm_hive_brief_2");
				mission.setInstructionsKey("cataclysm_scan_unknown_structure");
				mission.unmarkSystem({ system: 216, name: this.name });
				mission.markSystem({ system: 51, name: this.name }, { system: 73, name: this.name });
				this.choice = null;
				delete missionVariables.offering;
				missionVariables.cataclysm_hivemission = "INVESTIGATE";
			}
			else if (missionVariables.cataclysm_hivemission == "SCANNED" && system.ID == 73 && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_hive_brief_3", null, null, "cataclysm_thargoid_hive_1");
				this.$addPadLogEntry(expandDescription("[cataclysm_scanned_hive]"));
				mission.setInstructionsKey("cataclysm_wait_a_minute");
				missionVariables.cataclysm_hivemission = "WAIT_A_MINUTE";
			}
			else if (missionVariables.cataclysm_hivemission == "WAIT_ENDED" && system.ID == 73 && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_hive_brief_4", null, "cataclysm_continue", "cataclysm_thargoid_hive_1");
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm_hivemission = "WAITING2";
			}
			else if (missionVariables.cataclysm_hivemission == "WAITING2" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runMissionScreen("cataclysm_hive_brief_5", null, null, "cataclysm_thargoid_hive_core");
				mission.setInstructionsKey("cataclysm_destroy_hive");
				this.choice = null;
				delete missionVariables.offering;
				missionVariables.cataclysm_hivemission = "DESTROY_HIVE";
			}
			else if (missionVariables.cataclysm_hivemission == "HIVE_DESTROYED" && (missionVariables.cataclysm == "STAGE8A" || missionVariables.cataclysm == "STAGE8B") && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_hive_debrief", null, null, "cataclysm_thargoid_hive_1");
				this.$addPadLogEntry(expandDescription("[cataclysm_destroyed_hive]"));
				mission.setInstructionsKey("cataclysm_goto_Aquxein");
				mission.unmarkSystem({ system: 51, name: this.name }, { system: 73, name: this.name });
				mission.markSystem({ system: 216, name: this.name });
				player.credits += 25000;
				missionVariables.cataclysm_hivemission = "COMPLETE";
			}
			else if (missionVariables.cataclysm == "STAGE8A" && missionVariables.cataclysm_hivemission == "COMPLETE" && system.ID == 216 && !missionVariables.offering) {
				this.runAltMissionScreen("cataclysm_aquxein_brief_A_1", { name: "cataclysm_chart6.png", height: 546 }, "cataclysm_continue", null, null, 5, 19);
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm = "STAGE8Aa";
			}
			else if (missionVariables.cataclysm == "STAGE8B" && missionVariables.cataclysm_hivemission == "COMPLETE" && system.ID == 216 && !missionVariables.offering) {
				this.runAltMissionScreen("cataclysm_aquxein_brief_B_1", { name: "cataclysm_chart6.png", height: 546 }, "cataclysm_continue", null, null, 5, 19);
				missionVariables.offering = "CATACLYSM";
				delete missionVariables.cataclysm_hivemission;
				missionVariables.cataclysm = "STAGE8Ba";
			}
			else if ((missionVariables.cataclysm == "STAGE8Aa" || missionVariables.cataclysm == "STAGE8Ba") && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runAltMissionScreen("cataclysm_aquxein_brief_2", { name: "cataclysm_chart5.png", height: 546 }, null, null, null, 5, 19);
				mission.setInstructionsKey("cataclysm_goto_Inbe");
				mission.unmarkSystem({ system: 216, name: this.name });
				mission.markSystem({ system: 129, name: this.name });
				this.choice = null;
				delete missionVariables.offering;
				if (missionVariables.cataclysm == "STAGE8Aa") missionVariables.cataclysm = "STAGE9A";
				else missionVariables.cataclysm = "STAGE9B";
			}
		}
	}
	else if (galaxyNumber == 5) {
		if (player.ship.dockedStation.isMainStation) {
			if (missionVariables.cataclysm == "STAGE9A" && system.ID == 55 && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_estebiin_brief_A", null, null, "cataclysm_disabled_warship_1");
				mission.setInstructionsKey("cataclysm_goto_Tetier");
				mission.markSystem({ system: 33, name: this.name });
				missionVariables.cataclysm = "STAGE9Aa";
			}
			else if (missionVariables.cataclysm == "STAGE9B" && system.ID == 55 && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_estebiin_brief_B", null, null, "cataclysm_disabled_warship_1");
				mission.setInstructionsKey("cataclysm_goto_Tetier");
				mission.markSystem({ system: 33, name: this.name });
				missionVariables.cataclysm = "STAGE9Ba";
			}
			else if (missionVariables.cataclysm == "STAGE11e" && system.ID == 55 && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_estebiin_brief_2");
				mission.unmarkSystem({ system: 55, name: this.name });
				mission.markSystem({ system: 33, name: this.name });
				player.ship.removeAllCargo();
				player.ship.useSpecialCargo(expandDescription("[cataclysm_tetier_supplies]"));
				missionVariables.cataclysm_replica = "AVAILABLE";
				missionVariables.cataclysm = "STAGE12";
			}
		}
		else if (player.ship.dockedStation.name == "Tetier Military Station") {
			if (missionVariables.cataclysm == "STAGE9Aa" && !missionVariables.offering) {
				missionVariables.cataclysm_species = expandDescription("[cataclysm_species]");
				this.runMissionScreen("cataclysm_tetier_brief_A_1", null, "cataclysm_continue");
				this.$addPadCharacter("arbuthnot", expandDescription("%N") + " " + expandDescription("[cataclysm_arbuthnot_name]"), null, missionVariables.cataclysm_species);
				delete missionVariables.cataclysm_species;
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm = "STAGE9Ab";
			}
			else if (missionVariables.cataclysm == "STAGE9Ab" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runMissionScreen("cataclysm_tetier_brief_A_2", null, "cataclysm_continue");
				this.choice = null;
				missionVariables.cataclysm = "STAGE9Ac";
			}
			else if (missionVariables.cataclysm == "STAGE9Ac" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				missionVariables.cataclysm_species = expandDescription("[cataclysm_species]");
				this.runMissionScreen("cataclysm_tetier_brief_A_3", null, "cataclysm_continue");
				this.$addPadCharacter("cunynghame", expandDescription("%N") + " " + expandDescription("[cataclysm_cunynghame_name]"), null, missionVariables.cataclysm_species);
				delete missionVariables.cataclysm_species;
				this.choice = null;
				missionVariables.cataclysm = "STAGE9d";
			}
			else if (missionVariables.cataclysm == "STAGE9Ba" && !missionVariables.offering) {
				missionVariables.cataclysm_species = expandDescription("[cataclysm_species]");
				this.runMissionScreen("cataclysm_tetier_brief_B_1", null, "cataclysm_continue");
				this.$addPadCharacter("arbuthnot", expandDescription("%N") + " " + expandDescription("[cataclysm_arbuthnot_name]"), null, missionVariables.cataclysm_species);
				delete missionVariables.cataclysm_species;
				missionVariables.offering = "CATACLYSM";
				if (missionVariables.cataclysm_engineer == "YES") {
					mission.addMessageTextKey("cataclysm_tetier_brief_B_1a");
					delete missionVariables.cataclysm_engineer;
				}
				else {
					mission.addMessageTextKey("cataclysm_tetier_brief_B_1b");
				}
				this.$addPadCharacter("farquharson", expandDescription("%N") + " " + expandDescription("[cataclysm_farquharson_name]"), null, expandDescription("[cataclysm_race_humanoid]"));
				missionVariables.cataclysm = "STAGE9Bb";
			}
			else if (missionVariables.cataclysm == "STAGE9Bb" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				missionVariables.cataclysm_species = expandDescription("[cataclysm_species]");
				this.runMissionScreen("cataclysm_tetier_brief_B_2", null, "cataclysm_continue");
				this.$addPadCharacter("cunynghame", expandDescription("%N") + " " + expandDescription("[cataclysm_cunynghame_name]"), null, missionVariables.cataclysm_species);
				delete missionVariables.cataclysm_species;
				this.choice = null;
				missionVariables.cataclysm = "STAGE9d";
			}
			else if (missionVariables.cataclysm == "STAGE9d" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runMissionScreen("cataclysm_tetier_brief_4", null, "cataclysm_continue");
				this.choice = null;
				missionVariables.cataclysm = "STAGE9e";
			}
			else if (missionVariables.cataclysm == "STAGE9e" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runMissionScreen("cataclysm_tetier_brief_5", "cataclysm_warship_blueprint.png", "cataclysm_continue")
				this.choice = null;
				missionVariables.cataclysm = "STAGE9f";
			}
			else if (missionVariables.cataclysm == "STAGE9f" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runMissionScreen("cataclysm_tetier_brief_6");
				mission.setInstructionsKey("cataclysm_test_replica");
				mission.unmarkSystem({ system: 33, name: this.name });
				this.choice = null;
				delete missionVariables.offering;
				missionVariables.cataclysm = "STAGE10";
			}
			else if (missionVariables.cataclysm == "STAGE10m" && !missionVariables.offering) {
				// repair any damaged equipment for the player
				this.$repairPlayerEquipment();
				this.runMissionScreen("cataclysm_tetier_brief_7", null, "cataclysm_continue");
				this.$addPadLogEntry(expandDescription("[cataclysm_helped_test_replica]"));
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm = "STAGE11";
			}
			else if (missionVariables.cataclysm == "STAGE11" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runMissionScreen("cataclysm_tetier_brief_8", null, "cataclysm_launch", null, "siren.ogg");
				this.choice = null;
				mission.setInstructionsKey("cataclysm_defend_tetier_station");
				//system.legacy_addShipsWithinRadius("thargoid", 20, "abs", [-460295, 1925320, 350817], 25000);
				system.addShips("thargoid", 20, Vector3D(-460295, 1925320, 350817), 25000);
				this.currentSystem = "Tetier";
				this.startThargoidsRemainingTimer();
				missionVariables.cataclysm = "STAGE11a";
			}
			else if (missionVariables.cataclysm == "STAGE11a" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_LAUNCH") {
				this.choice = null;
				player.ship.launch();
				delete missionVariables.offering;
				missionVariables.cataclysm = "STAGE11b";
				system.shipsWithPrimaryRole("cataclysm_tetier_station")[0].reactToAIMessage("LAUNCH_WARSHIP_REPLICA_2");
			}
			else if (missionVariables.cataclysm == "STAGE11c" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_tetier_debrief_1", { name: "cataclysm_tetier_station_view.png", height: 546 }, "cataclysm_continue");
				this.$addPadLogEntry(expandDescription("[cataclysm_defended_tetier]"));
				missionVariables.offering = "CATACLYSM";
				missionVariables.cataclysm = "STAGE11d";
			}
			else if (missionVariables.cataclysm == "STAGE11d" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runMissionScreen("cataclysm_tetier_debrief_2");
				mission.setInstructionsKey("cataclysm_goto_Estebiin_2");
				mission.markSystem({ system: 55, name: this.name });
				this.choice = null;
				delete missionVariables.offering;
				missionVariables.cataclysm = "STAGE11e";
			}
			else if (missionVariables.cataclysm == "STAGE12" && !missionVariables.offering) {
				this.runMissionScreen("cataclysm_reward_brief_1", { name: "cataclysm_navy_star.png", height: 546 }, "cataclysm_continue");
				this.$addPadLogEntry(expandDescription("[cataclysm_navy_reward]"));
				missionVariables.offering = "CATACLYSM";
				player.ship.removeAllCargo();
				mission.setInstructionsKey(null);
				mission.unmarkSystem({ system: 33, name: this.name });
				player.credits += 100000;
				missionVariables.cataclysm = "STAGE12a";
			}
			else if (missionVariables.cataclysm == "STAGE12a" && missionVariables.offering == "CATACLYSM" && this.choice == "cataclysm_CONT") {
				this.runMissionScreen("cataclysm_reward_brief_2", null, null, "cataclysm_warship_replica_1");
				this.choice = null;
				delete missionVariables.offering;
				missionVariables.cataclysm = "MISSION_COMPLETE";
			}
		}
	}
	else if (missionVariables.cataclysm == "MISSION_COMPLETE" && missionVariables.cataclysm_hivemission == "COMPLETE" && player.bounty == 0 && !missionVariables.offering) {
		var getHiveMission = Math.random();
		if (getHiveMission <= 0.532 || getHiveMission > 0.555) return;
		if (galaxyNumber == 2 && (system.ID == 133 || system.ID == 206)) return;
		if (galaxyNumber == 5 && this.systemList["5"].indexOf(system.ID)) return;
		if (galaxyNumber == 7 && system.ID == 162) return;
		this.hiveLocation = Math.floor(Math.random() * 6);
		if (galaxyNumber == 6 && this.systemList["6".indexOf(system.ID) >= 0]) this.hiveLocation = 6;
		missionVariables.cataclysm_hive_location = this.hiveLocation;
		missionVariables.cataclysm_hive_location_1 = system.systemNameForID(this.hiveLocations[galaxyNumber][this.hiveLocation * 2]);
		missionVariables.cataclysm_hive_location_2 = system.systemNameForID(this.hiveLocations[galaxyNumber][this.hiveLocation * 2 + 1]);
		this.runMissionScreen("cataclysm_another_hive_brief", null, null, "cataclysm_thargoid_hive_1");
		mission.setInstructionsKey("cataclysm_destroy_another_hive");
		mission.markSystem({ system: this.hiveLocations[galaxyNumber][this.hiveLocation * 2], name: this.name }, { system: this.hiveLocations[galaxyNumber][this.hiveLocation * 2 + 1], name: this.name });
		missionVariables.cataclysm_hivemission = "DESTROY_HIVE";
	}
	else if (missionVariables.cataclysm == "MISSION_COMPLETE" && missionVariables.cataclysm_hivemission == "HIVE_DESTROYED" && !missionVariables.offering) {
		this.runMissionScreen("cataclysm_another_hive_debrief", { name: "cataclysm_navy_star.png", height: 546 });
		this.$addPadLogEntry(expandDescription("[cataclysm_killed_another_hive]"));
		mission.setInstructionsKey(null);
		mission.unmarkSystem({ system: this.hiveLocations[galaxyNumber][missionVariables.cataclysm_hive_location * 2], name: this.name }, { system: this.hiveLocations[galaxyNumber][missionVariables.cataclysm_hive_location * 2 + 1], name: this.name });
		player.credits += 5000;
		delete missionVariables.cataclysm_hive_location;
		delete missionVariables.cataclysm_hive_location_1;
		delete missionVariables.cataclysm_hive_location_2;
		missionVariables.cataclysm_hivemission = "COMPLETE";
	}
}

//-------------------------------------------------------------------------------------------------------------
this.thargoidsKillThePlayer = function () {
	player.ship.fuelLeakRate = 10;
	system.shipsWithPrimaryRole("cataclysm_defector")[0].remove();
	//system.legacy_addShipsWithinRadius("cataclysm_defector_thargoid", 1, "abs", player.ship.position, 15000);
	system.addShips("cataclysm_defector_thargoid", 1, player.ship.position, 15000);
	//system.legacy_addShipsWithinRadius("thargoid", 15, "abs", player.ship.position, 10000);
	system.addShips("thargoid", 15, player.ship.position, 10000);
	system.shipsWithPrimaryRole("thargoid", player.ship, 15000).forEach(
		function (ship) {
			ship.target = player.ship;
			ship.reactToAIMessage("ATTACKED");
		}
	)
}

/* event handlers */

//-------------------------------------------------------------------------------------------------------------
this.startUp = function () {
	this.illicitEquipment = 0;
	this.blockSystemRedux();

	// check for hathor - it can spawn in the same place as the ribilebi research station
	if (worldScripts["Hathor-Nephthys-populator.js"]) {
		var hth = worldScripts["Hathor-Nephthys-populator.js"];
		hth.$hold_systemWillPopulate = hth.systemWillPopulate;
		delete hth.systemWillPopulate;
	}
}

//-------------------------------------------------------------------------------------------------------------
this.startUpComplete = function () {
	// add new penalty type to the bounty system
	if (worldScripts.BountySystem_Core) {
		var b = worldScripts.BountySystem_Core;
		b._offenceTypes["war crimes"] = expandDescription("[cataclysm_war_crimes]");
	}
	// tell ShipConfig not to apply rules to the replica ships
	if (worldScripts.ShipConfiguration_NPCShips) {
		var npc = worldScripts.ShipConfiguration_NPCShips;
		npc._excludeRoles.push("cataclysm_warship_replica_1");
		npc._excludeRoles.push("cataclysm_warship_replica_2");
	}
	this.dealWithIllicitEquipment2();

	var pad = worldScripts.Lib_PAD;
	if (!pad) return;
	pad.$config.defOrgs[21] = "lib_pad_org_navy.png";

	if (missionVariables.cataclysm_padchars) {
		this._padInfo = JSON.parse(missionVariables.cataclysm_padchars);
		var people = Object.keys(this._padInfo);
		for (var i = 0; i < people.length; i++) {
			var obj = this._padInfo[people[i]];
			if (people[i] == "carruthers") {
				this.$updateCurruthers();
			} else {
				this.$addPadCharacter(people[i], obj.name, obj.origin, obj.species, obj.info);
			}
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.systemWillPopulate = function () {
	this.dealWithIllicitEquipment1();
	var popRef = 0;

	if (worldScripts["Hathor-Nephthys-populator.js"]) {
		if ((galaxyNumber == 0 && system.ID == 164) || (galaxyNumber == 2 && system.ID == 86) || (galaxyNumber == 5 && system.ID == 33)) {
			// skip the hathor populator, so do nothing
			// logic is easier to understand this way
		} else {
			// if we disabled it, run the hathor populator now, but only if we're not in one of the above systems
			worldScripts["Hathor-Nephthys-populator.js"].$hold_systemWillPopulate();
		}
	}

	if (galaxyNumber == 0) {
		if (system.ID == 164) {
			popRef++;
			var stnPos = Vector3D(-93000, 53000, -79000).fromCoordinateSystem("pwm");
			system.setPopulator("cataclysm_" + popRef.toString(), {
				callback: function (pos) {

					//system.legacy_addShipsAtPrecisely("cataclysm_ribilebi_station", 1, "pwm", [-93000, 53000, -79000]);
					var station = system.addShips("cataclysm_ribilebi_station", 1, pos, 0)[0];
					//var station = system.shipsWithPrimaryRole("cataclysm_ribilebi_station")[0];
					worldScripts.Cataclysm.turnStationToPlanet(station);
					var hideBeaconStages = ["STAGE3c", "STAGE3b", "STAGE3a", "STAGE3", "STAGE2", "STAGE2a", "STAGE1a", "STAGE1b", "STAGE1c", "STAGE1d"];
					if (hideBeaconStages.indexOf(missionVariables.cataclysm) >= 0) {
						station.beaconCode = null;
						station.beaconLabel = null;
					}
				},
				location: "COORDINATES",
				coordinates: stnPos,
				deterministic: true
			});
		} else {
			if (missionVariables.cataclysm == "STAGE3") {
				popRef++;
				system.setPopulator("cataclysm_" + popRef.toString(), {
					callback: function (pos) {
						if (Math.random() < 0.5) {
							//system.legacy_addShips("thargoid", 2);
							system.addShips("thargoid", 2);
							if (Math.random() < 0.6) {
								//system.legacy_addShips("thargoid", 1);
								system.addShips("thargoid", 1);
								if (Math.random() < 0.75) {
									//system.legacy_addShips("thargoid", 1);
									system.addShips("thargoid", 1);
								}
							}
						}
						if (Math.random() < 0.4) {
							//system.legacy_addSystemShips("thargoid", 2, 0.3);
							system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.3));
						}
						if (Math.random() < 0.3) {
							//system.legacy_addSystemShips("thargoid", 2, 0.7);
							system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.7));
						}
					},
					location: "WITCHPOINT",
				});
			}
		}
	} else if (missionVariables.cataclysm == "STAGE5") {
		popRef++;
		system.setPopulator("cataclysm_" + popRef.toString(), {
			callback: function (pos) {
				if (Math.random() < 0.4) {
					//system.legacy_addShips("thargoid", 2);
					system.addShips("thargoid", 2);
					if (Math.random() < 0.5) {
						//system.legacy_addShips("thargoid", 1);
						system.addShips("thargoid", 1);
						if (Math.random() < 0.6) {
							//system.legacy_addShips("thargoid", 1);
							system.addShips("thargoid", 1);
						}
					}
				}
				if (Math.random() < 0.4) {
					//system.legacy_addSystemShips("thargoid", 2, 0.3);
					system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.3));
				}
				if (Math.random() < 0.3) {
					//system.legacy_addSystemShips("thargoid", 2, 0.7);
					system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.7));
				}
			},
			location: "WITCHPOINT",
		});

	} else if (galaxyNumber == 2) {
		// create the station regardless of the missionVariables
		if (system.ID == 86) {
			system.addMoon("cataclysm_enrece_moon");
			var stnPos = Vector3D(-99221.3, -20562.3, 468026);

			popRef++;
			system.setPopulator("cataclysm_" + popRef.toString(), {
				callback: function (pos) {
					if (system.countShipsWithPrimaryRole("cataclysm_enrece_station") == 0) {
						//system.legacy_addShipsAtPrecisely("cataclysm_enrece_station", 1, "abs", [-99221.3, -20562.3, 453026]);
						var station = system.addShips("cataclysm_enrece_station", 1, pos, 0)[0];
						//var station = system.shipsWithPrimaryRole("cataclysm_enrece_station")[0];
						worldScripts.Cataclysm.turnStationToPlanet(station);
						//system.legacy_addShipsWithinRadius("cataclysm_wreckage", 30, "abs", station.position, 12000);
						system.addShips("cataclysm_wreckage", 30, pos, 12000);
						//system.legacy_addShipsWithinRadius("cataclysm_viper_wreck", 4, "abs", station.position, 5000);
						var wrecks = system.addShips("cataclysm_viper_wreck", 4, pos, 5000);
						for (var i = 0; i < wrecks.length; i++) {
							worldScripts.Cataclysm.$makeShipDerelict(wrecks[i]);
							wrecks.orientation = Vector3D.random();
						}
					}
				},
				location: "COORDINATES",
				coordinates: stnPos,
				deterministic: true
			});
		}
		if (missionVariables.cataclysm == "STAGE6") {
			missionVariables.cataclysm_trigger = Math.floor(Math.random() * 100);
			if (missionVariables.cataclysm_missions == "DONE")
				delete missionVariables.cataclysm_missions;

			popRef++;
			system.setPopulator("cataclysm_" + popRef.toString(), {
				callback: function (pos) {

					if (missionVariables.cataclysm_missions == "EVACUATION") {
						//system.legacy_addSystemShips("thargoid", 2, 0);
						system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0));
						//system.legacy_addSystemShips("thargoid", 2, 0.5);
						system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.5));
					}
					if (Math.random() < 0.4) {
						//system.legacy_addShips("thargoid", 2);
						system.addShips("thargoid", 2);
						if (Math.random() < 0.5) {
							//system.legacy_addShips("thargoid", 1);
							system.addShips("thargoid", 1);
						}
					}
					if (Math.random() < 0.35) {
						//system.legacy_addSystemShips("thargoid", 2, 0.3);
						system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.3));
					}
					if (Math.random() < 0.25) {
						//system.legacy_addSystemShips("thargoid", 2, 0.7);
						system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.7));
					}
				},
				location: "WITCHPOINT",
			});

			//} else if (missionVariables.cataclysm == "STAGE6a") {

		} else if (missionVariables.cataclysm == "STAGE7" && system.countShipsWithPrimaryRole("cataclysm_disabled_warship_2") == 0) {
			popRef++;
			system.setPopulator("cataclysm_" + popRef.toString(), {
				callback: function (pos) {

					if (Math.random() < 0.8) {
						//system.legacy_addShips("thargoid", 2);
						system.addShips("thargoid", 2);
						if (Math.random() < 0.6) {
							//system.legacy_addShips("thargoid", 1);
							system.addShips("thargoid", 1);
							if (Math.random() < 0.4) {
								//system.legacy_addShips("thargoid", 1);
								system.addShips("thargoid", 1);
							}
						}
					}
					if (Math.random() < 0.75) {
						//system.legacy_addSystemShips("thargoid", 2, 0.3);
						system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.3));
					}
					if (Math.random() < 0.5) {
						//system.legacy_addSystemShips("thargoid", 2, 0.7);
						system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.7));
					}
				},
				location: "WITCHPOINT",
			});
		}

	} else if (missionVariables.cataclysm == "STAGE8A" || missionVariables.cataclysm == "STAGE8B") {
		popRef++;
		system.setPopulator("cataclysm_" + popRef.toString(), {
			callback: function (pos) {
				if (Math.random() < 0.4) {
					//system.legacy_addShips("thargoid", 2);
					system.addShips("thargoid", 2);
					if (Math.random() < 0.5) {
						//system.legacy_addShips("thargoid", 1);
						system.addShips("thargoid", 1);
						if (Math.random() < 0.6) {
							//system.legacy_addShips("thargoid", 1);
							system.addShips("thargoid", 1);
						}
					}
				}
				if (Math.random() < 0.3) {
					//system.legacy_addSystemShips("thargoid", 2, 0.3);
					system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.3));
				}
				if (Math.random() < 0.25) {
					//system.legacy_addSystemShips("thargoid", 2, 0.7);
					system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.7));
				}
			},
			location: "WITCHPOINT",
		});

	} else if (galaxyNumber == 5) {
		if (system.ID == 33) {
			system.addMoon("cataclysm_tetier_moon");
			var stnPos = Vector3D(-460295, 1925320, 350817);
			popRef++;
			system.setPopulator("cataclysm_" + popRef.toString(), {
				callback: function (pos) {

					//system.legacy_addShipsAtPrecisely("cataclysm_tetier_station", 1, "abs", [-460295, 1925320, 350817]);
					var station = system.addShips("cataclysm_tetier_station", 1, pos, 0)[0];
					//var station = system.shipsWithPrimaryRole("cataclysm_tetier_station")[0];
					worldScripts.Cataclysm.turnStationToPlanet(station);

					//system.legacy_addShipsWithinRadius("asteroid", 12, "abs", [-464763, 1919432, 350817], 10000);
					system.addShips("asteroid", 12, Vector3D(-464763, 1919432, 350817), 10000);
					//system.legacy_addShipsWithinRadius("asteroid", 12, "abs", [-461784, 1923357, 341125], 10000);
					system.addShips("asteroid", 12, Vector3D(-461784, 1923357, 341125), 10000);
					//system.legacy_addShipsWithinRadius("asteroid", 12, "abs", [-458806, 1927283, 360509], 10000);
					system.addShips("asteroid", 12, Vector3D(-458806, 1927283, 360509), 10000);
					//system.legacy_addShipsWithinRadius("asteroid", 12, "abs", [-455827, 1931208, 379892], 10000);
					system.addShips("asteroid", 12, Vector3D(-455827, 1931208, 379892), 10000);
					//system.legacy_addShipsAtPrecisely("asteroid", 1, "abs", [-463561, 1917933, 342665]);
					system.addShips("asteroid", 1, Vector3D(-463561, 1917933, 342665));
					//system.legacy_addShipsAtPrecisely("asteroid", 1, "abs", [-461556, 1933831, 358793]);
					system.addShips("asteroid", 1, Vector3D(-461556, 1933831, 358793));
				},
				location: "COORDINATES",
				coordinates: stnPos,
				deterministic: true
			});
		}
		if ((missionVariables.cataclysm == "STAGE9A" || missionVariables.cataclysm == "STAGE9B") && system.ID == 55) {
			mission.setInstructionsKey("cataclysm_goto_Estebiin");

			popRef++;
			system.setPopulator("cataclysm_" + popRef.toString(), {
				callback: function (pos) {
					//system.legacy_addSystemShips("thargoid", 2, 0);
					system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.0));
					//system.legacy_addSystemShips("thargoid", 1, 0.65);
					system.addShips("thargoid", 1, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.65));
				},
				location: "WITCHPOINT",
			});

		} else if (missionVariables.cataclysm == "STAGE9Ba" || missionVariables.cataclysm_replica || missionVariables.cataclysm == "STAGE9Aa") {
			popRef++;
			system.setPopulator("cataclysm_" + popRef.toString(), {
				callback: function (pos) {
					if (missionVariables.cataclysm == "STAGE9Aa") {
						//system.legacy_addShipsAtPrecisely("cataclysm_disabled_warship_3", 1, "abs", [-459741, 1923775, 351249]);
						system.addShips("cataclysm_disabled_warship_3", 1, Vector3D(-459741, 1923775, 351249));
					}
					//system.legacy_addShipsWithinRadius("cataclysm_military", 8, "abs", [-460295, 1925320, 350817], 30000);
					system.addShips("cataclysm_military", 8, Vector3D(-460295, 1925320, 350817), 30000);
				},
				location: "COORDINATES",
				coordinates: stnPos,
			});
		}
	}
	if (missionVariables.cataclysm == "DELAY") {
		missionVariables.cataclysm_delay_counter++;
		popRef++;
		system.setPopulator("cataclysm_" + popRef.toString(), {
			callback: function (pos) {
				if (Math.random() >= 0.75) {
					//system.legacy_addShips("thargoid", 1);
					system.addShips("thargoid", 1);
					//system.legacy_addSystemShips("thargoid", 1, 0.65);
					system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.65));
				}
				if (Math.random() < 0.25) {
					//system.legacy_addShips("thargoid", 1);
					system.addShips("thargoid", 1);
					//system.legacy_addSystemShips("thargoid", 1, 0.35);
					system.addShips("thargoid", 2, Vector3D.interpolate(Vector3D(0, 0, 0), system.mainStation.position, 0.35));
				}
			},
			location: "WITCHPOINT",
		});
	}
}

//-------------------------------------------------------------------------------------------------------------
this.playerWillSaveGame = function () {
	missionVariables.cataclysm_padchars = JSON.stringify(this._padInfo);
}

//-------------------------------------------------------------------------------------------------------------
this.shipDockedWithStation = function () {
	this.dealWithIllicitEquipment2();
}

//-------------------------------------------------------------------------------------------------------------
this.missionScreenEnded = function () {
	if (!player.ship.docked) return;
	if (missionVariables.cataclysm_hivemission == "WAIT_A_MINUTE" && (!this.waitTimer || !this.waitTimer.isRunning))
		this.waitTimer = new Timer(this, this.stopWaiting, 45);
}

//-------------------------------------------------------------------------------------------------------------
this.missionScreenOpportunity = function () {
	if (missionVariables.cataclysm_hivemission != "WAIT_A_MINUTE") {
		this.missionScreens();
	}
}

//-------------------------------------------------------------------------------------------------------------
this.guiScreenChanged = function (to, from) {
	if (!player.ship.docked) return;
	if (player.ship.hasEquipmentProviding("EQ_CATACLYSM_ALL_INCLUSIVE"))
		player.ship.removeEquipment("EQ_CATACLYSM_ALL_INCLUSIVE");
}

//-------------------------------------------------------------------------------------------------------------
this.shipLaunchedFromStation = function () {
	this.dealWithIllicitEquipment1();
	if (missionVariables.cataclysm == "STAGE10") {
		var p = player.ship;
		if (p.script.shipEnergyIsLow) p.script.$hold_sshipTakingDamage = p.script.shipTakingDamage;
		player.ship.script.shipTakingDamage = this.$player_shipTakingDamage;
		system.shipsWithPrimaryRole("cataclysm_tetier_station")[0].reactToAIMessage("LAUNCH_WARSHIP_REPLICA_1");
		missionVariables.cataclysm == "STAGE10a";
		//system.legacy_addShipsAtPrecisely("cataclysm_target_asteroid_1", 1, "abs", [-467902, 1998274, 365325]);
		system.addShips("cataclysm_target_asteroid_1", 1, Vector3D(-467902, 1998274, 365325), 0);
		//system.legacy_addShipsAtPrecisely("cataclysm_target_asteroid_2", 1, "abs", [-476866, 1995981, 365150]);
		system.addShips("cataclysm_target_asteroid_2", 1, Vector3D(-476866, 1995981, 365150), 0);
		//system.legacy_addShipsAtPrecisely("cataclysm_target_asteroid_3", 1, "abs", [-477147, 1996492, 359577]);
		system.addShips("cataclysm_target_asteroid_3", 1, Vector3D(-477147, 1996492, 359577), 0);
		//system.legacy_addShipsAtPrecisely("cataclysm_target_asteroid_4", 1, "abs", [-472985, 2000370, 358859]);
		system.addShips("cataclysm_target_asteroid_4", 1, Vector3D(-472985, 2000370, 358859), 0);

		// we need to turn off ShipRepurchase, because if the replica kills the player in the combat test, we want it to reload the game
		// not send the player to the main station for a repurchase
		if (worldScripts.ShipRepurchase) {
			var sr = worldScripts.ShipRepurchase;
			sr.$hide_shipTakingDamage = sr.shipTakingDamage;
			delete sr.shipTakingDamage;
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.shipWillEnterWitchspace = function (cause) {
	if (cause == "galactic jump") {
		this.checkForGalDriveMod();
	}
	if (cause == "wormhole" && missionVariables.cataclysm_missions == "DEFECTOR_ESCAPED") {
		this.followingDefector = true;
	}
	if (missionVariables.cataclysm == "MISSION_COMPLETE" && missionVariables.cataclysm_replica) {
		delete missionVariables.cataclysm_replica;
	}
}

//-------------------------------------------------------------------------------------------------------------
this.shipWillExitWitchspace = function () {
	if (this.followingDefector) this.thargoidsKillThePlayer();
	if (system.isInterstellarSpace) return;
	this.advanceJumpCounters();
}

//-------------------------------------------------------------------------------------------------------------
this.shipExitedWitchspace = function () {
	if (system.isInterstellarSpace && missionVariables.cataclysm_hivemission == "DESTROY_HIVE")
		this.switchMilitaryAI();
}

//-------------------------------------------------------------------------------------------------------------
this.playerEnteredNewGalaxy = function (galaxyNumber) {
	this.resetGalHyperspaceBehaviour();
	if (galaxyNumber == 4 && missionVariables.cataclysm_hivemission == "WAITING")
		mission.markSystem({ system: 216, name: this.name });
}

//-------------------------------------------------------------------------------------------------------------
this.$player_shipTakingDamage = function (amount, whom, type) {
	if (this.ship.script.$hold_shipTakingDamage) this.ship.script.$hold_shipTakingDamage();
	if (missionVariables.cataclysm == "STAGE10k") {
		// if we get the player down to 40% energy - call it over
		if (this.ship.energy / this.ship.maxEnergy < 0.4) {
			var s = system.shipsWithRole("cataclysm_warship_replica_1");
			var w = null;
			if (s && s.length > 0) w = s[0];
			if (w) {
				w.script.stopCombat();
				delete this.ship.script.shipTakingDamage;
				if (this.ship.script.$hold_shipTakingDamage) {
					this.ship.script.shipTakingDamage = this.ship.script.$hold_shipTakingDamage;
					delete this.ship.script.$hold_shipTakingDamage;
				}
			}
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.runMissionScreen = function (textKey, background, choicesKey, modelKey, musicFile) {
	var opts = {};
	opts.messageKey = textKey;
	opts.screenID = "cataclysm_mission";
	if (background) opts.overlay = background;
	if (choicesKey) opts.choicesKey = choicesKey;
	if (modelKey) opts.model = modelKey;
	if (musicFile) opts.music = musicFile;

	mission.runScreen(opts, function (choice) { this.choice = choice; });
}

//-------------------------------------------------------------------------------------------------------------
this.runAltMissionScreen = function (textKey, background, choicesKey, modelKey, musicFile, toplines, width) {
	var opts = {};

	opts.message = this.$reformatText(textKey, toplines, width);
	opts.screenID = "cataclysm_mission";
	if (background) opts.overlay = background;
	if (choicesKey) opts.choicesKey = choicesKey;
	if (modelKey) opts.model = modelKey;
	if (musicFile) opts.music = musicFile;

	mission.runScreen(opts, function (choice) { this.choice = choice; });
}

//-------------------------------------------------------------------------------------------------------------
this.$bigSpacer = function (width) {
	var hairSpace = String.fromCharCode(31);
	var hairSpaceLength = defaultFont.measureString(hairSpace);
	var output = "";
	var counter = 0;
	do {
		output += hairSpace;
		counter += 1;
	} while (counter * hairSpaceLength < width);
	return output;
}

//-------------------------------------------------------------------------------------------------------------
this.$reformatText = function (textkey, toplines, bigspacewidth) {
	var output = [];
	var text = expandMissionText(textkey);
	var words = text.split(' ');
	var bigspace = this.$bigSpacer(bigspacewidth);
	var word = 0;
	do {
		var line = "";
		if (output.length >= toplines) line = bigspace;
		do {
			if (defaultFont.measureString(line + words[word]) > 31.9) break;
			if (words[word].search(/\n/) >= 0) {
				word += 1;
				break;
			}
			line += words[word] + " ";
			word += 1;
		} while (word <= words.length - 1);
		output.push(line.trimRight());
	} while (word <= words.length - 1);
	var final = "";
	for (var i = 0; i < output.length; i++) {
		final += (final == "" ? "" : "\n") + output[i];
	}
	return final;
}

//-------------------------------------------------------------------------------------------------------------
this.$repairPlayerEquipment = function () {
	var p = player.ship;
	var eq = p.equipment;
	var eqLen = eq.length;
	while (eqLen--) {
		var item = eq[eqLen].equipmentKey;
		if (p.equipmentStatus(item) == "EQUIPMENT_DAMAGED") p.setEquipmentStatus(eq[eqLen].equipmentKey, "EQUIPMENT_OK");
	}
	if (worldScripts["Battle Damage"] && missionVariables.BattleDamage_status != "OK") {
		missionVariables.BattleDamage_status = "OK";
		p.awardEquipment("EQ_HULL_REPAIR");
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$makeShipDerelict = function (shp) {
	shp.bounty = 0;
	// set script to default, to avoid a special script for the trader doing stuff. (like setting a new AI)
	shp.setScript("oolite-default-ship-script.js");
	shp.switchAI("oolite-nullAI.js");

	// remove any escorts that came with the ship
	if (shp.escorts) {
		for (var k = shp.escorts.length - 1; k >= 0; k--) shp.escorts[k].remove(true);
	}

	shp.script.shipLaunchedEscapePod = this.$cataclysm_derelict_shipLaunchedEscapePod; // function to remove the escapepod after launch.
	if (shp.equipmentStatus("EQ_ESCAPE_POD") === "EQUIPMENT_UNAVAILABLE") shp.awardEquipment("EQ_ESCAPE_POD");
	shp.abandonShip(); // make sure no pilot is left behind and this command turns the ship into cargo.
	shp.primaryRole = "cataclysm_derelict"; // to avoid pirate attacks
	shp.displayName = shp.displayName + " " + expandDescription("[cataclysm_derelict]");
	shp.lightsActive = false;
}

//-------------------------------------------------------------------------------------------------------------
this.$cataclysm_derelict_shipLaunchedEscapePod = function $himsn_derelict_shipLaunchedEscapePod(pod, passengers) {
	pod.remove(true); // we don't want floating escapepods around but need them initially to create the derelict.
}

//-------------------------------------------------------------------------------------------------------------
this.$addPadLogEntry = function (text) {
	var pad = worldScripts.Lib_PAD;
	if (!pad) return;
	pad._setPageEntry("LOGS.GENERIC.list", text);
}

//-------------------------------------------------------------------------------------------------------------
this.$updateCurruthers = function () {
	var pad = worldScripts.Lib_PAD;
	if (!pad) return;
	if (pad.$data.PERSONS["CAPTAIN CURRUTHERS"]) {
		delete pad.$data.PERSONS["CAPTAIN CURRUTHERS"];
		this.$addPadCharacter("curruthers");
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$addPadCharacter = function (person, name, origin, species, info) {
	var pad = worldScripts.Lib_PAD;
	if (!pad) return;
	var dta = {};
	var cat = [];

	switch (person) {
		case "curruthers":
			var str = expandDescription("[cataclysm_curruthers]").split("|");
			dta.name = str[0];
			dta.origin = str[1];
			dta.species = str[2];
			dta.gender = str[3];
			dta.age = str[4];
			dta.ship = str[5];
			dta.rank = str[6];
			dta.t0 = 21;
			dta.t1 = "lib_ovc_curruthers.png";
			dta.t2 = 11;
			cat.push("GALCOP.NAVY");
			break;
		case "ambassador":
			dta.name = name;
			dta.origin = (origin ? origin : system.name);
			dta.species = (species ? species : system.info.inhabitant);
			dta.gender = expandDescription("[cataclysm_gender_male]");
			dta.age = Math.floor(Math.random() * 30) + 40;
			dta.ship = expandDescription("[cataclysm_boa2]");
			dta.rank = expandDescription("[cataclysm_ambassador]");
			dta.t0 = Math.floor(Math.random() * 4) + 28;
			dta.info = [];
			if (info) dta.info.push(info);
			cat.push("GALCOP.GENERIC");
			break;
		case "urquhart":
			var str = expandDescription("[cataclysm_urquhart]").split("|");
			dta.name = name;
			dta.origin = str[0];
			dta.species = str[0];
			dta.gender = str[1];
			dta.age = Math.floor(Math.random() * 30) + 40;
			dta.ship = str[0];
			dta.rank = str[2];
			dta.t0 = 21;
			dta.t2 = 10;
			dta.info = [];
			if (info) dta.info.push(info);
			cat.push("GALCOP.NAVY");
			break;
		case "arbuthnot":
			var str = expandDescription("[cataclysm_arbuthnot]").split("|");
			dta.name = name;
			dta.origin = str[0];
			dta.species = (species ? species : system.info.inhabitant);
			dta.gender = str[1];
			dta.age = Math.floor(Math.random() * 30) + 40;
			dta.ship = str[0];
			dta.rank = str[2];
			dta.t0 = 21;
			dta.t2 = 12;
			dta.info = [];
			if (info) dta.info.push(info);
			cat.push("GALCOP.NAVY");
			break;
		case "cunynghame":
			var str = expandDescription("[cataclysm_cunynghame]").split("|");
			dta.name = name;
			dta.origin = str[0];
			dta.species = (species ? species : system.info.inhabitant);
			dta.gender = str[1];
			dta.age = Math.floor(Math.random() * 30) + 40;
			dta.ship = str[0];
			dta.rank = str[2];
			dta.t0 = 21;
			dta.t2 = 7;
			dta.info = [];
			if (info) dta.info.push(info);
			cat.push("GALCOP.NAVY");
			break;
		case "farquharson":
			var str = expandDescription("[cataclysm_farquharson]").split("|");
			dta.name = name;
			dta.origin = str[0];
			dta.species = (species ? species : system.info.inhabitant);
			dta.gender = str[1];
			dta.age = Math.floor(Math.random() * 30) + 40;
			dta.ship = str[0];
			dta.rank = str[2];
			dta.t0 = 21;
			dta.info = [];
			if (info) dta.info.push(info);
			cat.push("GALCOP.NAVY");
			break;
	}

	if (!this._padInfo) {
		this._padInfo = {};
	}
	var keys = Object.keys(this._padInfo)
	if (keys.indexOf(person) == -1) {
		this._padInfo[person] = { name: dta.name, origin: dta.origin, species: dta.species, age:dta.age, info: info };
	} else {
		// update the things that might have been randomised from a previous save game
		var upd = this._padInfo[person];
		dta.age = upd.age;
	}
	
	var id = "PERSONS." + dta.rank.toUpperCase() + " " + dta.name.split(" ")[1].toUpperCase();
	pad._addPageInCategory(id, dta, cat, false);
}