Back to Home

ESO Lua File v100018

internalingame/market/gamepad/market_gamepad.lua

[◄ back to folders ]
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
ZO_GAMEPAD_MARKET_SCENE_NAME  = "gamepad_market"
ZO_GAMEPAD_MARKET_PREVIEW_SCENE_NAME = "gamepad_market_preview"
ZO_GAMEPAD_MARKET_BUNDLE_CONTENTS_SCENE_NAME = "gamepad_market_bundle_contents"
ZO_GAMEPAD_MARKET_LOCKED_SCENE_NAME = "gamepad_market_locked"
ZO_GAMEPAD_MARKET_PRE_SCENE_NAME = "gamepad_market_pre_scene"
ZO_GAMEPAD_MARKET_CONTENT_LIST_SCENE_NAME = "gamepad_market_content_list"
local DEFAULT_AMOUNT_CROWNS = 0
local FIRST_CATEGORY_INDEX = 1
local GAMEPAD_MARKET_LABELED_GROUP_LABEL_TEMPLATE = "ZO_GamepadMarket_GroupLabel"
local LABELED_GROUP_PADDING = 110 --padding from bottom of one gorup to the top of the next
local LABELED_GROUP_LABEL_PADDING = -10 --padding from the top of a group to the bottom of it's header
local MARKET_BUY_CROWNS_BUTTON =
{
    alignment = KEYBIND_STRIP_ALIGN_RIGHT,
    gamepadOrder = 1,
    name = GetString(SI_MARKET_BUY_CROWNS),
    keybind = "UI_SHORTCUT_TERTIARY",
    callback = function() ZO_GAMEPAD_MARKET:OnShowBuyCrownsDialogInternal() end
}
--
--[[ Gamepad Market ]]--
--
local GamepadMarket = ZO_Object.MultiSubclass(ZO_GamepadMarket_GridScreen, ZO_Market_Shared)
function GamepadMarket:New(...)
    return ZO_Market_Shared.New(self, ...)
end
function GamepadMarket:Initialize(control)
    GAMEPAD_MARKET_PREVIEW_SCENE = ZO_RemoteScene:New(ZO_GAMEPAD_MARKET_PREVIEW_SCENE_NAME, SCENE_MANAGER)
    local EMPTY_TAB_HEADER = {}
    ZO_GamepadMarket_GridScreen.Initialize(self, control, ZO_GAMEPAD_MARKET_BUNDLE_PRODUCTS_PER_ROW, ZO_GAMEPAD_MARKET_PRODUCTS_PER_COLUMN, EMPTY_TAB_HEADER)
    ZO_Market_Shared.Initialize(self)
end
function GamepadMarket:SetupSceneGroupCallback()
    self.marketSceneGroup = self.marketScene:GetSceneGroup()
    self.marketSceneGroup:RegisterCallback("StateChange", function(oldState, newState)
        if newState == SCENE_GROUP_SHOWING then
            self:OnInitialInteraction()
        elseif newState == SCENE_GROUP_HIDDEN then
            self:OnEndInteraction()
        end
    end)
end
function GamepadMarket:PerformDeferredInitialization()
    if self.isInitialized then
        return
    end
    self.isLockedForCategoryRefresh = false
    self.OnGamepadDialogHidden = function()
    end
    self.subCategoryDataMarketProductIdMap = {} -- Used to map product IDs to product subcategories during category building
    self.subCategoryLabeledGroupTableMap = {} -- Used to lookup subcategory "LabeledGroup" tables during category building
    self.subscriptionBenefitLinePool = ZO_ControlPool:New("ZO_GamepadMarket_SubscriptionBenefitLine", self.control)
    MARKET_CURRENCY_GAMEPAD:RegisterCallback("OnCurrencyUpdated", function() self:OnCurrencyUpdated() end)
    self.isInitialized = true
end
function GamepadMarket:GetLabeledGroupLabelTemplate()
    return GAMEPAD_MARKET_LABELED_GROUP_LABEL_TEMPLATE
end
function GamepadMarket:LayoutSelectedMarketProduct()
    local marketProduct = self.selectedMarketProduct
    if marketProduct ~= nil and not marketProduct:IsBlank() then
        marketProduct:LayoutTooltip(GAMEPAD_RIGHT_TOOLTIP)
    else
        GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_RIGHT_TOOLTIP)
    end
end
function GamepadMarket:OnSelectionChanged(selectedData)
    ZO_GamepadMarket_GridScreen.OnSelectionChanged(self, selectedData)
    local previouslySelectedMarketProduct = self.selectedMarketProduct
    if selectedData then
        self.selectedMarketProduct = selectedData.marketProduct
    elseif not self.isLockedForCategoryRefresh then
        GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_RIGHT_TOOLTIP)
        self.selectedMarketProduct = nil
    end
    self:UpdatePreviousAndNewlySelectedProducts(previouslySelectedMarketProduct, self.selectedMarketProduct)
    KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptors)
end
function GamepadMarket:OnStateChanged(oldState, newState)
    if newState == SCENE_SHOWING then
        self:OnShowing()
    elseif newState == SCENE_SHOWN then
        self:OnShown()
    elseif newState == SCENE_HIDING then
        self:OnHiding()
    elseif newState == SCENE_HIDDEN then
        self:OnHidden()
    end
end
function GamepadMarket:OnInitialInteraction()
    -- ensure that we are in the correct state
    if self.marketState ~= GetMarketState(MARKET_DISPLAY_GROUP_CROWN_STORE) then
        self:UpdateMarket()
    elseif self.marketState == MARKET_STATE_OPEN then
        self:UpdateCurrentCategory()
    end
    
    if self.isInitialized and self.marketState == MARKET_STATE_OPEN then
        GAMEPAD_TOOLTIPS:ClearStatusLabel(GAMEPAD_LEFT_DIALOG_TOOLTIP) -- Clear status labels on entry to the market
        GAMEPAD_TOOLTIPS:ClearStatusLabel(GAMEPAD_RIGHT_TOOLTIP)
        self.isLockedForCategoryRefresh = false
    end
end
function GamepadMarket:OnEndInteraction()
    self:ClearProducts()
    self.currentCategoryMarketProductPool:ReleaseAllObjects()
    self.lastCategoryData = nil
    self.currentCategoryData = nil
    self.header.tabBar:Clear()
    g_activeMarketScreen = nil
    
    ZO_Market_Shared.OnEndInteraction(self)
    KEYBIND_STRIP:SetStyle(KEYBIND_STRIP_STANDARD_STYLE)
end
function GamepadMarket:OnShowing()
    ZO_Market_Shared.OnShowing(self)
end
function GamepadMarket:OnShown()
    if self.marketState == MARKET_STATE_OPEN then
        self:OnMarketOpen()
        self:ReleasePreviousCategoryProducts() -- Cleans up any products left over from entering submenus like bundle details or product preview
        self:Activate()
        self:AddKeybinds()
        g_activeMarketScreen = ZO_GAMEPAD_MARKET
        self:UpdateTooltip()
        ZO_Market_Shared.OnShown(self)
        ZO_GamepadMarket_GridScreen.OnShown(self)
        self:RefreshKeybinds()
        CALLBACK_MANAGER:RegisterCallback("OnGamepadDialogHidden", self.OnGamepadDialogHidden)
        if self.queuedMarketProductId then
            self:ShowMarketProduct(self.queuedMarketProductId)
            self.queuedMarketProductId = nil
        end
    else
        self:OnMarketLocked()
    end
end
function GamepadMarket:OnHiding()
    ZO_Market_Shared.OnHiding(self)
    if self.currentCategoryData then
        -- just fade out because we are hiding
        self.currentCategoryData.fragment:SetDirection(ZO_GAMEPAD_MARKET_PAGE_NO_DIRECTION)
    end
    self.queuedTutorial = nil
    ZO_GAMEPAD_MARKET_BUNDLE_CONTENTS:SetQueuedTutorial(nil)
    self.currentCategoryControl = nil
    self:Deactivate()
    self:RemoveKeybinds()
    CALLBACK_MANAGER:UnregisterCallback("OnGamepadDialogHidden", self.OnGamepadDialogHidden)
end
function GamepadMarket:InitializeKeybindDescriptors()
    local function RefreshOnPurchase() -- Only called on transaction success
        self.selectedMarketProduct:Refresh()
    end
    local function OnPurchaseEnd(reachedConfirmationScene, purchasedConsumables, triggerTutorialOnPurchase)
        self.isLockedForCategoryRefresh = reachedConfirmationScene
        if purchasedConsumables then
            self:SetQueuedTutorial(TUTORIAL_TRIGGER_CROWN_CONSUMABLE_PURCHASED)
        end
        -- Check if an item triggers a tutorial on purchase second, since that takes priority over the consumable tutorial
        if triggerTutorialOnPurchase then
            self:SetQueuedTutorial(triggerTutorialOnPurchase)
        end
        -- We push the purchase scene when we reach the confirmation step
        -- So when we show the market again we will reactivate.
        -- Otherwise, we need to reactivate since we are just hiding a dialog.
        if not reachedConfirmationScene then
            self:Activate()
        end
    end
    self.keybindStripDescriptors =
    {
        alignment = KEYBIND_STRIP_ALIGN_LEFT,
        -- Purchase Keybind
        {
             name =  function()
                        if self.selectedMarketProduct:IsBundle() then
                            return GetString(SI_MARKET_PURCHASE_BUNDLE_KEYBIND_TEXT)
                        else
                            return GetString(SI_MARKET_PURCHASE_KEYBIND_TEXT)
                        end
                    end,
            keybind = "UI_SHORTCUT_PRIMARY",
            visible = function()
                            return self.selectedMarketProduct and not (self.selectedMarketProduct:IsPurchaseLocked() or self.selectedMarketProduct:IsBlank() or self.selectedMarketProduct:IsHouseCollectible())
                        end,
            enabled = function() return not self:HasQueuedTutorial() and self.selectedMarketProduct:CanBePurchased() end,
            callback = function()
                self.isLockedForCategoryRefresh = true
                self:PurchaseMarketProductInternal(self.selectedMarketProduct:GetId(), self.selectedMarketProduct:GetPresentationIndex(), RefreshOnPurchase, OnPurchaseEnd)
                self:Deactivate()
            end,
        },
        -- "Preview" Keybind
        {
            alignment = KEYBIND_STRIP_ALIGN_CENTER,
            name =  function()
                        local previewType = self.GetMarketProductPreviewType(self.selectedMarketProduct)
                        if previewType == ZO_MARKET_PREVIEW_TYPE_BUNDLE or previewType == ZO_MARKET_PREVIEW_TYPE_BUNDLE_HIDES_CHILDREN then
                            return GetString(SI_MARKET_BUNDLE_DETAILS_KEYBIND_TEXT)
                        else
                            return GetString(SI_MARKET_PREVIEW_KEYBIND_TEXT)
                        end
                    end,
            keybind = "UI_SHORTCUT_SECONDARY",
            visible =   function()
                            local marketProduct = self.selectedMarketProduct
                            if marketProduct ~= nil then
                                local previewType = self.GetMarketProductPreviewType(marketProduct)
                                return not self.selectedMarketProduct:IsBlank()
                            end
                            return false
                        end,
            enabled =   function()
                            local marketProduct = self.selectedMarketProduct
                            if marketProduct ~= nil then
                                local previewType = self.GetMarketProductPreviewType(marketProduct)
                                if previewType == ZO_MARKET_PREVIEW_TYPE_PREVIEWABLE then
                                    return marketProduct:HasPreview() and IsCharacterPreviewingAvailable()
                                else
                                    return true
                                end
                            end
                            return false
                        end,
            callback =  function()
                            local marketProduct = self.selectedMarketProduct
                            local previewType = self.GetMarketProductPreviewType(marketProduct)
                            if previewType == ZO_MARKET_PREVIEW_TYPE_BUNDLE then
                                self:ShowBundleContents(marketProduct)
                            elseif previewType == ZO_MARKET_PREVIEW_TYPE_CROWN_CRATE or previewType == ZO_MARKET_PREVIEW_TYPE_BUNDLE_HIDES_CHILDREN then
                                self:ShowMarketProductContentsAsList(marketProduct, previewType)
                            elseif previewType == ZO_MARKET_PREVIEW_TYPE_HOUSE then
                                self:ShowHousePreviewDialog(marketProduct)
                            else -- ZO_MARKET_PREVIEW_TYPE_PREVIEWABLE
                                self:BeginPreview()
                            end
                        end,
        },
        MARKET_BUY_CROWNS_BUTTON,
        KEYBIND_STRIP:GetDefaultGamepadBackButtonDescriptor(),
    }
    self.esoPluskeybindStripDescriptor =
    {
        alignment = KEYBIND_STRIP_ALIGN_LEFT,
        {
            name = GetString(SI_GAMEPAD_MARKET_BUY_PLUS_KEYBIND_LABEL),
            keybind = "UI_SHORTCUT_PRIMARY",
            callback = ZO_GamepadMarket_ShowBuyPlusDialog,
            visible = function() return not IsESOPlusSubscriber() end,
        },
        MARKET_BUY_CROWNS_BUTTON,
        KEYBIND_STRIP:GetDefaultGamepadBackButtonDescriptor(),
    }
end
function GamepadMarket:GetPrimaryButtonDescriptor()
    return self.primaryButtonDescriptor
end
function GamepadMarket:BeginPreview()
    self.isLockedForCategoryRefresh = true
    self.currentCategoryData.fragment:SetDirection(ZO_GAMEPAD_MARKET_PAGE_NO_DIRECTION)
    g_activeMarketScreen = ZO_GAMEPAD_MARKET_PREVIEW
    ZO_GamepadMarket_GridScreen.BeginPreview(self)
end 
function GamepadMarket:OnCategorySelected(data)
    if self.marketScene:IsShowing() and self.marketState == MARKET_STATE_OPEN then
        self.lastCategoryData, self.currentCategoryData = self.currentCategoryData, data
        local lastCategoryControl = self.currentCategoryControl
        self.currentCategoryControl = data.control
        if self.lastCategoryData ~= self.currentCategoryData then
            self.isLockedForCategoryRefresh = false
        end
        
        if not self.isLockedForCategoryRefresh then
            ZO_ClearTable(self.subCategoryDataMarketProductIdMap)
            ZO_ClearTable(self.subCategoryLabeledGroupTableMap)
            
            if data.type == ZO_MARKET_CATEGORY_TYPE_FEATURED then
                self:BuildFeaturedMarketProductList()
            elseif data.type == ZO_MARKET_CATEGORY_TYPE_ESO_PLUS then
                self:DisplayEsoPlusOffer()
            else
                self:BuildMarketProductList(data)
            end
        else
            self:UpdateScrollbarAlpha()
        end
        if lastCategoryControl ~= self.currentCategoryControl then
            -- This temporarily disables scrolling for the old and new categories, but allows for the paging animation to work correctly.
            -- The category controls will be re-anchored to the scroll child if/when they are shown
            if self.lastCategoryData then
                if not self.isLockedForCategoryRefresh then
                    lastCategoryControl:ClearAnchors()
                    lastCategoryControl:SetAnchorFill(self.contentContainer)
                end
                
                SCENE_MANAGER:RemoveFragment(self.lastCategoryData.fragment)
            end
            if not self.isLockedForCategoryRefresh then
                self.currentCategoryControl:ClearAnchors()
                self.currentCategoryControl:SetAnchorFill(self.contentContainer)
            end
            
            SCENE_MANAGER:AddFragment(data.fragment)
        end
        if not self.isLockedForCategoryRefresh then
            local categoryIndex, subCategoryIndex
            -- faked category types don't have real category indices so keep them as nil
            if data.type == ZO_MARKET_CATEGORY_TYPE_NONE then
                if data.parentData then
                    categoryIndex = data.parentData.categoryIndex
                    subCategoryIndex = data.categoryIndex
                else
                    categoryIndex = data.categoryIndex
                end
            end
            OnMarketCategorySelected(MARKET_DISPLAY_GROUP_CROWN_STORE, categoryIndex, subCategoryIndex)
        end
    end
end
do
    local MARKET_PRODUCT_SORT_KEYS =
    {
        name = { tiebreaker = "stackCount", tieBreakerSortOrder = ZO_SORT_ORDER_DOWN },
        stackCount = {},
    }
    function GamepadMarket:CompareMarketProducts(entry1, entry2)
        return ZO_TableOrderingFunction(entry1, entry2, "name", MARKET_PRODUCT_SORT_KEYS, ZO_SORT_ORDER_UP)
    end
end
function GamepadMarket:OnCurrencyUpdated()
    if not self.control:IsHidden() then
        self:RefreshKeybinds()
    elseif GAMEPAD_MARKET_BUNDLE_CONTENTS_SCENE and GAMEPAD_MARKET_BUNDLE_CONTENTS_SCENE:IsShowing() then
        ZO_GAMEPAD_MARKET_BUNDLE_CONTENTS:RefreshKeybinds()
    end
end
function GamepadMarket:CreateMarketScene()
    local scene = ZO_RemoteScene:New(ZO_GAMEPAD_MARKET_SCENE_NAME, SCENE_MANAGER)
    SYSTEMS:RegisterGamepadRootScene(ZO_MARKET_NAME, scene)
    self:SetMarketScene(scene)
end
function GamepadMarket:AcquireBlankTile()
    return self.currentCategoryBlankProductPool:AcquireObject()
end
function GamepadMarket:InitializeBlankProductPool()
    ZO_GamepadMarket_GridScreen.InitializeBlankProductPool(self)
    self.currentCategoryBlankProductPool = ZO_MetaPool:New(self.blankTilePool)
    self.lastCategoryBlankProductPool = ZO_MetaPool:New(self.blankTilePool)
 end
function GamepadMarket:InitializeMarketProductPool()
    ZO_GamepadMarket_GridScreen.InitializeMarketProductPool(self)
    self.currentCategoryMarketProductPool = ZO_MetaPool:New(self.marketProductPool)
    self.lastCategoryMarketProductPool = ZO_MetaPool:New(self.marketProductPool)
end
-- Cache the current products in lastCategoryMarketProductPool. These will be released after the category change animation has finished
function GamepadMarket:ReleaseAllProducts()
    self.currentCategoryMarketProductPool, self.lastCategoryMarketProductPool = self.lastCategoryMarketProductPool, self.currentCategoryMarketProductPool
    self.currentCategoryBlankProductPool, self.lastCategoryBlankProductPool = self.lastCategoryBlankProductPool, self.currentCategoryBlankProductPool
end
function GamepadMarket:ReleasePreviousCategoryProducts()
    self.lastCategoryMarketProductPool:ReleaseAllObjects()
    self.lastCategoryBlankProductPool:ReleaseAllObjects()
end
    self.currentCategoryControl:ClearAnchors()
    self.currentCategoryControl:SetAnchor(TOPLEFT, self.contentContainer.scrollChild, TOPLEFT)
end
do
    local function CreateSubCategoryData(name, parentData, index, numProducts)
        return {
            text = name,
            numProducts = numProducts,
            soundId = SOUNDS.MARKET_SUB_CATEGORY_SELECTED,
            parentData = parentData,
            parent = parentData.control,
            categoryIndex = index,
        }
    end
    local GAMEPAD_MARKET_CATEGORY_TEMPLATE = "ZO_GamepadMarket_CategoryTemplate"
    local GAMEPAD_MARKET_ESO_PLUS_CATEGORY_TEMPLATE = "ZO_GamepadMarket_EsoPlusCategoryTemplate"
    local function GetOrCreateCategoryControl(parent, marketCategoryIndex, categoryType)
        local currentControlName = GAMEPAD_MARKET_CATEGORY_TEMPLATE
        if marketCategoryIndex and marketCategoryIndex > 0 then
            currentControlName = currentControlName .. marketCategoryIndex
        else -- this is a faked category
            currentControlName = currentControlName .. categoryType
        end
        local currentControl = GetControl(currentControlName)
        if currentControl ~= nil then
            return currentControl
        else
            if categoryType == ZO_MARKET_CATEGORY_TYPE_ESO_PLUS then
                return CreateControlFromVirtual(currentControlName, parent, GAMEPAD_MARKET_ESO_PLUS_CATEGORY_TEMPLATE)
            else
                return CreateControlFromVirtual(currentControlName, parent, GAMEPAD_MARKET_CATEGORY_TEMPLATE)
            end
        end
    end
    local ALWAYS_ANIMATE = true
    local function CreateCategoryData(name, parent, marketCategoryIndex, tabIndex, numSubCategories, categoryType)
        categoryType = categoryType or ZO_MARKET_CATEGORY_TYPE_NONE
        local control = GetOrCreateCategoryControl(parent, marketCategoryIndex, categoryType)
        return {
            text = name,
            control = control,
            subCategories = {},
            numSubCategories = numSubCategories,
            soundId = SOUNDS.MARKET_CATEGORY_SELECTED,
            categoryIndex = marketCategoryIndex, -- Market category index used for def lookup
            tabIndex = tabIndex, -- Index in the tab header, as displayed. This can be different from the market category index when there are faked categories
            type = categoryType,
            fragment = ZO_GamepadMarketPageFragment:New(control, ALWAYS_ANIMATE)
        }
    end
    local SUBCATEGORY_GEM_FORMATTED_ICON = zo_iconFormat("EsoUI/Art/currency/gamepad/gp_crown_gems.dds", 32, 32)
    function GamepadMarket:AddTopLevelCategory(categoryIndex, tabIndex, name, numSubCategories, categoryType)
        name = zo_strformat(SI_MARKET_PRODUCT_NAME_FORMATTER, name)
        
        local categoryData = CreateCategoryData(name, self.contentContainer.scrollChild, categoryIndex, tabIndex, numSubCategories, categoryType)
        local hasChildren = numSubCategories > 0
        if hasChildren then
            for i = 1, numSubCategories do
                local subCategoryName, numSubCategoryMarketProducts, showGemIcon = GetMarketProductSubCategoryInfo(MARKET_DISPLAY_GROUP_CROWN_STORE, categoryIndex, i)
                if showGemIcon then
                    subCategoryName = zo_strformat(SI_FORMAT_ICON_TEXT, SUBCATEGORY_GEM_FORMATTED_ICON, subCategoryName)
                else
                    subCategoryName = zo_strformat(SI_MARKET_PRODUCT_NAME_FORMATTER, subCategoryName)
                end
                local subCategoryData = CreateSubCategoryData(subCategoryName, categoryData, i, numSubCategoryMarketProducts)
                table.insert(categoryData.subCategories, subCategoryData)
            end
        end
        local function OnCategoryFragmentStateChanged(oldState, newState)
            if newState == SCENE_FRAGMENT_HIDDEN then
                self:ReleasePreviousCategoryProducts() -- Wait to release products until the after the animation has finished
            elseif newState == SCENE_FRAGMENT_SHOWN and not self.isLockedForCategoryRefresh then
                local categoryControl = categoryData.control
                -- Re-anchoring after animation to enable scrolling of the category control
                self:AnchorCurrentCategoryControlToScrollChild()
            end
        end
        categoryData.fragment:RegisterCallback("StateChange", OnCategoryFragmentStateChanged)
        
        local tabEntry =
        {
            text = name,
            categoryData = categoryData,
            callback = function()
                self:OnCategorySelected(categoryData)
            end,
        }
        table.insert(self.headerData.tabBarEntries, tabEntry)
    end
end
do
    local currentTabIndex = FIRST_CATEGORY_INDEX
    local function GetFirstTabIndex()
        currentTabIndex = FIRST_CATEGORY_INDEX
        return currentTabIndex
    end
    local function GetNextTabIndex()
        currentTabIndex = currentTabIndex + 1
        return currentTabIndex
    end
    local ZERO_SUBCATEGORIES = 0
    function GamepadMarket:BuildCategories(control)
        if self.marketState == MARKET_STATE_OPEN then
            ZO_ClearTable(self.headerData.tabBarEntries)
            local firstIndex = GetFirstTabIndex()
            local numFeaturedMarketProducts = GetNumFeaturedMarketProducts()
            local hasFeaturedCategory = numFeaturedMarketProducts > 0
            if hasFeaturedCategory then
                self:AddTopLevelCategory(ZO_MARKET_FEATURED_CATEGORY_INDEX, firstIndex, GetString(SI_MARKET_FEATURED_CATEGORY), ZERO_SUBCATEGORIES, ZO_MARKET_CATEGORY_TYPE_FEATURED)
            end
            local esoPlusIndex = hasFeaturedCategory and GetNextTabIndex() or firstIndex
            self:AddTopLevelCategory(ZO_MARKET_ESO_PLUS_CATEGORY_INDEX, esoPlusIndex, GetString(SI_MARKET_ESO_PLUS_CATEGORY), ZERO_SUBCATEGORIES, ZO_MARKET_CATEGORY_TYPE_ESO_PLUS)
            -- adding in the custom categories offsets our market product cateogry indices
            -- so even though a category is index 1 from data, it might actually be index 3
            -- since we show a featured and ESO Plus category
            self.categoryIndexOffset = esoPlusIndex
            local numCategories = GetNumMarketProductCategories(MARKET_DISPLAY_GROUP_CROWN_STORE)
            for i = 1, numCategories do
                local name, numSubCategories = GetMarketProductCategoryInfo(MARKET_DISPLAY_GROUP_CROWN_STORE, i)
                self:AddTopLevelCategory(i, GetNextTabIndex(), name, numSubCategories)
            end
            self.categoriesInitialized = true
            self.refreshCategories = false
        end
    end
end
function GamepadMarket:BuildMarketProductList(data)
    local parentData = data.parentData
    local categoryIndex, subCategoryIndex = self:GetCategoryIndices(data, parentData)
    self.currentSubCategoryBuildInProgress = nil
    
    --subcategories will be accumulated into the parent categories, so ignore them
    if not subCategoryIndex then
        -- For gamepad, if the top level category is set to disable the LTO grouping, we won't show it at all in the category
        -- so even though the subcategories aren't flagged as such their products won't go into a LTO grouping
        local disableLTOGrouping = IsLTODisabledForMarketProductCategory(MARKET_DISPLAY_GROUP_CROWN_STORE, categoryIndex, subCategoryIndex)
        local marketProductPresentations = { self:GetCategoryProductIds(data, 1, data.numSubCategories) }
        self:LayoutMarketProducts(marketProductPresentations, disableLTOGrouping)
    end
end
-- ... is a list of tables containing product ids and presentationIndexes
function GamepadMarket:GetCategoryProductIds(data, currentSubCategory, numSubCategories, ...)
    if currentSubCategory <= numSubCategories then
        local subCategoryData = data.subCategories[currentSubCategory]
        local categoryIndex, subCategoryIndex = self:GetCategoryIndices(subCategoryData, subCategoryData.parentData)
        local numMarketProducts = select(2, GetMarketProductSubCategoryInfo(MARKET_DISPLAY_GROUP_CROWN_STORE, categoryIndex, subCategoryIndex))
        self.currentSubCategoryBuildInProgress = subCategoryData
        currentSubCategory = currentSubCategory + 1
        return self:GetCategoryProductIds(data, currentSubCategory, numSubCategories, self:GetMarketProductIds(categoryIndex, subCategoryIndex, numMarketProducts, ...))
    else
        local categoryIndex, subCategoryIndex = self:GetCategoryIndices(data, data.parentData)
        local numMarketProducts = select(3, GetMarketProductCategoryInfo(MARKET_DISPLAY_GROUP_CROWN_STORE, categoryIndex, subCategoryIndex))
        self.currentSubCategoryBuildInProgress = nil
        return self:GetMarketProductIds(categoryIndex, subCategoryIndex, numMarketProducts, ...)
    end
end
-- ... is a list of tables containing product ids and presentationIndexes
function GamepadMarket:GetMarketProductIds(categoryIndex, subCategoryIndex, index, ...)
    if index >= 1 then
        local id, presentationIndex = GetMarketProductPresentationIds(MARKET_DISPLAY_GROUP_CROWN_STORE, categoryIndex, subCategoryIndex, index)
        self.subCategoryDataMarketProductIdMap[id] = self.currentSubCategoryBuildInProgress
        local presentationInfo =    {
                                        id = id,
                                        presentationIndex = presentationIndex,
                                    }
        index = index - 1
        return self:GetMarketProductIds(categoryIndex, subCategoryIndex, index, presentationInfo, ...)
    end
    return ...
end
-- override from ZO_GamepadMarket_GridScreen
function GamepadMarket:FinishBuild()
    self:FinishCurrentLabeledGroup() -- must come before call to parent's FinishBuild
    ZO_GamepadMarket_GridScreen.FinishBuild(self)
end
-- override from ZO_GamepadMarket_GridScreen
function GamepadMarket:EndCurrentPreview()
    ZO_GamepadMarket_GridScreen.EndCurrentPreview(self)
end
function GamepadMarket:AddBlankTile(blankTile)
    self:AddEntry(blankTile, blankTile:GetControl())
end
function GamepadMarket:FinishCurrentLabeledGroup()
    if self:GetCurrentLabeledGroupNumProducts() > 0 then
        self.gridYPaddingOffset = self.gridYPaddingOffset + LABELED_GROUP_PADDING
    end
end
function GamepadMarket:AddLabeledGroupTable(labeledGroupName, labeledGroupTable, ignoreHasPreview)
    if #self.labeledGroups > 0 then
        self:FinishCurrentLabeledGroup()
    end
    ZO_Market_Shared.AddLabeledGroupTable(self, labeledGroupName, labeledGroupTable)
    for i, entry in ipairs(labeledGroupTable) do
        self:AddEntry(entry.product, entry.control, ignoreHasPreview)
        if i == 1 and labeledGroupName then
            self:AddLabel(labeledGroupName, entry.control, LABELED_GROUP_LABEL_PADDING)
        end
    end
end
local function SubcategoryListSort(firstEntry, secondEntry)
    return firstEntry.categoryIndex < secondEntry.categoryIndex
end
-- the table of subcategory data may have holes in it if a category ends up not displaying
-- any market products (they were all featured for example) so we need to resort to get rid of holes
local function CreateSortedSubcategoryList(subcategoryData)
    local sortedList = {}
    for k, v in pairs(subcategoryData) do
        table.insert(sortedList, { categoryIndex = k, data = v.data, groupTable = v.groupTable})
    end
    table.sort(sortedList, SubcategoryListSort)
    return sortedList
end
function GamepadMarket:FindOrCreateSubCategoryLabeledGroupTable(subCategoryData)
    local categoryIndex = subCategoryData.categoryIndex
    if not self.subCategoryLabeledGroupTableMap[categoryIndex] then
        self.subCategoryLabeledGroupTableMap[categoryIndex] = { data = subCategoryData, groupTable = {}}
    end
    return self.subCategoryLabeledGroupTableMap[categoryIndex].groupTable
end
function GamepadMarket:FindSubCategoryLabeledGroupTable(categoryIndex)
    local categoryData = self.subCategoryLabeledGroupTableMap[categoryIndex]
    if categoryData then
        return categoryData.groupTable
    end
    return {}
end
function GamepadMarket:AddMarketProductToLabeledGroupOrGeneralGroup(name, marketProduct, id)
    local subCategoryData = self.subCategoryDataMarketProductIdMap[id]
    if subCategoryData then
        self:AddProductToLabeledGroupTable(self:FindOrCreateSubCategoryLabeledGroupTable(subCategoryData), name, marketProduct)
    else
        self:AddProductToLabeledGroupTable(self.marketProducts, name, marketProduct)
    end
end
function GamepadMarket:ClearMarketProducts()
    self:ClearProducts()
end
function GamepadMarket:UpdateCategoryAnimationDirection()
    local direction = ZO_GAMEPAD_MARKET_PAGE_LEFT_DIRECTION
    if self.lastCategoryData and self.lastCategoryData ~= self.currentCategoryData then
        -- We have to account for tab wrapping and perceived direction traversal
        if self.currentCategoryData.tabIndex < self.lastCategoryData.tabIndex  then
            if self.currentCategoryData.tabIndex ~= FIRST_CATEGORY_INDEX or self.lastCategoryData.tabIndex ~= #self.headerData.tabBarEntries then
                direction = ZO_GAMEPAD_MARKET_PAGE_RIGHT_DIRECTION
            end
        elseif self.currentCategoryData.tabIndex == #self.headerData.tabBarEntries and self.lastCategoryData.tabIndex == FIRST_CATEGORY_INDEX then
            direction = ZO_GAMEPAD_MARKET_PAGE_RIGHT_DIRECTION
        end
    else -- we don't have a last category or its the same as the current so no need to animate
        direction = ZO_GAMEPAD_MARKET_PAGE_NO_DIRECTION
    end
    if self.lastCategoryData then
        self.lastCategoryData.fragment:SetDirection(direction)
    end
    
    self.currentCategoryData.fragment:SetDirection(self.isLockedForCategoryRefresh and ZO_GAMEPAD_MARKET_PAGE_NO_DIRECTION or direction)
end
function GamepadMarket:SetCurrentKeybinds(keybindDescriptor)
    if keybindDescriptor ~= self.currentKeybindDescriptor then
        KEYBIND_STRIP:RemoveKeybindButtonGroup(self.currentKeybindDescriptor)
        KEYBIND_STRIP:AddKeybindButtonGroup(keybindDescriptor)
        self.currentKeybindDescriptor = keybindDescriptor
    end
end
function GamepadMarket:DisplayEsoPlusOffer()
    self:SetCurrentKeybinds(self.esoPluskeybindStripDescriptor)
    self:ResetGrid()
    local overview, image = GetMarketSubscriptionGamepadInfo()
    local control = self.currentCategoryData.control
    control:GetNamedChild("Overview"):SetText(overview)
    control:GetNamedChild("MembershipInfoBanner"):SetTexture(image)
    local lineContainer = control:GetNamedChild("BenefitsLineContainer")
    self.subscriptionBenefitLinePool:ReleaseAllObjects()
    local numLines = GetNumGamepadMarketSubscriptionBenefitLines()
    local numLeftSideLines = zo_ceil(numLines / 2) -- do it this way so if we have 7 bullets 4 are on the left and 3 on the right
    local firstRightSideLineIndex = numLeftSideLines + 1
    local controlToAnchorTo = lineContainer
    for i = 1, numLines do
        local line = GetGamepadMarketSubscriptionBenefitLine(i);
        local benefitLine = self.subscriptionBenefitLinePool:AcquireObject()
        benefitLine:SetText(line)
        benefitLine:ClearAnchors()
        if i == 1 then -- first left side line
            benefitLine:SetAnchor(TOPLEFT, lineContainer, TOPLEFT, 0, 4)
            benefitLine:SetAnchor(TOPRIGHT, lineContainer, CENTER, 0, 4)
        else
            --rest of the left side
            if i <= numLeftSideLines then
                benefitLine:SetAnchor(TOPLEFT, controlToAnchorTo, BOTTOMLEFT, 0, 4)
                benefitLine:SetAnchor(TOPRIGHT, controlToAnchorTo, BOTTOMRIGHT, 0, 4)
            else
                -- right side layout
                if i == firstRightSideLineIndex then
                    benefitLine:SetAnchor(TOPLEFT, lineContainer, CENTER, 0, 4)
                    benefitLine:SetAnchor(TOPRIGHT, lineContainer, TOPRIGHT, 0, 4)
                else
                    benefitLine:SetAnchor(TOPLEFT, controlToAnchorTo, BOTTOMLEFT, 0, 4)
                    benefitLine:SetAnchor(TOPRIGHT, controlToAnchorTo, BOTTOMRIGHT, 0, 4)
                end
            end
        end
        benefitLine:SetParent(lineContainer)
        controlToAnchorTo = benefitLine
    end
    local isSubscribed = IsESOPlusSubscriber()
    local statusText = isSubscribed and SI_MARKET_SUBSCRIPTION_PAGE_SUBSCRIPTION_STATUS_ACTIVE or SI_MARKET_SUBSCRIPTION_PAGE_SUBSCRIPTION_STATUS_NOT_ACTIVE
    control:GetNamedChild("MembershipInfoStatus"):SetText(GetString(statusText))
    ZO_GamepadMarket_GridScreen.FinishBuild(self)
end
function GamepadMarket:LayoutMarketProducts(marketProductPresentations, disableLTOGrouping)
    self:SetCurrentKeybinds(self.keybindStripDescriptors)
    local numProducts = #marketProductPresentations
    local productsPerRow, productPadding, productWidth, productHeight
    productsPerRow, productPadding, productWidth, productHeight = ZO_GAMEPAD_MARKET_INDIVIDUAL_PRODUCTS_PER_ROW, ZO_GAMEPAD_MARKET_PRODUCT_PADDING , ZO_GAMEPAD_MARKET_INDIVIDUAL_PRODUCT_WIDTH, ZO_GAMEPAD_MARKET_INDIVIDUAL_PRODUCT_HEIGHT
    local productsPerColumn = zo_ceil(numProducts / productsPerRow)
    self:PrepareGridForBuild(productsPerRow, productsPerColumn, productWidth, productHeight, productPadding)
    local categoryType = self.currentCategoryData.type
    for _, presentationInfo in ipairs(marketProductPresentations) do
        local id = presentationInfo.id
        local presentationIndex = presentationInfo.presentationIndex
        local marketProduct = self.currentCategoryMarketProductPool:AcquireObject()
        marketProduct:Show(id, presentationIndex)
        local name, description, icon, isNew, isFeatured = marketProduct:GetMarketProductInfo()
        local isLimitedTime = marketProduct:IsLimitedTimeProduct()
        local doesContainDLC = DoesMarketProductContainDLC(id)
        if doesContainDLC and categoryType == ZO_MARKET_CATEGORY_TYPE_FEATURED then
            self:AddProductToLabeledGroupTable(self.dlcProducts, name, marketProduct)
        else
            if isLimitedTime and not disableLTOGrouping then
                self:AddProductToLabeledGroupTable(self.limitedTimedOfferProducts, name, marketProduct)
            elseif isFeatured then
                self:AddProductToLabeledGroupTable(self.featuredProducts, name, marketProduct)
            else
                self:AddMarketProductToLabeledGroupOrGeneralGroup(name, marketProduct, id)
            end
        end
    end
    self:AddLabeledGroupTable(GetString(SI_MARKET_LIMITED_TIME_OFFER_CATEGORY), self.limitedTimedOfferProducts)
    self:AddLabeledGroupTable(GetString(SI_MARKET_DLC_CATEGORY), self.dlcProducts)
    self:AddLabeledGroupTable(GetString(SI_MARKET_FEATURED_CATEGORY), self.featuredProducts)
    if categoryType == ZO_MARKET_CATEGORY_TYPE_FEATURED then
        self:AddLabeledGroupTable(GetString(SI_MARKET_ALL_LABEL), self.marketProducts)
    else
        local sortedSubcategories = CreateSortedSubcategoryList(self.subCategoryLabeledGroupTableMap)
        for categoryIndex, subcategoryInfo in ipairs(sortedSubcategories) do
            local subCategoryName = subcategoryInfo.data.text
            self:AddLabeledGroupTable(subCategoryName, subcategoryInfo.groupTable)
        end
        self:AddLabeledGroupTable(GetString(SI_MARKET_ALL_LABEL), self.marketProducts)
    end
    self:FinishBuild()
end
function GamepadMarket:OnMarketOpen()
    if ZO_GAMEPAD_MARKET_LOCKED then -- This can be called before the lock screen has been initialized
        ZO_GAMEPAD_MARKET_LOCKED:OnMarketOpen()
    end
    if self.isInitialized then
        ZO_GamepadMarket_GridScreen.OnShowing(self)
        if not self.categoriesInitialized or self.refreshCategories then
            self:BuildCategories()
        else
            self:UpdateCurrentCategory()
        end
        self.isLockedForCategoryRefresh = true -- prevent double category initialization on first entry
        self:RefreshHeader()
        self:SelectAfterPreview()
        self.isLockedForCategoryRefresh = false
    end
end
function GamepadMarket:OnMarketLocked()
    if self.isInitialized and SCENE_MANAGER:IsShowing(ZO_GAMEPAD_MARKET_SCENE_NAME) and (not ZO_GAMEPAD_MARKET_LOCKED_SCENE:IsShowing()) then
        SCENE_MANAGER:SwapCurrentScene(ZO_GAMEPAD_MARKET_LOCKED_SCENE_NAME)
    end
end
-- we shouldn't get into this state when the gamepad Crown Store is open, so treat it like a lock (as before)
function GamepadMarket:OnMarketLoading()
    self:OnMarketLocked()
end
function GamepadMarket:OnMarketPurchaseResult()
    -- handled by GamepadMarketPurchaseManager
end
do
    local PURCHASE_MANAGER = ZO_GamepadMarketPurchaseManager:New() -- Singleton purchase manager
    local FROM_INGAME = true
    local FROM_CROWN_STORE = false
    function GamepadMarket:PurchaseMarketProduct(marketProductId, presentationIndex)
        PURCHASE_MANAGER:BeginPurchase(marketProductId, presentationIndex, FROM_INGAME)
    end
    function GamepadMarket:PurchaseMarketProductInternal(marketProductId, presentationIndex, onPurchaseSuccessCallback, onPurchaseEndCallback)
        PURCHASE_MANAGER:BeginPurchase(marketProductId, presentationIndex, FROM_CROWN_STORE, onPurchaseSuccessCallback, onPurchaseEndCallback)
    end
    function GamepadMarket:OnShowBuyCrownsDialog()
        PURCHASE_MANAGER:ShowBuyCrownsDialog(FROM_INGAME)
    end
    function GamepadMarket:OnShowBuyCrownsDialogInternal()
        PURCHASE_MANAGER:ShowBuyCrownsDialog(FROM_CROWN_STORE)
    end
end
function GamepadMarket:ShowBundleContents(bundle)
    self:Deactivate()
    self.isLockedForCategoryRefresh = true
    ZO_GAMEPAD_MARKET_BUNDLE_CONTENTS:SetBundle(bundle)
    SCENE_MANAGER:Push(ZO_GAMEPAD_MARKET_BUNDLE_CONTENTS_SCENE_NAME)
end
function GamepadMarket:ShowMarketProductContentsAsList(marketProduct, previewType)
    self:Deactivate()
    self.isLockedForCategoryRefresh = true
    SCENE_MANAGER:Push(ZO_GAMEPAD_MARKET_CONTENT_LIST_SCENE_NAME)
    ZO_GAMEPAD_MARKET_PRODUCT_LIST:SetMarketProduct(marketProduct:GetId(), previewType)
end
function GamepadMarket:ShowHousePreviewDialog(marketProduct)
    local marketProductId = marketProduct:GetId()
    local mainTextParams = {mainTextParams = ZO_MarketDialogs_Shared_GetPreviewHouseDialogMainTextParams(marketProductId)}
    ZO_Dialogs_ShowGamepadDialog("CROWN_STORE_PREVIEW_HOUSE", { marketProductId = marketProduct:GetId() }, mainTextParams)
end
function GamepadMarket:OnTutorialShowing()
    g_activeMarketScreen:RemoveKeybinds()
    g_activeMarketScreen:Deactivate()
end
function GamepadMarket:OnTutorialHidden()
    g_activeMarketScreen:Activate()
    g_activeMarketScreen:AddKeybinds()
end
function GamepadMarket:RestoreActionLayerForTutorial()
    PushActionLayerByName(GetString(SI_KEYBINDINGS_LAYER_GENERAL))
end
function GamepadMarket:RemoveActionLayerForTutorial()
    -- we exit the gamepad tutotial by pressing "A"
    RemoveActionLayerByName(GetString(SI_KEYBINDINGS_LAYER_GENERAL))
end
function GamepadMarket:ClearProducts()
    ZO_GamepadMarket_GridScreen.ClearProducts(self)
    self.selectedMarketProduct = nil
    KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptors)
end
function GamepadMarket:GetMarketProductInfoFromLabeledGroup(labeledGroup, productId)
    for i = 1, #labeledGroup do
        if labeledGroup[i].product:GetId() == productId then
            return labeledGroup[i]
        end
    end
    return nil
end
function GamepadMarket:GetCurrentCategoryMarketProductInfoById(productId)
    -- First check all our special categories to see if the MarketProduct is in one of them
    local marketProductInfo = self:GetMarketProductInfoFromLabeledGroup(self.featuredProducts, productId)
    if marketProductInfo then
        return marketProductInfo
    end
    marketProductInfo = self:GetMarketProductInfoFromLabeledGroup(self.limitedTimedOfferProducts, productId)
    if marketProductInfo then
        return marketProductInfo
    end
    marketProductInfo = self:GetMarketProductInfoFromLabeledGroup(self.dlcProducts, productId)
    if marketProductInfo then
        return marketProductInfo
    end
    marketProductInfo = self:GetMarketProductInfoFromLabeledGroup(self.marketProducts, productId)
    if marketProductInfo then
        return marketProductInfo
    end
    -- We didn't find it in one of the special buckets, check the normal subcategories
    local numSubCategories = self.currentCategoryData.numSubCategories
    for subcategoryIndex = 1, numSubCategories do
        local subCategoryProducts = self:FindSubCategoryLabeledGroupTable(subcategoryIndex)
        for productIndex = 1, #subCategoryProducts do
            if subCategoryProducts[productIndex].product.marketProductId == productId then
                return subCategoryProducts[productIndex]
            end
        end
    end
end
function GamepadMarket:RequestShowMarketProduct(id)
    self.queuedMarketProductId = id
end
function GamepadMarket:ShowMarketProduct(id)
    local data = self:GetCategoryDataForMarketProduct(id)
    if data then
        local targetIndex = data.tabIndex
        if self.header.tabBar:GetSelectedIndex() ~= targetIndex then
            self.header.tabBar:SetSelectedDataIndex(targetIndex)
        end
        local targetMarketProduct = self:GetCurrentCategoryMarketProductInfoById(id)
        if targetMarketProduct then
            self:ScrollToGridEntry(targetMarketProduct.product:GetFocusData(), true)
            local listIndex = targetMarketProduct.product:GetListIndex()
            self.focusList:SetFocusByIndex(listIndex)
        end
    end
end
function GamepadMarket:GetCategoryData(categoryIndex)
    local categoryTable = self.headerData.tabBarEntries[categoryIndex + self.categoryIndexOffset]
    if categoryTable ~= nil then
        return categoryTable.categoryData
    end
end
-- overrides from ZO_Market_Shared
function GamepadMarket:AddKeybinds()
    KEYBIND_STRIP:AddKeybindButtonGroup(self.currentKeybindDescriptor)
end
function GamepadMarket:RemoveKeybinds()
    KEYBIND_STRIP:RemoveKeybindButtonGroup(self.currentKeybindDescriptor)
end
function GamepadMarket:RefreshKeybinds()
    KEYBIND_STRIP:UpdateKeybindButtonGroup(self.currentKeybindDescriptor)
end
-- copy the standard gamepad style but change the center and right offsets
ZO_GAMEPAD_KEYBIND_STRIP_MARKET_GAMEPAD_STYLE = ZO_ShallowTableCopy(KEYBIND_STRIP_GAMEPAD_STYLE)
ZO_GAMEPAD_KEYBIND_STRIP_MARKET_GAMEPAD_STYLE.centerAnchorOffset = -230
    local currencyStyle = MARKET_CURRENCY_GAMEPAD:ModifyKeybindStripStyleForCurrency(ZO_GAMEPAD_KEYBIND_STRIP_MARKET_GAMEPAD_STYLE)
    KEYBIND_STRIP:SetStyle(currencyStyle)
end
--
-- [[ Market Product Tooltip ]]--
--
do
    local MarketTooltipMixin = {}
    do
        local BUNDLE_HEADER = GetString(SI_MARKET_PRODUCT_TOOLTIP_BUNDLE)
        local DLC_HEADER = GetString(SI_MARKET_PRODUCT_TOOLTIP_DLC)
        local UPGRADE_HEADER = GetString(SI_MARKET_PRODUCT_TOOLTIP_UPGRADE)
        local UNLOCK_LABEL = GetString(SI_MARKET_PRODUCT_TOOLTIP_UNLOCK)
        local SERVICE_HEADER = GetString(SI_SERVICE_TOOLTIP_TYPE)
        local QUALITY_NORMAL = nil
        local NO_CATEGORY_NAME = nil
        local NO_NICKNAME = nil
        local IS_PURCHASEABLE = true
        local BLANK_HINT = ""
        local HIDE_VISUAL_LAYER_INFO = false
        local NO_COOLDOWN = nil
        local HIDE_BLOCK_REASON = false
        function MarketTooltipMixin:AddInstantUnlockEligibilityFailures(...)
            local count = select("#", ...)
            if count > 0 then
                local ineligibilitySection = self:AcquireSection(self:GetStyle("instantUnlockIneligibilitySection"))
                for i = 1, count do
                    local errorStringId = select(i, ...)
                    if errorStringId ~= 0 then
                        ineligibilitySection:AddLine(GetErrorString(errorStringId), self:GetStyle("instantUnlockIneligibilityLine"))
                    end
                end
                self:AddSection(ineligibilitySection)
            end
        end
        function MarketTooltipMixin:LayoutMarketProduct(productId)
            local productType = GetMarketProductType(productId)
            -- For some market product types we can just use other tooltip layouts
            if productType == MARKET_PRODUCT_TYPE_COLLECTIBLE then
                local collectibleId, _, name, type, description, owned, isPlaceholder = GetMarketProductCollectibleInfo(productId)
                self:LayoutCollectible(collectibleId, NO_CATEGORY_NAME, name, NO_NICKNAME, IS_PURCHASEABLE, description, BLANK_HINT, isPlaceholder, HIDE_VISUAL_LAYER_INFO, NO_COOLDOWN, HIDE_BLOCK_REASON)
                return
            elseif productType == MARKET_PRODUCT_TYPE_ITEM then
                local itemLink = GetMarketProductItemLink(productId)
                local stackCount = GetMarketProductStackCount(productId)
                self:LayoutItemWithStackCountSimple(itemLink, stackCount)
                return
            end
            --things added to the topSection stack upwards
            local topSection = self:AcquireSection(self:GetStyle("topSection"))
            local instantUnlockType = MARKET_INSTANT_UNLOCK_NONE
            if productType == MARKET_PRODUCT_TYPE_BUNDLE then
                if DoesMarketProductContainDLC(productId) and GetMarketProductNumBundledProducts(productId) == 1 then
                    topSection:AddLine(DLC_HEADER)
                else
                    topSection:AddLine(BUNDLE_HEADER)
                end
            elseif productType == MARKET_PRODUCT_TYPE_CROWN_CRATE then
                local crateId = GetMarketProductCrownCrateId(productId)
                local crateCount = GetCrownCrateCount(crateId)
                if crateCount > 0 then
                    local topSubsection = topSection:AcquireSection(self:GetStyle("topSubsectionItemDetails"))
                    topSubsection:AddLine(zo_iconTextFormat("EsoUI/Art/Tooltips/icon_crown_crate.dds", 24, 24, crateCount))
                    topSection:AddSection(topSubsection)
                end
            elseif productType == MARKET_PRODUCT_TYPE_INSTANT_UNLOCK then
                instantUnlockType = GetMarketProductInstantUnlockType(productId)
                if instantUnlockType ~= MARKET_INSTANT_UNLOCK_NONE then
                    if IsMarketInstantUnlockServiceToken(productId) then
                        topSection:AddLine(SERVICE_HEADER)
                    else
                        topSection:AddLine(UPGRADE_HEADER)
                    end
                end
            end
            self:AddSection(topSection)
            -- Name
            local displayName = GetMarketProductDisplayName(productId)
            local stackCount = GetMarketProductStackCount(productId)
            if stackCount > 1 then
                displayName = zo_strformat(SI_TOOLTIP_ITEM_NAME_WITH_QUANTITY, displayName, stackCount)
            else
                displayName = zo_strformat(SI_TOOLTIP_ITEM_NAME, displayName)
            end
            self:AddLine(displayName, QUALITY_NORMAL, self:GetStyle("title"))
            local tooltipLines = {}
            if IsMarketInstantUnlockUpgrade(productId) then
                local statsSection = self:AcquireSection(self:GetStyle("baseStatsSection"))
                local statValuePair = statsSection:AcquireStatValuePair(self:GetStyle("statValuePair"))
                statValuePair:SetStat(UNLOCK_LABEL, self:GetStyle("statValuePairStat"))
            
                local currentUnlock
                local maxUnlock
                local unlockDescription
                if instantUnlockType == MARKET_INSTANT_UNLOCK_PLAYER_BACKPACK then
                    currentUnlock = GetCurrentBackpackUpgrade()
                    maxUnlock = GetMaxBackpackUpgrade()
                    unlockDescription = zo_strformat(SI_MARKET_PRODUCT_TOOLTIP_BACKPACK_UPGRADE_DESCRIPTION, GetNumBackpackSlotsPerUpgrade())
                elseif instantUnlockType == MARKET_INSTANT_UNLOCK_PLAYER_BANK then
                    currentUnlock = GetCurrentBankUpgrade()
                    maxUnlock = GetMaxBankUpgrade()
                    unlockDescription = zo_strformat(SI_MARKET_PRODUCT_TOOLTIP_BANK_UPGRADE_DESCRIPTION, GetNumBankSlotsPerUpgrade())
                elseif instantUnlockType == MARKET_INSTANT_UNLOCK_CHARACTER_SLOT then
                    currentUnlock = GetCurrentCharacterSlotsUpgrade()
                    maxUnlock = GetMaxCharacterSlotsUpgrade()
                    unlockDescription = zo_strformat(SI_MARKET_PRODUCT_TOOLTIP_CHARACTER_SLOT_UPGRADE_DESCRIPTION, GetNumCharacterSlotsPerUpgrade())
                end
                table.insert(tooltipLines, unlockDescription)
                statValuePair:SetValue(zo_strformat(SI_MARKET_PRODUCT_TOOLTIP_UNLOCK_LEVEL, currentUnlock, maxUnlock), self:GetStyle("statValuePairValue"))
                statsSection:AddStatValuePair(statValuePair)
                self:AddSection(statsSection)
            elseif IsMarketInstantUnlockServiceToken(productId) then
                local tokenDescription
                local tokenUsageRequirement = GetString(SI_SERVICE_TOKEN_USAGE_REQUIREMENT_CHARACTER_SELECT) -- All tokens only usable from character select
                local tokenCountString
                if instantUnlockType == MARKET_INSTANT_UNLOCK_RENAME_TOKEN then
                    tokenDescription = GetString(SI_SERVICE_TOOLTIP_NAME_CHANGE_TOKEN_DESCRIPTION)
                    tokenCountString = zo_strformat(SI_SERVICE_TOOLTIP_SERVICE_TOKENS_AVAILABLE, GetNumServiceTokens(SERVICE_TOKEN_NAME_CHANGE), GetString("SI_SERVICETOKENTYPE", SERVICE_TOKEN_NAME_CHANGE))
                elseif instantUnlockType == MARKET_INSTANT_UNLOCK_RACE_CHANGE_TOKEN then
                    tokenDescription = GetString(SI_SERVICE_TOOLTIP_RACE_CHANGE_TOKEN_DESCRIPTION)
                    tokenCountString = zo_strformat(SI_SERVICE_TOOLTIP_SERVICE_TOKENS_AVAILABLE, GetNumServiceTokens(SERVICE_TOKEN_RACE_CHANGE), GetString("SI_SERVICETOKENTYPE", SERVICE_TOKEN_RACE_CHANGE))
                elseif instantUnlockType == MARKET_INSTANT_UNLOCK_APPEARANCE_CHANGE_TOKEN then
                    tokenDescription = GetString(SI_SERVICE_TOOLTIP_APPEARANCE_CHANGE_TOKEN_DESCRIPTION)
                    tokenCountString = zo_strformat(SI_SERVICE_TOOLTIP_SERVICE_TOKENS_AVAILABLE, GetNumServiceTokens(SERVICE_TOKEN_APPEARANCE_CHANGE), GetString("SI_SERVICETOKENTYPE", SERVICE_TOKEN_APPEARANCE_CHANGE))
                end
                table.insert(tooltipLines, tokenDescription)
                table.insert(tooltipLines, tokenUsageRequirement)
                table.insert(tooltipLines, tokenCountString)
            else
                table.insert(tooltipLines, GetMarketProductDescription(productId))
            end
            -- Description
            local bodySection = self:AcquireSection(self:GetStyle("collectionsInfoSection"))
            for i = 1, #tooltipLines do
                bodySection:AddLine(tooltipLines[i], self:GetStyle("bodyDescription"))
            end
            self:AddSection(bodySection)
            --Instant Unlock Restrictions
            if instantUnlockType ~= MARKET_INSTANT_UNLOCK_NONE then
                local GET_CACHED_STATE = true
                local purchaseState = GetMarketProductPurchaseState(productId, GET_CACHED_STATE)
                if purchaseState == MARKET_PRODUCT_PURCHASE_STATE_INSTANT_UNLOCK_INELIGIBLE then
                    self:AddInstantUnlockEligibilityFailures(GetMarketProductEligibilityErrorStringIds(productId))
                end
            end
        end
    end
    -- Using a mixin because adding a method to ZO_Tooltip doesn't work with GAMEPAD_TOOLTIPS if the method is added after ZO_Tooltip_Gamepad.lua is loaded
    local rightTooltip = GAMEPAD_TOOLTIPS:GetTooltip(GAMEPAD_RIGHT_TOOLTIP)
    zo_mixin(rightTooltip, MarketTooltipMixin)
    local leftTooltip = GAMEPAD_TOOLTIPS:GetTooltip(GAMEPAD_LEFT_TOOLTIP)
    zo_mixin(leftTooltip, MarketTooltipMixin)
end
--
--[[ Gamepad Market Bundle Contents ]]--
--
local GamepadMarketBundleContents = ZO_GamepadMarket_GridScreen:Subclass()
function GamepadMarketBundleContents:New(...)
    local bundleContents = ZO_Object.New(self)
    bundleContents:Initialize(...)
    return bundleContents
end
function GamepadMarketBundleContents:Initialize(control)
    ZO_GamepadMarket_GridScreen.Initialize(self, control, ZO_GAMEPAD_MARKET_INDIVIDUAL_PRODUCTS_PER_ROW, ZO_GAMEPAD_MARKET_PRODUCTS_PER_COLUMN)
    GAMEPAD_MARKET_BUNDLE_CONTENTS_SCENE = ZO_RemoteScene:New(ZO_GAMEPAD_MARKET_BUNDLE_CONTENTS_SCENE_NAME, SCENE_MANAGER)
    GAMEPAD_MARKET_BUNDLE_CONTENTS_SCENE:RegisterCallback("StateChange", function(...) self:OnStateChanged(...) end)
end
function GamepadMarketBundleContents:InitializeMarketProductPool()
    local BUNDLE_ATTACHMENT_NAME = self.control:GetName() .. ZO_GAMEPAD_MARKET_PRODUCT_BUNDLE_ATTACHMENT_TEMPLATE
    
    local function ResetMarketProduct(marketProduct)
        marketProduct:Reset()
    end
    
    local function CreateMarketBundleAttachment(objectPool)
        return ZO_GamepadMarketProductBundleAttachment:New(objectPool:GetNextControlId(), self.currentCategoryControl, self, BUNDLE_ATTACHMENT_NAME)
    end
    self.marketBundleAttachmentPool = ZO_ObjectPool:New(CreateMarketBundleAttachment, ResetMarketProduct)
end
function GamepadMarketBundleContents:OnStateChanged(oldState, newState)
    if newState == SCENE_SHOWING then
        self:OnShowing()
    elseif newState == SCENE_SHOWN then
        self:OnShown()
    elseif newState == SCENE_HIDDEN then
        self:OnHiding()
    end
end
function GamepadMarketBundleContents:PerformDeferredInitialization()
    if not self.isInitialized then
        self.titleControl = self.header:GetNamedChild("TitleContainerTitle")
        local function RefreshOnPurchase()
            self:RefreshProducts()
        end
        local function QueueTutorial(_, purchasedConsumables, triggerTutorialOnPurchase)
            if purchasedConsumables then
                self:SetQueuedTutorial(TUTORIAL_TRIGGER_CROWN_CONSUMABLE_PURCHASED)
            end
            if triggerTutorialOnPurchase then
                self:SetQueuedTutorial(triggerTutorialOnPurchase)
            end
        end
        GAMEPAD_MARKET_BUNDLE_CONTENTS_SCENE:GetSceneGroup():RegisterCallback("StateChange", function(oldState, newState)
            if newState == SCENE_GROUP_SHOWING then
                self:OnInitialInteraction()
            elseif newState == SCENE_GROUP_HIDDEN then
                self:OnEndInteraction()
            end
        end)
        self.keybindStripDescriptors =
        {
            alignment = KEYBIND_STRIP_ALIGN_LEFT,
            {
                name = GetString(SI_MARKET_PURCHASE_BUNDLE_KEYBIND_TEXT),
                keybind = "UI_SHORTCUT_PRIMARY",
                visible = function()
                    return self.bundle ~= nil and not self.bundle:IsPurchaseLocked()
                end,
                enabled = function() return not self:HasQueuedTutorial() end,
                callback = function()
                    self.prePurchaseSelectedIndex = self.focusList:GetSelectedIndex()
                    ZO_GAMEPAD_MARKET:PurchaseMarketProductInternal(self.bundle:GetId(), self.bundle:GetPresentationIndex(), RefreshOnPurchase, QueueTutorial)
                end,
            },
            {
                alignment = KEYBIND_STRIP_ALIGN_CENTER,
                name =  GetString(SI_MARKET_PREVIEW_KEYBIND_TEXT),
                keybind = "UI_SHORTCUT_SECONDARY",
                visible = function()
                    return self.selectedMarketProduct ~= nil and self.bundle ~= nil and self.selectedMarketProduct:HasPreview() and IsCharacterPreviewingAvailable()
                end,
                callback = function() self:BeginPreview() end
            },
            MARKET_BUY_CROWNS_BUTTON,
            KEYBIND_STRIP:GetDefaultGamepadBackButtonDescriptor()
        }
        self.isInitialized = true
    end
end
function GamepadMarketBundleContents:SetBundle(bundle)
    self.bundle = bundle
    self.headerData.titleText = bundle.title:GetText()
end
function GamepadMarketBundleContents:LayoutBundleProducts(bundle)
    self:ClearProducts()
    self:PrepareGridForBuild(ZO_GAMEPAD_MARKET_INDIVIDUAL_PRODUCTS_PER_ROW, ZO_GAMEPAD_MARKET_PRODUCTS_PER_COLUMN, ZO_GAMEPAD_MARKET_INDIVIDUAL_PRODUCT_WIDTH, ZO_GAMEPAD_MARKET_INDIVIDUAL_PRODUCT_HEIGHT, ZO_GAMEPAD_MARKET_PRODUCT_PADDING)
    local numChildren = bundle:GetNumChildren()
    if numChildren > 0 then
        local childTiles = {}
        for childIndex = 1, numChildren do
            local childMarketProductId = bundle:GetChildMarketProductId(childIndex)
            local displayName = GetMarketProductDisplayName(childMarketProductId)
            local marketProduct = self.marketBundleAttachmentPool:AcquireObject()
            marketProduct:SetBundle(bundle)
            marketProduct:Show(childMarketProductId)
            table.insert(childTiles, {displayName = displayName, marketProduct = marketProduct})
        end
        -- Sort the child tiles alphabetically
        table.sort(childTiles, function(a,b)
                                        return a.displayName < b.displayName
                                    end)
        for i = 1, #childTiles do
            local marketProduct = childTiles[i].marketProduct
            self:AddEntry(marketProduct, marketProduct:GetControl())
        end
    end
    self:FinishBuild()
end
function GamepadMarketBundleContents:OnShowing()
    ZO_GamepadMarket_GridScreen.OnShowing(self)
    self:LayoutBundleProducts(self.bundle)
    self.titleControl:SetText(self.headerData.titleText)
    self:AddKeybinds()
    self:Activate()
    if self.prePurchaseSelectedIndex then
        self.focusList:SetFocusByIndex(self.prePurchaseSelectedIndex)
        self.prePurchaseSelectedIndex = nil
    end
end
function GamepadMarketBundleContents:OnShown()
    g_activeMarketScreen = ZO_GAMEPAD_MARKET_BUNDLE_CONTENTS
    ZO_GamepadMarket_GridScreen.OnShown(self)
end
function GamepadMarketBundleContents:OnHiding()
    self:RemoveKeybinds()
    self:Deactivate()
end
function GamepadMarketBundleContents:LayoutSelectedMarketProduct()
    self.selectedMarketProduct:LayoutTooltip(GAMEPAD_RIGHT_TOOLTIP)
end
function GamepadMarketBundleContents:OnSelectionChanged(selectedData)
    ZO_GamepadMarket_GridScreen.OnSelectionChanged(self, selectedData)
    local previouslySelectedMarketProduct = self.selectedMarketProduct
    if selectedData then
        self.selectedMarketProduct = selectedData.marketProduct
    else
        GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_RIGHT_TOOLTIP)
        self.selectedMarketProduct = nil
    end
    self:UpdatePreviousAndNewlySelectedProducts(previouslySelectedMarketProduct, self.selectedMarketProduct)
end
function GamepadMarketBundleContents:OnInitialInteraction()
end
function GamepadMarketBundleContents:OnEndInteraction()
    self.prePurchaseSelectedIndex = nil
end
function GamepadMarketBundleContents:ReleaseAllProducts()
    self.marketBundleAttachmentPool:ReleaseAllObjects()
    self.blankTilePool:ReleaseAllObjects()
end
function GamepadMarketBundleContents:AddKeybinds()
    KEYBIND_STRIP:AddKeybindButtonGroup(self.keybindStripDescriptors)
end
function GamepadMarketBundleContents:RemoveKeybinds()
    KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptors)
end
function GamepadMarketBundleContents:RefreshKeybinds()
    KEYBIND_STRIP:UpdateKeybindButtonGroup(self.keybindStripDescriptors)
end
-- override from ZO_GamepadMarket_GridScreen
function GamepadMarketBundleContents:FinishBuild()
    ZO_GamepadMarket_GridScreen.FinishBuild(self)
end
-- override from ZO_GamepadMarket_GridScreen
function GamepadMarketBundleContents:EndCurrentPreview()
    ZO_GamepadMarket_GridScreen.EndCurrentPreview(self)
end
-- MarketClasses_Shared expects us to have this function (because Market_Shared does)
function GamepadMarketBundleContents:RefreshActions()
end
--
--[[ Gamepad Market Product List Scene ]]--
--
local GamepadMarketProductListScene = ZO_Gamepad_ParametricList_Screen:Subclass()
function GamepadMarketProductListScene:New(...)
    return ZO_Gamepad_ParametricList_Screen.New(self, ...)
end
function GamepadMarketProductListScene:Initialize(control)
    ZO_GAMEPAD_MARKET_LIST_SCENE = ZO_RemoteScene:New(ZO_GAMEPAD_MARKET_CONTENT_LIST_SCENE_NAME, SCENE_MANAGER)
    local ACTIVATE_ON_SHOW = true
    ZO_Gamepad_ParametricList_Screen.Initialize(self, control, ZO_GAMEPAD_HEADER_TABBAR_DONT_CREATE, ACTIVATE_ON_SHOW, ZO_GAMEPAD_MARKET_LIST_SCENE)
    self.list = self:GetMainList()
    self.previewProducts = {}
end
function GamepadMarketProductListScene:OnDeferredInitialize()
end
function GamepadMarketProductListScene:InitializeKeybindStripDescriptors()
    self.keybindStripDescriptor =
    {
        alignment = KEYBIND_STRIP_ALIGN_LEFT,
        -- "Preview" Keybind
        {
            name = GetString(SI_MARKET_PREVIEW_KEYBIND_TEXT),
            keybind = "UI_SHORTCUT_PRIMARY",
            visible =   function()
                            local targetData = self.list:GetTargetData()
                            if targetData then
                                return true
                            end
                            return false
                        end,
            enabled =   function()
                            local targetData = self.list:GetTargetData()
                            if targetData then
                                local productId = targetData.marketProductId
                                return targetData.hasPreview and IsCharacterPreviewingAvailable()
                            end
                            return false
                        end,
            callback =  function()
                            self:BeginPreview()
                        end,
        },
        -- Back
        KEYBIND_STRIP:GetDefaultGamepadBackButtonDescriptor(),
    }
    self.previewKeybindStripDesciptor =
    {
        alignment = KEYBIND_STRIP_ALIGN_CENTER,
        {
            name = GetString(SI_GAMEPAD_PREVIEW_PREVIOUS),
            keybind = "UI_SHORTCUT_LEFT_TRIGGER",
            callback = function()
                self:MoveToPreviousPreviewProduct()
            end,
            visible = function() return self:HasMultiplePreviewProducts() end,
            enabled = function() return ITEM_PREVIEW_GAMEPAD:CanChangePreview() end,
        },
        {
            name = GetString(SI_GAMEPAD_PREVIEW_NEXT),
            keybind = "UI_SHORTCUT_RIGHT_TRIGGER",
            callback = function()
                self:MoveToNextPreviewProduct()
            end,
            visible = function() return self:HasMultiplePreviewProducts() end,
            enabled = function() return ITEM_PREVIEW_GAMEPAD:CanChangePreview() end,
        },
        KEYBIND_STRIP:GetDefaultGamepadBackButtonDescriptor()
    }
end
function GamepadMarketProductListScene:InitializeHeader()
    self.headerData = {
        titleText = "",
    }
    ZO_GamepadGenericHeader_Refresh(self.header, self.headerData)
end
function GamepadMarketProductListScene:OnShowing()
    ZO_Gamepad_ParametricList_Screen.OnShowing(self)
    if self.queuedMarketProductId ~= nil then
        self:ShowMarketProduct(self.queuedMarketProductId, self.queuedPreviewType)
        self.queuedMarketProductId = nil
        self.queuedPreviewType = nil
    else
        if self.isPreviewing then
            self:SelectAfterPreview()
        end
    end
    self.isPreviewing = false
    self.previewIndex = nil
end
function GamepadMarketProductListScene:OnHiding()
    GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_LEFT_TOOLTIP)
    self.queuedMarketProductId = nil
    self.queuedPreviewType = nil
end
function GamepadMarketProductListScene:SetMarketProduct(marketProductId, previewType)
    if SCENE_MANAGER:IsShowing(self.scene.name) then
        self:ShowMarketProduct(marketProductId, previewType)
    else
        self.queuedMarketProductId = marketProductId
        self.queuedPreviewType = previewType
    end
end
function GamepadMarketProductListScene:ShowMarketProduct(marketProductId, previewType)
    if previewType == ZO_MARKET_PREVIEW_TYPE_CROWN_CRATE then
        self:ShowCrownCrateContents(marketProductId)
    elseif previewType == ZO_MARKET_PREVIEW_TYPE_BUNDLE or previewType == ZO_MARKET_PREVIEW_TYPE_BUNDLE_HIDES_CHILDREN then
        self:ShowMarketProductBundleContents(marketProductId)
    end
end
function GamepadMarketProductListScene:ShowCrownCrateContents(marketProductId)
    self.headerData.titleText = zo_strformat(SI_MARKET_PRODUCT_NAME_FORMATTER, GetMarketProductDisplayName(marketProductId))
    ZO_GamepadGenericHeader_Refresh(self.header, self.headerData)
    local marketProducts = ZO_Market_Shared.GetCrownCrateContentsProductInfo(marketProductId)
    table.sort(marketProducts, function(...)
                                    return ZO_Market_Shared.CompareCrateMarketProducts(...)
                                end)
    local firstEntry = marketProducts[1]
    if firstEntry then
        firstEntry.header = GetString(SI_MARKET_CRATE_LIST_HEADER)
    end
    self:ShowMarketProducts(marketProducts)
end
function GamepadMarketProductListScene:ShowMarketProductBundleContents(marketProductId)
    self.headerData.titleText = zo_strformat(SI_MARKET_PRODUCT_NAME_FORMATTER, GetMarketProductDisplayName(marketProductId))
    ZO_GamepadGenericHeader_Refresh(self.header, self.headerData)
    local marketProducts = ZO_Market_Shared.GetMarketProductBundleChildProductInfo(marketProductId)
    table.sort(marketProducts, function(...)
                return ZO_Market_Shared.CompareBundleMarketProducts(...)
            end)
    self:ShowMarketProducts(marketProducts)
end
-- marketProducts is a table of Market Product info
function GamepadMarketProductListScene:ShowMarketProducts(marketProducts)
    self.list:Clear()
    ZO_ClearNumericallyIndexedTable(self.previewProducts)
    for i = 1, #marketProducts do
        local productInfo = marketProducts[i]
        local productId = productInfo.productId
        local name, description, icon, isNew, isFeatured = GetMarketProductInfo(productId)
        local entryData = ZO_GamepadEntryData:New(zo_strformat(SI_MARKET_PRODUCT_NAME_FORMATTER, name), icon)
        entryData.marketProductId = productId
        entryData.listIndex = i
        entryData:SetStackCount(productInfo.stackCount)
        entryData.quality = productInfo.quality or ITEM_QUALITY_NORMAL
        entryData:SetNameColors(entryData:GetColorsBasedOnQuality(entryData.quality))
        if productInfo.header ~= nil then
            entryData:SetHeader(productInfo.header)
            self.list:AddEntryWithHeader("ZO_GamepadMenuEntryTemplate", entryData)
        else
            self.list:AddEntry("ZO_GamepadMenuEntryTemplate", entryData)
        end
        local hasPreview = CanPreviewMarketProduct(productId)
        entryData.hasPreview = hasPreview
        if hasPreview then
            table.insert(self.previewProducts, entryData)
            entryData.previewIndex = #self.previewProducts
        end
    end
    self.list:Commit()
end
function GamepadMarketProductListScene:OnTargetChanged(list, targetData, oldTargetData)
    GAMEPAD_TOOLTIPS:ClearTooltip(GAMEPAD_LEFT_TOOLTIP)
    if targetData then
        local productId = targetData.marketProductId
        GAMEPAD_TOOLTIPS:LayoutMarketProduct(GAMEPAD_LEFT_TOOLTIP, productId)
    end
end
function GamepadMarketProductListScene:BeginPreview()
    self.isPreviewing = true
    local targetData = self.list:GetTargetData()
    if targetData then
        self.previewIndex = targetData.previewIndex
    end
    self.RefreshPreviewKeybindStrip = function()
        KEYBIND_STRIP:UpdateKeybindButtonGroup(self.previewKeybindStripDesciptor)
    end
    self.PreviewSceneOnStateChange = function(oldState, newState)
        if newState == SCENE_SHOWING then
            KEYBIND_STRIP:AddKeybindButtonGroup(self.previewKeybindStripDesciptor)
            ITEM_PREVIEW_GAMEPAD:RegisterCallback("RefreshActions", self.RefreshPreviewKeybindStrip)
        elseif newState == SCENE_SHOWN then
            --Preventing an out of order issue with the begin preview mode
            self:UpdatePreviewToCurrentPreviewedProduct()
        elseif newState == SCENE_HIDDEN then
            KEYBIND_STRIP:RemoveKeybindButtonGroup(self.previewKeybindStripDesciptor)
            GAMEPAD_MARKET_PREVIEW_SCENE:UnregisterCallback("StateChange", self.PreviewSceneOnStateChange)
            ITEM_PREVIEW_GAMEPAD:UnregisterCallback(self.RefreshPreviewKeybindStrip)
        end
    end
    GAMEPAD_MARKET_PREVIEW_SCENE:RegisterCallback("StateChange", self.PreviewSceneOnStateChange)
    SCENE_MANAGER:Push(ZO_GAMEPAD_MARKET_PREVIEW_SCENE_NAME)    
end
function GamepadMarketProductListScene:HasMultiplePreviewProducts()
    return #self.previewProducts > 1
end
function GamepadMarketProductListScene:RefreshActions()
end
function GamepadMarketProductListScene:MoveToPreviousPreviewProduct()
    self.previewIndex = self.previewIndex - 1
    if self.previewIndex < 1 then
        self.previewIndex = #self.previewProducts - self.previewIndex
    end
end
function GamepadMarketProductListScene:MoveToNextPreviewProduct()
    self.previewIndex = self.previewIndex + 1
    if self.previewIndex > #self.previewProducts then
        self.previewIndex = self.previewIndex - #self.previewProducts
    end
end
function GamepadMarketProductListScene:UpdatePreviewToCurrentPreviewedProduct()
    ZO_Market_Shared.PreviewMarketProduct(ITEM_PREVIEW_GAMEPAD, self:GetCurrentPreviewProductId())
    GAMEPAD_TOOLTIPS:LayoutMarketProduct(GAMEPAD_RIGHT_TOOLTIP, self:GetCurrentPreviewProductId())
end
function GamepadMarketProductListScene:GetCurrentPreviewProductId()
    return self.previewProducts[self.previewIndex].marketProductId
end
function GamepadMarketProductListScene:GetCurrentPreviewData()
    return self.previewProducts[self.previewIndex]
end
function GamepadMarketProductListScene:SelectAfterPreview()
    local index = self:GetCurrentPreviewData().listIndex
end
function GamepadMarketProductListScene:PerformUpdate()
    -- This function is required but unused
    self.dirty = false
end
--
-- [[ Market Locked Screen ]]--
--
local GamepadMarketLockedScreen = ZO_Object:New()
function GamepadMarketLockedScreen:New(...)
    local locked = ZO_Object.New(self)
    locked:Initialize(...)
    return locked
end
function GamepadMarketLockedScreen:Initialize(control)
    control.owner = self
    self.control = control
    self.keybindStripDescriptors =
    {
        alignment = KEYBIND_STRIP_ALIGN_LEFT,
        KEYBIND_STRIP:GetDefaultGamepadBackButtonDescriptor()
    }
    ZO_GAMEPAD_MARKET_LOCKED_SCENE = ZO_RemoteScene:New(ZO_GAMEPAD_MARKET_LOCKED_SCENE_NAME, SCENE_MANAGER)
    ZO_GAMEPAD_MARKET_LOCKED_SCENE:RegisterCallback("StateChange", function(...) self:OnStateChanged(...) end)
end
function GamepadMarketLockedScreen:OnStateChanged(oldState, newState)
    if newState == SCENE_SHOWN then
        KEYBIND_STRIP:AddKeybindButtonGroup(self.keybindStripDescriptors)
    elseif newState == SCENE_HIDDEN then
        KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptors)
        KEYBIND_STRIP:SetStyle(KEYBIND_STRIP_STANDARD_STYLE)
    end
end
function GamepadMarketLockedScreen:OnMarketOpen()
    if ZO_GAMEPAD_MARKET_LOCKED_SCENE:IsShowing() then
        SCENE_MANAGER:SwapCurrentScene(ZO_GAMEPAD_MARKET_SCENE_NAME)
    end
end
--
-- [[ Market Pre Scene ]]--
--
local GamepadMarketPreScene = ZO_Object:New()
function GamepadMarketPreScene:New(...)
    local preScene = ZO_Object.New(self)
    preScene:Initialize(...)
    return preScene
end
function GamepadMarketPreScene:Initialize(control)
    self.control = control
    self.keybindStripDescriptors =
    {
        alignment = KEYBIND_STRIP_ALIGN_LEFT,
        KEYBIND_STRIP:GetDefaultGamepadBackButtonDescriptor()
    }
    ZO_GAMEPAD_MARKET_PRE_SCENE = ZO_RemoteScene:New(ZO_GAMEPAD_MARKET_PRE_SCENE_NAME, SCENE_MANAGER)
    ZO_GAMEPAD_MARKET_PRE_SCENE:RegisterCallback("StateChange", function(...) self:OnStateChanged(...) end)
end
function GamepadMarketPreScene:OnStateChanged(oldState, newState)
    if newState == SCENE_SHOWN then
        self:OnShown()
    elseif newState == SCENE_HIDING then
        self:OnHiding()
    end
end
function GamepadMarketPreScene:OnShown()
    self.marketState = GetMarketState(MARKET_DISPLAY_GROUP_CROWN_STORE)
    self.loadingStartTime = nil
    EVENT_MANAGER:RegisterForEvent(ZO_GAMEPAD_MARKET_PRE_SCENE_NAME, EVENT_MARKET_STATE_UPDATED, function(eventId, ...) self:OnMarketStateUpdated(...) end)
    EVENT_MANAGER:RegisterForUpdate(ZO_GAMEPAD_MARKET_PRE_SCENE_NAME, 0, function(...) self:OnUpdate(...) end)
    ZO_MARKET_SINGLETON:RequestOpenMarket()
    if self.marketState ~= MARKET_STATE_UNKNOWN then
        self:SwapToMarketScene()
    end
end
function GamepadMarketPreScene:OnHiding()
    EVENT_MANAGER:UnregisterForUpdate(ZO_GAMEPAD_MARKET_PRE_SCENE_NAME)
    EVENT_MANAGER:UnregisterForEvent(ZO_GAMEPAD_MARKET_PRE_SCENE_NAME, EVENT_MARKET_STATE_UPDATED)
    ZO_GAMEPAD_MARKET_PRE_SCENE:RemoveFragment(GAMEPAD_MARKET_PRE_SCENE_FRAGMENT)
    KEYBIND_STRIP:RemoveKeybindButtonGroup(self.keybindStripDescriptors)
end
function GamepadMarketPreScene:OnMarketStateUpdated(displayGroup, marketState)
    if displayGroup == MARKET_DISPLAY_GROUP_CROWN_STORE then
        self.marketState = marketState
        self:SwapToMarketScene()
    end
end
function GamepadMarketPreScene:OnUpdate(currentMs)
    if self.loadingStartTime == nil then
        self.loadingStartTime = currentMs
    end
    if currentMs - self.loadingStartTime >= ZO_MARKET_DISPLAY_LOADING_DELAY_MS then
        -- show the loading text
        ZO_GAMEPAD_MARKET_PRE_SCENE:AddFragment(GAMEPAD_MARKET_PRE_SCENE_FRAGMENT)
        KEYBIND_STRIP:AddKeybindButtonGroup(self.keybindStripDescriptors)
    end
end
function GamepadMarketPreScene:SwapToMarketScene()
    if ZO_GAMEPAD_MARKET_PRE_SCENE:IsShowing() then
        if self.marketState == MARKET_STATE_OPEN then
            SCENE_MANAGER:SwapCurrentScene(ZO_GAMEPAD_MARKET_SCENE_NAME)
        else
            SCENE_MANAGER:SwapCurrentScene(ZO_GAMEPAD_MARKET_LOCKED_SCENE_NAME)
        end
    end
end
--
--[[ XML Handlers ]]--
--
    ZO_GAMEPAD_MARKET = GamepadMarket:New(control)
    SYSTEMS:RegisterGamepadObject(ZO_MARKET_NAME, ZO_GAMEPAD_MARKET)
end
    ZO_GAMEPAD_MARKET_BUNDLE_CONTENTS = GamepadMarketBundleContents:New(control)
end
    ZO_GAMEPAD_MARKET_LOCKED = GamepadMarketLockedScreen:New(control)
end
    ZO_MARKET_PRE_SCENE = GamepadMarketPreScene:New(control)
end
    ZO_GAMEPAD_MARKET_PRODUCT_LIST = GamepadMarketProductListScene:New(control)
end