-----------------------------------
--This file modifies the Pilot Select UI into a full fledged Title Screen
-----------------------------------

(function()

    local topics = require('lib_ui_topics')
    local bta = require('btafunctions')
    local utils = require('lib_utils')

    --Creates the special functions used by the title screen
    topics.pilotselect.initialize:bind(1, function(message, context)

        local sideStories = require('sidestories')
        sideStories:loadGlobalData()

        if (#sideStories.unlocks > 0) then
            message.SideStories = sideStories.unlocks
        else
            message.SideStories = nil
        end

        local function start_clicked()
            message.Document:GetElementById("main_menu"):SetClass("hidden", false)
            message.Document:GetElementById("start_btn_cont"):SetClass("hidden", true)
            message.state = "menu"
        end
        message.start_clicked = start_clicked

        local function load_clicked()
            message.Document:GetElementById("pilot_select"):SetClass("hidden", false)
            message.Document:GetElementById("main_menu"):SetClass("hidden", true)
            message.state = "select"
        end
        message.load_clicked = load_clicked

        local function stories_clicked()
            message.Document:GetElementById("stories_bg"):SetClass("hidden", false)
            message.Document:GetElementById("main_menu"):SetClass("hidden", true)
            message.Document:GetElementById("stories_view_inner").scroll_top = 0
            message.Document:GetElementById("stories_list_inner").scroll_top = 0
            ScpuiSystem:uncheckChildren(message.Document:GetElementById("list_stories_ul"))
            message.Document:GetElementById("stories_view").first_child.inner_rml = ""
            message.state = "stories"
        end
        message.stories_clicked = stories_clicked

        local function links_clicked()
            message.Document:GetElementById("external_links"):SetClass("hidden", false)
            message.Document:GetElementById("main_menu"):SetClass("hidden", true)
            message.Document:GetElementById("link_list_wrapper").scroll_top = 0
            message.state = "links"
        end
        message.links_clicked = links_clicked

        local function credits_clicked()
            ScpuiSystem:beginSubstate("Credits")
        end
        message.credits_clicked = credits_clicked

        local function info_clicked()
            message.Document:GetElementById("licensing"):SetClass("hidden", false)
            message.Document:GetElementById("main_menu"):SetClass("hidden", true)
            message.state = "info"
        end
        message.info_clicked = info_clicked

        local function quit_clicked()
            ba.postGameEvent(ba.GameEvents["GS_EVENT_QUIT_GAME"])
        end
        message.quit_clicked = quit_clicked

        local function GetTextFromFile(file)
            local lang = ba.getCurrentLanguageExtension()
            local candidate = file

            if lang ~= "" then
                local base, ext = file:match("^(.*)%.([^%.]+)$")
                if base and ext then
                    candidate = base .. "-" .. lang .. "." .. ext
                else
                    candidate = file .. "-" .. lang
                end
            end

            local function tryOpen(path)
                if not cf.fileExists(path, "data/fiction") then
                    return nil
                end
                local f = cf.openFile(path, "rb", "data/fiction")
                local t = f:read("*a") or ""
                f:close()
                return t
            end

            local text = tryOpen(candidate)
            if text ~= nil then
                return text
            end

            -- Fallback to the base language file
            text = tryOpen(file)
            return text or ""
        end
        message.GetTextFromFile = GetTextFromFile

        local function SelectStory(entry)
            ScpuiSystem:uncheckChildren(message.Document:GetElementById("list_stories_ul"))
            local list_el = message.Document:GetElementById(entry.Title)
            list_el:SetPseudoClass("checked", true)
            if not entry.Seen then
                list_el:RemoveChild(list_el.first_child)
                entry.Seen = true
                sideStories:saveSeen(entry)
            end

            local text = message.GetTextFromFile(entry.Filename)
            local story_el = message.Document:GetElementById("stories_view").first_child
            story_el.inner_rml = text
            story_el.scroll_top = 0
        end
        message.SelectStory = SelectStory

        local function CreateStoryItem(entry, index)
            local li_el = message.Document:CreateElement("li")
            local new_el = "<span class=\"new_text\">NEW! </span>"
            local vis_name = "<span>" .. ba.XSTR(entry.Title, entry.Xstr) .. "</span>"

            --Maybe append "NEW!" to non-heading entries
            if not entry.Seen then
                vis_name = new_el .. vis_name
            end

            li_el.inner_rml = vis_name
            li_el.id = entry.Title

            li_el:SetClass("list_element", true)

            li_el:SetClass("button_1", true)
            li_el:AddEventListener("click", function(_, _, _)
                message.SelectStory(entry)
            end)

            return li_el
        end
        message.CreateStoryItem = CreateStoryItem

        local function CreateStoriesList()
            local list_el = message.Document:GetElementById("list_stories_ul")
            ScpuiSystem:clearEntries(list_el)

            for i, v in ipairs(message.SideStories) do
                list_el:AppendChild(message.CreateStoryItem(v, i))
            end
        end
        message.CreateStoriesList = CreateStoriesList

        local function LaunchURL(url)
            ui.launchURL(url)
        end
        message.LaunchURL = LaunchURL

        local function buildLinksHeader(context, title)
            local li_el = context.Document:CreateElement("li")
            li_el.inner_rml = "<span class=\"white bold\">" .. utils.xstr(title) .. "</span>"
            li_el:SetClass("link_list_header", true)
            return li_el
        end
        message.buildLinksHeader = buildLinksHeader

        local function buildLinksItem(context, text, links)
            local li_el = context.Document:CreateElement("li")
            li_el.inner_rml = text
            li_el:SetClass("link_list_item", true)

            for _, link in pairs(links) do
                local link_el = context.Document:CreateElement("li")
                link_el.inner_rml = link
                link_el:SetClass("button_1", true)
                link_el:SetClass("link", true)
                link_el:AddEventListener("click", function(_, _, _)
                context.LaunchURL(link)
                end)
                li_el:AppendChild(link_el)
            end
            return li_el
        end
        message.buildLinksItem = buildLinksItem

        local function GetLinks(parent_el)
            local list_el = parent_el.first_child
            ui.TechRoom.buildCredits()
            local credits = ui.TechRoom.Credits.Complete
            local _, endIndex = string.find(credits, "VOICE ACTING")

            if endIndex then
                credits = string.sub(credits, endIndex + 1)
            end

            local startIndex, _ = string.find(credits, "CUTSCENES")

            if startIndex then
                credits = string.sub(credits, 1, startIndex - 1)
            end

            --Remove the dash headers
            credits = credits:gsub("----------------------------------", "")

            --Now split up the data and make a table
            local voiceData = {}
            local currentVoice = ""

            for line in credits:gmatch("[^\n]+") do
                if line:find("~") then
                    local value, key = line:match("([^~]+) ~ (.+)")
                    if key and value then
                        local tbl = {}
                        if voiceData[key] then
                            tbl = voiceData[key]
                        end
                        local utils = require("lib_utils")
                        if not utils.table.contains(tbl, value) then
                            table.insert(tbl, value)
                            voiceData[key] = tbl
                        end
                    end
                else
                    currentVoice = line:match("-(.-)-")
                end
            end

            --do backflips to sort the table by key value
            local sortedKeys = {}
            for key in pairs(voiceData) do
                table.insert(sortedKeys, key)
            end
            table.sort(sortedKeys)

            --Get the links table
            local linksTable = bta:parseLinks("credits_links.tbl")

            list_el:AppendChild(message.buildLinksHeader(message, {"Between the Ashes Links", 10849}))
            for k, v in pairs(linksTable.generalLinks) do
                list_el:AppendChild(message.buildLinksItem(message, k, v))
            end

            list_el:AppendChild(message.buildLinksHeader(message, {"Asset Source Links", 10848}))
            for k, v in pairs(linksTable.otherLinks) do
                list_el:AppendChild(message.buildLinksItem(message, k, v))
            end

            list_el:AppendChild(message.buildLinksHeader(message, {"Music Source Links", 10847}))
            for k, v in pairs(linksTable.musicLinks) do
                list_el:AppendChild(message.buildLinksItem(message, k, v))
            end

            list_el:AppendChild(message.buildLinksHeader(message, {"Voice Actor Links", 10846}))

            --Build the voice actor links list
            for _, k in pairs(sortedKeys) do
                if linksTable.voiceLinks[k] ~= nil then
                    local tbl = voiceData[k]
                    local text =  "<p><span class=\"bold\">" .. k .. "</span>&nbsp;<span class=\"italic\">("
                    for i, v in ipairs(tbl) do
                        text = text .. v
                        if i < #tbl then
                            text = text .. ", "
                        end
                    end
                    text = text .. ")</span></p>"
                    list_el:AppendChild(message.buildLinksItem(message, text, linksTable.voiceLinks[k]))
                end
            end
        end
        message.GetLinks = GetLinks

        local function play_sfx()
            local async_util = require("lib_async")
            async.run(function()
                async.await(async_util.wait_for(15))
                if message.state ~= "stories" then
                    message.voice_handle = ad.openAudioStream("bta1_m2_09L_ms25.ogg", AUDIOSTREAM_VOICE)
                    message.voice_handle:play(utils.clamp(ad.MasterVoiceVolume - 0.7, 0.1, 1), false)
                end
            end, async.OnFrameExecutor)

            async.run(function()
                async.await(async_util.wait_for(60))
                if message.voice_handle then
                    message.voice_handle:close()
                end
                if message.state ~= "stories" then
                    message.voice_handle = ad.openAudioStream("bta1_m2_09L_ms63.ogg", AUDIOSTREAM_VOICE)
                    message.voice_handle:play(utils.clamp(ad.MasterVoiceVolume - 0.7, 0.1, 1), false)
                end
            end, async.OnFrameExecutor)

            async.run(function()
                async.await(async_util.wait_for(180))
                message.play_sfx()
            end, async.OnFrameExecutor)
        end
        message.play_sfx = play_sfx

        local function return_to_start()
            message.Document:GetElementById("pilot_select"):SetClass("hidden", true)
            message.Document:GetElementById("main_menu"):SetClass("hidden", true)
            message.Document:GetElementById("start_btn_cont"):SetClass("hidden", false)
            message.state = "start"
        end
        message.return_to_start = return_to_start

        local function return_to_menu()
            message.Document:GetElementById("pilot_select"):SetClass("hidden", true)
            message.Document:GetElementById("licensing"):SetClass("hidden", true)
            message.Document:GetElementById("external_links"):SetClass("hidden", true)
            message.Document:GetElementById("stories_bg"):SetClass("hidden", true)
            message.Document:GetElementById("start_btn_cont"):SetClass("hidden", true)
            message.Document:GetElementById("main_menu"):SetClass("hidden", false)
            message.state = "menu"
        end
        message.return_to_menu = return_to_menu

        local function uncheck_menu_items()
            message.Document:GetElementById("load_btn"):SetPseudoClass("checked", false)
            message.Document:GetElementById("stories_btn"):SetPseudoClass("checked", false)
            message.Document:GetElementById("links_btn"):SetPseudoClass("checked", false)
            message.Document:GetElementById("credits_btn"):SetPseudoClass("checked", false)
            message.Document:GetElementById("info_btn"):SetPseudoClass("checked", false)
            message.Document:GetElementById("quit_btn"):SetPseudoClass("checked", false)
        end
        message.uncheck_menu_items = uncheck_menu_items

        local function menu_down()
        message.uncheck_menu_items()
        ui.playElementSound(message.start_button, "click", "success")
            if message.menu_choice == "load" then
                if message.SideStories then
                    message.menu_choice = "stories"
                    message.Document:GetElementById("stories_btn"):SetPseudoClass("checked", true)
                else
                    message.menu_choice = "links"
                    message.Document:GetElementById("links_btn"):SetPseudoClass("checked", true)
                end
            elseif message.menu_choice == "stories" then
                message.menu_choice = "links"
                message.Document:GetElementById("links_btn"):SetPseudoClass("checked", true)
            elseif message.menu_choice == "links" then
                message.menu_choice = "credits"
                message.Document:GetElementById("credits_btn"):SetPseudoClass("checked", true)
            elseif message.menu_choice == "credits" then
                message.menu_choice = "info"
                message.Document:GetElementById("info_btn"):SetPseudoClass("checked", true)
            elseif message.menu_choice == "info" then
                message.menu_choice = "quit"
                message.Document:GetElementById("quit_btn"):SetPseudoClass("checked", true)
            else
                message.menu_choice = "load"
                message.Document:GetElementById("load_btn"):SetPseudoClass("checked", true)
            end
        end
        message.menu_down = menu_down

        local function menu_up()
            message.uncheck_menu_items()
            ui.playElementSound(message.start_button, "click", "success")
            if message.menu_choice == "quit" then
                message.menu_choice = "info"
                message.Document:GetElementById("info_btn"):SetPseudoClass("checked", true)
            elseif message.menu_choice == "info" then
                message.menu_choice = "credits"
                message.Document:GetElementById("credits_btn"):SetPseudoClass("checked", true)
            elseif message.menu_choice == "credits" then
                message.menu_choice = "links"
                message.Document:GetElementById("links_btn"):SetPseudoClass("checked", true)
            elseif message.menu_choice == "links" then
                if message.SideStories then
                    message.menu_choice = "stories"
                    message.Document:GetElementById("stories_btn"):SetPseudoClass("checked", true)
                else
                    message.menu_choice = "load"
                    message.Document:GetElementById("load_btn"):SetPseudoClass("checked", true)
                end
            elseif message.menu_choice == "stories" then
                message.menu_choice = "load"
                message.Document:GetElementById("load_btn"):SetPseudoClass("checked", true)
            else
                message.menu_choice = "quit"
                message.Document:GetElementById("quit_btn"):SetPseudoClass("checked", true)
            end
        end
        message.menu_up = menu_up

        local function menu_selected()
            if message.menu_choice == "load" then
                message.load_clicked()
                ui.playElementSound(message.start_button, "click", "success")
            elseif message.menu_choice == "stories" then
                message.stories_clicked()
                ui.playElementSound(message.start_button, "click", "success")
            elseif message.menu_choice == "links" then
                message.links_clicked()
                ui.playElementSound(message.start_button, "click", "success")
            elseif message.menu_choice == "credits" then
                message.credits_clicked()
                ui.playElementSound(message.start_button, "click", "success")
            elseif message.menu_choice == "info" then
                message.info_clicked()
                ui.playElementSound(message.start_button, "click", "success")
            elseif message.menu_choice == "quit" then
                message.quit_clicked()
                ui.playElementSound(message.start_button, "click", "success")
            end
        end
        message.menu_selected = menu_selected

    end)

    --Creates all the custom visual elements to change pilot select to a title screen
    topics.pilotselect.initialize:bind(2, function(message, context)

        --Hide the wide logo
        message.Document:GetElementById("logo_wide"):SetClass("hidden", true)

        local parent_el = ScpuiSystem:getRootParent(message.Document)
        local pilot_select_el = message.Document:GetElementById("pilot_select")
        pilot_select_el:SetClass("hidden", true)
        pilot_select_el.style["margin-top"] = "30%"

        local copyright_el = message.Document:GetElementById("copyright_info")
        copyright_el.style.margin = "1%"
        copyright_el.style["text-align"] = "left"

        --Add a back button to the pilot select window
        local back_btn_el, back_btn = ScpuiSystem:makeTextButton(message, "s_back_btn_cont", "s_back_btn", {"s_back", "button_1"}, "s_back_text", {"pos"}, ba.XSTR("Back", 9307))
        back_btn_el:AddEventListener("click", function(event, _, _)
            message.return_to_menu()
        end)
        back_btn_el.style.position = "absolute"
        back_btn_el.style.width = "50%"
        back_btn_el.style.left = "25%"
        back_btn_el.style.top = "110%"
        back_btn_el.style["text-align"] = "center"
        pilot_select_el:AppendChild(back_btn_el)

        --main background is a decorator affected by color, so add a div as an image on top
        local bg = ScpuiSystem:makeElement(message, "div", "title_background")
        bg.style.width = "0"
        bg.style.height = "0"

        local bg_img = ScpuiSystem:makeImg(message, "bg-titlescreen.png")
        bg_img.style.width = "100%"
        bg_img.style.height = "auto"
        bg_img.style.position = "absolute"

        bg:AppendChild(bg_img)
        parent_el:InsertBefore(bg, parent_el.first_child)

        --create the animated suns
        local ant_min_el = ScpuiSystem:makeElement(message, "div", "antares_minor")
        ant_min_el.style.width = "0"
        ant_min_el.style.height = "0"
        local ant_min_img = ScpuiSystem:makeImg(message, "antminor.png", true)
        ant_min_img.style.width = "8%"
        ant_min_img.style.height = "auto"
        ant_min_img.style.position = "absolute"
        ant_min_img.style.left = "85%"
        ant_min_img.style.top = "10%"
        local ant_maj_el = ScpuiSystem:makeElement(message, "div", "antares_major")
        ant_maj_el.style.width = "0"
        ant_maj_el.style.height = "0"
        local ant_maj_img = ScpuiSystem:makeImg(message, "antmajor.png", true)
        ant_maj_img.style.width = "60%"
        ant_maj_img.style.height = "auto"
        ant_maj_img.style.position = "absolute"
        ant_maj_img.style.left = "40%"
        ant_maj_img.style.top = "30%"
        local masada_el = ScpuiSystem:makeElement(message, "div", "masada_control")
        masada_el.style.width = "0"
        masada_el.style.height = "0"
        local masada_img = ScpuiSystem:makeImg(message, "masada.png", true)
        masada_img.style.width = "5%"
        masada_img.style.height = "auto"
        masada_img.style.position = "absolute"
        masada_img.style.left = "75%"
        masada_img.style.top = "75%"
        local title_el = ScpuiSystem:makeElement(message, "div", "main_title")
        title_el.style["font-family"] = "glitch inside"
        title_el.style.position = "absolute"
        title_el.style.top = "8%"
        title_el.style.left = "8%"
        title_el.style.color = "white"
        local title_text = ScpuiSystem:makeElement(message, "p")
        title_text.inner_rml = "Between The Ashes"
        title_text:SetClass("p2", true)

        ant_min_el:AppendChild(ant_min_img)
        ant_maj_el:AppendChild(ant_maj_img)
        masada_el:AppendChild(masada_img)
        title_el:AppendChild(title_text)

        parent_el:InsertBefore(ant_min_el, pilot_select_el)
        parent_el:InsertBefore(ant_maj_el, pilot_select_el)
        parent_el:InsertBefore(masada_el, pilot_select_el)
        parent_el:InsertBefore(title_el, pilot_select_el)

        --create the buttons
        local start_el, start_btn = ScpuiSystem:makeTextButton(message, "start_btn_cont", "start_btn", {"start", "button_1"}, "start_text", {"pos"}, ba.XSTR("START", 9308))
        start_el.style.width = "15%"
        start_el.style.position = "absolute"
        start_el.style.top = "55%"
        start_el.style.left = "9%"
        start_btn:AddEventListener("click", function(event, _, _)
            message.start_clicked()
        end)
        message.start_button = start_btn

        local load_el, load_btn = ScpuiSystem:makeTextButton(message, "load_btn_cont", "load_btn", {"load", "button_1"}, "load_text", {"pos"}, ba.XSTR("Load Pilot", 9309))
        load_el.style["margin-bottom"] = "5%"
        load_btn:AddEventListener("click", function(event, _, _)
            message.load_clicked()
        end)

        local stories = ba.XSTR("Side Stories", 10893)
        if message.SideStories then
            stories = stories .. " (" .. tostring(#message.SideStories) .. ")"
        end
        local stories_el, stories_btn = ScpuiSystem:makeTextButton(message, "stories_btn_cont", "stories_btn", {"stories", "button_1"}, "stories_text", {"pos"}, stories)
        stories_btn:AddEventListener("click", function(event, _, _)
            message.stories_clicked()
        end)

        local links_el, links_btn = ScpuiSystem:makeTextButton(message, "links_btn_cont", "links_btn", {"links", "button_1"}, "links_text", {"pos"}, ba.XSTR("Links & Resources", 9310))
        links_btn:AddEventListener("click", function(event, _, _)
            message.links_clicked()
        end)

        local credits_el, credits_btn = ScpuiSystem:makeTextButton(message, "credits_btn_cont", "credits_btn", {"credits", "button_1"}, "credits_text", {"pos"}, ba.XSTR("View Credits", 9311))
        credits_btn:AddEventListener("click", function(event, _, _)
            message.credits_clicked()
        end)

        local info_el, info_btn = ScpuiSystem:makeTextButton(message, "info_btn_cont", "info_btn", {"info", "button_1"}, "info_text", {"pos"}, ba.XSTR("Licensing & Info", 9312))
        info_btn:AddEventListener("click", function(event, _, _)
            message.info_clicked()
        end)

        local quit_el, quit_btn = ScpuiSystem:makeTextButton(message, "quit_btn_cont", "quit_btn", {"quit", "button_1"}, "quit_text", {"pos"}, ba.XSTR("Quit Game", 9313))
        quit_btn:AddEventListener("click", function(event, _, _)
            message.quit_clicked()
        end)

        local menu_el = ScpuiSystem:makeElement(message, "div", "main_menu")
        menu_el.style.position = "absolute"
        menu_el.style.top = "25%"
        menu_el.style.left = "10%"
        menu_el.style.width = "30%"
        menu_el.style.height = "auto"
        menu_el.style.overflow = "hidden"
        menu_el:SetClass("hidden", true)

        menu_el:AppendChild(load_el)
        menu_el:AppendChild(stories_el)
        menu_el:AppendChild(links_el)
        menu_el:AppendChild(credits_el)
        menu_el:AppendChild(info_el)
        menu_el:AppendChild(quit_el)

        if not message.SideStories then
            stories_el:SetClass("hidden", true)
        end

        parent_el:InsertBefore(start_el, pilot_select_el)
        parent_el:InsertBefore(menu_el, pilot_select_el)

        --Create the licensing div and text
        local licensing_el = ScpuiSystem:makeElement(message, "div", "licensing")
        licensing_el:SetClass("hidden", true)
        licensing_el.style.width = "47%"
        licensing_el.style.height = "auto"
        licensing_el.style.position = "absolute"
        licensing_el.style.left = "3%"
        licensing_el.style.top = "25%"
        licensing_el.style["text-align"] = "center"
        local licensing_text = ScpuiSystem:makeElement(message, "div", "license_text")
        licensing_text.inner_rml = bta:GetLicensing()
        local licensing_btn_el, licensing_btn = ScpuiSystem:makeTextButton(message, "l_back_btn_cont", "l_back_btn", {"l_back", "button_1"}, "l_back_text", {"pos"}, ba.XSTR("Back", 9307))
        licensing_btn:AddEventListener("click", function(event, _, _)
            message.return_to_menu()
        end)

        licensing_el:AppendChild(licensing_text)
        licensing_el:AppendChild(licensing_btn_el)
        parent_el:InsertBefore(licensing_el, pilot_select_el)

        --Create the stories divs and elements
        local stories_bg_el = ScpuiSystem:makeElement(message, "div", "stories_bg")
        stories_bg_el:SetClass("hidden", true)
        stories_bg_el.style["background-color"] = "#000000e6"
        stories_bg_el.style.position = "absolute"
        stories_bg_el.style.width = "100%"
        stories_bg_el.style.height = "100%"

        local stories_list_el = ScpuiSystem:makeElementPanel(message, "stories_list", "tech-room-list-window.png")
        stories_list_el.style.position = "absolute"
        stories_list_el.style.top = "30%"
        stories_list_el.style.left = "15%"
        stories_list_el.style.width = "20%"
        stories_list_el.style.height = "auto"
        stories_list_el.first_child:AppendChild(ScpuiSystem:makeElement(message, "ul", "list_stories_ul"))
        stories_list_el.first_child.style.top = "5%"
        stories_list_el.first_child.style.left =  "13%"
        stories_list_el.first_child.style.width =  "85%"
        stories_list_el.first_child.style.height =  "90%"
        stories_list_el.first_child.style.overflow =  "scroll"

        --parent_el:InsertBefore(stories_list_el, pilot_select_el)

        local stories_view_el = ScpuiSystem:makeElementPanel(message, "stories_view", "debrief-window.png")
        stories_view_el.style.position = "absolute"
        stories_view_el.style.top = "16%"
        stories_view_el.style.left = "37%"
        stories_view_el.style.width = "50%"
        stories_view_el.style.height = "auto"
        stories_view_el.first_child.style.overflow = "scroll"
        stories_view_el.first_child.style.top = "2%"
        stories_view_el.first_child.style.left =  "9%"
        stories_view_el.first_child.style.width =  "84%"
        stories_view_el.first_child.style.height =  "90%"

        local stories_btn_el, stories_btn = ScpuiSystem:makeTextButton(message, "s_back_btn_cont", "s_back_btn", {"l_back", "button_1"}, "l_back_text", {"pos"}, ba.XSTR("Back", 9307))
        stories_btn_el.style.position = "absolute"
        stories_btn_el.style.top = "25%"
        stories_btn_el.style.left = "15%"
        stories_btn_el:SetClass("h1", true)
        stories_btn_el:AddEventListener("click", function(event, _, _)
            message.return_to_menu()
        end)

        stories_bg_el:AppendChild(stories_list_el)
        stories_bg_el:AppendChild(stories_view_el)
        stories_bg_el:AppendChild(stories_btn_el)

        parent_el:InsertBefore(stories_bg_el, pilot_select_el)

        if message.SideStories then
            message.CreateStoriesList()
        end

        --Create the links list div and text
        local links_el = ScpuiSystem:makeElement(message, "div", "external_links")
        links_el:SetClass("hidden", true)
        links_el.style.width = "54%"
        links_el.style.position = "absolute"
        links_el.style.left = "7%"
        links_el.style.top = "18%"
        links_el.style["text-align"] = "left"
        local links_img = ScpuiSystem:makeImg(message, "select-window-right.png")
        links_img.style.display = "block"
        links_img.style.width = "100%"
        links_img.style.height = "auto"
        local links_wrap = ScpuiSystem:makeElement(message, "div", "link_list_wrapper")
        links_wrap.style.height = "91.5%"
        links_wrap.style.overflow = "scroll"
        links_wrap.style.position = "absolute"
        links_wrap.style.top = "8%"
        links_wrap.style.left = "3%"
        local links_list = ScpuiSystem:makeElement(message, "ul", "links_list")
        local links_btn_el, links_btn = ScpuiSystem:makeTextButton(message, "el_back_btn_cont", "el_back_btn", {"el_back", "button_1"}, "el_back_text", {"pos"}, ba.XSTR("Back", 9307))
        links_btn:AddEventListener("click", function(event, _, _)
            message.return_to_menu()
        end)
        links_btn_el.style.position = "absolute"
        links_btn_el.style.top = "1%"
        links_btn_el.style.left = "1%"

        links_wrap:AppendChild(links_list)
        links_el:AppendChild(links_wrap)
        links_el:AppendChild(links_btn_el)
        links_el:AppendChild(links_img)
        message.GetLinks(links_el)

        parent_el:InsertBefore(links_el, pilot_select_el)

        title_el:SetClass("h3", true)
        start_btn:SetClass("h1", true)
        menu_el:SetClass("h1", true)
        licensing_text:SetClass("p1", true)
        links_el:SetClass("p1", true)

        message.state = "start"

        if ScpuiSystem.MainMenuReturn then
            message.start_clicked()
            ScpuiSystem.MainMenuReturn = nil
        end

        --Start the audio effects
        ad.stopMusic(0, true, "mainhall") --Stop any mainhall music
        ui.MainHall.stopAmbientSound() --Stop any mainhall ambiance
        ScpuiSystem.data.memory.MusicHandle = ad.openAudioStream("titlescreenaudio.ogg", AUDIOSTREAM_MENUMUSIC)
        ScpuiSystem.data.memory.MusicHandle:play(ad.MasterEventMusicVolume / 6, true)
        message.play_sfx()
    end)

    topics.pilotselect.startsound:bind(9999, function(message, context)
        context.value = false
    end)

    topics.pilotselect.escKeypress:bind(9999, function(message, context)
        context.value = false
        if message.state == "start" then
            ba.postGameEvent(ba.GameEvents["GS_EVENT_QUIT_GAME"])
        elseif utils.isOneOf(message.state, "select", "info", "links", "stories") then
            message.return_to_menu()
        else --catch all
            message.return_to_start()
        end
    end)

    topics.pilotselect.upKeypress:bind(9999, function(message, context)
        context.value = false
        if message.state == "select" then
            message:down_button_pressed()
        end
    end)

    topics.pilotselect.dwnKeypress:bind(9999, function(message, context)
        context.value = false
        if message.state == "select" then
            message:up_button_pressed()
        end
    end)

    topics.pilotselect.retKeypress:bind(9999, function(message, context)
        context.value = false
        if message.state == "select" then
            message:commit_pressed()
        end
    end)

    topics.pilotselect.delKeypress:bind(9999, function(message, context)
        context.value = false
        if message.state == "select" then
            message:delete_player()
        end
    end)

    topics.pilotselect.globalKeypress:bind(9999, function(message, context)
        if message[1].state == "start" and message[2].parameters.key_identifier ~= rocket.key_identifier.ESCAPE then
            message[1].start_clicked()
            ui.playElementSound(message[1].start_button, "click", "success")
        elseif message[1].state == "links" then
            if message[2].parameters.key_identifier == rocket.key_identifier.UP then
                ScpuiSystem:scrollUp(message[1].Document:GetElementById("link_list_wrapper"))
            elseif message[2].parameters.key_identifier == rocket.key_identifier.DOWN then
                ScpuiSystem:scrollDown(message[1].Document:GetElementById("link_list_wrapper"))
            end
        elseif message[1].state == "menu" then
            if message[2].parameters.key_identifier == rocket.key_identifier.UP then
                message[1].menu_up()
            elseif message[2].parameters.key_identifier == rocket.key_identifier.DOWN then
                message[1].menu_down()
            elseif message[2].parameters.key_identifier == rocket.key_identifier.RETURN then
                message[1].menu_selected()
            end
        end
    end)

    --Make sure the player is in single player mode
    topics.pilotselect.commit:bind(9999, function(message, context)
        message:set_player_mode(nil, "single")
    end)

    topics.pilotselect.unload:bind(9999, function(message, context)
        if message.voice_handle ~= nil then
            message.voice_handle:close()
        end
        if ScpuiSystem.data.memory.MusicHandle ~= nil then
            ScpuiSystem.data.memory.MusicHandle:close()
        end
    end)

  end)()