#####################################################################
#                SUPPORT FUNCTIONS
#####################################################################
screen header(*args):
    # zorder 100
    image "05_gui/gui_header_bar.png"
    frame xsize 1920 ysize 60 background Solid("#00000000"):
        hbox spacing 5 xalign 0.5 yalign 0.5:
            text "Day {}".format(GAME.day) size FSIZE
            text " {}:00".format(GAME.hour) size FSIZE
            text "|  {}".format(GAME.getSpaceLoc().name) size FSIZE
            text "|  {}".format(GAME.ship.status.title()) size FSIZE
            text "|  {:,} Cr".format(GAME.money) size FSIZE
            if "seen manifest" in GAME.mc.done:
                $ cloakInfo = ""
                if GAME.ship.cargoLimitCloak():
                    $ cloakInfo = " ({}t Cloaked)".format(GAME.ship.cargoLimitCloak())
                text "|  {} of {}t{}".format(GAME.ship.cargoLoaded(), GAME.ship.cargoLimit(), C_SU_B+cloakInfo+C_SU_E) size FSIZE
            if GAME.mc.hasItem("ITMControlBand"):
                text "|  Captain {} - {}".format(GAME.mc.name[:12], GAME.mc.getRating()) size FSIZE
                #text "| AP: {}".format(GAME.ap) size FSIZE

screen console_overlay():
    default console_active = False
    zorder 100
    key ["u", "U"] action ToggleScreenVariable("console_active")

    if console_active:
        frame xsize 900 ysize 600 xalign 1.0 pos 1880, 120 padding 20,20 background Solid("#45B39D88"):
            vbox xsize 900: 
                text "- - - CONSOLE - - - [[u] to close - - -\n" size FSIZE_MED
                for i in GAME.consoleGet()[-25:]:
                    text "{}".format(i) size FSIZE_MED     

#####################################################################
#                VERSION CHECK
#####################################################################
label version_check():
    if GAME.version == 0:
        $ GAME.version = str(config.version)
    elif GAME.version.split("_")[0] != config.version.split("_")[0]:
        play sound "audio/notify.wav"
        call large_notify("CONFIGURATION WARNING", "You are using a save game, which is unfortunately not compatible with this version '{}'.\n\nYou will be missing new features and new content with your old save game. Data corruption will most likely occur, if you continue. (Hint: Use the multiverse pod to transfer items from any V0.4+ save)".format( C_GR_B+config.version+C_GR_E), ["To Start"], False, "red") from _call_large_notify_104 
        if _return == "To Start":
            scene intermission with fade
            $ renpy.full_restart()
    return()


#####################################################################
#					GUI PRESENT SPRITES		
#####################################################################
screen displayPresentActors(loc):
    $ aElems = [x for x in GAME.aElem.values() if x.loc == loc]
    $ aElems.sort(key = lambda x : x.ID)
    for i in aElems: 
        if eval(i.cond) and "sprite" in i.tags:
            image "{}_smart_idle".format(i.ID) pos i.coord    

#####################################################################
#					GUI SPRITE								        #
#####################################################################
screen showActiveElem(activeElemID):
    $ aElem = GAME.aElem[activeElemID]
    image "{}_smart_idle".format(activeElemID) pos aElem.coord[0], aElem.coord[1]

#####################################################################
#                SKILL AND ATTRIBUTES
#####################################################################

label attr_mod(actor, attr, amount, limit, prob, verbose=True):
    if attr not in actor.attr.keys():
        $ actor.attr[attr] = 0
    if random.randint(1,100) > prob:
        return(-1)
    if actor == GAME.mc:
        $ name = "Your"
    else:
        $ name = actor.name+"'s"

    if amount < 0:
        $ C_B, C_E = C_RE_B, C_RE_E
        if attr in ["STS"]:
            $ C_B, C_E = C_GR_B, C_GR_E
        $ amount = max(-(actor.attr[attr]-limit), amount)
        $ message = C_B+"{} {} has decreased! ({} {})".format(name, GAME.attr[attr].lower(), amount, GAME.attr[attr])+C_E
        if actor.attr[attr] <= limit:
            return(-2)
    else:
        $ C_B, C_E = C_GR_B, C_GR_E
        if attr in ["STS"]:
            $ C_B, C_E = C_RE_B, C_RE_E
        $ amount = min(-(actor.attr[attr]-limit), amount)
        $ message = C_B+"{} {} has increased! (+{} {})".format(name, GAME.attr[attr].lower(), amount, GAME.attr[attr])+C_E
        if actor.attr[attr] >= min(limit, actor.getAttrMax(attr)):
            return(-3)
        $ GAME.mc.exp += amount * 20

    $ actor.setAttr(attr, capValue(actor.getAttr(attr) + amount, 0,100)) 
    
    if verbose:
        queue sound "audio/notify.wav"
        "[message]"
    return(True)

#####################################################################
#                ITEMS
#####################################################################
screen item_show_scr(items, header = "INVENTORY", mode = "interact", cRows = 10, itemIDsEmphasize = []):

    frame xsize 908 ysize 70 background Solid("#0099cc55") pos 540, 90
    text C_WH_B+"{}".format(header)+C_WH_E size FSIZE_LARGE pos 960, 100 xalign 0.5
    if mode == "interact":
        modal True

    #####################################################################
    #                EXIT BUTTON
    #####################################################################
    frame xsize 350 ysize 64 pos 0,900 background Solid("#00000000") padding 0,0:
        image "05_gui/gui_menu_option.png" yalign 0.5
        button action Return(False)xpos 20
        textbutton "Exit (X)" yalign 0.5 action Return(False)xpos 20
        # key "x" action Return (False)
        # key "X" action Return (False)
        key ("x", "i", "X", "I") action Return (False)

    side "c r":
        area 540,200,1000,768
        viewport id "vp":
            draggable True
            mousewheel True
            #frame background Solid ("#00000088"):
            #    pass

            grid 7 cRows spacing 2:


                $ itemsU = list(set(items))
                $ itemsU = sorted(itemsU, key=lambda x: x.getKey())
                for i in range(7 * cRows):
                    frame xsize 128 ysize 128 background Solid("#0099cc55"):
                        # image "08_items/ico bg1.png" zoom 0.25 yalign 0.5 xalign 0.5
                        if i < len(itemsU):
                            image "{}{}".format(itemsU[i].getPath(), itemsU[i].getIco()) zoom 0.25 yalign 0.5 xalign 0.5
                            if items.count(itemsU[i])>1:
                                text "{}x".format(items.count(itemsU[i])) size FSIZE
                            if mode == "interact":
                                button action Return(itemsU[i]) tooltip itemsU[i]
                            else:
                                button action NullAction() tooltip itemsU[i]
                            if itemsU[i].ID in itemIDsEmphasize:
                                image "05_gui/check.png" zoom 0.5 xalign -0.1 yalign 1.1

                        else:
                            text " "
                            #image "08_items/ico bg1.png" zoom 0.25 yalign 0.5

        vbar value YScrollValue("vp")

    $ tooltip = GetTooltip()
    if tooltip and isinstance(tooltip, Item): # CR-0498 paranoid check
        frame padding 20,20 xsize 560 ysize 920 pos 50 , 204 background Solid("#39210000"):
            image "08_items/ico bg1.png" zoom 0.75
            image "{}/{}".format(tooltip.getPath(),tooltip.getIco()) zoom 0.75
            vbox xsize 430 ypos 380 xpos -25 spacing 20:
                text tooltip.getName(["col", "cap", "noArt"]) xalign 0.5
                text tooltip.description xalign 0.5 size FSIZE
                text "Value: {:,} Cr".format(tooltip.price) xalign 0.5 size FSIZE
    
    # CR-2018 START
    elif tooltip and isinstance(tooltip, SexbotPart): # CR-0498 paranoid check
        frame padding 20,20 xsize 560 ysize 920 pos 40 , 200 background Solid("#39210000"):
            image "08_items/ico bg1.png" zoom 0.5 xpos 50 ypos 100
            image "{}/{}".format(tooltip.getPath(),tooltip.getIco()) zoom 0.5 xpos 50 ypos 100
            vbox xsize 440 ypos 420 xpos -25 spacing 10:
                text tooltip.getName() xalign 0.5 size FSIZE
                text tooltip.getDesc() xalign 0.5 size FSIZE
                if tooltip.getBoostOneLiner():
                    text tooltip.getBoostOneLiner() xalign 0.0 size FSIZE
                text "Value: {:,} Cr".format(int(tooltip.getPrice())) xalign 0.5 size FSIZE
    else:
        frame padding 20,20 xsize 560 ysize 920 pos 1300, 244 background Solid("#39210000"):
            text " "
            #image "08_items/ico bg1.png" zoom 0.25 yalign 0.5
    # CR-2018 END

# CR-2105 START
label item_show(items, kinds = False, mTitle = "INVENTORY", itemsExclude = [], itemsForce = [], itemIDsEmphasize = []):
    # show items
    $ result = False
    $ mask = "05_gui/mask 50.png"
    show image mask
    play sound "audio/click.wav"
    if kinds:
        $ items = [x for x in items if x.kind in kinds and x.ID not in itemsExclude]
    elif itemsForce:
        $ items = [x for x in items if x.ID in itemsForce]
        
    call screen item_show_scr(items, mTitle, "interact", 10, itemIDsEmphasize)

    if _return:
        play sound "audio/{}".format(_return.getSound())
        $ result = _return
    hide image mask
    return(result)
    # CR-2105 END
    
#OhWee mod code

screen subunit_popup_screen(matrixPos2):

    #$ matrixPos2 = globals()["matrixPos2"]

    modal True

    add "05_gui/mask 50.png"

    $ cRows = [0, 120, 240]
    $ cCols = [0, 110, 220, 330]
    
    #if click elsewhere
    button action Hide("subunit_popup_screen")
        
    frame xsize 96 pos 630+cCols[matrixPos2[1]]+72, 260+cRows[matrixPos2[0]]+74:
    
        vbox:
            $ itemID = {0: "ITMAICore", 1: "ITMPositron", 2:"ITMFlux", 3:"ITMOutput"}[matrixPos2[1]]
            $ subunittype = itemID

                
            
            $ itemsU = [x for x in GAME.ship.cargo if subunittype in x.ID]
            $ itemsUCount = len(itemsU)
            if subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] == 1:
                $ itemsUCount += 1
                
            if itemsUCount > 0:
                fixed xsize 80 ysize 80:
                    $ subsys_imagepath = "08_items/ico " + itemID + ".png"
                    image subsys_imagepath zoom 0.25 yalign 0.5 xalign 0.5
                    if itemsUCount > 1:
                        text str(itemsUCount) size FSIZE
                    button action Return(["subunit2", 1, matrixPos2, itemID]) tooltip itemID
                    
                    
            $ itemsT = [x for x in GAME.ship.cargo if "ITMTunneling" in x.ID]
            $ itemsTCount = len(itemsT)
            if subSys[subSystems[0]][matrixPos2[0]+1][matrixPos2[1]] == 9:
               $ itemsTCount += 1
            if itemsTCount > 0:
                fixed xsize 80 ysize 80:
                    $ subsys_imagepath = "08_items/ico " + "ITMTunneling" + ".png"
                    image subsys_imagepath zoom 0.25 yalign 0.5 xalign 0.5
                    if itemsTCount > 0:
                        text str(itemsTCount) size FSIZE
                        if itemsTCount > 1:
                            text str(itemsTCount) size FSIZE
                    
                    button action Return(["subunit2", 9, matrixPos2, itemID]) tooltip "ITMTunneling"
                    
                    
            fixed xsize 80 ysize 80:
                text "NONE" size FSIZE xalign 0.5 yalign 0.5
                
                button action Return(["subunit2", 0, matrixPos2, itemID])
                
                
screen plating_popup_screen(plateQuad, plateSlot):

    add "05_gui/mask 50.png"

    $ plating_types = ["ITMUnderversePlating", "ITMPhasicPlating", "ITMInferniumPlating", "ITMXenoCeramPlating", "ITMBoronPlating", "ITMDuraniumPlating"]
    #$ platePos = {"bow":[1375, 630], "stern":[1375, 930], "starboard": [1760, 715], "port": [1250, 715]}
    
    #if click elsewhere
    button action Hide("plating_popup_screen")
    
    frame pos 1423, 805 yanchor 0.5:
        
        has vbox   
        
        text "\nSELECT PLATING TYPE\nTO INSTALL" size FSIZE xalign 0.5 text_align 0.5
    
        vpgrid:
            cols 3
                
            for p in plating_types:
                $ platingID = "SS{}".format(plateQuad.title())
                $ itemsP = [x for x in GAME.ship.cargo if p in x.ID]
                $ itemsPCount = len(itemsP)
                if GAME.ship.subSys_NEW[platingID].slotsPlating[plateSlot] != None:
                    if GAME.ship.subSys_NEW[platingID].slotsPlating[plateSlot].ID == p:
                        $ itemsPCount += 1
                    
                if itemsPCount > 0:
                    fixed xysize 90,90:
                        image "08_items/ico {}.png".format(p) zoom 0.25 xalign 0.5 yoffset -24
                        button action Return(["plating", p, plateQuad, plateSlot]) tooltip p
                        
                        if itemsPCount > 1:
                            text str(itemsPCount) size FSIZE
                        if GAME.ship.subSys_NEW[platingID].slotsPlating[plateSlot] != None:
                            if GAME.ship.subSys_NEW[platingID].slotsPlating[plateSlot].ID == p:
                                text "Installed" size 20 yalign 1.0 xalign 0.5 color "#0ac"
                            
        hbox:
            fixed xysize 90,90:
                if GAME.ship.subSys_NEW[platingID].slotsPlating[plateSlot] != None:
                    #if GAME.ship.subSys_NEW[platingID].slotsPlating[plateSlot].ID == p:
                    text " REMOVE" yoffset 25
                else:
                    text "  NONE" yoffset 25
                    
                $ p1 = "Empty"
                button action Return(["plating", p1, plateQuad, plateSlot])
                
            fixed xysize 180,90:
                $ pSlot = str(plateSlot + 1)
                text "[plateQuad!c]  \n  Slot [pSlot]  " xalign 1.0 yalign 0.85 color "#0ac" size 24
    

#End OhWee mod code

#####################################################################
#                INTERACTIVE MENU 
#####################################################################
screen menu_interactive_scr(*args):
    $ mTitle = args[0]
    $ mCondOptions = args[1]
    $ mActiveElem = args[2]
    $ timeout = False
    if len(args) >= 4:
        $ timeout = args[3]

    $ mOptionsKeys = []
    $ mOptionsText = []

    $ mOptions = []
    # compile eligible Options
    for i in range(0,len(mCondOptions),2):
        if eval(mCondOptions[i+1]):
            $ mOptions.append(mCondOptions[i])

    for i in mOptions:
        $ parts = i.split("/")
        $ mOptionsText.append(parts[0])
        if len(parts) >=2:
            $ mOptionsKeys.append(parts[1])
        else:
            $ mOptionsKeys.append(False)

    if mTitle:
        frame xsize 1920 ysize 80 ypos 120 background Solid("#00000000"):
            text C_HI_B+mTitle+C_HI_E xalign 0.5 yalign 0.5 size FSIZE_LARGE

    # text options
    vbox spacing 40 xpos 0 ypos 1000 yalign 1.0:
        for i in  range(len(mOptions)):
            frame xsize 350 ysize 64 padding 0,0 background Solid("#00000000"):
                image "05_gui/gui_menu_option.png" yalign 0.5
                button action Return(mOptionsText[i])
                if mOptionsKeys[i]:
                    textbutton "{} ({})".format(mOptionsText[i], mOptionsKeys[i].upper())  action Return(mOptionsText[i]) yalign 0.5 xpos 20
                else:
                    textbutton "{}".format(mOptions[i])  action Return(mOptionsText[i]) yalign 0.5 xpos 20


    # Active Elements
    for i in mActiveElem:
        if eval(i.cond):
            $ xCoord = i.coord[0]
            $ yCoord = i.coord[1]
            if "frame" in i.tags:
                if "mouse" in i.attr.keys():
                    frame xsize 128 ysize 128 pos i.coord:
                        button action Return(["action", i]) mouse i.attr["mouse"]
                else:
                    frame xsize 128 ysize 128 pos i.coord:
                        button action Return(["action", i])

            elif "icon" in i.tags:
                imagebutton auto "{}_%s.png".format(i.ID) focus_mask True pos i.coord action Return(i.name)
                text i.name size FSIZE xpos i.coord[0]+64 ypos i.coord[1]+140 xalign 0.5

            elif "button" in i.tags: # xxx
                $ bX = i.attr["dim"][0]
                $ bY = i.attr["dim"][1]
                frame pos i.coord background Solid("#00000000") xsize bX ysize bY padding 0,0:
                    imagebutton auto "{}_%s.png".format(i.ID) focus_mask True action Return(i.name)
                    text "{}".format(i.attr["label"]) size FSIZE xalign 0.5 yalign 0.5

            else:
                imagebutton auto "{}_smart_%s".format(i.ID) focus_mask True pos i.coord action Return(["action", i])

    # timers 
    if timeout:
        timer timeout action Return("timeout")

    # Keys
    for k in range(len(mOptionsKeys)):
        if mOptionsKeys[k]:
            key mOptionsKeys[k] action Return(mOptionsText[k])


screen gallery_view(galleryItem):
    if galleryItem.anim == None:
        image "20_gallery/gallery {}.jpg".format(galleryItem.ID)
    else:
        image galleryItem.anim
    # frame xsize 1280 ysize 60 xalign 0.5 yalign 0.5  background Solid("#ffffff00")
    text  galleryItem.name xalign 0.5 yalign 0.95 size 48 color "#ffffff88"
    key ["mouseup_1"] action Return()
    key "K_SPACE" action Return()

###########################################################################
# ANIMATION SCANNER INCREASING
###########################################################################

screen activity_bar(*args):
    $ title =  args[0]
    $ position = args[1]
    $ img = args[2]
    $ timeout = args[3]

    frame xsize 600 ysize 300 xalign 0.5 yalign 0.5 padding 20,20:
        $ barWidth = 400
        if img:
            image img xalign 0.5 zoom 0.5 ypos -40
        text "{}%".format(position*2) size 48 xalign 0.5 ypos 50  
        text title xalign 0.5 ypos 130 size FSIZE
        frame xsize barWidth ysize 34 xalign 0.5 ypos 180:
            bar value position range 50 xsize barWidth-6 ysize 28 yalign 0.5 xalign 0.5
        timer timeout action Return("timeout")

label activity_bar(title, img = False, timeout=0.1):
    show image "05_gui/mask 50.png"
    $ position = 0
    # Scanner loop until button pressed
    # play sound "sounds/scan_003.mp3"
    while not position >= 48:
        # move bar indicator on screen
        $ position += 2
        call screen activity_bar(title, position, img, timeout)
    hide image "05_gui/mask 50.png"
    return()

#####################################################################
#              GAME LOG
#####################################################################
screen quest_help_scr(guiHelpMode, gPage=1, tags = [], partialGallery):


    #image "05_gui/mask 50.png"
    hbox spacing 5 xalign 0.5 yalign 0.03:
        for i in [["Active Quests","Q", "quest log"], ["Gallery", "G", "gallery"], ["Mission Log", "M", "missions"]]:
            $ cPref, cSuff = C_GY_B, C_GY_E 
            if guiHelpMode == i[2]:
                $ cPref, cSuff = C_HI_B, C_HI_E 
            frame xsize 260 ysize 50 background Solid("#0099cc55"):
                button action Return(i[2]) 
                text cPref+"{} ({})".format(i[0], i[1])+cSuff  size FSIZE xalign 0.5 yalign 0.5

        key "q" action Return("quest log")
        key "g" action Return("gallery")
        key "m" action Return("missions")

    frame xsize 350 ysize 64 pos 0,950 background Solid("#00000000") padding 0,0:
        image "05_gui/gui_menu_option.png" yalign 0.5
        button action Return(False)xpos 20
        textbutton "Exit (X)" yalign 0.5 action Return(False) xpos 20
        key "x" action Return(False)


    #####################################################################
    #                QUEST LOG guiHelpMode
    #####################################################################
    if guiHelpMode == "quest log":
        text "ACTIVE QUESTS" size FSIZE_LARGE pos 960,100 xalign 0.5 outlines [ (absolute(5), "#0099cc", absolute(0), absolute(0)) ]
        $ future_hide = "future_version" not in tags 

        if not future_hide:
            $ bCol = "#0099ccff"
            $ bText = "Hide Future Content"
        else:
            $ bCol = "#0099ccff"
            $ bText = "Show Future Content"

        if "future_on" in tags:
            frame xsize 260 ysize 30 xalign 0.5 ypos 160 background Solid(bCol):
                text bText size FSIZE_MED xalign 0.5 yalign 0.5
                button action Return("future_version")

        side "c r":
            area 100,220,1700,620
            viewport id "vp":
                draggable True
                mousewheel True
                vbox xsize 1660 xalign 0.5 ypos 240 spacing 10:
                    for q in GAME.questSys.activeQuests:  
                        $ hide = "future version" in q.hint.lower() and future_hide
                        if q.state == "in progress" and not hide:
                            # frame xsize 1600 ysize 60 xalign 0.4 background Solid("#0099cc55"): # CR-0301
                            frame xsize 1600 ysize 60 xalign 0.4 background Solid("#00000055"): # CR-0301
                                text "{} {}".format(C_HI_B+q.description+" |"+C_HI_E, q.hint) xpos 20 yalign 0.5 size FSIZE
                                if "hint" in q.tags:
                                    frame xsize 80 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos 1490:
                                        text "Hint" xalign 0.5 yalign 0.5 size FSIZE_MED
                                        button action Return(["hint",q])

            vbar value YScrollValue("vp")


    #####################################################################
    #                MISSION LOG
    #####################################################################
    elif guiHelpMode == "missions":
        # formatting data and header
        $ M_COLS = [20, 200, 450, 750, 1050, 1350, 1475, 1680] # CR-0818
        $ M_LABELS = ["Kind", "Star System", "Location", "Specifics", "Inventory", "Reward", "Contract Due"]
        text "ACTIVE MISSIONS" size FSIZE_LARGE pos 960,100 xalign 0.5 outlines [ (absolute(5), "#0099cc", absolute(0), absolute(0)) ]

        # listing
        vbox xsize 1660 xalign 0.5 ypos 250 spacing 20:
            frame xsize 1800 ysize 40 background Solid("#00000055") yoffset -30:
                for i, txt in enumerate(M_LABELS):
                    if txt not in ["Reward"]:
                        text txt size FSIZE xpos M_COLS[i] ypos 2
                    else:
                        text txt size FSIZE xpos M_COLS[i] xalign 1.0 ypos 2

            for i in GAME.missionSys.getDueMissions():
                if i.kind == "bounty":
                    $ C_B, C_E = C_OR_B, C_OR_E
                elif i.kind == "smuggling":
                    $ C_B, C_E = C_YE_B, C_YE_E
                else:
                    $ C_B, C_E = C_HI_B, C_HI_E
    
                frame xsize 1800 ysize 80 background Solid("#00000085"): # CR-0301
                    $ dueDays = i.due-GAME.day
                    if dueDays == 0:
                        $ dueDays = C_YE_B+"Today!"+ C_YE_E

                    # mission type
                    text "{}".format(C_B+i.name+ C_E) xpos M_COLS[0] yalign 0.5 size FSIZE

                    # mission star system
                    text "{}{}{}".format(C_B, GAME.starSys[i.starSysID].name, C_E) xpos M_COLS[1] yalign 0.5 size FSIZE

                    # mission location
                    if i.sLocID:
                        $ sLoc = GAME.getSpaceLoc(i.sLocID)
                        text "{}".format(sLoc.name) xpos M_COLS[2] yalign 0.5 size FSIZE

                    # specifics
                    if i.kind in ["transport", "smuggling"]:
                        $ itemID = i.attr["wareID"]
                        $ amount = i.attr["amount"]
                        text "{} ({}x)".format(GAME.items[itemID].getName(["cap", "col"]), amount) xpos M_COLS[3] yalign 0.5 size FSIZE
                        $ cargoamount =GAME.ship.cargo.count(GAME.items[itemID]) 
                        if cargoamount < amount:
                            $ amountcolor = "#F00"
                        else:
                            $ amountcolor = "#0F0"
                        text "{} in cargo".format(cargoamount) xpos M_COLS[4] yalign 0.5 size FSIZE color amountcolor
                    elif i.kind == "bounty":
                        text C_B+"Difficulty Level {}".format(i.lvl)+C_E xpos M_COLS[3] yalign 0.5 size FSIZE

                    # reward
                    text C_GO_B+"{:,} Cr".format(i.reward)+C_GO_E xpos M_COLS[5] xalign 1.0 yalign 0.5 size FSIZE

                    # due date
                    if dueDays == 0:
                        text C_YE_B + "  Today!"+ C_YE_E xpos M_COLS[6] xoffset 1 yalign 0.5 size FSIZE
                    elif dueDays == 1:
                        text "   {} Day".format(dueDays) xpos M_COLS[6] xoffset 1 yalign 0.5 size FSIZE
                    else:
                        text "   {} Days".format(dueDays) xpos M_COLS[6] xoffset 1 yalign 0.5 size FSIZE

                    # ====== CR-0818 START
                    # abandon
                    frame xsize 80 ysize 30 background Solid ("#0099ccff") yalign 0.5 xpos M_COLS[7]:
                        text "Abandon" xalign 0.5 yalign 0.5 size FSIZE_MED
                        button action Return(["abandon",i])
                    # ====== CR-0818 END
                

    #####################################################################
    #                GALLERY guiHelpMode
    #####################################################################
    elif guiHelpMode == "gallery":
        text "{} - PAGE {}".format(guiHelpMode.upper(), gPage) size FSIZE_LARGE pos 960,100 xalign 0.5 outlines [ (absolute(5), "#0099cc", absolute(0), absolute(0)) ]

        $ n = 0
        $ gX, gY = 5 , 4

        $ gMax = gX * gY # gridMax

        $ galMaxFiltered = len(partialGallery)
        $ galMaxAll = GAME.galleryGetMax()

        $ imgBase = (gPage-1)*20
        textbutton "Prev" pos 360, 170 action Return("gLeft")
        textbutton "Next" pos 1490, 170 action Return("gRight")

        # display filters
        # text "{}".format(len(partialGallery))
        vbox pos 60, 220 spacing 20:
            for i in range(len(galleryFilter.keys())):
                $ B_COL = {True: "#0099ccff", False: "#666666ff"}[galleryFilter[i][2]]
                frame xsize 120 ysize 30 background Solid (B_COL):
                        text "{}".format(galleryFilter[i][1]) xalign 0.5 yalign 0.5 size FSIZE_MED
                        button action Return(["filter", i])
        # images
        grid gX gY spacing 20 xalign 0.5 yalign 0.5:
            $ nGrid = 0 # gridcounter
            for nGrid in range(gMax):
                if len(partialGallery) > max (nGrid, nGrid+(gPage-1)*20) :
                    $ item = partialGallery[nGrid + (gPage-1)*20]
                else:
                    $ item = False
                # if image found
                if item and item.found:
                    # display image
                    # +(gPage-1)*20
                    frame xsize 249 ysize 144:
                        image "21_gallery_thumb/gallery {}.jpg".format(item.ID) xalign 0.5 yalign 0.5
                        button action Return(["image", "20_gallery/gallery {}.jpg".format(item.ID), item.ID]) tooltip ["gallery", "{}".format(item.name) ]
                        if item.anim:
                            image "05_gui/star.png" xalign 1.0 yalign 1.0
                elif item:
                    # display image
                    # +(gPage-1)*20
                    frame xsize 249 ysize 144:
                        image "05_gui/ico_gui_padlock.png" xalign 0.5 yalign 0.5 zoom 0.125
                        button action NullAction() tooltip ["gallery", "Hint: {}".format(item.hint) ]
                        if item.anim:
                            image "05_gui/star.png" xalign 1.0 yalign 1.0

                # space on page to fill
                elif nGrid < gMax:
                    frame xsize 166 ysize 96 background Solid ("#00000000")
                
        # # images
        # grid gX gY spacing 20 xalign 0.5 yalign 0.5:
        #     for i in range(gMax):
        #         if i+imgBase in GAME.gallery.keys() and GAME.gallery[i+(gPage-1)*20].found:
        #             frame xsize 249 ysize 144:
        #                 image "21_gallery_thumb/gallery {}.jpg".format(i+(gPage-1)*20) xalign 0.5 yalign 0.5
        #                 button action Return(["image", "20_gallery/gallery {}.jpg".format(i+imgBase), i+imgBase]) tooltip ["gallery", "{}".format(GAME.gallery[i+(gPage-1)*20].name) ]
        #                 if GAME.gallery[i+(gPage-1)*20].anim:
        #                     image "05_gui/star.png" xalign 1.0 yalign 1.0
        #         elif i+imgBase <= GAME.galleryGetMax():
        #             frame xsize 249 ysize 144:
        #                 image "05_gui/ico_gui_padlock.png" xalign 0.5 yalign 0.5 zoom 0.125
        #                 button action NullAction() tooltip ["gallery", "Hint: {}".format(GAME.gallery[i+(gPage-1)*20].hint) ]
        #         else:
        #             frame xsize 166 ysize 96 background Solid ("#00000000")

        key "K_RIGHT" action Return("gRight")
        key "K_LEFT" action Return("gLeft")

    $ tooltip = GetTooltip()
    if tooltip and "gallery" in tooltip:
        frame xsize 1100 ysize 200 xalign 0.5 ypos 920 background Solid ("#00000000"):
            text tooltip[1] xalign 0.5 size FSIZE

label quest_help(guiHelpMode ="quest log"):

    hide screen displayPresentActors
    $ gPage = 1
    $ tags = []
    $ galleryFilter = {
        0: ["ALL", "All", True],
        1: ["NONE", "None", True],
        2: ["OTHER", "Other", True],
        3: ["GALAXINA", "Galaxina", True],
        4: ["ACTTRIS", "T'Ris", True],
        5: ["ACTNIMHE", "Nimhe", True],
        6: ["ACTKHELARA", "Khelara", True],
        7: ["ACTVEE", "Vee", True],
        8: ["ACTSERA", "Seraphine", True],
        9: ["ACTMOIRA", "Moira", True]    
    }
    $ future_on = any(["Future Version" in x[1] for x in GAME.questSys.questDB.values()])
    if future_on:
        $ tags.append("future_on")
    # prepare screen
    #hide screen header
    hide screen header
    scene expression("11_backgrounds/backdrop_menu_01.jpg") # CR-0301 / CR-0318
    play music "audio/sjx_custom_menu.mp3"
     
    # create initial filtered gallery entry list 
    $ partialGallery = GAME.getPartialGallery(galleryFilter)

    # process screen input

    while True:
        
        call screen quest_help_scr(guiHelpMode, gPage, tags, partialGallery)
        if not _return:
            #show screen header
            stop music fadeout 2.0
            return()

        elif _return == "future_version":
            queue sound "audio/click.wav"
            if "future_version" in tags:
                $ tags.remove("future_version")
            else:
                $ tags.append("future_version")

        elif "image" in _return:
            $ galleryItem = GAME.gallery[_return[2]]
            play sound "audio/click.wav"
            call screen gallery_view(galleryItem) with Dissolve(1.0)
            play sound "audio/click.wav"

        elif "filter" in _return:
            queue sound "audio/click.wav"
            $ k = _return[1]
            python:
                if galleryFilter[k][0] == "ALL":
                    for i in range(2,10):
                        galleryFilter[i][2] = True 
                elif galleryFilter[k][0] == "NONE":
                    for i in range(2,10):
                        galleryFilter[i][2] = False 
                else:
                    galleryFilter[k][2] = not galleryFilter[k][2] 
                gPage = 1
            # update filtered gallery entry list 
            $ partialGallery = GAME.getPartialGallery(galleryFilter)

        elif "hint" in _return:
            $ quest = _return[1]
            if len(quest.tags) > quest.tags.index("hint"):
                $ hint = quest.tags[quest.tags.index("hint")+1]
            else:
                $ hint = "No data available."
            queue sound "audio/notify.wav"
            call large_notify(C_HI_B+quest.description.upper()+C_HI_E, hint, ["Continue"], "05_gui/ico_gui_quest.png") from _call_large_notify_105 

        # abandon mission
        elif "abandon" in _return:
            queue sound "audio/notify.wav"
            "You abandon the mission... [C_RE_B](REP -1)[C_RE_E]"
            $ GAME.mc.attr["REP"] = max(0, GAME.mc.attr["REP"]-1)
            $ GAME.missionSys.purgeMission(_return[1])

        elif _return in ["gLeft", "gRight"]:
            if len(partialGallery) == gPage*20:
                $ gPageMax = int(len(partialGallery)/20.0)
            else:
                $ gPageMax = int(len(partialGallery)/20.0)+1
            if _return == "gLeft":
                play sound "audio/click.wav"
                if gPage > 1:
                    $ gPage -= 1
                else:
                    $ gPage = gPageMax

            elif _return == "gRight":
                play sound "audio/click.wav"
                if len(partialGallery) > gPage*20:
                    $ gPage += 1
                else: 
                    $ gPage = 1
        else:
            play sound "audio/click.wav"
            $ guiHelpMode = _return
    return()

#####################################################################
#                SHOW STATS
#####################################################################
screen show_stats_scr(*args):
    $ actor = args[0]
    $ aImg = args[1]

    modal True # CR-0740
  
    # controls
    key "x" action Return(False)
    key "K_SPACE" action Return(False)
    key "K_LEFT" action Return("left")
    key "K_RIGHT" action Return("right")
    key "mouseup_1" action Return(False)


    frame xsize 1400 ysize 800 xalign 0.5 yalign 0.5 background Solid("#000000cc") padding 0,0:   
        image "05_gui/frame_stats.png"
        hbox xsize 200 spacing 180 xpos 100 ypos 20: # CR-0257
            frame xsize 50 ysize 40 background Solid("#ffffff00"): # CR-0257
                image "05_gui/GUI arrow left.png" xalign 0.5 yalign 0.5 # CR-0257
                button action Return("left") # CR-0257
            frame xsize 50 ysize 40 background Solid("#ffffff00"): # CR-0257
                image "05_gui/GUI arrow right.png" xalign 0.5 yalign 0.5 # CR-0257
                button action Return("right")        # CR-0257
        $ pref = ""
        if actor.ID == "ACTMC":
            $ pref = "CAPTAIN "
        text C_HI_B+"{}{}".format(pref, actor.name.upper())+C_HI_E xalign 0.5 ypos 20 size FSIZE_LARGE
        #bar xsize 1000 ysize 4 xpos 350 ypos 80
        # actor image & data
        image aImg ypos -284 xpos 5
        # base stats
        hbox xsize 800 spacing 20 xpos 500 ypos 106:
            if actor.ID == "ACTMC":
                text "{} | Level: {} | Exp: {:,} | Next Level At: {:,.0f}".format(actor.race, actor.lvl, int(actor.exp), levelUpAt(300, GAME.mc.lvl)) 
            else:
                text "{} | Level: {} | FP: {} | {}".format(actor.race, actor.lvl, actor.fp, actor.getJob().name) 
        # actor backstory 
        vbox xsize 880 spacing 15 xpos 500 ypos 180:
            text actor.backstory size FSIZE
        # actor stats
        text C_HI_B+"ATTRIBUTES"+C_HI_E pos 475,260
        if actor == vee and not GAME.questSys.isActive("QID_VEE_FAMILIARIZE"):
            vbox xsize 200 spacing 15 xpos 500 ypos 300:
                text "Unknown" size FSIZE
        else:
            vbox xsize 200 spacing 15 xpos 500 ypos 300:
                #text C_HI_B+"ATTRIBUTES"+C_HI_E xoffset -25
                for k in sorted(actor.attr.keys()):
                    frame xsize 300 ysize 20 background Solid("ffffff00"):
                        if k in actor.skillProgDict.keys():
                            textbutton GAME.attr[k] action NullAction() xpos -6 ypos -6 text_style "text_std" tooltip k
                        else:
                            text GAME.attr[k] size FSIZE
                        text ":" xpos 220 size FSIZE
                        text "{}".format(actor.attr[k]) xpos 310 xalign 1.0 size FSIZE
                        
                    if k == "MLK" and actor.milkMod != None:
                      $ milk_num_ml = int(actor.milkMod.milk["left"] + actor.milkMod.milk["right"])
                      if milk_num_ml > 0:
                          $milk_ml = str(milk_num_ml)
                      else:
                          $milk_ml = " - "
                      $milk_max = str(actor.milkMod.breastCapa)
                      if actor.attr["MLK"] > 0:
                        fixed xsize 300 ysize 30:
                            text "    Milk Available" size FSIZE color "#09CF"
                            text ":" xpos 226 size FSIZE color "#09CF" yoffset 10
                            if milk_ml == " - ":
                                text " - " xpos 310 xalign 0.5 yoffset 10 size 26 color "#09CF"
                            else:
                                text "@ {size=26}" + milk_ml + "{/size} ml" xpos 310 xalign 0.5 yoffset 2 size 18 color "#09CF"
                                text "Max " + milk_max + " ml"  xpos 310 xalign 0.5 yoffset 25 size 18 color "#09CF"
                                
                            if actor.attr["MLK"] >= 45:
                                text "Exquisite Quality" size FSIZE color "#09CF" xpos 50 yoffset 25 italic True
                            elif actor.attr["MLK"] >= 15:
                                text "Creamy Quality" size FSIZE color "#09CF" xpos 50 yoffset 25 italic True
                            else:
                                text "Basic Quality" size 20 color "#09CF" xpos 50 yoffset 25 italic True


        # actor tally
        text C_HI_B+"DIARY"+C_HI_E pos 875,260
        side "c r":
            # ===== CR-0540 START
            area 900,300,470,345
            # ===== CR-0540 END
            viewport id "vp":
                draggable True
                mousewheel True
                #frame background Solid ("#00000088"):
                #    pass

                vbox xsize 200 spacing 15:
                    for k in sorted(actor.tally.keys()):
                        frame xsize 300 ysize 20 background Solid("ffffff00"):
                            text k size FSIZE
                            text ":" xpos 250 size FSIZE
                            text "{:,}".format(int(actor.getTally(k))) xpos 420 xalign 1.0 size FSIZE
                    text " "
 
            vbar value YScrollValue("vp")

        frame xsize 1392 ysize 150 xalign 0.5 ypos 646 background Solid("#00000088")
        vbox xsize 1200 spacing 15 xpos 100 ypos 660:
            text C_HI_B+"ACHIEVEMENTS"+C_HI_E xoffset -50
            $ aList = sorted(actor.achievements)
            text C_SU_B+", ".join(aList).upper()+C_SU_E size FSIZE yoffset -6

    $ tooltip = GetTooltip()
    if tooltip and tooltip in GAME.attr.keys():
        frame xsize 500 ysize 280 padding 20,20 xalign 0.5 ypos 750:
            vbox spacing 10:
                for job in actor.getJobTable(tooltip):
                    frame xsize 460 ysize 30 background Solid("#ffffff22"):
                        $ C_B, C_E = "", ""
                        if job[0] <= actor.getAttr(tooltip):
                            $ C_B, C_E = C_GR_B, C_GR_E     
                        text "{}{} {}{}".format(C_B,tooltip, job[0],C_E) size FSIZE xpos 0
                        text "{}{}{}".format(C_B,job[1],C_E) size FSIZE xpos 100
                         
label show_stats(actor): # xxx
    $ actors = GAME.crew + [GAME.mc]
    #if GAME.questSys.isDone("QID_SERAPHINE_ARELLARTI_FIND"): # CR-0441
    #    $ actors.append(seraphine) # CR-0441
    $ actors.remove(bb_2)
    if actor in actors:
        while actors[0] != actor:
            $ actors = actors[1:]+actors[:1]

    while True:
        # CR-0906 START ===============================    
        $ aImg = {"ACTTRIS":"side_tris_smart", "ACTMC":"side_mc_smart", "ACTNIMHE":"side_nimhe_smart", "ACTKHELARA": "side_khelara_smart", "ACTVEE":"side_vee_smart", "ACTSERA": "side_seraphine_smart", "ACTMOIRA": "side_moira_smart"}[actors[0].ID]
        call screen show_stats_scr(actors[0], aImg)
        # CR-0906 END ===============================

        play sound "audio/click.wav"
        if _return == False:
            return()
        elif _return == "left":
            $ actors = actors[1:]+ actors[:1]
        elif _return == "right":
            $ actors = actors[-1:]+ actors[:-1]
    return()

#####################################################################
#					NG		
#####################################################################
label transaction(category, amount, verbose=False):
    $ GAME.books.append([GAME.day, category, amount])
    $ GAME.money += amount 
    if verbose:
        play sound "audio/coin.wav"
    return()

#####################################################################
#					CREW ASSESSMENT
#####################################################################
label skill_assessment():
    $ GAME.reports = []
    python:
        # MC
        for i in ["TEC"]:
            if int(GAME.mc.attrFrac[i]) > GAME.mc.attr[i]:
                GAME.mc.attr[i] = int(GAME.mc.attrFrac[i])
                GAME.reports.append(["SKILL INCREASE!", "Through constant practice aboard your ship, your {} has increased to Level {}. Repair effectiveness is now improved.\n\nKeep up the good work.".format(C_HI_B+GAME.attr[i]+C_HI_E, GAME.mc.attr[i]), ["Continue"], "05_gui/ico_gui_cup.png", "blue"])  

        # Crew 
        for actor in GAME.crew:
            for i in ["EXH", "TEC"]:
                if int(actor.getAttrFrac(i)) > actor.getAttr(i):
                    actor.attr[i] = int(actor.getAttrFrac(i))
                    GAME.reports.append(["SKILL INCREASE!", "Through constant practice, {}'s {} has increased to Level {}.\n\nContinue training or tasking her in that fashion.".format(actor.name, C_HI_B+GAME.attr[i]+C_HI_E, actor.attr[i]), ["Continue"], "05_gui/ico_gui_cup.png", "blue"])  

                    # specific skill gains 
                    if actor == nimhe and i == "TEC": 
                        shellLevels = [
                            [25, "JOB_Shell_Exotic", "Exotic Shells (N, V)", "SBPShell3TypeV"],
                            [30, "JOB_Shell_Luxury", "Luxury Shells (L, P)", "SBPShell3TypeP"],
                            [35, "JOB_Shell_Rarified", "Rarified Shells (I, G)", "SBPShell3TypeG"],
                        ]
                        for record in shellLevels:
                            if actor.attr[i] >= record[0] and record[1] not in actor.jobs:
                                GAME.reports.append(["SKILL ACQUIRED!", "{name} can now learn to craft {MU_B}{kinds}{MU_E}.\n\nDonate Research Shells to {name} to add them to her Crafting Skillset.".format(name = actor.name, MU_B=C_HI_B, MU_E=C_HI_E, kinds=record[2]), ["Continue"], "03_minigames/ico SBPShell3TypeV.png".format(record[3]), "blue"]) 
                                actor.jobs.append(record[1])

                    elif actor == khelara and i == "TEC":
                        if actor.attr[i] >= 15 and "replate_skill_up" not in actor.done:
                            GAME.reports.append(["SKILL ACQUIRED!", "{name} will now initiate and supervise {MU_B}Hull Replating{MU_E} when you are docked or landed overnight and she is assigned Repair Tasks.\n\nPlates are automatically selected from Cargo or Warehouse.".format(name = actor.name, MU_B=C_HI_B, MU_E=C_HI_E), ["Continue"], "08_items/ico ITMDuraniumPlating.png", "blue"]) 
                            actor.hasDone("replate_skill_up")

                    elif actor == tris and i == "TEC" and actor.attr[i] >= 10 and "JOB_Pods" not in actor.jobs:
                        GAME.reports.append(["SKILL ACQUIRED!", "{name} can now {MU_B}Restock Pods{MU_E} throughout the day.\n\nUp to 5 Pods of each will be purchased as long as you have more than 50k Credit.".format(name = actor.name, MU_B=C_HI_B, MU_E=C_HI_E), ["Continue"], "08_items/ico ITMPodEnergy.png", "blue"]) 
                        actor.jobs.append("JOB_Pods")

                    elif actor == tris and i == "TEC" and actor.attr[i] >= 15 and "JOB_Torps" not in actor.jobs:
                        GAME.reports.append(["SKILL ACQUIRED!", "{name} will now {MU_B}Restock Torpedoes (High End){MU_E} when you dock or land and she is assigned the task in the morning.\n\n20 torpedoes in Cargo or funds < 5 Million will limit restocking.".format(name = actor.name, MU_B=C_HI_B, MU_E=C_HI_E), ["Continue"], "08_items/ico ITMTorpedoBFT.png", "blue"]) 
                        actor.jobs.append("JOB_Torps")


            for i in ["SUB"]:
                if int(actor.getAttrFrac(i)) > actor.getAttr(i):
                    actor.attr[i] = int(actor.getAttrFrac(i))
                    GAME.reports.append(["SKILL INCREASE!", "Through constant discipline, {}'s {} has increased to Level {}.\n\nContinue training her in that fashion.".format(actor.name, C_HI_B+GAME.attr[i]+C_HI_E, actor.attr[i]), ["Continue"], "05_gui/ico_gui_cup.png", "blue"])  


    while GAME.reports:
        $ report = GAME.reports.pop(0)
        queue sound "audio/notify.wav"
        call large_notify(report[0], report[1], report[2], report[3], report[4]) from _call_large_notify_106 
    return()

#####################################################################
#              TROPHY NIGHTLY UPDATES CR-0566
#####################################################################
label trophy_assessment():
    $ notify = []
    python:
        beacon = []
        # scholar (number of map fragments)
        if hasattr (GAME, "mgBeaconSta"):
            beacon = [x[2] for x in GAME.mgBeaconSta.slots.values() if x[2]]
        inventory = [x for x in GAME.mc.inventory if "ITMMapPre" in x.ID]

        GAME.trophies["scholar"] = capValue(len(beacon+inventory),0,5)
        if GAME.trophies["scholar"] == 5:
            notify.append("scholar")

        # casanova (sex with crew member)
        counter = len([x for x in GAME.crew if (x.getTally("Sex") or x.getTally("Anal Sex"))])
        GAME.trophies["casanova"] = counter
        if GAME.trophies["casanova"] >= 5:  # CR-2021
            notify.append("casanova")       # CR-2021

        # trainer (specific SUB quests done)
        counter = len([x for x in GAME.crew if x.attr.get("SUB",0) > 10])
        GAME.trophies["trainer"] = counter


        # pharaoh (money)
        counter = 0
        for i in range(1,6):
            if GAME.money >= [0,1,5,50, 100, 500][i]*1000000:
                counter = i
        GAME.trophies["pharaoh"] = counter
        if GAME.trophies["pharaoh"] == 5:
            notify.append("pharaoh")

        # admiral (ship achievements)
        counter = 0
        if GAME.mc.getTally("Eliminated Seekers") >= 100:
            counter += 1
        if GAME.mc.getTally("Eliminated Ships") >= 50:
            counter += 1
        if GAME.mc.getTally("Eliminated Ships") >= 100:
            counter += 1
        if GAME.mc.getTally("Eliminated Obliterators") >= 10:
            counter += 1
        if GAME.mc.getTally("Eliminated Obliterators") >= 20:
            counter += 1

        GAME.trophies["admiral"] = counter
        if GAME.trophies["admiral"] == 5:
            notify.append("admiral")

        # traveller (star systems)
        counter = 0 
        for i in ["SSIDIltari", "SSIDArellarti", "SSIDXenos", "SSIDNX010", "SSIDQuthor"]:
            if i in GAME.mc.done:
                counter += 1
        GAME.trophies["traveller"] = counter
        if GAME.trophies["traveller"] == 5:
            notify.append("traveller")

    #####################################################################
    #              notifications
    ##################################################################### 
    while notify:   
        $ item = notify.pop()
        $ achievements = {"traveller": 126, "scholar": 127, "pharaoh": 128, "admiral": 129, "casanova": 156}
        if not GAME.mc.hasAchievement(item):
            call achievement_notify(GAME.mc, item, "20_gallery/gallery {}.jpg".format(achievements[item]) ) from _call_achievement_notify_18 
            $ GAME.galleryAdd(achievements[item])
    return()

#####################################################################
#					DAILY REPORT		
#####################################################################

screen daily_financial_report_scr(*args):
    $ incList = args[0]
    $ expList = args[1]
    $ graph = args[2]
    $ repDay = args[3]
    $ C_SUM_Y = 760
    $ C_LIST_Y = 180
    $ C_LIST_X = 140
    $ incTotal = sum(x[1] for x in incList)
    $ expTotal = sum(x[1] for x in expList)
    image "05_gui/mask 50.png"    
    text C_HI_B+"INCOME & EXPENDITURES REPORT - DAY {}".format(repDay)+C_HI_E size FSIZE_LARGE pos 960, 60 xalign 0.5
    # list up income and expenditures 
    vbox xsize 800 pos C_LIST_X, C_LIST_Y spacing 10:
        for i in incList:
            frame xsize 800 ysize 30 background Solid("#ffffff22"):
                text i[0] xpos 40 yalign 0.5 size FSIZE
                text C_GR_B+"{:,} Cr".format(i[1])+C_GR_E xpos 760 xalign 1.0 yalign 0.5 size FSIZE
    vbox xsize 800 pos C_LIST_X, C_SUM_Y spacing 10:
        bar xsize 800 ysize 3        
        frame xsize 800 ysize 40 background Solid("#ffffff22"):
            text "Total Income" xpos 40 yalign 0.5 size FSIZE
            text C_GR_B+"{:,} Cr".format(incTotal)+C_GR_E xpos 760 xalign 1.0 yalign 0.5 
        if incTotal + expTotal >= 0:
            frame xsize 800 ysize 40 background Solid("#ffffff22"):
                text "Net Income" xpos 40 yalign 0.5 size FSIZE
                text C_GR_B+"{:,} Cr".format(incTotal+expTotal)+C_GR_E xpos 760 xalign 1.0 yalign 0.5 


    vbox xsize 800 pos C_LIST_X+860, C_LIST_Y spacing 10:
        for i in expList:
            frame xsize 800 ysize 30 background Solid("#ffffff22"):
                text i[0] xpos 40 yalign 0.5 size FSIZE
                text C_RE_B+"{:,} Cr".format(i[1])+C_RE_E xpos 760 xalign 1.0 yalign 0.5 size FSIZE

    vbox xsize 800 pos C_LIST_X+860, C_SUM_Y spacing 10:
        bar xsize 800 ysize 3        
        frame xsize 800 ysize 40 background Solid("#ffffff22"):
            text "Total Expenditures" xpos 40 yalign 0.5 size FSIZE
            text C_RE_B+"{:,} Cr".format(expTotal)+C_RE_E xpos 760 xalign 1.0 yalign 0.5 
        if incTotal + expTotal < 0:
            frame xsize 800 ysize 40 background Solid("#ffffff22"):
                text "Net Expenditures" xpos 40 yalign 0.5 size FSIZE
                text C_RE_B+"{:,} Cr".format(incTotal+expTotal)+C_RE_E xpos 760 xalign 1.0 yalign 0.5 


    # 30 day chart 
    frame xsize 330 ysize 110 pos 1470, 20  background Solid ("#ffffff22"):
        for y in [110, 90, 70, 50, 30,10]:
            bar xsize 320 ysize 2 pos 0, y-10
        $ n = 0
        for i in graph:
            image "05_gui/px_1x1_red.png" xsize 6 ysize abs(i[2]) pos n*6+4, 100 yalign 1.0
            image "05_gui/px_1x1_green.png" xsize 6 ysize i[1] pos n*6, 100 yalign 1.0
            $ n += 1


    # Exit button 
    frame xsize 350 ysize 64 pos 0,900 background Solid("#00000000") padding 0,0:
        image "05_gui/gui_menu_option.png" yalign 0.5
        button action Return(False) xpos 20    
        textbutton "Exit (X)" yalign 0.5 action Return(False) xpos 20
        key "x" action Return(False)
        key "K_SPACE" action Return(False)           

label daily_financial_report(repDay=False):
    if repDay == False:
        $ repDay = GAME.day
    # Compile Itemized List
    python:
        incDict = {} # to aggregate
        expDict = {} # to aggregate
        incList = []
        expList = []
        graphRaw = []
        graphNormal = []
        # aggregate positions
        for i in [x for x in GAME.books if x[0] == repDay]: # day, pos, amount
            if i[2] < 0:
                if i[1] not in expDict.keys():
                    expDict[i[1]] = 0
                expDict[i[1]] += i[2]
            elif i[2] > 0:
                if i[1] not in incDict.keys():
                    incDict[i[1]] = 0
                incDict[i[1]] += i[2]

        for k in sorted(incDict.keys()):
            incList.append([k, incDict[k]])
        for k in sorted(expDict.keys()):
            expList.append([k, expDict[k]])

        # create 30 day graph
        if GAME.day < 31: 
            x0, x1 = max(1, GAME.day-30), GAME.day+1 
        else:
            x0, x1 = max(1, GAME.day-30), max(30, GAME.day)+1
        for i in range(x0,x1):
            exp = sum([x[2] for x in GAME.books if x[0] == i and x[2]<0])
            inc = sum([x[2] for x in GAME.books if x[0] == i and x[2]>1])
            graphRaw.append([i, inc, exp])
  
        gMax = float(max([abs(x[1]) for x in graphRaw]+[abs(x[2]) for x in graphRaw]))/100

        for i in graphRaw:
            graphNormal.append([i[0], int(i[1]/gMax), int(i[2]/gMax)])

    # Compile PAST 30 DAYS Graph Data

    # Display Itemized List 
    call screen daily_financial_report_scr(incList, expList, graphNormal, repDay) with dissolve   
    return()

#####################################################################
#                THE END
#####################################################################

label THE_END(msg, img="02_locations/backdrop_gasgiant.jpg"):
    scene expression(img) with fade
    label end_loop:
        "[msg]"
        "THE END."

#####################################################################
#              INTERMISSION TEXT
#####################################################################
screen intermission_text(msg):
    frame xsize 1920 ysize 160 background Solid("#0099cc55") yalign 0.48
    # text "DAY {}".format(msg) size 128 color "#0099cc" outlines [ (absolute(5), "#ffffff", absolute(0), absolute(0)) ]xalign 0.5 yalign 0.5
    text "DAY {}".format(msg) size 128 xalign 0.5 yalign 0.5
    # Exit controls
    key "x" action Return(False)
    key "K_SPACE" action Return(False)
    key "mouseup_1" action Return(False)
