Bulletin Board System
By phkb

Overview
========
This OXP adds a bulletin board to most stations in Oolite, from which missions (added by other OXP's) can be viewed and accepted. This OXP doesn't include any missions itself - it is a framework that other OXP's can utilise to make the process of adding missions easier.

Player Usage
============
The Bulletin Board is accessed through the Interfaces screen (F4), and it's normally found under the "Contracts" section. If there are no missions available, and you don't have any active missions, the interface won't be listed. When there are missions available, or you have active missions, the number of these will be displayed on the interface entry. eg "GalCop bulletin board (4 available, 2 active)".

When the interface is opened, any active missions will be grouped at the top of the list. Active missions are marked with a "•" and also have a value in the "%" (percentage completed) column. All other entries in the list are available missions.

If the destination system of a mission is directly on your currently plotted course on the F6 system map, the mission will be coloured green. If the destination is within 7ly of any system on your currently plotted course, the mission will be colours dark green. Using the Library Config OXP (see http://wiki.alioth.net/index.php/Library), the use of colour can be changed to instead use markers, where a † beside the destination system name means "on current course", and a ‡ means "near current course". 

When a mission is selected from the list, details of the mission will be displayed. These details include:
    Description              The short description of this mission.
    Details                  Full details of the mission parameters.
    Destination system       Where the mission needs to be completed at.
    Mission expires in       How much time you have to complete the mission.
    Payment on completion    How much you will be paid when the mission is completed.
    Penalty                  How much you will be charged if you fail to complete the mission. This value will be scaled by how much of the mission you completed.

If you have accepted a mission you will also see:    
    Percent complete         How much of the mission has been completed so far.

At the bottom of the screen will be the following options:
    Accept mission           This will signal that you are starting this mission.
    Show destination         This will display a chart (either a short range or long range, depending on the distance to the destination), allowing the player to 
                             see where the destination is.

Once you have accepted a mission, you will see the following options:
    Terminate mission        This will signal that you are giving up on this mission. If the mission has a penalty, it will be applied now. The mission will be removed from the list.
    Complete mission         This will only be available once the percent complete reaches 100%. This option will give you your payment and remove the mission from the list.

Active missions are shown on the F5F5 Manifest screen, under the "Bulletin Board Missions" heading. Depending on the mission, you will likely see how much of the mission you have yet to complete, and how much time is remaining before the mission expires.

Some missions will automatically complete as soon as you reach 100%, some will complete the next time you dock. It's important to check back on the Bulletin Board to see if you need to "Complete" the mission yourself.

Technical Details
=================
The purpose of the Bulletin Board system is to create a simple yet flexible interface which OXP authors can use to offer custom missions to the player. Missions added to the list are intended to be only available in the current system. Active missions are stored by the system and saved in the save game file, but the list of available missions will be cleared out with each hyperspace jump. 

To add a new mission to the Bulletin Board, you need to run the "$addBBMission" function and pass an object with the following parameters:

   ---------------------------------------------------------------------------------------------------------------------------
    var bb = worldScripts.BulletinBoardSystem;
    if (bb) {
        var myID = bb.$addBBMission({
                description:"My first mission",
                source:7,
                destination:129,
                stationKey:"galcop",
                details:"This is my first sample mission available on the Bulletin board.",
                manifestText:"My mission is active!",
                statusText:"A special text description to include on the briefing screen.",
                expiry:clock.seconds + 86400,
                payment:1000,
                penalty:100,
                deposit:0,
                allowPartialComplete:false,
                allowTerminate:true,
                accepted:false,
                percentComplete:0,
                completionType:"AT_SOURCE",
                stopTimeAtComplete:false,
                markerShape:"MARKER_PLUS",
                markerColor:"cyanColor",
                markerScale:1.0,
                model:"police",
                spinModel:true,
                disablePercentDisplay:true,
                playAcceptedSound:true,
                noEmails:true,
                customDisplayItems:"",
                initiateCallback:"$myMissionInitiate",
                completedCallback:"$myMissionComplete",
                confirmCompleteCallback:"$myMissionConfirmComplete",
                terminateCallback:"$myMissionTerminate",
                failedCallback:"$myMissionFailed",
                manifestCallback:"$myMissionUpdateManifest",
                availableCallback:"$myMissionAvailableCheck",
                worldScript:"MyFirstMission",
                keepAvailable:false
        });
    }
   ---------------------------------------------------------------------------------------------------------------------------

In detail these parameters are:
    ID                          (optional) You can specify your own ID number, rather than let the BB system create one. 
                                    If the ID you specify is already in use an error will be generated.
    description                 (required) This is the description of the mission shown in the Bulletin board list
    source                      (optional) The system ID of the source of this mission. If not included it will default to the 
                                    current system's ID.
    destination                 (required) This is the system ID of the destination system where the mission will be carried out. 
                                    This can be the current system, if the mission is local.
                                    Setting destination to -1 equals Interstellar space.
                                    Setting destination to 256 means there is no fixed destination.
    stationKey                  (optional) The stationKey helps to limit which stations the mission will be offered in. 
                                    See the section below title "Station Keys" for more details. 
                                    If omitted this will default to "" (blank), meaning this mission will be available from all 
                                    stations in this system
    details                     This is the full details of the mission parameters.
    manifestText                (optional) This is the text to display on the F5F5 manifest screen when the mission has been 
                                    accepted. See also "manifestCallback" below.
    statusText                  (optional) This is the text to display on the mission briefing screen when the mission is active. 
                                    If not set, the "manifestText" property will be used instead.
    expiry                      (required) The time is clock seconds when the mission must be completed by. If set to -1 this
                                    means the item has no expiry time.
    payment                     (optional) The number of credits the player will be given when they complete the mission.
    penalty                     (optional) The number of credits the player will be charged if they fail to complete the mission, 
                                    scaled by the percentage completed.
    deposit                     (optional) The number of credits the player will need to pay up-front to accept the mission. 
                                    This amount will be refunded when the mission is completed.
    allowPartialComplete        (optional) True/false value that indicates whether the player can complete the mission with less 
                                    than the full percentage. 
                                    Payment and deposit will be scaled by the percentage completed. Penalties will also apply, 
                                    again scaled by the percentage completed.
                                    For example, if the payment is 100 cr and the penalty 10 cr, and the player completes 70% of 
                                    the mission, if they hand it in they would receive 70 cr (70% of 100), and the penalty would 
                                    be 3 cr (30% of 10), meaning their total payment would be 73 cr.
                                    Default is false.
    allowTerminate              (optional) True/false value indicating whether the "Terminate mission" will be available to the 
                                    player after accepting the mission. The default is true.
    accepted                    (optional) True/false value indicating whether this mission will be added to the list as already 
                                    accepted by the player. Under normal circumstances this item can be left out. However, if 
                                    you want to link missions together, so completing one mission automatically starts a second 
                                    mission, you may want to add the mission to the list as "accepted:true" so the player 
                                    doesn't have to go to the Bulletin Board and manually accept the second mission.
                                    The default is false.
    percentComplete             (optional) A decimal value between 0 and 1. Allows you to create missions that already have some 
                                    part completed.
    completionType              (optional) A text value indicating what should happen when the player completes the mission 
                                    (ie the percentComplete value reached 1, or 100%). Can be one of these:
                                    AT_SOURCE                Player must return to the source system/station, open the mission 
                                                                and select "Complete mission".
                                    AT_STATIONKEY            Player can return to any system, dock at any station with the same 
                                                                stationKey, open the mission and select "Complete mission".
                                    ANYWHERE                 Player can return to any system, dock at any station, open the 
                                                                mission and select "Complete mission".
                                    IMMEDIATE                Player is rewarded immediately when the mission is flagged as 100% 
                                                                complete - player won't need to dock anywhere.
                                    WHEN_DOCKED_SOURCE       Player is automatically rewarded as soon as they next dock at the 
                                                                source system/station. Notice will appear in arrival report.
                                    WHEN_DOCKED_STATIONKEY   Player is automatically rewarded as soon as they next dock at any 
                                                                station, any system, but with the same station key. Notice will 
                                                                appear in arrival report.
                                    WHEN_DOCKED_ANYWHERE     Player is automatically rewarded as soon as they next dock at any 
                                                                station, any system. Notice will appear in arrival report.
                                    The default is "AT_SOURCE".
    stopTimeAtComplete          (optional) True/false flag to indicate that the clock will stop when the mission is flagged 
                                    100% complete. 
                                    Default false. This means that, for a completionType of "AT_SOURCE" the player has to 
                                    return to the original station within the allowed time in order to complete the mission. 
                                    If this flag is set to true, once the player completes the mission at the destination, 
                                    they are free to take as much time as they like to return to the original station and 
                                    hand in their mission.
                                    This flag will be ignored if the completionType is set to "IMMEDIATE".
    arrivalReportText           (optional) When the completionType is set to "WHEN_DOCKED_*" this text will be displayed on the 
                                    arrival report when the player completes the mission.
                                    If omitted, will default to "'<description>' mission complete. You have been awarded <payment>."
    model                       (optional) Role of a ship to use as the background on the mission details screen.
    modelPersonality            (optional) The entityPersonality assigned to the ship model.
    spinModel                   (optional) True/false value indicating whether the ship model will rotate or not. 
                                    The default is true.
    background                  (optional) guiTextureSpecifier (name of a picture used as background)
    overlay                     (optional) guiTextureSpecifier (name of a picture used as overlay)
                                    Will default to the bulletin board graphic when not set.
    mapOverlay                  (optional) guiTextureSpecifier (name of a picture used as overlay) for the map screen.
                                    Will default to the "overlay" setting (if set), otherwise will use the bulletin board graphic.
    forceLongRangeChart         (optional) True/false value which, when true, indicates that the map display for this mission 
                                    should always be a long range chart. When false, map zoom will be chosen based on the distance
                                    between the source and destination systems.
                                    The default is false.
    markerShape                 (optional) Allows the shape of the galactic chart marker to be overridden. 
                                    Default is "MARKER_PLUS". Possible values are:
                                    NONE             No galactic chart marker will be added.
                                    MARKER_X         Uses an "X" to mark the system.
                                    MARKER_PLUS      Uses a "+" to mark the system.
                                    MARKER_SQUARE    Uses a square shape to mark the system.
                                    MARKER_DIAMOND   Uses a diamond shape to mark the system.
    markerColor                 (optional) Allows the color of the galactic chart marker to be overridden. 
                                    Default is "redColor".
    markerScale                 (optional) Allows the scale setting of the galactic chart marker to be overridden. 
                                    Value between 0.5 and 2.0. Default is 1.0.
    additionalMarkers           (optional) Array of marker dictionaries definition any extra systems that should be marked on
                                    the system map for this mission.
                                    Each item can have:
                                    system          system ID to mark (required)
                                    markerShape     one of the standard marker shapes (default MARKER_PLUS)
                                    markerColor     color of the marker (default redColor)
                                    markerScale     scale of the marker (default 1.0)
    disablePercentDisplay       (optional) Controls the display of the "Percent complete" value on this mission details page. 
                                    Default is false.
                                    When set to true, only the mission manifest text will be shown on the mission details page.
    playAcceptedSound           (optional) Controls whether the [contract-accepted] sound will be player upon contract acceptance. 
                                    Default is true.
    noEmails                    (optional) If the Email System is installed, but you don't want this item to send confirmation 
                                    emails, set this flag to true.
    customDisplayItems          (optional) Allows a mission to specify additional, non-standard items on the details page.
                                    When used, should be set to an array of dictionary items, having "heading" and "value" 
                                    properties in each dictionary object.
                                    eg [{heading:"Special Instructions:", value:"Be very, very qwiet..."}]
    customMenuItems             (optional) Provides a way for a third party to add custom menu entries to a BB item. 
                                    When used, should be set to an array of dictionary items, having the following elements:
                                    text            (required) Text to display in the menu item
                                    worldScript     (required) Name of the worldScript which contains the callback function
                                    callback        (required) Name of the callback function 
                                                        (the mission ID will be passed as a parameter)
                                    condition       (optional) Name of a callback function that will return either a blank string,
                                                        meaning the menu item is available, or a string containing the reason why
                                                        the menu item is unavailable.
                                                        (the mission ID will be passed as a parameter)
                                    activeOnly      (optional) Boolean value indicating the menu item is only visible when the
                                                        mission is active. Default is true.
                                    autoRemove      (optional) Boolean value that indicates the menu should be removed from 
                                                        the BB item as soon as the player selects it. Default is false.
    initiateCallback            (optional) The function name to call back when the mission is accepted by the player.
    completedCallback           (optional) The function name to call back when the mission is completed by the player, 
                                    based on the completionType setting.
    confirmCompleteCallback     (optional) A function name to call to confirm the mission has been completed. Useful if there 
                                    are secondary steps that must have been completed by the player.
                                    For instance, you might want to check that the player has a particular amount of a certain 
                                    commodity in their hold.
                                    Expects a string return value of blank (meaning mission is completed) or [string explaining 
                                    why mission cannot be completed] (meaning the mission is not complete).
    terminateCallback           (optional) The function name to call back when the mission is terminated/cancelled by the player.
    failedCallback              (optional) The function name to call back when the player fails to complete the mission in the 
                                    alloted time. Called during the "shipWillDockWithStation" event.
    manifestCallback            (optional) The function name to call back when the manifest entry for the mission requires updating.
                                    Note: If both the manifestText and manifestCallback are blank, no information will be
                                    displayed for this mission if it becomes active.
    availableCallback           (optional) The function to call to check if the mission is actually available. The mission ID will 
                                    be passed as a parameter. Function should return a string value of either a blank (""), to 
                                    indicate the mission is available, or a short description of the reason why the mission is
                                    unavailable (eg "Insufficient cargo space").
    bonusCalculationCallback    (optional) The function to call to calculate and return any bonus payment when the player 
                                    successfully completes a mission. Will only be called if the mission is 100% completed 
                                    inside the allotted time. If set, must return a number >= 0. Will be called after the 
                                    completedCallback function, if set.
    worldScript                 (required) The name of the worldScript where these functions reside.
    keepAvailable               (optional) Flag to indicate whether mission should kept when player leaves the system. Default false.
    postStatusMessages          (optional) Array of dictionary objects defining a message to be displayed to the player when 
                                    they accept, complete or terminate a mission.
                                    status             (required) Defines which status the message will follow. Possible values:
                                                           initiated, completed, terminated
                                    text               (required) The text of the message to be displayed
                                    return             (optional) Where to return the player to after the mission page is displayed
                                                           item     Returns player to the mission details page (N/A for completed/terminated)
                                                           list     Returns player to the mission listing
                                                           exit     Returns player to the F4 Interfaces screen
                                    background         (optional) guiTextureSpecifier to use for the background of the message
                                    overlay            (optional) guiTextureSpecifier to use for the overlay of the message
                                    model              (optional) ship model to use on the message.
                                    modelPersonality   (optional) The entityPersonality assigned to the ship model.
                                    spinModel          (optional) True/false value indicating whether the ship model will rotate or not. 
                                                           The default is true.
                                    If any of the optional parameters are left out, the equivalent parameter from the BB item will be used.
    data                        (optional) Any data that might be useful to store with the mission for later access.

This call will return a unique ID (integer) value (either created by the BB system or passed from the caller) that can be stored and used to reference this mission in other bulletin board functions.

Once a mission has been added, it is up to the calling script to work out and track the criteria required to complete a mission. The BB system will handle the display of information, and will pay or charge the player if they complete or fail the mission. But the rules which govern the mission criteria are controlled solely by the calling routine. It is up to the calling routine to track the mission and tell the BB system when updates are required.

With that in mind, the following functions will be of use to the calling party:

   ---------------------------------------------------------------------------------------------------------------------------
   $updateBBMissionPercentage(bbID, percentage);
   ---------------------------------------------------------------------------------------------------------------------------
   This function will update the percentage completed value for a given mission ID (as provided by the $addBBMission function).
   
   When this function is called, it will also initiate the "manifestCallback" routine, giving the OXP an opportunity to update the manifest entry.
   
   If the percentage is 1 (ie. 100%), and the completionType is "IMMEDIATE", the "completedCallback" routine will be called and the mission will be removed from the list. Otherwise, the mission will be completed at another event (eg when docking, or when the player selects "Complete Mission" on the mission details screen.)
   
   ---------------------------------------------------------------------------------------------------------------------------
   $updateBBManifestText(bbID, newtext);
   ---------------------------------------------------------------------------------------------------------------------------
   This function will update the manifest text entry for a given mission ID. This function should generally be called from the "manifestCallback" routine.

   ---------------------------------------------------------------------------------------------------------------------------
   $updateBBStatusText(bbID, newtext);
   ---------------------------------------------------------------------------------------------------------------------------
   This function will update the status text on the mission briefing screen for a given mission ID. This function should generally be called from the "manifestCallback" routine. If no status text is supplied, the "manifestText" property will be used instead.

   ---------------------------------------------------------------------------------------------------------------------------
   $shuffleBBList()
   ---------------------------------------------------------------------------------------------------------------------------
   A function to randomise the order of bulletin board items. This can be handy if you add missions to the list in a sequence, but you don't want that sequence to be visible to the player by having all the same types of missions grouped together.
   
   ---------------------------------------------------------------------------------------------------------------------------
   $percentCompleted(bbID)
   ---------------------------------------------------------------------------------------------------------------------------
   Returns the current percentage complete value for a particular mission ID.

   ---------------------------------------------------------------------------------------------------------------------------
   $removeBBMission(bbID)
   ---------------------------------------------------------------------------------------------------------------------------
   Removes a particular mission ID from the list. This method skips any mission constraints and completed/failed events and just removed the record. This can be useful when chaining missions together, if the previous mission needs to be removed completely, without performing any of the callbacks.

   ---------------------------------------------------------------------------------------------------------------------------
   $getItem(bbID)
   ---------------------------------------------------------------------------------------------------------------------------
   Returns a bulletin board mission object for the given mission ID.

   ---------------------------------------------------------------------------------------------------------------------------
   $getIndex(bbID)
   ---------------------------------------------------------------------------------------------------------------------------
   Returns the index value of the given mission ID in the internal data array. This can be useful if you would like to update mission parameters directly (eg. changing the "stopTimeAtComplete" flag).
   Note: Because index values are subject to change without notices (particularly between saves) the value returned from this function should be used and then discarded. Do not try to save the index value in some method and use it later - you may be updating a completely different mission!

   ---------------------------------------------------------------------------------------------------------------------------
   $removeCustomMenuItem(bbID, index)
   ---------------------------------------------------------------------------------------------------------------------------
   Removes the custom menu item from the passed mission ID at the index point.

   ---------------------------------------------------------------------------------------------------------------------------
   $registerBBEvent(wsName, fnName, eventName)
   ---------------------------------------------------------------------------------------------------------------------------
   Registers a worldScript/function to be called when a particular BB system event takes place. 
       wsName                         Name of worldscript where function can be found.
       fnName                         Name of the function to call.
       eventName                      Name of the event to attach to.
   At the moment, the possible events are:
       missionAdded                   Occurs when a mission is added to the BB.
       open                           Occurs when the BB is opened.
       close                          Occurs when the BB is closed using the "Close" option.
       exit                           Occurs when the BB is closed by the player selecting another Fn command.
       launchExit                     Occurs when the BB is closed by the player launching their ship. The station launched from will be passed as a parameter.
       preListDisplay                 Occurs just before the BB mission list is displayed
       postListDisplay                Occurs just after the BB mission list is displayed
       preItemDisplay                 Occurs just before a mission detail page is displayed. The mission ID will be passed as a parameter.
       postItemDisplay                Occurs just after a mission detail page is displayed. The mission ID will be passed as a parameter.
       preItemChartDisplay            Occurs just before the chart view of a mission is displayed. The mission ID will be passed as a parameter.
       postItemChartDisplay           Occurs just after the chart view of a mission is displayed. The mission ID will be passed as a parameter.
       shipWillDockWithStation_start  Occurs at the beginning of the shipWillDockWithStation world event.
       shipWillDockWithStation_end    Occurs at the end of the shipWillWillDockWithStation world event.

   ---------------------------------------------------------------------------------------------------------------------------
   $unregisterBBEvent(wsName, fnName, eventName)
   ---------------------------------------------------------------------------------------------------------------------------
   Removes a callback from the registration list.
       wsName                     Name of worldscript where function can be found.
       fnName                     Name of the function to call.
       eventName                  Name of the event to detach from.

   ---------------------------------------------------------------------------------------------------------------------------
   $setBackgroundDefault(guiTextureSpecifer)
   ---------------------------------------------------------------------------------------------------------------------------
   Sets the default background to use on the BB.

   ---------------------------------------------------------------------------------------------------------------------------
   $resetBackgroundDefault()
   ---------------------------------------------------------------------------------------------------------------------------
   Resets the default background back to the original default.

   ---------------------------------------------------------------------------------------------------------------------------
   $setOverlayDefault(guiTextureSpecifier)
   ---------------------------------------------------------------------------------------------------------------------------
   Sets the default overlay to use on the BB.

   ---------------------------------------------------------------------------------------------------------------------------
   $resetOverlayDefault()
   ---------------------------------------------------------------------------------------------------------------------------
   Resets the default overlay back to the original default.

Station Keys
------------
To limit the stations at which a mission will be available from, a station key is required. When the "stationKey" is not provided to the "$addBBMission" function, the mission will be available at all stations in the source system.

Each station can have multiple station keys, depending on the worldScript, but if no specific station key is added, the default station key will be the stations "allegiance" property. So, a station with an allegiance of "galcop" will have a default station key of "galcop". Therefore, if you want to limit your mission to only be available at GalCop-aligned stations, you would include "galcop" in the "stationKey" when adding the mission to the bulletin board. If you want to include your mission at both "galcop" and "chaotic" stations, you would use a comma separator and make your mission stationKey "galcop,chaotic".

But what if allegiance is insufficient to identify the specific station you want to add your mission to? In these cases, you need to give your target station a special stationKey of its own. At some point after the system has been populated, (for instance, during the systemWillPopulate or systemWillRepopulate events), find the station you want to give your special key to and perform the following function:

    var bb = worldScripts.BulletinBoardSystem;
    var stns = system.stations;
    
    // loop through all the available stations
    for (var i = 0; i < stns.length; i++) {
        // if this station is the one I'm looking for....you'll need to provide some logic for identifying your station
        if (stns[i].~~~something~~~) {
            // add the station key for this worldScript
            bb.$addStationKey(this.name, stns[i], "myStationKey");

            // first parameter is "worldScriptName". Normally this would be "this.name".
            // second parameter is "station". This is a reference to the station.
            // third parameter is "stationKey". This is the station key that will be added to the list of keys for this worldScript and station combination.
        }
    }

Once the station has been given this custom key for your worldScript, you can use that key when adding missions. The custom key will override whatever default key the station may have had previously. A station can have multiple keys for your worldScript.

For example, let's say I wanted to create a mission that was only available at the main station of the system. However, with OXP's like "Stations For Extra Planets" installed, I can't just rely on the station.allegiance. What I need to do is this:

    this.systemWillPopulate = function() {
        if (system.mainStation) {
            var bb = worldScript.BulletinBoardSystem;
            bb.$addStationKey(this.name, system.mainStation, "mainStation");
        }
    }

Now I can apply the "mainStation" station key to any bulletin board missions I add, and they will now only be visible at the main station in the system.

Removing the Bulletin Board from a Station
------------------------------------------
You may decide that you don't want to have the bulletin board at a particular station. This can be achieved in one of two ways:

1. In the shipdata.plist file for the station, include the following item in the "script_info" section:

    "script_info" = {
        "bb_hide" = 1;
    };

2. At some point after the system has been populated, find the station you want to hide the bulletin board on and add "bb_hide" value to the "script" property by doing the following:

    var stns = system.stations;
    for (var i = 0; i < stns.length; i++) {
        // if this station is the one I'm looking for....you'll need to provide some logic for identifying your station
        if (stns[i].~~~something~~~) {
            stns[i].script.bb_hide = 1;
        }
    }
    
Adding main menu items
======================
There may be times when you want a special menu item to appear on the main control listing page of the BB system, not just on the mission details page itself. To do this you can use the $addMainMenuItem and $removeMainMenuItem functions.

To add a menu item use the $addMainMenuItem function:

   ---------------------------------------------------------------------------------------------------------------------------
    var bb = worldScripts.BulletinBoardSystem;
    if (bb) {
        bb.$addMainMenuItem({
            text: "Special function text",
            color:"greenColor",
            unselectable: false,
            autoRemove: true,
            worldScript:"myWorldScriptName",
            menuCallback:"myFunctionName"
        });
    }
   ---------------------------------------------------------------------------------------------------------------------------

In detail these parameters are:
	text                    Text to display on the menu
	color                   Color of the item. Will default to this._menuColor (orangeColor)
	unselectable            Flag to control whether the item should be unselectable. Defaults to false.
                                If true, color will be set to this._disabledColor (darkGreyColor).
	autoRemove              Flag to indicate the item should be removed from the menu when selected by the player.
                                Defaults to false.
	worldScript             WorldScript name for the callback function.
	menuCallback            Function to call when the user selects the item.

To manually remove a menu item (ie if the "autoRemove" option is set to false), use the $removeMainMenuItem function:

   ---------------------------------------------------------------------------------------------------------------------------
    var bb = worldScripts.BulletinBoardSystem;
    if (bb) {
        bb.$removeMainMenuItem("myWorldScriptName", "myFunctionName");
    }
   ---------------------------------------------------------------------------------------------------------------------------

   This function accepts two parameters:
   worldScriptName          The name of the worldScript registered on the item.
   functionCallbackName     The name of the menu function callback on the item.

Example Mission Script
======================
The following is a very brief example demonstrating the methods of adding a mission to the bulletin board, and setting up the callbacks. This is a subset of a larger project, but should suffice in providing code examples of the techniques outlined above. This has also been included as an OXP in the "Resources" folder of the BB OXP package. Move the "AsteroidHunter.OXP" into your "AddOns" folder to see this OXP in action.

    "use strict";
    this.name        = "AsteroidHunter";
    this.author      = "phkb";
    this.copyright   = "2017 phkb";
    this.description = "Adds a simple asteroid hunt mission to the Bulletin Board";
    this.licence     = "CC BY-NC-SA 4.0";

    this._bb = null;				// link to Bulletin Board worldScript

    //-------------------------------------------------------------------------------------------------------------
    this.startUp = function() {
        // establish a link to the bulletin board worldscript
        this._bb = worldScripts.BulletinBoardSystem;
    }

    //-------------------------------------------------------------------------------------------------------------
    this.startUpComplete = function() {
        this.$addLocalMissions()
    }

    //-------------------------------------------------------------------------------------------------------------
    this.shipWillExitWitchspace = function() {
        // adds new missions to the list
        this.$addLocalMissions();
    }

    //-------------------------------------------------------------------------------------------------------------
    this.shipKilledOther = function(whom, damageType) {
        // mission type 1 - asteroid hunt - monitor when the player shoots an asteroid
        if (whom.hasRole("asteroid")) {
            var item = null;
            // cycle through the bulletin board list
            if (this._bb._data.length > 0) {
                for (var i = 0; i < this._bb._data.length; i++) {
                    item = this._bb._data[i];
                    // is this an accepted mission, and the target destination is the same as the current system...
                    if (item.accepted === true && item.destination === system.ID) {
                        // ..and there is some data on the item, and the data has a property of "type" and the type is 1 (asteroid hunt) 
                        // and the number of destroyed asteroids is less than the target quantity
                        if (item.hasOwnProperty("data") && item.data.hasOwnProperty("type") && item.data["type"] == 1 && item.data.quantity < item.data.targetQuantity) {
                            // ...then update the quantity
                            item.data.quantity += 1;
                            // signal the bulletin board that we've had a change in the mission completion percentage
                            this._bb.$updateBBMissionPercentage(item.missionID, (item.data.quantity / item.data.targetQuantity));

                            // notify the player that we just did something that affected a mission
                            player.consoleMessage("Mission goal updated");
                        }
                    }
                }
            }
        }
    }

    //-------------------------------------------------------------------------------------------------------------
    // handles the manifest entry callback from the bulletin board
    this.$updateManifestEntry = function(missID) {
        var item = this._bb.$getItem(missID);
        if (item.data.quantity == item.data.targetQuantity) {
            this._bb.$updateBBManifestText(missID, 
                expandDescription("Mission to destroy asteroids complete. Return to the main station in [system] to claim payment.", 
                    {system:System.systemNameForID(item.source)})
            );
        } else {
            // otherwise, just update the description with what is currently expected
            this._bb.$updateBBManifestText(
                missID,
                expandDescription("Destroy [quantity] asteroids in [destination] within [expiry].", 
                    {quantity:(item.data.targetQuantity - item.data.quantity), 
                    destination:system.name, 
                    expiry:this._bb.$getTimeRemaining(item.expiry)})
            );
        }
    }

    //-------------------------------------------------------------------------------------------------------------
    // adds the asteroid hunt mission to the bulletin board
    this.$addLocalMissions = function() {
        // if we haven't got any missions in the available list, try to add one now
        // first, count up the number already in player
        var chk = 0;
        if (this._bb._data.length > 0) {
            for (var i = 0; i < this._bb._data.length; i++) {
                if (this._bb._data[i].destination === system.ID &&
                    this._bb._data[i].hasOwnProperty("data") && 
                    this._bb._data[i].data.hasOwnProperty("type") && 
                    this._bb._data[i].data["type"] == 1) 
                    chk += 1;
            }
        }
        // if there's one there already, exit now
        if (chk > 0) return;

        // pick a random number of asteroid that need to be destroyed
        var qty = parseInt((Math.random() * 10) + 10);
        // calculate the payment
        var amt = qty * 10;
        // calculate the expiry time
        var expire = clock.adjustedSeconds + 21600; // 6 hours to complete.
        // add the mission to the bulletin board, and make a note of the id
        var id = this._bb.$addBBMission({
            source:system.ID,
            destination:system.ID,
            stationKey:"galcop",
            description:"Clean up the spaceways",
            details:expandDescription("Commanders are needed to help clean up the spacelanes by removing [quantity] asteroids in this system.", {quantity:qty}),
            payment:amt,
            expiry:expire,
            penalty:0,
            model:"asteroid",
            modelPersonality:parseInt(Math.random() * 32767),
            manifestCallback:"$updateManifestEntry",
            worldScript:this.name,
            data:{type:1, targetQuantity:qty, quantity:0}
        });
    }

Licence
=======
This work is licensed under the Creative Commons Attribution-Noncommercial-Share Alike 4.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/4.0/

Bulletin board image by icons8.com from http://www.iconsplace.com/black-icons/copy-icon with licence Creative Commons Attribution-NoDerivs 3.0 Unported

Version History
===============
2.11
- Tweaked logic for determining if a mission is expired, for missions with no specific destination.
- Darkened overlay images for better compatibility with Oolite 1.92.

2.10
- Fixed invalid descriptions key when sending confirmation email.

2.9
- Fixed issue where older HUD's that don't define certain HUD elements would have the comms log and console log positions changed when launching while the BB is open.

2.8
- Fixed issue where older HUD's that don't define certain HUD elements would have the comms log and console log positions changed on launch after using the BB.

2.7
- Moved all text into descriptions.plist for easier localisation.

2.6.3
- Added check for deferred bounty (Bounty System OXP) when missions with completion type "IMMEDIATE" are completed.
- Improved clarity for when you have completed a mission but are docked at the wrong station type.

2.6.2
- When a contract is complete, the "Set course for" option is now only shown if the completion type is "AT_SOURCE" or "WHEN_DOCKED_SOURCE".

2.6.1
- Corrected name of HUD.

2.6
- Switched method of displaying a full screen so that the message box is visible when messages are sent.

2.5
- Really fixed issue with missions not able to be created in systems with ID 0 or 255.

2.4
- Fixed issue that would prevent missions being created in systems with ID 0 or 255.
- Added a "keepAvailable" flag to prevent a mission from being dropped if it isn't accepted when you leave the system.

2.3
- Better protection against missions in the list whose worldscript is no longer available.
- Better cleanup of system markers where missions are removed from the bulletin board.

2.2
- Fixed issue that could lead to missions having the same ID.

2.1
- The email ID of the last email sent relating to a BB item is now accessible through the "lastEmailID" property. Requires Email System v1.7.8.

2.0 
- Fixed issue were text was covering the map when the Advanced Navigation Array wasn't installed.

1.9
- Tweaks to the calculation for determining if an unaccepted mission is expired.

1.8
- Fixed issue where the calculation to determine whether an unaccepted mission should be considered expired was being a little too broad.
- Bug fixes.
- Code refactoring.

1.7
- Calls to 'confirmCompletedCallback' now performed each time mission screen is opened when a "Complete mission" menu item is displayed.

1.6
- Added "additionalMarkers", an array of marker dictionaries, which enables a single mission to have multiple markers on the system chart.
- Added "forceLongRangeChart", a boolean value (default false), which will force the map screen to always show the long range chart, rather than a short range or custom chart.
- Fixed issue with "playAcceptedSound" not defaulting to true correctly.
- Fixed issue where some available items may not be shown on the main mission list if there are any active missions.

1.5.1
- Fixed issue calculating route time if there is no route to destination.

1.5
- Added option to highlight missions whose target system is on or near to your current course. Highlight can be via color or markers, switchable via Library.
- Code refactoring.
- Added mission description and payment amount to the map screen.
- Added "Next contract" menu item to mission details page.
- Included option (switchable via Library Config) of adding "Next contract" to map screen.

1.4
- Makes use of new short range chart and custom chart options available in Oolite 1.87.
- Better method of determining when missions are expired and then removing them from the BB list.
- Added a flag to Library Config that will allow the internal ID of a mission to be added to the mission details page, which can be useful for debugging.
- Now plays the "[contract-accepted]" sound when any contract is accepted.
- Added new flag to the "$addBBMission" object: "playAcceptedSound", a boolean value allowing the contract to control whether the "[contract-accepted]" sound will be played.

1.3
- When setting a course to a target system, F7 screen will now display the new destination.

1.2
- Added expiry time in hours to the mission details screen.
- When 1 day is remaining, it will now read "1 day" rather than "1 days" (same for hours, minutes and seconds).

1.1
- Better handling of scenario where player doesn't have the Advanced Navigational Array installed.

1.0
- Added option to force the Bulletin Board interface screen to always be shown, even if no contracts are available.
- Fixed bug where missions that do not have a specific system destination (ie 256) were always displaying a "Close to expiry" warning.
- Turned on decimal place display on all credit value output.
- Bug fixes.

0.29
- Added additional text to mission briefings for missions close to expiry, to better explain the fact.
- Added a cleanup function to remove marked systems that have become orphaned from their mission.

0.28
- Sorted available missions by payment amount. Accepted missions will still be sorted by when they were accepted.

0.27
- Added "shipWillDockWithStation_start" and "shipWillDockWithStation_end" events, triggers at the start and then at the end of the shipWillDockWithStation, to allow mission OXP's to know in which order things will be processed, which is particularly important for BB items flagged as "WHEN_DOCKED_SOURCE", "WHEN_DOCKED_STATIONKEY", and "WHEN_DOCKED_ANYWHERE".
- Method of using of "formatCredits" function is now consistent.

0.26
- Added the "condition" property to custom menu items, to allow for the item to be disabled in certain conditions.
- Added the "activeOnly" property to custom menu items, to allow the item to be hidden if the mission isn't active.

0.25
- At some point I'd managed to delete the "confirmCompleteCallback" property when adding a new mission to the board. Fixed.

0.24
- Fixed issue with missions where completion type is AT_SOURCE, where the "Complete mission" menu item was not being displayed.

0.23
- Improved handling of missions with intergalactic source or destination systems.
- Fixed issue with Xenon Redux UI sometimes losing its background images on the BB.

0.22
- Added facility to add menu items to the main BB contract listing page.
- A BB item can now have the destination set to -1 (Interstellar space), or 256 (no fixed destination).
- Setting the payment of a BB item to zero will now hide the "Payment" line on the mission details page.
- "payment" is no longer a required element.
- Fixed more JS errors when terminating a contract.

0.21
- Expanded number of contracts shown on main listing to 21.
- Added "bonusCalculationCallback" to allow bonus payments to be calculated and given to the player when a mission is successfully completed.
- Fixed JS error when terminating a contract.
- Fixed reference error when attempting to retrieve a postStatusMessage for a completed mission.
- Added validations for postStatusMessages when adding a mission to the board.

0.20
- Fixed issue with new sorting methods conflicting with old indexing system for selected item.

0.19
- Added postStatusMessages property for individual missions to allow a mission screen to be shown to the player after status changes.
- When missions are accepted they will appear in the accepted list and manifest screen in the same order as they were accepted in.
- "initiateCallback" and "completedCallback" are no longer required elements.
- Corrections and adjustments to the "AsteroidHunter" sample script.
- Code cleanup and refactoring.

0.18
- Adjusted precedence of colors for items in the mission list. If a mission is both unavailable and close to expiry, unavailability will be selected for the item color.
- Added new events: "open" (fires when BB is opened), "close" (fires when BB is closed from the menu), "exit" (fires when BB is exited without specifically selecting 'Close'), "launchExit" (fires when BB is exited by the player launching their ship).
- Added "data" element to BB item, so that relevant data can be stored with the mission, for later retrieval. This data is not displayed to the player.
- Adding a mission with the expiry parameter set to -1 will result in a mission with an unlimited expiry.
- Fixed issue where explicitly setting "allowTerminate:true" was not being correctly set.
- Page reset when returning from the map display to the briefing screen.
- Added the "mapOverlay" option to allow a specific image to be applied to the map screen for a mission.
- Added "setOverlayDefault" and "resetOverlayDefault" functions to control the default overlay used on the BB.
- Added "setBackgroundDefault" and "resetBackgroundDefault" functions to control the default background used on the BB.
- Overlay setting for item now applies on confirmation screen and mission incomplete screen.
- Adjusted procedure for applying overlays to screen, making better use of defaults.
- "terminateCallback" is no longer a required element.
- Simplified the sample script "AsteroidHunter".

0.17
- Added number of jumps to destination to the various mission screens.
- Origination system and destination system details will now wrap inside the column correctly.
- Cleanup of chart route mode handling.

0.16
- Attempt to fix the event callback function generating error when calling functions.

0.15
- Added "remoteDepositProcess" property, to control whether deduction of the deposit amount should be handled by the BB or by some external process.
- Changed colour of unavailable items in the main list to be a slightly darker shade of gray.
- Added a "Net payment" line to missions that have a deposit.
- Unavailable items will now be put at the bottom of the mission list.
- Removed the backgroundHeight and overlayHeight properties. The background and overlay properties are now defined as guiTextureSpecifier, which can include these other elements as part of a dictionary.

0.14
- The "availableCallback" function was not being called on the short or long range chart screens.
- Added an event registration and execution system, so OXP's can know when various interface events have taken place.
- Days now included in mission time remaining on the mission detail screen.
- Fixed issue where "Set course for" options were not being displayed on map screens.
- Fixed issue where numeric custom display item values were causing an error.
- Fixed issue where an error would occur if a mission does not have a manifestText entry as well as no manifestCallback.
- Fixed issue where adding multiple station keys to the same station were not adding data correctly.
- The stationKeys array was not being reset after a jump.
- Corrected errors in documentation.
- Bug fixes.
- Code refactoring.

0.13
- Added an "availableCallback" function, to allow for cases where a mission can be added to the BB, but conditions prevent the player from being able to accept it (eg insufficient cargo space).
- If a mission has a deposit amount as part of the terms of acceptance, this value will be deducted from the payment amount on the first page of the bulletin board display. Brings it into line with the cargo contracts screen.
- Fixed bug with displaying custom items on a mission detail page.

0.12
- Moved restoring data process to startUp function.

0.11
- Added custom menu items that can be used with callbacks to allow custom functions to be called on each mission.
- Changed methodology for creating mission ID's to eliminate the possibility of ever having two missions with the same ID.
- Changed short range chart selection range to 7.5ly, rather than 15ly.
- Fixed another minor bug with the players destination getting reset unexpectedly when viewing mission destinations.
- Missions added with "autoAccept" turned on will now get their destination marker put on the system map, and (if the Email System is installed) will have confirmation emails sent.
- Fixed Javascript reference error when terminating a mission.
- Better handling of interstellar space conditions.
- Added the "noEmails" option, to stop a mission from sending confirmation emails.
- Added ability for calling routines to specify their own ID for reference, overriding the default.
- Changed the console message that is displayed when a mission is manually terminated by the player.
- Chart markers were not being removed from the chart after missions were completed.
- Fixed issue with HUD not becoming visible again when launching while viewing the Bulletin Board.
- Setting a blank value ("") for a mission station key should have allowed the mission to be found and completed at any station in the source system.
- Swapped "Expiry" and "Payment" columns in the main list to align better with other contract screens (parcels, cargo, passengers).

0.10
- "terminateCallback" was not being called when a mission was terminated by the player. "failedCallback" was being called instead.
- Fixed Javascript bug in "failedCallback" routine.

0.9
- Added optional "deposit" property to mission items, which will be deducted from the player's account when accepting the mission.
- Added travel time (in hours) to the destination system info and source system info.
- "Set course" option now takes player's full course into consideration when working out whether the option should be displayed, rather than just the final destination.
- Fixed issue where player destination was getting reset when a chart screen is exited by pressing a function key, rather than via the "Exit" command.

0.8
- Fixed issue with AT_SOURCE missions that allow for partial completion, where they could be partially completed at non-source stations.
- Active but expired missions that are shown on the main BB list will now just show as "Expired".
- Added "customDisplayItems", so missions can add their own heading/value information items to the mission details page.
- "Set course for" menu items won't be shown if player already has that system set as their destination.
- Changed "==" comparisons to "===" for performance improvements.

0.7
- Accepting a mission now doesn't close the mission briefing screen.
- Added a "stopTimeAtComplete" boolean value to enable missions to be setup so that, as soon as the mission is flagged 100% complete, the expiry time countdown will stop. This means that the player can take as much time as they want to return to the system and hand in their completed mission. The default for this value is false.
- Added a "allowPartialComplete" boolean value so that a mission can be handed in early, with a reduction in the payment based on the percentage completed. If penalties also apply it will reduced by the percentage completed.
- Added a "statusText" text value that will be displayed on the mission briefing screen as the "Current status" instead of the manifestText value.
- Added the "$updateBBStatusText" function to enable the status text to be updated.
- Added the originating system to the mission details page.
- Added the destination system to the main mission list.
- Moved "Percentage Complete" column to be the last column on the main mission list screen.
- Changed the "Expires" column to only show hours (or minutes if the time remaining is less than 100 minutes) on the main mission list screen.
- Fixed issue with "allowTerminate" not defaulting correctly.
- Changed how stationKeys are added, making it possible for a station to have multiple keys, as well as allowing for multiple worldScripts to have different station keys for the same station.
- Fixed issue where exiting a multi-page mission briefing and re-opening it was not resetting the current page back to 1.
- Fixed issue where boolean values of true or false (that is not a text string with "true" or "false" in it) were not being recognised correctly when adding a mission.
- Changed the way the number of active missions is counted. Now any active mission is listed, not just the non-expired missions.
- When viewing a completed Bulletin Board mission and the player is not in the originating system, the option to "Set course for [originating system]" will now be available.
- Corrected logic for determining when a property has been passed in an object when adding new missions.
- Changed completion types "AT_STATION" and "WHEN_DOCKED_STATION" to be "AT_STATIONKEY" and "WHEN_DOCKED_STATIONKEY" to better describe their purpose.
- Added a debug flag to turn on/off log messages.
- If the Email System is installed, accepting, terminating, completing and failing missions will now generate a confirmation email.
- Added a comma between "# available" and "# active" on the interface screen.

0.6
- Added an additional check when creating a new mission. Expiry time must be in the future.
- Fixed bug with "markerShape" setting not being correctly set up.
- Active missions that have expired are now coloured red in the bulletin board list.
- Included manifest text on mission briefing page when mission is completed but not yet handed in. Also included expiry time, which is still relevant for completed-yet-not-handed-in missions.
- Forced manifest entries to be updated each time the manifest screen is viewed in order to keep "Expires in" field up to date.
- Added "%" to percentage completed text on mission screen.
- Added a "disablePercentDisplay" boolean value to enable a mission to turn off the display of the "Percent complete" value. This would leave just the manifest text as the method of showing mission status.
- Completed missions that are about to be handed in will no longer show as being close to expiry.
- Better handling missions complete when docking where the confirmCompleteCallback function returns a value.
- Fixed bug when attempting to show the long range chart.
- Fixed bug with mission variable declaration in $failedMission routine.
- Code refactoring.

0.5
- Fixed remainder of missing "clock" references.

0.4
- Turned off some debug messages.
- Fixed missing "clock" reference when updating mission percentage.

0.3
- Fixed Javascript reference error when displaying mission details.
- Fixed issue where setting course for the destination system wasn't actually setting the course.
- Bulletin Board was not resetting itself correctly between views.
- Fixed issue where the space between accepted and available missions was not appearing if there were only 1 of each type in the list.
- Added a confirmation screen to the terminate mission process.
- Added a "Set course for" option to the mission briefing page.
- Added the "confirmCompleteCallback" callback function, so that secondary steps can be confirmed before a mission can be accepted as complete. This would be useful if there is a possibility that something might have changed between completing the required steps of a mission, and getting to a dock to enter the "Complete Mission" response (eg loosing or selling cargo).

0.2
- Missions whose expiry time has already passed are now excluded from the list of available missions.
- Missions whose expiry time is extremely tight are now highlighted on the list of available missions and in the mission details as well.
- clock.adjustedSeconds now used to calculate remaining time to complete mission.
- Spelling corrections.

0.1
- Initial release
