"use strict";
this.name = "GalCopBB_ShipInteractions";
this.author = "phkb";
this.copyright = "2017 phkb";
this.description = "Controls ship interactions for missions 33-36";
this.license = "CC BY-NC-SA 4.0";

/*
	TODO:
	- For 33, add more pirates on the return trip who demand you drop the recovered items
	- For 33, need some sort of cue that you've missed the ship when it jumped in

	*30 (ship-to-ship) - random trader along space lane or at witchpoint tells you to meet another ship (mission 30)
		- determine if this system will have one of these ships (only in safer systems 5,6,7)
		- pick one or two random ships in the system, and start monitoring range to player
		- if the range drops below 20000 then signal the player with the info about the contact mission
		- player won't have the option of declining the mission, but there will be no penalty for terminating it.
		
	*33 - intercept ship carrying stolen item,  (use Broadcast comms to demand data pack), which must then be scooped
		- player is told ship is heading to Y, a planet to which it is possible to travel two ways, one quicker, one slower. Player must get there first by taking the quicker route
		- once in system, player needs to wait at the witchpoint for the ship to arrive
		- spawn ship after a variable delay (3-5 mins?), give player the chance to request cache
		- if ship is destroyed, cache will be ejected in a cargopod (scripted)
		- ship may eject cargo if fighting starts
		- Player must scoop cargo pod and return it to X.
				
	34 - track ship from witchpoint to station, then return
			- player must wait at witchpoint and target all incoming vessels
			- one of these ships will be the target and a console message will display confirmation.
			- if player gets with 25 km of target and appears to be following them (eg heading is roughly the same and the player is behind them) they will detect player and flee (mission failed)
		- spawn ship at witchpoint
			- check if ship and player are within scanner range of wp beacon. if not, start monitoring player ship distance to target, 
			- if it drops below 24500 the mission is ended
		
	36 - Find ship in system X by sending a pass phrase to any/all ships - one of which will reply with a message with details of where to find special cargo to be returned to system Y
		- pick one or two random ships in the system to be the target 
		- add custom message to BCC
		- have a variety of negative responses
		- once the right ship is found, send details to player of special cargo location in sys Y

*/

this._type33ShipKey = "";
this._type33StolenType = "";
this._type33Ship = null;
this._type33Created = false;
this._type33MissionID = 0;
this._addGetawayShipTimer = null;
this._type30Ships = [];
this._type30ScanTimer = null;
this._type30MissionInfo = [];
this._type30MissionData = null;
this._type30CommsTimer = null;
this._type30Message = "";
this._type30MessageIndex = -1;
this._type30Ship = null;
this._type30RangeCounter = 0;
this._debug = true;
this._ignoreShipTypes = ["Hognose"];

//-------------------------------------------------------------------------------------------------------------
this.startUp = function () {
	var gcm = worldScripts.GalCopBB_Missions;
	// add these mission types into the main control
	gcm._availableMissionTypes.push(33);
	//gcm._availableMissionTypes.push(34);
	//gcm._availableMissionTypes.push(36);
}

//-------------------------------------------------------------------------------------------------------------
this.startUpComplete = function () {
	this._type33Created = missionVariables.GalCopBBMissions_Type33Created;
	if (missionVariables.GalCopBBMissions_type30MissionInfo) {
		this._type30MissionInfo = JSON.parse(missionVariables.GalCopBBMissions_Type30MissionInfo);
		delete missionVariables.GalCopBBMissions_Type30MissionInfo;
	}
	this.$setupTimers();
	this.$setupType30();
}

//-------------------------------------------------------------------------------------------------------------
this.playerWillSaveGame = function () {
	missionVariables.GalCopBBMissions_Type33Created = this._type33Created;
	if (this._type30MissionInfo.length > 0) missionVariables.GalCopBBMissions_Type30MissionInfo = JSON.stringify(this._type30MissionInfo);
}

//-------------------------------------------------------------------------------------------------------------
this.shipWillEnterWitchspace = function (cause, destination) {
	this._type30Ships.length = 0;
	this._type30MissionInfo.length = 0;
	if (this._type33Created === true) {
		var bb = worldScripts.BulletinBoardSystem;
		var item = bb.$getItem(this._type33MissionID);
		item.data.destroyedQuantity = 1;
		this._type33Created = false;
		this._type33Ship = null;
		this._type33StolenType = "";
		this._type33MissionID = 0;
	}
	this.$stopTimers();
}

//-------------------------------------------------------------------------------------------------------------
this.shipExitedWitchspace = function () {
	this.$setupTimers();
	this.$setupType30();
}

//-------------------------------------------------------------------------------------------------------------
this.shipDied = function (whom, why) {
	this.$stopTimers();
}

//-------------------------------------------------------------------------------------------------------------
this.$addNotifyMission = function $addNotifyMission(data) {
	this._type30MissionInfo.push(data);
	// start the scan timer, if it isn't already started, and we have some ships in our array
	if ((!this._type30ScanTimer || this._type30ScanTimer.isRunning === false) && this._type30Ships.length > 0)
		this._type30ScanTimer = new Timer(this, this.$type30Scanner, 2, 2);
}

//-------------------------------------------------------------------------------------------------------------
this.$setupTimers = function $setupTimers() {
	var gcm = worldScripts.GalCopBB_Missions;
	var list = gcm.$getListOfMissions(true, 33);
	for (var i = 0; i < list.length; i++) {
		if (list[i].destination === system.ID &&
			list[i].expiry > clock.adjustedSeconds &&
			list[i].data.destroyedQuantity === 0 &&
			list[i].data.quantity === 0) {
			this._type33ShipKey = list[i].data.targetShipKey;
			this._type33StolenType = list[i].data.stolenItemType;
			this._type33MissionID = list[i].ID;
			if (this._type33Created === true) {
				this.$addType33ShipToSystem();
			} else {
				this._addGetawayShipTimer = new Timer(this, this.$addType33ShipToSystem, parseInt((Math.random() * 120) + 180), 0);
			}
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$stopTimers = function $stopTimers() {
	if (this._addGetawayShipTimer && this._addGetawayShipTimer.isRunning) this._addGetawayShipTimer.stop();
	delete this._addGetawayShipTimer;
	this._type33Created = false;
	if (this._type30ScanTimer && this._type30ScanTimer.isRunning) this._type30ScanTimer.stop();
	delete this._type30ScanTimer;
	if (this._type30CommsTimer && this._type30CommsTimer.isRunning) this._type30CommsTimer.stop();
	delete this._type30CommsTimer;
}

//-------------------------------------------------------------------------------------------------------------
this.$setupType30 = function $setupType30() {
	function gcm_findtraders(entity) {
		return (entity.isShip && entity.primaryRole.indexOf("trader") >= 0 && entity.bounty === 0 && this._ignoreShipTypes.indexOf(entity.shipClassName) === -1);
	}
	// only in safer systems
	if (system.info.government >= 0) {
		// find some traders
		var plt = system.mainPlanet;
		var targets = system.filteredEntities(this, gcm_findtraders);
		if (targets.length > 0) {
			for (var i = 0; i < targets.length; i++) {
				var vect = targets[i].position.toCoordinateSystem("wpu");
				if (vect.z >= 0 && vect.z <= 1) {
					var a = targets[i].position;
					if (a && plt && a.magnitude() * Math.sin(a.angleTo(plt.position)) < 51200) {
						if (Math.random() > 0.7) {
							this._type30Ships.push(targets[i]);
							if (worldScripts.GalCopBB_Missions._debug) {
								targets[i].beaconCode = "E";
								targets[i].beaconLabel = expandDescription("[gcm_comms_target]");
							}
							if (this._type30Ships.length >= 2) break; // we only want a couple of ships set up for this
						}
					}
				}
			}
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$type30Scanner = function $type30Scanner() {
	if (this._type30MissionData != null) {
		this._type30ScanTimer.stop();
		this._type30ScanTimer = null;
		return;
	}
	// if we don't have any missions to communicate, stop the scanner now.
	if (this._type30MissionInfo.length === 0) {
		this._type30Ships.length = 0;
		this._type30ScanTimer.stop();
		this._type30ScanTimer = null;
		return;
	}
	// to cope with player ejecting
	if (!player.ship || !player.ship.position) return;
	for (var i = this._type30Ships.length - 1; i >= 0; i--) {
		if (this._type30Ships[i].isValid == false || this._type30Ships[i].isInSpace === false) {
			this._type30Ships.splice(i, 1);
			continue;
		}
		if (this._type30Ships[i].position.distanceTo(player.ship) < 23000 && this._type30Ships[i].alertCondition != 3 && player.alertHostiles === false) {
			// we have a winner
			// send transmission
			this._type30Ship = this._type30Ships[i];
			// select a random item from the list of available missions
			this._type30MissionData = this._type30MissionInfo[Math.floor(Math.random() * this._type30MissionInfo.length)];
			this._type30Message = expandDescription("[missionType" + this._type30MissionData.missionType + "_shipBriefing]", {
				destination: this._type30MissionData.destination,
				amount: formatCredits(this._type30MissionData.payment, false, true),
				name: this._type30MissionData.name
			});
			this._type30MessageIndex = 0;
			// start a timer for transmitting
			this._type30CommsTimer = new Timer(this, this.$transmitMessage, 5, 5);
			// clear array - once someone has sent a request, don't ask again
			this._type30Ships.length = 0;
			this._type30ScanTimer.stop();
			this._type30ScanTimer = null;

			break;
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$transmitMessage = function $transmitMessage(ship, msg) {
	if (this._type30Ship && this._type30Ship.isInSpace) {
		if (player.ship.position.distanceTo(this._type30Ship) < player.ship.scannerRange && this._type30Ship.alertCondition != 3) {
			// yay! comms is working!
			var items = this._type30Message.split("\n");
			this._type30Ship.commsMessage(items[this._type30MessageIndex], player.ship);
			// remove the greeting option from BCC
			if (this._type30MessageIndex === 0) {
				var bcc = worldScripts.BroadcastCommsMFD;
				bcc.$addShipToArray(this._type30Ship, bcc._greeted);
				bcc.$buildMessageList();
			}
			// increase the pointer for the next part of the message
			this._type30MessageIndex += 1;
			// have we got to the end?
			if (this._type30MessageIndex >= items.length) {
				this._type30CommsTimer.stop();
				this._type30CommsTimer = null;
				worldScripts.GalCopBB_Missions.$acceptMissionFromOther(this._type30MissionData);
				this._type30MissionData = null;
				this._type30Ship = null;
			}
		} else {
			this._type30RangeCounter += 1;
			if (this._type30RangeCounter >= 10) {
				this._type30CommsTimer.stop();
				this._type30CommsTimer = null;
				this._type30MissionData = null;
				this._type30Ship = null;
			}
		}
	} else {
		this._type30CommsTimer.stop();
		this._type30CommsTimer = null;
	}

}

//-------------------------------------------------------------------------------------------------------------
this.$addType33ShipToSystem = function $addType33ShipToSystem() {
	// if the player is more than 25k (scanner range) from the witchpoint, wait a bit more
	if (player.ship.position.distanceTo([0, 0, 0]) > player.ship.scannerRange) {
		this._addGetawayShipTimer = new Timer(this, this.$addType33ShipToSystem, parseInt((Math.random() * 30) + 30), 0);
		return;
	}
	var pop = worldScripts["oolite-populator"];
	// get the ship datakey from the mission data
	var checkShips = system.addShips("[" + this._type33ShipKey + "]", 1, player.ship.position, 20000);
	var shp = null;
	if (checkShips) shp = checkShips[0];
	if (shp) {
		shp.entityPersonality = Math.floor(system.scrambledPseudoRandomNumber(this._type33MissionID) * 32768);

		shp.primaryRole = "trader";
		shp.accuracy = 7;

		pop._setWeapons(shp, 4);
		pop._setMissiles(shp, 2);
		shp.heatInsulation = 2;
		shp.setBounty(parseInt(Math.random() * 20 + 20), "setup actions");
		shp.homeSystem = Math.floor(Math.random() * 256);

		// so the ship can't accidentally scoop the barrel it ejects
		shp.removeEquipment("EQ_FUEL_SCOOPS");

		shp.switchAI("oolite-traderAI.js");

		// attach some scripts to monitor what happens to ship
		if (shp.script.shipDied) shp.script.$gcm_hold_shipint_shipDied = shp.script.shipDied;
		shp.script.shipDied = this.$gcm_shipint_shipDied;

		if (shp.script.shipBeingAttacked) shp.script.$gcm_hold_shipint_shipBeingAttacked = shp.script.shipBeingAttacked;
		shp.script.shipBeingAttacked = this.$gcm_shipint_shipBeingAttacked;

		if (shp.script.shipBeingAttackedByCloaked) ship.script.$gcm_hold_shipint_shipBeingAttackedByCloaked = shp.script.shipBeingAttackedByCloaked;
		shp.script.shipBeingAttackedByCloaked = this.$gcm_shipint_shipBeingAttackedByCloaked;

		shp.script._missionID = this._type33MissionID;
		shp.script._stolenItemType = this._type33StolenType;
		shp.script._cargoSpawned = false;

		this._type33Ship = shp;
		this._type33Created = true;

		// add BCC message options
		var bcc = worldScripts.BroadcastCommsMFD;
		bcc.$createMessage({
			messageName: "gcm_address_thief",
			callbackFunction: this.$thiefResponse.bind(this),
			displayText: expandDescription("[gcm_demand_return]"),
			messageText: expandDescription("[gcm_address_thief]"),
			transmissionType: "target",
			ship: shp,
			deleteOnTransmit: true,
			delayCallback: 5
		});
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$gcm_shipint_shipDied = function $gcm_shipint_shipDied(whom, why) {
	if (this.ship.script.$gcm_hold_shipint_shipDied) this.ship.script.$gcm_hold_shipint_shipDied(whom, why);
	// make sure the cargo gets created even if the ship dies at someone elses hands
	worldScripts.GalCopBB_ShipInteractions.$createCargo(this.ship);
}

//-------------------------------------------------------------------------------------------------------------
this.$gcm_shipint_shipBeingAttacked = function $gcm_shipint_shipBeingAttacked(whom) {
	if (this.ship.script.$gcm_hold_shipint_shipBeingAttacked) this.ship.script.$gcm_hold_shipint_shipBeingAttacked(whom);
	if (whom.isPlayer === false) return;
	if (this.ship.isFleeing) worldScripts.GalCopBB_ShipInteractions.$createCargo(this.ship);
}

//-------------------------------------------------------------------------------------------------------------
this.$gcm_shipint_shipBeingAttackedByCloaked = function $gcm_shipint_shipBeingAttackedByCloaked() {
	if (this.ship.script.$gcm_hold_shipint_shipBeingAttackedByCloaked) this.ship.script.$gcm_hold_shipint_shipBeingAttackedByCloaked();
	if (this.ship.isFleeing) worldScripts.GalCopBB_ShipInteractions.$createCargo(this.ship);
}

//-------------------------------------------------------------------------------------------------------------
this.$createCargo = function $createCargo(ship) {
	// cargo was created, so we don't want any more ships created
	// if the player doesn't find the cargo now, mission is a bust
	worldScripts.GalCopBB_ShipInteractions._type33Created = false;
	var bb = worldScripts.BulletinBoardSystem;
	var item = bb.$getItem(ship.script._missionID);
	if (ship.script._cargoSpawned === false && item.data.targetQuantity === 1 && item.data.quantity === 0) {
		//var sw = ship.spawnOne("gcm_stolen_items");
		// we're doing it manually because if the ship is running and goes into a wormhole, the pod may follow. This way it stays behind.
		var checkShips = system.addShips("gcm_stolen_items", 1, ship.position.add(ship.vectorUp.multiply((ship.boundingBox.y + 15) * -1)), 0);
		var sw = null;
		if (checkShips) sw = checkShips[0];
		if (sw) {
			sw.setScript("oolite-default-ship-script.js");
			sw.script.shipWasScooped = worldScripts.GalCopBB_ShipInteractions.$gcm_stolenCargo_shipWasScooped;
			sw.script.shipDied = worldScripts.GalCopBB_ShipInteractions.$gcm_stolenCargo_shipDied;
			sw.script._missionID = ship.script._missionID;
			sw.script._stolenItemType = ship.script._stolenItemType;
			ship.script._cargoSpawned = true;
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$gcm_stolenCargo_shipWasScooped = function $gcm_stolenCargo_shipWasScooped(scooper) {
	var bb = worldScripts.BulletinBoardSystem;
	if (worldScripts.GalCopBB_ShipInteractions._debug) log(this.name, "cargo scooped!");
	if (!this.ship.script._missionID || this.ship.script._missionID === 0) return;
	// if someone other that the player scoops it - bad luck! mission can't be completed.
	if (scooper.isPlayer === false) {
		var item = bb.$getItem(this.ship.script._missionID);
		item.data.destroyedQuantity = 1;
		this._type33Created = false;
		return;
	}
	var eq = "";
	switch (this.ship.script._stolenItemType) {
		case expandDescription("[gcm_stolen_item_types_1]"):
			eq = "EQ_GCM_STOLEN_SCHEMATICS";
			break;
		case expandDescription("[gcm_stolen_item_types_2]"):
			eq = "EQ_GCM_STOLEN_CODES";
			break;
		case expandDescription("[gcm_stolen_item_types_3]"):
			eq = "EQ_GCM_STOLEN_DOCUMENTS";
			break;
		case expandDescription("[gcm_stolen_item_types_4]"):
			eq = "EQ_GCM_STOLEN_WEAPONDESIGNS";
			break;
	}
	var gcm = worldScripts.GalCopBB_Missions;
	player.ship.awardEquipment(eq);
	if (bb.$percentCompleted(this.ship.script._missionID) < 1) {
		var item = bb.$getItem(this.ship.script._missionID);
		bb.$updateBBMissionPercentage(this.ship.script._missionID, 1);
		item.data.quantity = 1;
		gcm.$logMissionData(item.ID);
		player.consoleMessage(expandDescription("[goal_updated]"));
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$gcm_stolenCargo_shipDied = function $gcm_stolenCargo_shipDied(whom, why) {
	if (worldScripts.GalCopBB_ShipInteractions._debug) log(this.name, "!!OUCH! Special cargo destroyed");
	var bb = worldScripts.BulletinBoardSystem;
	var item = bb.$getItem(this.ship.script._missionID);
	item.data.destroyedQuantity = 1;

}

//-------------------------------------------------------------------------------------------------------------
this.$thiefResponse = function $thiefResponse() {
	// turn off the normal greeting option
	var bcc = worldScripts.BroadcastCommsMFD;
	bcc.$addShipToArray(this._type33Ship, bcc._greeted);
	bcc.$buildMessageList();

	if (this._type33Ship.threatAssessment() < player.ship.threatAssessment()) {
		// response OK
		this._type33Ship.commsMessage(expandDescription("[gcm_thief_response_ok]"), player.ship);
		// then flee
		this._type33Ship.target = player.ship;
		this._type33Ship.performFlee();
		this.$createCargo(this._type33Ship);
		this._type33Ship = null;
	} else {
		// response No
		this._type33Ship.commsMessage(expandDescription("[gcm_thief_response_no]"), player.ship);
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$acceptedMission = function $acceptedMission(missID) {
	var bb = worldScripts.BulletinBoardSystem;
	var item = bb.$getItem(missID);
	var gcm = worldScripts.GalCopBB_Missions;

	if (this._debug) log(this.name, "accepted mission id = " + missID);

	if (!item) {
		log(this.name, "!!ERROR: BB returned null value from $getItem on mission ID " + missID);
		return;
	}
	gcm.$updateLastMissionDate(item.source, item.data.missionType);


}

//-------------------------------------------------------------------------------------------------------------
this.$completedMission = function $completedMission(missID) {
	var p = player.ship;
	var bb = worldScripts.BulletinBoardSystem;
	var item = bb.$getItem(missID);
	var gcm = worldScripts.GalCopBB_Missions;

	// update mission history
	gcm.$updateSuccessHistoryReputation(item);

	var sbm = worldScripts.Smugglers_BlackMarket;
	if (item.data.missionType === 33) {
		var eq = "";
		var typ = item.data.stolenItemType;
		switch (typ) {
			case expandDescription("[gcm_stolen_item_types_1]"):
				eq = "EQ_GCM_STOLEN_SCHEMATICS";
				break;
			case expandDescription("[gcm_stolen_item_types_2]"):
				eq = "EQ_GCM_STOLEN_CODES";
				break;
			case expandDescription("[gcm_stolen_item_types_3]"):
				eq = "EQ_GCM_STOLEN_DOCUMENTS";
				break;
			case expandDescription("[gcm_stolen_item_types_4]"):
				eq = "EQ_GCM_STOLEN_WEAPONDESIGNS";
				break;
		}
		p.removeEquipment(eq);
		if (sbm) sbm.$removeSaleItem(eq + ":" + missID);
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$confirmCompleted = function $confirmCompleted(missID) {
	var p = player.ship;
	var result = "";
	var bb = worldScripts.BulletinBoardSystem;
	var item = bb.$getItem(missID);
	if (item) {
		// *** type 33 - stolen items
		if (item.data.missionType === 33) {
			var eq = "";
			var typ = item.data.stolenItemType;
			switch (typ) {
				case expandDescription("[gcm_stolen_item_types_1]"):
					eq = "EQ_GCM_STOLEN_SCHEMATICS";
					break;
				case expandDescription("[gcm_stolen_item_types_2]"):
					eq = "EQ_GCM_STOLEN_CODES";
					break;
				case expandDescription("[gcm_stolen_item_types_3]"):
					eq = "EQ_GCM_STOLEN_DOCUMENTS";
					break;
				case expandDescription("[gcm_stolen_item_types_4]"):
					eq = "EQ_GCM_STOLEN_WEAPONDESIGNS";
					break;
			}
			var chk = p.equipmentStatus(eq);
			if (chk !== "EQUIPMENT_OK") {
				result += (result === "" ? "" : "\n") + expandDescription("[gcm_stolen_item_not_found]", { type: typ });
			}
		}
	}
	return result;
}

//-------------------------------------------------------------------------------------------------------------
this.$terminateMission = function $terminateMission(missID) {
	var bb = worldScripts.BulletinBoardSystem;
	var item = bb.$getItem(missID);
	var sbm = worldScripts.Smugglers_BlackMarket;
	var gcm = worldScripts.GalCopBB_Missions;

	// adjust reputation only when the terminatePenalty flag is set to true 
	if (item.data.terminatePenalty === true) {
		// update mission history
		gcm.$updateFailedHistoryReputation(item);
	}

	// *** type 33 - recovered stolen items
	if (item.data.missionType === 33) {
		// if the player terminates the mission after they have the software package, it can only mean the player is going to sell it
		if (item.data.quantity === 1) {
			var eq = "";
			typ = item.data.stolenItemType;
			switch (typ) {
				case expandDescription("[gcm_stolen_item_types_1]"):
					eq = "EQ_GCM_STOLEN_SCHEMATICS";
					break;
				case expandDescription("[gcm_stolen_item_types_2]"):
					eq = "EQ_GCM_STOLEN_CODES";
					break;
				case expandDescription("[gcm_stolen_item_types_3]"):
					eq = "EQ_GCM_STOLEN_DOCUMENTS";
					break;
				case expandDescription("[gcm_stolen_item_types_4]"):
					eq = "EQ_GCM_STOLEN_WEAPONDESIGNS";
					break;
			}
			var eqsts = player.ship.equipmentStatus(eq);
			if (eqsts === "EQUIPMENT_OK") {
				player.ship.removeEquipment(eq);
				if (sbm) sbm.$removeSaleItem(eq + ":" + missID);
			}
		}
	}
}

//-------------------------------------------------------------------------------------------------------------
this.$failedMission = function $failedMission(missID) {
	var bb = worldScripts.BulletinBoardSystem;
	var sbm = worldScripts.Smugglers_BlackMarket;
	var gcm = worldScripts.GalCopBB_Missions;
	var eq = "";

	if (!sbm) {
		// if there's no blackmarket option, just remove the equipment
		this.$terminateMission(missID);
		return;
	}

	var item = bb.$getItem(missID);
	// update mission history
	gcm.$updateFailedHistoryReputation(item);

	if (item.data.missionType === 33) {
		if (item.data.quantity === 1) {
			var typ = item.data.stolenItemType;
			switch (typ) {
				case expandDescription("[gcm_stolen_item_types_1]"):
					eq = "EQ_GCM_STOLEN_SCHEMATICS";
					break;
				case expandDescription("[gcm_stolen_item_types_2]"):
					eq = "EQ_GCM_STOLEN_CODES";
					break;
				case expandDescription("[gcm_stolen_item_types_3]"):
					eq = "EQ_GCM_STOLEN_DOCUMENTS";
					break;
				case expandDescription("[gcm_stolen_item_types_4]"):
					eq = "EQ_GCM_STOLEN_WEAPONDESIGNS";
					break;
			}
			if (player.ship.equipmentStatus(eq) != "EQUIPMENT_OK") eq = "";
		}
	}

	if (eq != "") gcm._equipmentFromFailedMissions.push({
		missionType: item.data.missionType,
		source: item.source,
		equip: eq,
		date: clock.adjustedSeconds
	});
}

//-------------------------------------------------------------------------------------------------------------
this.$updateManifestEntry = function $updateManifestEntry(missID) {
	var gcm = worldScripts.GalCopBB_Missions;
	gcm.$updateManifestEntry(missID);
}

//-------------------------------------------------------------------------------------------------------------
this.$missionAvailability = function $missionAvailability(missID, missType, origSysID) {
	return "";
}

//-------------------------------------------------------------------------------------------------------------
// 33 - recover stolen item
this.$missionType33_Values = function $missionType33_Values(workTime, routeTime, routeDistance, destSysInfo) {
	var result = {};
	result["quantity"] = 1;
	result["price"] = parseInt((parseInt(Math.random() * 400) + 500) / 10) * 10 + (7 - destSysInfo.government) * 50 +
		worldScripts.GalCopBB_CoreMissionValues.$calcPlayerBonus(200) // plus a possible bonus price, based on player score 
		+
		worldScripts.GalCopBB_CoreMissionValues.$calcDistanceBonus(routeDistance, 20); // plus a distance bonus
	result["expiry"] = clock.adjustedSeconds + routeTime + workTime; // transit time + 1 hour to complete
	result["penalty"] = parseInt(result.price / 2);
	return result;
}