aboutsummaryrefslogtreecommitdiff
path: root/Northstar.Client/scripts/vscripts/ui/_menus.nut
blob: ffae9a30e4001329346ad97558770700f4e1857a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
untyped

global const bool EDIT_LOADOUT_SELECTS = true
global const string PURCHASE_SUCCESS_SOUND = "UI_Menu_Store_Purchase_Success"

global function UICodeCallback_CloseAllMenus
global function UICodeCallback_ActivateMenus
global function UICodeCallback_LevelInit
global function UICodeCallback_LevelLoadingStarted
global function UICodeCallback_LevelLoadingFinished
global function UICodeCallback_LevelShutdown
global function UICodeCallback_OnConnected
global function UICodeCallback_OnFocusChanged
global function UICodeCallback_NavigateBack
global function UICodeCallback_ToggleInGameMenu
global function UICodeCallback_TryCloseDialog
global function UICodeCallback_UpdateLoadingLevelName
global function UICodeCallback_ConsoleKeyboardClosed
global function UICodeCallback_ErrorDialog
global function UICodeCallback_AcceptInvite
global function UICodeCallback_OnDetenteDisplayed
global function UICodeCallback_OnSpLogDisplayed
global function UICodeCallback_EntitlementsChanged
global function UICodeCallback_StoreTransactionCompleted
global function UICodeCallback_GamePurchased
global function UICodeCallback_PartyUpdated
global function UICodeCallback_KeyBindOverwritten

global function AdvanceMenu
global function OpenSubmenu // REMOVE
global function CloseSubmenu // REMOVE
global function CloseActiveMenu
global function CloseActiveMenuNoParms
global function CloseAllMenus
global function CloseAllInGameMenus
global function CloseAllDialogs
global function CloseAllToTargetMenu
global function PrintMenuStack
global function CleanupInGameMenus
global function GetActiveMenu
global function GetMenu
global function GetPanel
global function GetAllMenuPanels
global function InitGamepadConfigs
global function InitMenus
global function AdvanceMenuEventHandler
global function PCSwitchTeamsButton_Activate
global function PCToggleSpectateButton_Activate
global function AddMenuElementsByClassname
global function FocusDefault
global function SetPanelDefaultFocus
global function PanelFocusDefault
global function OpenMenuWrapper
global function CloseMenuWrapper
global function IsLevelMultiplayer
global function AddMenuEventHandler
global function AddPanelEventHandler
global function AddButtonEventHandler
global function AddEventHandlerToButton
global function AddEventHandlerToButtonClass
global function DisableMusic
global function EnableMusic
global function PlayMusic
global function StopMusic
global function IsMenuInMenuStack
global function GetTopNonDialogMenu
global function IsDialog
global function IsDialogActive
global function IsDialogOnlyActiveMenu
global function SetNavUpDown
global function SetNavLeftRight
global function IsTrialPeriodActive
global function LaunchGamePurchaseOrDLCStore
global function SetMenuThinkFunc

global function PCBackButton_Activate

global function RegisterMenuVarInt
global function GetMenuVarInt
global function SetMenuVarInt
global function RegisterMenuVarBool
global function GetMenuVarBool
global function SetMenuVarBool
global function RegisterMenuVarVar
global function GetMenuVarVar
global function SetMenuVarVar
global function AddMenuVarChangeHandler

global function InviteFriends

global function HACK_DelayedSetFocus_BecauseWhy

#if DURANGO_PROG
	global function OpenXboxPartyApp
	global function OpenXboxHelp
#endif // DURANGO_PROG

global function OpenReviewTermsDialog
global function ClassicMusic_OnChange
global function IsClassicMusicAvailable


void function UICodeCallback_CloseAllMenus()
{
	printt( "UICodeCallback_CloseAllMenus" )
	CloseAllMenus()
	// This is usually followed by a call to UICodeCallback_ActivateMenus().
}

// Bringing up the console will cause this, and it probably shouldn't
void function UICodeCallback_ActivateMenus()
{
	if ( IsConnected() )
		return

	printt( "UICodeCallback_ActivateMenus:", uiGlobal.activeMenu && Hud_GetHudName( uiGlobal.activeMenu ) )

	if ( uiGlobal.menuStack.len() == 0 )
	{
		AdvanceMenu( GetMenu( "MainMenu" ) )
	}

	if ( uiGlobal.activeMenu == GetMenu( "MainMenu" ) )
		Signal( uiGlobal.signalDummy, "OpenErrorDialog" )

	PlayMusic()

	#if DURANGO_PROG
		Durango_LeaveParty()
	#endif // DURANGO_PROG
}

void function UICodeCallback_ToggleInGameMenu()
{
	if ( !IsFullyConnected() )
		return

	var activeMenu = uiGlobal.activeMenu
	bool isMP = IsLevelMultiplayer( GetActiveLevel() )
	bool isLobby = IsLobby()

	var ingameMenu
	if ( isMP )
	{
		ingameMenu = GetMenu( "InGameMPMenu" )
	}
	else
	{
		// Disable this callback for this special case menu so players can't skip it.
		var spTitanTutorialMenu = GetMenu( "SPTitanLoadoutTutorialMenu" )
		if ( activeMenu == spTitanTutorialMenu )
			return

		ingameMenu = GetMenu( "InGameSPMenu" )
	}

	if ( IsDialog( uiGlobal.activeMenu ) )
	{
		// Do nothing if a dialog is showing
	}
	else if ( TeamTitanSelectMenuIsOpen() )
	{
		if ( uiGlobal.activeMenu == GetMenu( "TeamTitanSelectMenu" ) )
		{
			// Do nothing here either
		}
		else
		{
			CloseActiveMenu()
		}
	}
	else if ( ( isMP && !isLobby ) || !isMP )
	{
		if ( !activeMenu )
			AdvanceMenu( ingameMenu )
		else
			CloseAllInGameMenus()
	}
}

// Return true to show load screen, false to not show load screen.
// levelname can be "" because the level to load isn't always known when the load screen starts
bool function UICodeCallback_LevelLoadingStarted( string levelname )
{
	printt( "UICodeCallback_LevelLoadingStarted: " + levelname )

	CloseAllDialogs()

	uiGlobal.loadingLevel = levelname

	StopMusic()

	if ( uiGlobal.playingVideo )
		Signal( uiGlobal.signalDummy, "PlayVideoEnded" )

	if ( uiGlobal.playingCredits )
		Signal( uiGlobal.signalDummy, "PlayingCreditsDone" )

	// kill lingering postgame summary since persistent data may not be available at this point
	Signal( uiGlobal.signalDummy, "PGDisplay" )

#if CONSOLE_PROG
	if ( !Console_IsSignedIn() )
		return false
#endif

	return true
}

// Return true to show load screen, false to not show load screen.
bool function UICodeCallback_UpdateLoadingLevelName( string levelname )
{
	printt( "UICodeCallback_UpdateLoadingLevelName: " + levelname )

#if CONSOLE_PROG
	if ( !Console_IsSignedIn() )
		return false
#endif

	return true
}

void function UICodeCallback_LevelLoadingFinished( bool error )
{
	printt( "UICodeCallback_LevelLoadingFinished: " + uiGlobal.loadingLevel + " (" + error + ")" )

	if ( !IsLobby() )
	{
		HudChat_ClearTextFromAllChatPanels()
		ResetActiveChatroomLastModified()
	}
	else
	{
		uiGlobal.lobbyFromLoadingScreen = true
	}

	uiGlobal.loadingLevel = ""
	Signal( uiGlobal.signalDummy, "LevelFinishedLoading" )
}

void function UICodeCallback_LevelInit( string levelname )
{
	Assert( IsConnected() )

	StopVideo()

	uiGlobal.loadedLevel = levelname

	printt( "UICodeCallback_LevelInit: " + uiGlobal.loadedLevel )

	if ( !uiGlobal.loadoutsInitialized )
	{
		string gameModeString = GetConVarString( "mp_gamemode" )
		if ( gameModeString != "solo" )
		{
			InitStatsTables()
		}
	}

	InitItems()

	if ( IsMultiplayer() )
	{
		ShWeaponXP_Init()
		ShTitanXP_Init()
		ShFactionXP_Init()
	}
	else
	{
		SPObjectiveStringsInit()
	}

	#if DEV
	UpdatePrecachedSPWeapons()
	#endif


	if ( !uiGlobal.loadoutsInitialized )
	{
		string gameModeString = GetConVarString( "mp_gamemode" )
		if ( gameModeString != "solo" )
		{
			DeathHints_Init()
			InitDefaultLoadouts()
			CreateChallenges()
			uiGlobal.loadoutsInitialized = true
		}
	}

	if ( IsLevelMultiplayer( levelname ) || IsLobbyMapName( levelname ) )
	{
		thread UpdateCachedLoadouts()
		thread UpdateCachedNewItems()
		thread InitUISpawnLoadoutIndexes()

		if ( !uiGlobal.eventHandlersAdded )
		{
			uiGlobal.eventHandlersAdded = true
		}

		UI_GetAllChallengesProgress()

		bool isLobby = IsLobbyMapName( levelname )

		string gameModeString = GetConVarString( "mp_gamemode" )
		if ( gameModeString == "" )
			gameModeString = "<null>"

		Assert( gameModeString == GetConVarString( "mp_gamemode" ) )
		Assert( gameModeString != "" )

	    int gameModeId = GameMode_GetGameModeId( gameModeString )

	    int mapId = eMaps.invalid
	    if ( levelname in getconsttable().eMaps )
	    {
	    	mapId = expect int( getconsttable().eMaps[ levelname ] )
	    }
	    else
	    {
	    	// Don't worry about this until we have to consider R2 Durango TCRs (10/2015)
	    	//if ( !IsTestMap() )
		    //	CodeWarning( "No map named '" + levelname + "' exists in eMaps, all shipping maps should be in this enum" )
	    }

	    int difficultyLevelId = 0
	    int roundId = 0

	    if ( isLobby )
	    	Durango_OnLobbySessionStart( gameModeId, difficultyLevelId )
	    else
	    	Durango_OnMultiplayerRoundStart( gameModeId, mapId, difficultyLevelId, roundId, 0 )
	}
	else
	{
		// SP loadout stuff
		UI_GetAllChallengesProgress() // TODO: Can this be moved so we don't call it twice? It's called above.

		SP_ResetObjectiveStringIndex() // Since this persists thru level load, we need to explicitely clear it.
	}

	if ( IsMultiplayer() )
	{
		foreach ( callbackFunc in uiGlobal.onLevelInitCallbacks )
		{
			thread callbackFunc()
		}

	}
	thread UpdateMenusOnConnect( levelname )

	uiGlobal.previousLevel = uiGlobal.loadedLevel
	uiGlobal.previousPlaylist = GetCurrentPlaylistName()
}

void function UICodeCallback_LevelShutdown()
{
	Signal( uiGlobal.signalDummy, "LevelShutdown" )

	printt( "UICodeCallback_LevelShutdown: " + uiGlobal.loadedLevel )

	StopVideo()

	if ( uiGlobal.loadedLevel != "" )
		CleanupInGameMenus()

	uiGlobal.loadedLevel = ""
	uiGlobal.mapSupportsMenuModelsUpdated = false
	uiGlobal.sp_showAlternateMissionLog = false
}

void function UICodeCallback_NavigateBack()
{
	if ( uiGlobal.activeMenu == null )
		return

	if ( IsDialog( uiGlobal.activeMenu ) )
	{
		if ( uiGlobal.menuData[ uiGlobal.activeMenu ].dialogData.noChoice ||
			 uiGlobal.menuData[ uiGlobal.activeMenu ].dialogData.forceChoice ||
			 Time() < uiGlobal.dialogInputEnableTime )
			return
	}

	Assert( uiGlobal.activeMenu in uiGlobal.menuData )
	if ( uiGlobal.menuData[ uiGlobal.activeMenu ].navBackFunc != null )
	{
		thread uiGlobal.menuData[ uiGlobal.activeMenu ].navBackFunc()
		return
	}

	if ( uiGlobal.activeMenu.GetType() == "submenu" ) // REMOVE
	{
		CloseSubmenu()
		return
	}

	CloseActiveMenu( true )
}

// Called when IsConnected() will start returning true.
void function UICodeCallback_OnConnected()
{

}

void function UICodeCallback_OnFocusChanged( var oldFocusedPanel, var newFocusedPanel )
{

}

// Accepting an origin invite closes dialogs, or aborts if they can't be closed
bool function UICodeCallback_TryCloseDialog()
{
	if ( !IsDialog( uiGlobal.activeMenu ) )
		return true

	if ( uiGlobal.menuData[ uiGlobal.activeMenu ].dialogData.forceChoice )
		return false

	CloseAllDialogs()
	Assert( !IsDialog( uiGlobal.activeMenu ) )
	return true
}

void function UICodeCallback_ConsoleKeyboardClosed()
{
	switch ( uiGlobal.activeMenu )
	{
		case GetMenu( "EditPilotLoadoutMenu" ):
			string oldName = GetPilotLoadoutName( GetCachedPilotLoadout( uiGlobal.editingLoadoutIndex ) )
			string newName = GetPilotLoadoutRenameText()

			// strip doesn't work on UTF-8 strings
			// newName = strip( newName ) // Remove leading/trailing whitespace
			if ( newName == "" ) // If all whitespace entered reset to previous name
				newName = oldName

			SetPilotLoadoutName( newName )
			SelectPilotLoadoutRenameText()
			if ( newName != oldName )
				EmitUISound( "Menu.Accept" ) // No callback when cancelled so for now assume name was changed
			break

		default:
			break
	}
}

void function UICodeCallback_OnDetenteDisplayed()
{
//	thread PlayDetentSound()
//}
//
//void function PlayDetentSound()
//{
//	WaitFrame() // otherwise gets killed off by code pause
//	WaitFrame() // otherwise gets killed off by code pause
//	EmitUISound( "Pilot_Killed_Indicator" )
}

void function UICodeCallback_OnSpLogDisplayed()
{
}

void function UICodeCallback_ErrorDialog( string errorDetails )
{
	printt( "UICodeCallback_ErrorDialog: " +  errorDetails )
	thread OpenErrorDialog( errorDetails )
}

void function UICodeCallback_AcceptInviteThread( string accesstoken )
{
	printt( "UICodeCallback_AcceptInviteThread '" + accesstoken + "'")

	#if PS4_PROG
		if ( !Ps4_PSN_Is_Loggedin() )
		{
			Ps4_LoginDialog_Schedule();
			while( Ps4_LoginDialog_Running() )
				WaitFrame()
			if ( !Ps4_PSN_Is_Loggedin() )
				return;
		}

		if( Ps4_CheckPlus_Schedule() )
		{
			while( Ps4_CheckPlus_Running() )
				WaitFrame()
			if( !Ps4_CheckPlus_Allowed() )
			{
				if( Ps4_CheckPlus_GetLastRequestResults() != 0 )
				{
					return
				}

				if( Ps4_ScreenPlusDialog_Schedule() )
				{
					while( Ps4_ScreenPlusDialog_Running() )
						WaitFrame()
					if( !Ps4_ScreenPlusDialog_Allowed() )
						return;
				}
				else
				{
  					return;
				}
			}
		}

	#endif // #if PS4_PROG

    SubscribeToChatroomPartyChannel( accesstoken );

}


void function UICodeCallback_AcceptInvite( string accesstoken )
{
	printt( "UICodeCallback_AcceptInvite '" + accesstoken + "'")
	thread 	UICodeCallback_AcceptInviteThread( accesstoken )
}

// TODO: replaceCurrent should not be an option. It should be a different function.
void function AdvanceMenu( var menu, bool replaceCurrent = false )
{
	//foreach ( index, menu in uiGlobal.menuStack )
	//{
	//	if ( menu != null )
	//		printt( "menu index " + index + " is named " + menu.GetDisplayName() )
	//}

	if ( uiGlobal.activeMenu )
	{
		// Don't open the same menu again if it's already open
		if ( uiGlobal.activeMenu == menu )
			return

		// Opening a normal menu while a dialog is open
		Assert( !IsDialog( uiGlobal.activeMenu ), "Tried opening menu: " + Hud_GetHudName( menu ) + " when uiGlobal.activeMenu was: " + Hud_GetHudName( uiGlobal.activeMenu ) )
	}

	if ( uiGlobal.activeMenu && !IsDialog( menu ) ) // Dialogs show on top so don't close existing menu when opening them
	{
		SetBlurEnabled( false )

		if ( replaceCurrent )
		{
			CloseMenuWrapper( uiGlobal.activeMenu )
			uiGlobal.menuStack.pop()
		}
		else
		{
			CloseMenu( uiGlobal.activeMenu )
			printt( Hud_GetHudName( uiGlobal.activeMenu ), "menu closed" )
		}
	}

	if ( IsDialog( menu ) && uiGlobal.activeMenu )
		SetFooterPanelVisibility( uiGlobal.activeMenu, false )

	uiGlobal.menuStack.push( menu )
	uiGlobal.activeMenu = menu

	uiGlobal.lastMenuNavDirection = MENU_NAV_FORWARD

	if ( uiGlobal.activeMenu )
	{
		if ( !IsLobby() && !uiGlobal.mapSupportsMenuModels )
			SetBlurEnabled( true )

		OpenMenuWrapper( uiGlobal.activeMenu, true )
	}

	Signal( uiGlobal.signalDummy, "ActiveMenuChanged" )
}

void function SetFooterPanelVisibility( var menu, bool visible )
{
	if ( !Hud_HasChild( menu, "FooterButtons" ) )
		return

	var panel = Hud_GetChild( menu, "FooterButtons" )
	Hud_SetVisible( panel, visible )
}

void function OpenSubmenu( var menu, bool updateMenuPos = true )
{
	Assert( menu )
	Assert( menu.GetType() == "submenu" )

	if ( uiGlobal.activeMenu )
	{
		// Don't open the same menu again if it's already open
		if ( uiGlobal.activeMenu == menu )
			return
	}

	local submenuPos = Hud_GetAbsPos( GetFocus() )

	uiGlobal.menuStack.push( menu )
	uiGlobal.activeMenu = menu

	OpenMenuWrapper( uiGlobal.activeMenu, true )

	if ( updateMenuPos )
	{
		var vguiButtonFrame = Hud_GetChild( uiGlobal.activeMenu, "ButtonFrame" )
		Hud_SetPos( vguiButtonFrame, submenuPos[0], submenuPos[1] )
	}

	uiGlobal.lastMenuNavDirection = MENU_NAV_FORWARD

	Signal( uiGlobal.signalDummy, "ActiveMenuChanged" )
}

void function CloseSubmenu( bool openStackMenu = true )
{
	if ( !uiGlobal.activeMenu )
		return

	if ( uiGlobal.activeMenu.GetType() != "submenu" )
		return

	CloseMenuWrapper( uiGlobal.activeMenu )
	uiGlobal.menuStack.pop()

	uiGlobal.lastMenuNavDirection = MENU_NAV_FORWARD

	if ( uiGlobal.menuStack.len() )
	{
		uiGlobal.activeMenu = uiGlobal.menuStack.top()

		// This runs any OnOpen function for the menu and sets focus, but doesn't actually open the menu because it is already open
		if ( openStackMenu )
			OpenMenuWrapper( uiGlobal.activeMenu, false )
	}
	else
	{
		uiGlobal.activeMenu = null
	}

	Signal( uiGlobal.signalDummy, "ActiveMenuChanged" )
}

void function CloseActiveMenuNoParms()
{
	CloseActiveMenu()
}

void function CloseActiveMenu( bool cancelled = false, bool openStackMenu = true )
{
	bool updateBlur = true
	bool wasDialog = false

	if ( uiGlobal.activeMenu )
	{
		if ( IsDialog( uiGlobal.activeMenu ) )
		{
			updateBlur = false
			wasDialog = true
			uiGlobal.dialogInputEnableTime = 0.0

			if ( uiGlobal.dialogCloseCallback )
			{
				uiGlobal.dialogCloseCallback( cancelled )
				uiGlobal.dialogCloseCallback = null
			}
		}

		if ( updateBlur )
			SetBlurEnabled( false )

		CloseMenuWrapper( uiGlobal.activeMenu )
	}

	uiGlobal.menuStack.pop()
	if ( uiGlobal.menuStack.len() )
		uiGlobal.activeMenu = uiGlobal.menuStack.top()
	else
		uiGlobal.activeMenu = null

	uiGlobal.lastMenuNavDirection = MENU_NAV_BACK

	if ( wasDialog )
	{
		if ( uiGlobal.activeMenu )
			SetFooterPanelVisibility( uiGlobal.activeMenu, true )

		if ( IsDialog( uiGlobal.activeMenu ) )
			openStackMenu = true
		else
			openStackMenu = false
	}

	if ( uiGlobal.activeMenu )
	{
		if ( uiGlobal.activeMenu.GetType() == "submenu" )
		{
			Hud_SetFocused( uiGlobal.menuData[ uiGlobal.activeMenu ].lastFocus )
		}
		else if ( openStackMenu )
		{
			OpenMenuWrapper( uiGlobal.activeMenu, false )

			if ( updateBlur && !IsLobby() && !uiGlobal.mapSupportsMenuModels )
				SetBlurEnabled( true )
		}
	}

	Signal( uiGlobal.signalDummy, "ActiveMenuChanged" )
}

void function CloseAllMenus()
{
	if ( IsDialog( uiGlobal.activeMenu ) )
		CloseActiveMenu( true )

	if ( uiGlobal.activeMenu && uiGlobal.activeMenu.GetType() == "submenu" )
		CloseSubmenu( false )

	if ( uiGlobal.activeMenu )
	{
		SetBlurEnabled( false )
		CloseMenuWrapper( uiGlobal.activeMenu )
	}

	uiGlobal.menuStack = []
	uiGlobal.activeMenu = null

	uiGlobal.lastMenuNavDirection = MENU_NAV_BACK

	Signal( uiGlobal.signalDummy, "ActiveMenuChanged" )
}

void function CloseAllInGameMenus()
{
	while ( uiGlobal.activeMenu )
	{
		if ( uiGlobal.activeMenu.GetType() == "submenu" )
			CloseSubmenu( false )

		CloseActiveMenu( true, false )
	}
}

void function CloseAllDialogs()
{
	while ( IsDialog( uiGlobal.activeMenu ) )
		CloseActiveMenu( true )
}

void function CloseAllToTargetMenu( var targetMenu )
{
	while ( uiGlobal.activeMenu != targetMenu )
		CloseActiveMenu( true, false )
}

void function PrintMenuStack()
{
	array<var> stack = clone uiGlobal.menuStack
	stack.reverse()

	printt( "MENU STACK:" )

	foreach ( menu in stack )
	{
		if ( menu )
			printt( "   ", Hud_GetHudName( menu ) )
		else
			printt( "    null" )
	}
}

// Happens on any level load
void function UpdateMenusOnConnect( string levelname )
{
	EndSignal( uiGlobal.signalDummy, "LevelShutdown" ) // HACK fix because UICodeCallback_LevelInit() incorrectly runs when disconnected by client error. Test with "script_error_client" while a level is loaded.

	CloseAllDialogs()

	var mainMenu = GetMenu( "MainMenu" )
	if ( IsMenuInMenuStack( mainMenu ) && !IsMenuInMenuStack( null ) )
		CloseAllToTargetMenu( mainMenu )

	Assert( uiGlobal.activeMenu != null || uiGlobal.menuStack.len() == 0 )

	AdvanceMenu( null )

	// TODO: The order things are called in should be predictable so this isn't needed
	while ( !uiGlobal.mapSupportsMenuModelsUpdated )
	{
		//printt( Time(), "beginning waitframe, uiGlobal.mapSupportsMenuModelsUpdated is:", uiGlobal.mapSupportsMenuModelsUpdated )
		WaitFrame()
		//printt( Time(), "ended waitframe, uiGlobal.mapSupportsMenuModelsUpdated is:", uiGlobal.mapSupportsMenuModelsUpdated )
	}

	if ( IsLevelMultiplayer( levelname ) )
	{
		bool isLobby = IsLobbyMapName( levelname )

		if ( isLobby )
		{
			if ( IsPrivateMatch() )
			{
				AdvanceMenu( GetMenu( "PrivateLobbyMenu" ) )
			}
			else
			{
				AdvanceMenu( GetMenu( "LobbyMenu" ) )
			}

			thread UpdateAnnouncementDialog()
		}
		else
		{
			UI_SetPresentationType( ePresentationType.INACTIVE )
		}
	}
}

bool function IsMenuInMenuStack( var searchMenu )
{
	foreach ( menu in uiGlobal.menuStack )
	{
		// loading a map pushes a null sentinel onto the menu stack
		if ( !menu )
			continue

		if ( menu == searchMenu )
			return true
	}

	return false
}

var function GetTopNonDialogMenu()
{
	array<var> menuArray = clone uiGlobal.menuStack
	menuArray.reverse()

	foreach ( menu in menuArray )
	{
		if ( menu == null || IsDialog( menu ) )
			continue

		return menu
	}

	return null
}

void function CleanupInGameMenus()
{
	Signal( uiGlobal.signalDummy, "CleanupInGameMenus" )

	CloseAllInGameMenus()
	Assert( uiGlobal.activeMenu == null )
	if ( uiGlobal.menuStack.len() )
	{
		if ( uiGlobal.loadingLevel == "" )
			CloseActiveMenu() // Disconnected. Remove stack null and open main menu.
		else
			CloseActiveMenu( true, false ) // Level to level transition. Remove stack null and DON'T open main menu.
	}
}

var function GetActiveMenu()
{
	return uiGlobal.activeMenu
}

var function GetMenu( string menuName )
{
	return uiGlobal.menus[ menuName ]
}

var function GetPanel( string panelName )
{
	return uiGlobal.panels[ panelName ]
}

array<var> function GetAllMenuPanels( var menu )
{
	array<var> menuPanels

	foreach ( panel in uiGlobal.allPanels )
	{
		if ( Hud_GetParent( panel ) == menu )
			menuPanels.append( panel )
	}

	return menuPanels
}

void function InitGamepadConfigs()
{
	uiGlobal.buttonConfigs = [ { orthodox = "gamepad_button_layout_default.cfg", southpaw = "gamepad_button_layout_default_southpaw.cfg" } ]
	uiGlobal.buttonConfigs.append( { orthodox = "gamepad_button_layout_bumper_jumper.cfg", southpaw = "gamepad_button_layout_bumper_jumper_southpaw.cfg" } )
	uiGlobal.buttonConfigs.append( { orthodox = "gamepad_button_layout_bumper_jumper_alt.cfg", southpaw = "gamepad_button_layout_bumper_jumper_alt_southpaw.cfg" } )
	uiGlobal.buttonConfigs.append( { orthodox = "gamepad_button_layout_pogo_stick.cfg", southpaw = "gamepad_button_layout_pogo_stick_southpaw.cfg" } )
	uiGlobal.buttonConfigs.append( { orthodox = "gamepad_button_layout_button_kicker.cfg", southpaw = "gamepad_button_layout_button_kicker_southpaw.cfg" } )
	uiGlobal.buttonConfigs.append( { orthodox = "gamepad_button_layout_circle.cfg", southpaw = "gamepad_button_layout_circle_southpaw.cfg" } )
	uiGlobal.buttonConfigs.append( { orthodox = "gamepad_button_layout_ninja.cfg", southpaw = "gamepad_button_layout_ninja_southpaw.cfg" } )
	uiGlobal.buttonConfigs.append( { orthodox = "gamepad_button_layout_custom.cfg", southpaw = "gamepad_button_layout_custom.cfg" } )

	uiGlobal.stickConfigs = []
	uiGlobal.stickConfigs.append( "gamepad_stick_layout_default.cfg" )
	uiGlobal.stickConfigs.append( "gamepad_stick_layout_southpaw.cfg" )
	uiGlobal.stickConfigs.append( "gamepad_stick_layout_legacy.cfg" )
	uiGlobal.stickConfigs.append( "gamepad_stick_layout_legacy_southpaw.cfg" )

	foreach ( key, val in uiGlobal.buttonConfigs )
	{
		VPKNotifyFile( "cfg/" + val.orthodox )
		VPKNotifyFile( "cfg/" + val.southpaw )
	}

	foreach ( key, val in uiGlobal.stickConfigs )
		VPKNotifyFile( "cfg/" + val )

	ExecCurrentGamepadButtonConfig()
	ExecCurrentGamepadStickConfig()

	SetStandardAbilityBindingsForPilot( GetLocalClientPlayer() )
}

void function InitMenus()
{
	InitGlobalMenuVars()
	SpShWeaponsInit()

	AddMenu( "MainMenu", $"resource/ui/menus/main.menu", InitMainMenu, "#MAIN" )
	AddPanel( GetMenu( "MainMenu" ), "EstablishUserPanel", InitEstablishUserPanel )
	AddPanel( GetMenu( "MainMenu" ), "MainMenuPanel", InitMainMenuPanel )
	
	// stub
	void functionref() InitModMenu = void function(){}
	AddMenu( "ModListMenu", $"resource/ui/menus/modlist.menu", InitModMenu, "#MENU_MODS" )

	AddMenu( "PlayVideoMenu", $"resource/ui/menus/play_video.menu", InitPlayVideoMenu )
	AddMenu( "LobbyMenu", $"resource/ui/menus/lobby.menu", InitLobbyMenu, "#LOBBY" )
	
	// stub
	void functionref() InitServerBrowserMenu = void function(){}
	AddMenu( "ServerBrowserMenu", $"resource/ui/menus/server_browser.menu", InitServerBrowserMenu, "#MENU_SERVER_BROWSER" )

	AddMenu( "FDMenu", $"resource/ui/menus/playlist_fd.menu", InitFDPlaylistMenu )
	AddMenu( "TeamTitanSelectMenu", $"resource/ui/menus/team_titan_select.menu", InitTeamTitanSelectMenu )
	AddMenu( "PlaylistMenu", $"resource/ui/menus/playlist.menu", InitPlaylistMenu )
	AddMenu( "PlaylistMixtapeMenu", $"resource/ui/menus/playlist_mixtape.menu", InitPlaylistMixtapeMenu )
	AddMenu( "PlaylistMixtapeChecklistMenu", $"resource/ui/menus/playlist_mixtape_checklist.menu", InitPlaylistMixtapeChecklistMenu )

	AddMenu( "SinglePlayerDevMenu", $"resource/ui/menus/singleplayer_dev.menu", InitSinglePlayerDevMenu, "SINGLE PLAYER DEV" )
	AddMenu( "SinglePlayerMenu", $"resource/ui/menus/singleplayer.menu", InitSinglePlayerMenu, "SINGLE PLAYER" )

	AddMenu( "SearchMenu", $"resource/ui/menus/search.menu", InitSearchMenu )

	AddMenu( "GammaMenu", $"resource/ui/menus/gamma.menu", InitGammaMenu, "#BRIGHTNESS" )

	AddMenu( "CommunitiesMenu", $"resource/ui/menus/community.menu", InitCommunitiesMenu )
	AddMenu( "Notifications", $"resource/ui/menus/notifications.menu", InitNotificationsMenu )
	AddMenu( "MyNetworks", $"resource/ui/menus/communities_mine.menu", InitMyNetworksMenu )
	AddMenu( "InboxFrontMenu", $"resource/ui/menus/inbox_front.menu", InitInboxFrontMenu )
	AddMenu( "Inbox", $"resource/ui/menus/inbox.menu", InitInboxMenu )
	AddMenu( "BrowseCommunities", $"resource/ui/menus/communities_browse.menu" )
	AddMenu( "CommunityEditMenu", $"resource/ui/menus/community_edit.menu" )
	AddMenu( "CommunityAdminSendMessage", $"resource/ui/menus/community_sendMessage.menu" )
	AddMenu( "CommunityAdminInviteRequestMenu", $"resource/ui/menus/community_inviteRequest.menu" )
#if NETWORK_INVITE
	AddMenu( "InviteFriendsToNetworkMenu", $"resource/ui/menus/invite_friends.menu", InitInviteFriendsToNetworkMenu )
#endif

	AddMenu( "InGameMPMenu", $"resource/ui/menus/ingame_mp.menu", InitInGameMPMenu )
	AddMenu( "InGameSPMenu", $"resource/ui/menus/ingame_sp.menu", InitInGameSPMenu )

	AddMenu( "Dialog", $"resource/ui/menus/dialog.menu", InitDialogMenu )
	AddMenu( "AnnouncementDialog", $"resource/ui/menus/dialog_announcement.menu", InitAnnouncementDialog )
	AddMenu( "ConnectingDialog", $"resource/ui/menus/dialog_connecting.menu", InitConnectingDialog )
	AddMenu( "DataCenterDialog", $"resource/ui/menus/dialog_datacenter.menu", InitDataCenterDialogMenu )
	AddMenu( "EULADialog", $"resource/ui/menus/dialog_eula.menu", InitEULADialog )
	AddMenu( "ReviewTermsDialog", $"resource/ui/menus/dialog_review_terms.menu", InitReviewTermsDialog )
	AddMenu( "RegistrationDialog", $"resource/ui/menus/dialog_registration.menu", InitRegistrationDialog )
	AddMenu( "AdvocateGiftDialog", $"resource/ui/menus/dialog_advocate_gift.menu", InitAdvocateGiftDialog )

	AddMenu( "ControlsMenu", $"resource/ui/menus/controls.menu", InitControlsMenu, "#CONTROLS" )
	AddMenu( "ControlsAdvancedLookMenu", $"resource/ui/menus/controls_advanced_look.menu", InitControlsAdvancedLookMenu, "#CONTROLS_ADVANCED_LOOK" )
	AddMenu( "GamepadLayoutMenu", $"resource/ui/menus/gamepadlayout.menu", InitGamepadLayoutMenu )
#if PC_PROG
	AddMenu_WithCreateFunc( "MouseKeyboardBindingsMenu", $"resource/ui/menus/mousekeyboardbindings.menu", InitMouseKeyboardMenu, CreateKeyBindingMenu )
	AddMenu( "AudioMenu", $"resource/ui/menus/audio.menu", InitAudioMenu, "#AUDIO" )
	AddMenu_WithCreateFunc( "VideoMenu", $"resource/ui/menus/video.menu", InitVideoMenu, CreateVideoOptionsMenu )
#elseif CONSOLE_PROG
	AddMenu( "AudioVideoMenu", $"resource/ui/menus/audio_video.menu", InitAudioVideoMenu, "#AUDIO_VIDEO" )
#endif

	AddMenu( "AdvancedHudMenu", $"resource/ui/menus/advanced_hud.menu", InitAdvancedHudMenu, "#ADVANCED_HUD" )

	AddMenu( "PilotLoadoutsMenu", $"resource/ui/menus/pilotloadouts.menu", InitPilotLoadoutsMenu )
	AddMenu( "TitanLoadoutsMenu", $"resource/ui/menus/titanloadouts.menu", InitTitanLoadoutsMenu )
	AddMenu( "EditPilotLoadoutsMenu", $"resource/ui/menus/pilotloadouts.menu", InitEditPilotLoadoutsMenu )
	AddMenu( "EditTitanLoadoutsMenu", $"resource/ui/menus/titanloadouts.menu", InitEditTitanLoadoutsMenu )
	AddMenu( "EditPilotLoadoutMenu", $"resource/ui/menus/editpilotloadout.menu", InitEditPilotLoadoutMenu )
	AddMenu( "EditTitanLoadoutMenu", $"resource/ui/menus/edittitanloadout.menu", InitEditTitanLoadoutMenu )

	AddMenu( "SPTitanLoadoutMenu", $"resource/ui/menus/sptitanloadout.menu", InitSPTitanLoadoutMenu )
	AddMenu( "SPTitanLoadoutTutorialMenu", $"resource/ui/menus/sptitanloadout_tutorial.menu", InitSPTitanLoadoutTutorialMenu )

	AddMenu( "SuitSelectMenu", $"resource/ui/menus/suitselect.menu", InitSuitSelectMenu )
	AddMenu( "WeaponSelectMenu", $"resource/ui/menus/weaponselect.menu", InitWeaponSelectMenu )
	AddMenu( "CategorySelectMenu", $"resource/ui/menus/categoryselect.menu", InitCategorySelectMenu )
	AddMenu( "AbilitySelectMenu", $"resource/ui/menus/abilityselect.menu", InitAbilitySelectMenu )
	AddMenu( "PassiveSelectMenu", $"resource/ui/menus/passiveselect.menu", InitPassiveSelectMenu )
	AddSubmenu( "ModSelectMenu", $"resource/ui/menus/modselect.menu", InitModSelectMenu )
	AddMenu( "CamoSelectMenu", $"resource/ui/menus/camoselect.menu", InitCamoSelectMenu )
	AddMenu( "NoseArtSelectMenu", $"resource/ui/menus/noseartselect.menu", InitNoseArtSelectMenu )
	AddMenu( "CallsignCardSelectMenu", $"resource/ui/menus/callsigncardselect.menu", InitCallsignCardSelectMenu )
	AddMenu( "CallsignIconSelectMenu", $"resource/ui/menus/callsigniconselect.menu", InitCallsignIconSelectMenu )
	AddMenu( "BoostStoreMenu", $"resource/ui/menus/booststore.menu", InitBoostStoreMenu )

	AddMenu( "PrivateLobbyMenu", $"resource/ui/menus/private_lobby.menu", InitPrivateMatchMenu, "#PRIVATE_MATCH" )
	AddMenu( "MapsMenu", $"resource/ui/menus/map_select.menu", InitMapsMenu )
	AddMenu( "ModesMenu", $"resource/ui/menus/mode_select.menu", InitModesMenu )
	AddMenu( "MatchSettingsMenu", $"resource/ui/menus/match_settings.menu", InitMatchSettingsMenu )

	AddMenu( "Advocate_Letter", $"resource/ui/menus/advocate_letter.menu", InitAdvocateLetterMenu )
	AddMenu( "Generation_Respawn", $"resource/ui/menus/generation_respawn.menu", InitGenerationRespawnMenu )
	AddMenu( "ChallengesMenu", $"resource/ui/menus/challenges.menu", InitChallengesMenu )

	AddMenu( "ViewStatsMenu", $"resource/ui/menus/viewstats.menu", InitViewStatsMenu, "#PERSONAL_STATS" )
	AddMenu( "ViewStats_Overview_Menu", $"resource/ui/menus/viewstats_overview.menu", InitViewStatsOverviewMenu )
	//AddMenu( "ViewStats_Kills_Menu", $"resource/ui/menus/viewstats_kills.menu", InitViewStatsKillsMenu )
	AddMenu( "ViewStats_Time_Menu", $"resource/ui/menus/viewstats_time.menu", InitViewStatsTimeMenu )
	//AddMenu( "ViewStats_Distance_Menu", $"resource/ui/menus/viewstats_distance.menu", InitViewStatsDistanceMenu )
	AddMenu( "ViewStats_Weapons_Menu", $"resource/ui/menus/viewstats_weapons.menu", InitViewStatsWeaponsMenu )
	AddMenu( "ViewStats_Titans_Menu", $"resource/ui/menus/viewstats_titans.menu", InitViewStatsTitansMenu )
	AddMenu( "ViewStats_Misc_Menu", $"resource/ui/menus/viewstats_misc.menu", InitViewStatsMiscMenu )
	AddMenu( "ViewStats_Maps_Menu", $"resource/ui/menus/viewstats_maps.menu", InitViewStatsMapsMenu )

	AddMenu( "PostGameMenu", $"resource/ui/menus/postgame.menu", InitPostGameMenu )
	AddMenu( "EOG_XP", $"resource/ui/menus/eog_xp.menu", InitEOG_XPMenu )
	AddMenu( "EOG_Coins", $"resource/ui/menus/eog_coins.menu", InitEOG_CoinsMenu )
	AddMenu( "EOG_Challenges", $"resource/ui/menus/eog_challenges.menu", InitEOG_ChallengesMenu )
	AddMenu( "EOG_Unlocks", $"resource/ui/menus/eog_unlocks.menu", InitEOG_UnlocksMenu )
	AddMenu( "EOG_Scoreboard", $"resource/ui/menus/eog_scoreboard.menu", InitEOG_ScoreboardMenu )

	AddMenu( "CreditsMenu", $"resource/ui/menus/credits.menu", InitCreditsMenu, "#CREDITS" )

	AddMenu( "BurnCardMenu", $"resource/ui/menus/burn_cards.menu", InitBurnCardMenu, "#MENU_BURNCARD_MENU" )
	AddMenu( "FactionChoiceMenu", $"resource/ui/menus/faction_choice.menu", InitFactionChoiceMenu, "#FACTION_CHOICE_MENU" )
	AddMenu( "ArmoryMenu", $"resource/ui/menus/armory.menu", InitArmoryMenu, "#ARMORY_MENU" )

	AddMenu( "StoreMenu", $"resource/ui/menus/store.menu", InitStoreMenu, "#STORE_MENU" )
	AddMenu( "StoreMenu_NewReleases", $"resource/ui/menus/store_new_releases.menu", InitStoreMenuNewReleases, "#STORE_NEW_RELEASES" )
	AddMenu( "StoreMenu_Limited", $"resource/ui/menus/store_limited.menu", InitStoreMenuLimited, "#STORE_LIMITED" )
	AddMenu( "StoreMenu_Sales", $"resource/ui/menus/store_bundles.menu", InitStoreMenuSales, "#STORE_BUNDLES" )
	AddMenu( "StoreMenu_Titans", $"resource/ui/menus/store_prime_titans.menu", InitStoreMenuTitans, "#STORE_TITANS" ) // reusing store_prime_titans.menu
	AddMenu( "StoreMenu_PrimeTitans", $"resource/ui/menus/store_prime_titans.menu", InitStoreMenuPrimeTitans, "#STORE_PRIME_TITANS" )
	//AddMenu( "StoreMenu_WeaponSelect", $"resource/ui/menus/store_weapon_select.menu", InitStoreMenuWeaponSelect )
	//AddMenu( "StoreMenu_WeaponSkinPreview", $"resource/ui/menus/store_weapon_skin_preview.menu", InitStoreMenuWeaponSkinPreview )
	AddMenu( "StoreMenu_WeaponSkinBundles", $"resource/ui/menus/store_weapon_skin_bundles.menu", InitStoreMenuWeaponSkinBundles )
	AddMenu( "StoreMenu_WeaponSkins", $"resource/ui/menus/store_weapons.menu", InitStoreMenuWeaponSkins )
	AddMenu( "StoreMenu_Customization", $"resource/ui/menus/store_customization.menu", InitStoreMenuCustomization, "#STORE_CUSTOMIZATION_PACKS" )
	AddMenu( "StoreMenu_CustomizationPreview", $"resource/ui/menus/store_customization_preview.menu", InitStoreMenuCustomizationPreview, "#STORE_CUSTOMIZATION_PACKS" )
	AddMenu( "StoreMenu_Camo", $"resource/ui/menus/store_camo.menu", InitStoreMenuCamo, "#STORE_CAMO_PACKS" )
	AddMenu( "StoreMenu_CamoPreview", $"resource/ui/menus/store_camo_preview.menu", InitStoreMenuCamoPreview, "#STORE_CAMO_PACKS" )
	AddMenu( "StoreMenu_Callsign", $"resource/ui/menus/store_callsign.menu", InitStoreMenuCallsign, "#STORE_CALLSIGN_PACKS" )
	AddMenu( "StoreMenu_CallsignPreview", $"resource/ui/menus/store_callsign_preview.menu", InitStoreMenuCallsignPreview, "#STORE_CALLSIGN_PACKS" )

	AddMenu( "KnowledgeBaseMenu", $"resource/ui/menus/knowledgebase.menu", InitKnowledgeBaseMenu )
	AddMenu( "KnowledgeBaseMenuSubMenu", $"resource/ui/menus/knowledgebase_submenu.menu", InitKnowledgeBaseMenuSubMenu )

	AddMenu( "DevMenu", $"resource/ui/menus/dev.menu", InitDevMenu, "Dev" )
	InitSharedStartPoints()

	foreach ( menu in uiGlobal.allMenus )
	{
		if ( uiGlobal.menuData[ menu ].initFunc != null )
			uiGlobal.menuData[ menu ].initFunc()

		array<var> elems = GetElementsByClassname( menu, "TabsCommonClass" )
		if ( elems.len() )
			uiGlobal.menuData[ menu ].hasTabs = true

		elems = GetElementsByClassname( menu, "EnableKeyBindingIcons" )
		foreach ( elem in elems )
			Hud_EnableKeyBindingIcons( elem )
	}

	InitTabs()

	var tabbedMenu = GetMenu( "PostGameMenu" )
	AddPanel( tabbedMenu, "PVEPanel", InitPVEPanel )
	AddPanel( tabbedMenu, "SummaryPanel", InitSummaryPanel )
	AddPanel( tabbedMenu, "FDAwardsPanel", InitFDAwardsPanel )

	AddPanel( tabbedMenu, "ScoreboardPanel", InitScoreboardPanel )

	foreach ( panel in uiGlobal.allPanels )
	{
		if ( uiGlobal.panelData[ panel ].initFunc != null )
			uiGlobal.panelData[ panel ].initFunc()
	}

	// A little weird, but GetElementsByClassname() uses menu scope rather than parent scope.
	foreach ( menu in uiGlobal.allMenus )
	{
		array<var> buttons = GetElementsByClassname( menu, "DefaultFocus" )
		foreach ( button in buttons )
		{
			var panel = Hud_GetParent( button )

			//Assert( elems.len() == 1, "More than 1 panel element set as DefaultFocus!" )
			Assert( panel != null, "no parent panel found for button " + Hud_GetHudName( button ) )
			Assert( panel in uiGlobal.panelData, "panel " + Hud_GetHudName( panel ) + " isn't in uiGlobal.panelData, but button " + Hud_GetHudName( button ) + " has defaultFocus set!" )
			uiGlobal.panelData[ panel ].defaultFocus = button
			//printt( "Found DefaultFocus, button was:", Hud_GetHudName( button ), "panel was:", Hud_GetHudName( panel ) )
		}
	}

	InitFooterOptions()

	#if DEV
	if ( Dev_CommandLineHasParm( "-autoprecache_all" ) )
	{
		// repreache all levels
		ExecuteLoadingClientCommands_SetStartPoint( "sp_training" )
		ClientCommand( "map sp_training" )
		CloseAllMenus()
	}
	#endif
}

void functionref( var ) function AdvanceMenuEventHandler( var menu )
{
	return void function( var item ) : ( menu )
	{
		if ( Hud_IsLocked( item ) )
			return

		AdvanceMenu( menu )
	}
}

void function PCBackButton_Activate( var button )
{
	UICodeCallback_NavigateBack()
}

void function PCSwitchTeamsButton_Activate( var button )
{
	ClientCommand( "PrivateMatchSwitchTeams" )
}

void function PCToggleSpectateButton_Activate( var button )
{
	ClientCommand( "PrivateMatchToggleSpectate" )
}

void function ToggleButtonStates( var button )
{
	for ( ;; )
	{
		Hud_SetEnabled( button, true )
		wait 1
		Hud_SetSelected( button, true )
		wait 1
		Hud_SetLocked( button, true )
		wait 1
		Hud_SetNew( button, true )
		wait 1
		Hud_SetNew( button, false )
		wait 1
		Hud_SetLocked( button, false )
		wait 1
		Hud_SetSelected( button, false )
		wait 1
		Hud_SetEnabled( button, false )
		wait 1
	}
}

void function AddMenuElementsByClassname( var menu, string classname )
{
	array<var> elements = GetElementsByClassname( menu, classname )

	if ( !(classname in menu.classElements) )
		menu.classElements[classname] <- []

	menu.classElements[classname].extend( elements )
}

void function FocusDefault( var menu )
{
	if (
				menu == GetMenu( "MainMenu" ) ||
				menu == GetMenu( "CategorySelectMenu" ) ||
			  menu == GetMenu( "AbilitySelectMenu" ) ||
			  menu == GetMenu( "PassiveSelectMenu" ) ||
			  menu == GetMenu( "WeaponSelectMenu" ) ||
			  menu == GetMenu( "SuitSelectMenu" ) ||
			  menu == GetMenu( "CamoSelectMenu" ) ||
			  menu == GetMenu( "NoseArtSelectMenu" ) ||
			  menu == GetMenu( "FactionChoiceMenu" ) ||
			  menu == GetMenu( "BurnCardMenu" ) ||
			  menu == GetMenu( "CallsignCardSelectMenu" ) ||
			  menu == GetMenu( "CallsignIconSelectMenu" ) )
	{
	}
	else
	{
		//printt( "FocusDefaultMenuItem() called" )
		FocusDefaultMenuItem( menu )
	}
}

void function SetPanelDefaultFocus( var panel, var button )
{
	uiGlobal.panelData[ panel ].defaultFocus = button
}

void function PanelFocusDefault( var panel )
{
	//printt( "PanelFocusDefault called" )
	if ( uiGlobal.panelData[ panel ].defaultFocus )
	{
		Hud_SetFocused( uiGlobal.panelData[ panel ].defaultFocus )
		//printt( "PanelFocusDefault if passed,", Hud_GetHudName( uiGlobal.panelData[ panel ].defaultFocus ), "focused" )
	}
}

void function SetMenuThinkFunc( var menu, void functionref() func )
{
	Assert( uiGlobal.menuData[ menu ].thinkFunc == null )
	uiGlobal.menuData[ menu ].thinkFunc = func
}

void function AddMenuEventHandler( var menu, int event, void functionref() func )
{
	if ( event == eUIEvent.MENU_OPEN )
	{
		Assert( uiGlobal.menuData[ menu ].openFunc == null )
		uiGlobal.menuData[ menu ].openFunc = func
	}
	else if ( event == eUIEvent.MENU_CLOSE )
	{
		Assert( uiGlobal.menuData[ menu ].closeFunc == null )
		uiGlobal.menuData[ menu ].closeFunc = func
	}
	else if ( event == eUIEvent.MENU_SHOW )
	{
		Assert( uiGlobal.menuData[ menu ].showFunc == null )
		uiGlobal.menuData[ menu ].showFunc = func
	}
	else if ( event == eUIEvent.MENU_HIDE )
	{
		Assert( uiGlobal.menuData[ menu ].hideFunc == null )
		uiGlobal.menuData[ menu ].hideFunc = func
	}
	else if ( event == eUIEvent.MENU_NAVIGATE_BACK )
	{
		Assert( uiGlobal.menuData[ menu ].navBackFunc == null )
		uiGlobal.menuData[ menu ].navBackFunc = func
	}
	else if ( event == eUIEvent.MENU_TAB_CHANGED )
	{
		Assert( uiGlobal.menuData[ menu ].tabChangedFunc == null )
		uiGlobal.menuData[ menu ].tabChangedFunc = func
	}
	else if ( event == eUIEvent.MENU_ENTITLEMENTS_CHANGED )
	{
		Assert( uiGlobal.menuData[ menu ].entitlementsChangedFunc == null )
		uiGlobal.menuData[ menu ].entitlementsChangedFunc = func
	}
	else if ( event == eUIEvent.MENU_INPUT_MODE_CHANGED )
	{
		Assert( uiGlobal.menuData[ menu ].inputModeChangedFunc == null )
		uiGlobal.menuData[ menu ].inputModeChangedFunc = func
	}
}

void function AddPanelEventHandler( var panel, int event, void functionref() func )
{
	if ( event == eUIEvent.PANEL_SHOW )
		uiGlobal.panelData[ panel ].showFunc = func
	else if ( event == eUIEvent.PANEL_HIDE )
		uiGlobal.panelData[ panel ].hideFunc = func
}

// TODO: Get a real on open event from code?
void function OpenMenuWrapper( var menu, bool focusDefault )
{
	OpenMenu( menu )
	printt( Hud_GetHudName( menu ), "menu opened" )

	Assert( menu in uiGlobal.menuData )
	if ( uiGlobal.menuData[ menu ].openFunc != null )
	{
		thread uiGlobal.menuData[ menu ].openFunc()
		//printt( "Called openFunc for:", menu.GetHudName() )
	}

	if ( focusDefault )
		FocusDefault( menu )

	//UpdateMenuTabs()
	UpdateFooterOptions()
}

void function CloseMenuWrapper( var menu )
{
	CloseMenu( menu )
	printt( Hud_GetHudName( menu ), "menu closed" )

	Assert( menu in uiGlobal.menuData )
	if ( uiGlobal.menuData[ menu ].closeFunc != null )
	{
		thread uiGlobal.menuData[ menu ].closeFunc()
		//printt( "Called closeFunc for:", Hud_GetHudName( menu ) )
	}
}

bool function IsLevelMultiplayer( string levelname )
{
	return levelname.find( "mp_" ) == 0
}

void function AddButtonEventHandler( var button, int event, void functionref( var ) func )
{
	Hud_AddEventHandler( button, event, func )
}

void function AddEventHandlerToButton( var menu, string buttonName, int event, void functionref( var ) func )
{
	var button = Hud_GetChild( menu, buttonName )
	Hud_AddEventHandler( button, event, func )
}

void function AddEventHandlerToButtonClass( var menu, string classname, int event, void functionref( var ) func )
{
	array<var> buttons = GetElementsByClassname( menu, classname )

	foreach ( button in buttons )
	{
		//printt( "button name:", Hud_GetHudName( button ) )
		Hud_AddEventHandler( button, event, func )
	}
}

// Added slight delay to main menu music to work around a hitch caused when the game first starts up
void function PlayMusicAfterDelay()
{
	wait MAINMENU_MUSIC_DELAY
	if ( uiGlobal.playingMusic )
		EmitUISound( "MainMenu_Music" )
}

void function DisableMusic()
{
	EmitUISound( "Movie_MuteAllGameSound" )
}

void function EnableMusic()
{
	StopUISoundByName( "Movie_MuteAllGameSound" )
}

void function PlayMusic()
{
	if ( !uiGlobal.playingMusic && !uiGlobal.playingVideo && !uiGlobal.playingCredits )
	{
		//printt( "PlayMusic() called. Playing: MainMenu_Music. uiGlobal.playingMusic:", uiGlobal.playingMusic, "uiGlobal.playingVideo:", uiGlobal.playingVideo, "uiGlobal.playingCredits:", uiGlobal.playingCredits )
		uiGlobal.playingMusic = true
		thread PlayMusicAfterDelay()
	}
	else
	{
		//printt( "PlayMusic() called, but doing nothing. uiGlobal.playingMusic:", uiGlobal.playingMusic, "uiGlobal.playingVideo:", uiGlobal.playingVideo, "uiGlobal.playingCredits:", uiGlobal.playingCredits )
	}
}

void function StopMusic()
{
	//printt( "StopMusic() called. Stopping: MainMenu_Music" )
	StopUISound( "MainMenu_Music" )
	uiGlobal.playingMusic = false
}

void function RegisterMenuVarInt( string varName, int value )
{
	table<string, int> intVars = uiGlobal.intVars

	Assert( !( varName in intVars ) )

	intVars[varName] <- value
}

void function RegisterMenuVarBool( string varName, bool value )
{
	table<string, bool> boolVars = uiGlobal.boolVars

	Assert( !( varName in boolVars ) )

	boolVars[varName] <- value
}

void function RegisterMenuVarVar( string varName, var value )
{
	table<string, var> varVars = uiGlobal.varVars

	Assert( !( varName in varVars ) )

	varVars[varName] <- value
}

int function GetMenuVarInt( string varName )
{
	table<string, int> intVars = uiGlobal.intVars

	Assert( varName in intVars )

	return intVars[varName]
}

bool function GetMenuVarBool( string varName )
{
	table<string, bool> boolVars = uiGlobal.boolVars

	Assert( varName in boolVars )

	return boolVars[varName]
}

var function GetMenuVarVar( string varName )
{
	table<string, var> varVars = uiGlobal.varVars

	Assert( varName in varVars )

	return varVars[varName]
}

void function SetMenuVarInt( string varName, int value )
{
	table<string, int> intVars = uiGlobal.intVars

	Assert( varName in intVars )

	if ( intVars[varName] == value )
		return

	intVars[varName] = value

	table<string, array<void functionref()> > varChangeFuncs = uiGlobal.varChangeFuncs

	if ( varName in varChangeFuncs )
	{
		foreach ( func in varChangeFuncs[varName] )
		{
			//printt( varName, "changed, calling changeFunc:", string( func ) )
			func()
		}
	}
}

void function SetMenuVarBool( string varName, bool value )
{
	table<string, bool> boolVars = uiGlobal.boolVars

	Assert( varName in boolVars )

	if ( boolVars[varName] == value )
		return

	boolVars[varName] = value

	table<string, array<void functionref()> > varChangeFuncs = uiGlobal.varChangeFuncs

	if ( varName in varChangeFuncs )
	{
		foreach ( func in varChangeFuncs[varName] )
		{
			//printt( varName, "changed, calling changeFunc:", string( func ) )
			func()
		}
	}
}

void function SetMenuVarVar( string varName, var value )
{
	table<string, var> varVars = uiGlobal.varVars

	Assert( varName in varVars )

	if ( varVars[varName] == value )
		return

	varVars[varName] = value

	table<string, array<void functionref()> > varChangeFuncs = uiGlobal.varChangeFuncs

	if ( varName in varChangeFuncs )
	{
		foreach ( func in varChangeFuncs[varName] )
		{
			//printt( varName, "changed, calling changeFunc:", string( func ) )
			func()
		}
	}
}

void function AddMenuVarChangeHandler( string varName, void functionref() func )
{
	table<string, array<void functionref()> > varChangeFuncs = uiGlobal.varChangeFuncs

	if ( !( varName in varChangeFuncs ) )
		varChangeFuncs[varName] <- []

	// TODO: Verify we're not duplicating an existing func
	varChangeFuncs[varName].append( func )
}

// These are common menu statuses that trigger menu logic any time they change
// They should become code callbacks, so script doesn't poll
void function InitGlobalMenuVars()
{
	RegisterMenuVarVar( "focus", null )
	RegisterMenuVarBool( "isConnected", false )
	RegisterMenuVarBool( "isFullyConnected", false )
	RegisterMenuVarBool( "isPartyLeader", false )
	RegisterMenuVarBool( "isPrivateMatch", false )
	RegisterMenuVarBool( "isGamepadActive", IsControllerModeActive() )

	#if CONSOLE_PROG
		RegisterMenuVarBool( "CONSOLE_isOnline", false )
		RegisterMenuVarBool( "CONSOLE_isSignedIn", false )
	#endif // CONSOLE_PROG

	#if DURANGO_PROG
		RegisterMenuVarBool( "DURANGO_isGameFullyInstalled", false )
		RegisterMenuVarBool( "DURANGO_canInviteFriends", false )
		RegisterMenuVarBool( "DURANGO_isJoinable", false )
    #elseif PS4_PROG
		RegisterMenuVarBool( "PS4_canInviteFriends", false)
	#elseif PC_PROG
		RegisterMenuVarBool( "ORIGIN_isEnabled", false )
		RegisterMenuVarBool( "ORIGIN_isJoinable", false )
	#endif

	thread UpdateFocus()
	thread UpdateIsConnected()
	thread UpdateIsFullyConnected()
	thread UpdateAmIPartyLeader()
	thread UpdateIsPrivateMatch()
	thread UpdateActiveMenuThink()

	#if CONSOLE_PROG
		thread UpdateConsole_IsOnline()
		thread UpdateConsole_IsSignedIn()
	#endif // CONSOLE_PROG

	#if DURANGO_PROG
		thread UpdateDurango_IsGameFullyInstalled()
		thread UpdateDurango_CanInviteFriends()
		thread UpdateDurango_IsJoinable()
    #elseif PS4_PROG
		thread UpdatePS4_CanInviteFriends()
	#elseif PC_PROG
		thread UpdateOrigin_IsEnabled()
		thread UpdateOrigin_IsJoinable()
		thread UpdateIsGamepadActive()
	#endif
}

void function UpdateFocus()
{
	while ( true )
	{
		SetMenuVarVar( "focus", GetFocus() )
		WaitFrame()
	}
}

void function UpdateActiveMenuThink()
{
	while ( true )
	{
		var menu = GetActiveMenu()
		if ( menu )
		{
			Assert( menu in uiGlobal.menuData )
			if ( uiGlobal.menuData[ menu ].thinkFunc != null )
				uiGlobal.menuData[ menu ].thinkFunc()
		}

		WaitFrame()
	}
}

void function UpdateIsConnected()
{
	while ( true )
	{
		SetMenuVarBool( "isConnected", IsConnected() )
		WaitFrame()
	}
}

void function UpdateIsFullyConnected()
{
	while ( true )
	{
		SetMenuVarBool( "isFullyConnected", IsFullyConnected() )
		WaitFrame()
	}
}

void function UpdateAmIPartyLeader()
{
	while ( true )
	{
		SetMenuVarBool( "isPartyLeader", AmIPartyLeader() )
		WaitFrame()
	}
}

void function UpdateIsPrivateMatch()
{
	while ( true )
	{
		SetMenuVarBool( "isPrivateMatch", IsPrivateMatch() )
		WaitFrame()
	}
}

#if CONSOLE_PROG
	void function UpdateConsole_IsOnline()
	{
		while ( true )
		{
			SetMenuVarBool( "CONSOLE_isOnline", Console_IsOnline() )
			WaitFrame()
		}
	}

	void function UpdateConsole_IsSignedIn()
	{
		while ( true )
		{
			SetMenuVarBool( "CONSOLE_isSignedIn", Console_IsSignedIn() )
			WaitFrame()
		}
	}
#endif // CONSOLE_PROG


#if PS4_PROG
	void function UpdatePS4_CanInviteFriends()
	{
		while ( true )
		{
			SetMenuVarBool( "PS4_canInviteFriends", PS4_canInviteFriends() )
			WaitFrame()
		}
	}
#endif // PS4_PROG



#if DURANGO_PROG
	void function UpdateDurango_IsGameFullyInstalled()
	{
		while ( true )
		{
			SetMenuVarBool( "DURANGO_isGameFullyInstalled", IsGameFullyInstalled() )
			wait 1 // Poll less frequent
		}
	}

	void function UpdateDurango_CanInviteFriends()
	{
		while ( true )
		{
			SetMenuVarBool( "DURANGO_canInviteFriends", Durango_CanInviteFriends() )
			WaitFrame()
		}
	}

	void function UpdateDurango_IsJoinable()
	{
		while ( true )
		{
			SetMenuVarBool( "DURANGO_isJoinable", Durango_IsJoinable() )
			WaitFrame()
		}
	}
#endif // DURANGO_PROG

#if PC_PROG
	void function UpdateOrigin_IsEnabled()
	{
		while ( true )
		{
			SetMenuVarBool( "ORIGIN_isEnabled", Origin_IsEnabled() )
			WaitFrame()
		}
	}

	void function UpdateOrigin_IsJoinable()
	{
		while ( true )
		{
			SetMenuVarBool( "ORIGIN_isJoinable", Origin_IsJoinable() )
			WaitFrame()
		}
	}

	void function UpdateIsGamepadActive()
	{
		while ( true )
		{
			SetMenuVarBool( "isGamepadActive", IsControllerModeActive() )
			WaitFrame()
		}
	}
#endif // PC_PROG

void function InviteFriends( var button )
{
	//AdvanceMenu( GetMenu( "InviteFriendsToPartyMenu" ) )

	#if DURANGO_PROG
		Durango_InviteFriends()
	#elseif PS4_PROG
	    ClientCommand("session_debug_invite");
	#elseif PC_PROG
		Assert( Origin_IsEnabled() )
		Assert( Origin_IsJoinable() )

		Origin_ShowInviteFriendsDialog()
	#endif
}

#if DURANGO_PROG
void function OpenXboxPartyApp( var button )
{
	Durango_OpenPartyApp()
}

void function OpenXboxHelp( var button )
{
	Durango_ShowHelpWindow()
}
#endif // DURANGO_PROG

void function OpenReviewTermsDialog( var button )
{
	AdvanceMenu( GetMenu( "ReviewTermsDialog" ) )
}

void function OpenErrorDialog( string errorDetails )
{
	DialogData dialogData
	dialogData.header = "#ERROR"
	dialogData.message = errorDetails
	dialogData.image = $"ui/menu/common/dialog_error"

#if PC_PROG
	AddDialogButton( dialogData, "#DISMISS" )

	AddDialogFooter( dialogData, "#A_BUTTON_SELECT" )
#endif // PC_PROG
	AddDialogFooter( dialogData, "#B_BUTTON_DISMISS_RUI" )

	while ( uiGlobal.activeMenu != GetMenu( "MainMenu" ) )
	{
		WaitSignal( uiGlobal.signalDummy, "OpenErrorDialog", "ActiveMenuChanged" )
	}

	OpenDialog( dialogData )
}

bool function IsDialog( var menu )
{
	if ( menu == null )
		return false

	return uiGlobal.menuData[ menu ].isDialog
}

bool function IsDialogActive( DialogData dialogData )
{
	if ( !IsDialog( uiGlobal.activeMenu ) )
		return false

	return uiGlobal.menuData[ uiGlobal.activeMenu ].dialogData == dialogData
}

bool function IsDialogOnlyActiveMenu()
{
	if ( !IsDialog( uiGlobal.activeMenu ) )
		return false

	int stackLen = uiGlobal.menuStack.len()
	if ( stackLen < 1 )
		return false

	if ( uiGlobal.menuStack[stackLen - 1] != uiGlobal.activeMenu )
		return false

	if ( stackLen == 1 )
		return true

	if ( uiGlobal.menuStack[stackLen - 2] == null )
		return true

	return false
}

void function SetNavUpDown( array<var> buttons, var wrap = true )
{
	Assert( buttons.len() > 0 )

	var first = buttons[0]
	var last = buttons[buttons.len() - 1]
	var prev
	var next
	var button

	for ( int i = 0; i < buttons.len(); i++ )
	{
		button = buttons[i]

		if ( button == first )
			prev = last
		else
			prev = buttons[i - 1]

		if ( button == last )
			next = first
		else
			next = buttons[i + 1]

		button.SetNavUp( prev )
		button.SetNavDown( next )

		//printt( "SetNavUP for:", Hud_GetHudName( button ), "to:", Hud_GetHudName( prev ) )
		//printt( "SetNavDown for:", Hud_GetHudName( button ), "to:", Hud_GetHudName( next ) )
	}
}

void function SetNavLeftRight( array<var> buttons, var wrap = true )
{
	Assert( buttons.len() > 0 )

	var first = buttons[0]
	var last = buttons[buttons.len() - 1]
	var prev
	var next
	var button

	for ( int i = 0; i < buttons.len(); i++ )
	{
		button = buttons[i]

		if ( button == first )
			prev = last
		else
			prev = buttons[i - 1]

		if ( button == last )
			next = first
		else
			next = buttons[i + 1]

		button.SetNavLeft( prev )
		button.SetNavRight( next )

		//printt( "SetNavUP for:", Hud_GetHudName( button ), "to:", Hud_GetHudName( prev ) )
		//printt( "SetNavDown for:", Hud_GetHudName( button ), "to:", Hud_GetHudName( next ) )
	}
}

void function UICodeCallback_EntitlementsChanged()
{
	if ( uiGlobal.activeMenu == null )
		return

	if ( uiGlobal.menuData[ uiGlobal.activeMenu ].entitlementsChangedFunc != null )
		thread uiGlobal.menuData[ uiGlobal.activeMenu ].entitlementsChangedFunc()
}

#if PC_PROG
void function QuitGame()
{
	ClientCommand( "quit" )
}
#endif

void function UICodeCallback_StoreTransactionCompleted()
{
	// this callback is only supported and needed on PS4 currently
#if PS4_PROG
	if ( InStoreMenu() )
		OnOpenDLCStore()
#endif
}

void function UICodeCallback_GamePurchased()
{
	// this callback is only supported and needed on PC currently
#if PC_PROG
	DialogData dialogData
	dialogData.header = "#PURCHASE_GAME_COMPLETE"
	dialogData.message = "#PURCHASE_GAME_RESTART"
	AddDialogButton( dialogData, "#QUIT", QuitGame )

	OpenDialog( dialogData )
#endif
}

bool function IsTrialPeriodActive()
{
	return GetConVarBool( "trialPeriodIsActive" )
}

void function LaunchGamePurchaseOrDLCStore( array<string> menuNames = [ "StoreMenu" ] )
{
	if ( Script_IsRunningTrialVersion() )
	{
		LaunchGamePurchase()
	}
	else
	{
		void functionref() preOpenFunc = null

		foreach ( menuName in menuNames )
		{
			// Special case because this menu needs a few properties set before opening
			if ( menuName == "StoreMenu_WeaponSkins" )
			{
				preOpenFunc = DefaultToDLC11WeaponWarpaintBundle
				break
			}
		}

		OpenStoreMenu( menuNames, preOpenFunc )
	}
}

void function UICodeCallback_PartyUpdated()
{
	if ( AmIPartyLeader() )
	{
		string activeSearchingPlaylist = GetActiveSearchingPlaylist()
		if ( activeSearchingPlaylist != "" && !CanPlaylistFitMyParty( activeSearchingPlaylist ) )
		{
			CancelMatchSearch()

			DialogData dialogData
			dialogData.header = "#MATCHMAKING_CANCELED"
			dialogData.message = "#MATCHMAKING_CANCELED_REASON_PARTY_SIZE"
			AddDialogButton( dialogData, "#OK" )

			OpenDialog( dialogData )
		}
	}
}


void function HACK_DelayedSetFocus_BecauseWhy( var item )
{
	wait 0.1
	if ( IsValid( item ) )
		Hud_SetFocused( item )
}

void function ClassicMusic_OnChange( var button )
{
	bool isEnabled = GetConVarBool( "sound_classic_music" )

	if ( IsFullyConnected() && IsMultiplayer() && GetUIPlayer() )
	{
		if ( IsItemLocked( GetUIPlayer(), "classic_music" ) )
			SetConVarBool( "sound_classic_music", false )

		if ( IsLobby() )
			thread RunClientScript( "OnSoundClassicMusicChanged" )
	}
}

bool function IsClassicMusicAvailable()
{
	bool classicMusicAvailable = false
	if ( IsFullyConnected() && IsMultiplayer() && GetUIPlayer() )
		classicMusicAvailable = !IsItemLocked( GetUIPlayer(), "classic_music" )

	return classicMusicAvailable
}

void function UICodeCallback_KeyBindOverwritten( string key, string oldbinding, string newbinding )
{
	DialogData dialogData
	dialogData.header = Localize( "#MENU_KEYBIND_WAS_BEING_USED", key )
	dialogData.message = Localize( "#MENU_KEYBIND_WAS_BEING_USED_SUB", key, Localize( oldbinding ) )

	AddDialogButton( dialogData, "#OK" )

	OpenDialog( dialogData )
}