-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1213 lines (1057 loc) · 55.9 KB
/
Copy pathscript.js
File metadata and controls
1213 lines (1057 loc) · 55.9 KB
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
// Global Variables
let mode = null;
let subject = null;
let currentQuery = null;
let currentFavorites = null;
let numSeasonTables = new Object({
"TeamSeasonTable": null
});
let currentSeasonTable = new Object({
"TeamSeasonTable": null
});
let seasonTables = new Object({
"TeamSeasonTable": null
});
const seasonTableNameToID = new Object({
"TeamSeasonTable": "team-season-table",
"PlayerRegularSeasonTable" : "player-regular-season-table",
"PlayerPostSeasonTable" : "player-post-season-table",
"PlayerAllStarSeasonTable" : "player-allstar-season-table",
"PlayerCollegeSeasonTable" : "player-college-season-table",
"PlayerShowcaseSeasonTable" : "player-showcase-season-table"
});
const playerHeaderMap = new Map([
["CareerTotalsRegularSeason", "Regular Season Career"],
["CareerTotalsPostSeason", "Post Season Career"],
["CareerTotalsAllStarSeason", "All-Star Season Career"],
["CareerTotalsCollegeSeason", "College Season Career"],
["CareerTotalsShowcaseSeason", "Showcase Season Career"],
["SeasonTotalsRegularSeason", "Regular Seasons"],
["SeasonTotalsPostSeason", "Post Seasons"],
["SeasonTotalsAllStarSeason", "All-Star Seasons"],
["SeasonTotalsCollegeSeason", "College Seasons"],
["SeasonTotalsShowcaseSeason", "Showcase Seasons"]
]);
const playerSeasonTypeToSeasonTableName = new Object({
"SeasonTotalsRegularSeason": "PlayerRegularSeasonTable",
"SeasonTotalsPostSeason": "PlayerPostSeasonTable",
"SeasonTotalsAllStarSeason" : "PlayerAllStarSeasonTable",
"SeasonTotalsCollegeSeason" : "PlayerCollegeSeasonTable",
"SeasonTotalsShowcaseSeason" : "PlayerShowcaseSeasonTable"
});
// ID Variables
let playerNames = null;
let playerNameToID = null;
let teamNames = null;
let teamAbbToName = null;
let teamNameToID = null;
// Event calls
// Runs when the website loads
window.addEventListener("load", function() {
currentURL = window.location.href;
if (currentURL.indexOf("/signup.html") == -1 && currentURL.indexOf("/login.html") == -1 && currentURL.indexOf("/account.html") == -1) {
loginLink();
}
if (currentURL.indexOf("/index.html") != -1 || currentURL == (window.location.origin + "/") || currentURL == window.location.origin) {
loadRecentQueries();
loadFavoriteQueries();
}
if (currentURL.indexOf("/account.html") != -1) {
getUserInfo();
}
if (currentURL.indexOf("/players.html") != -1) {
getPlayerInfo();
}
if (currentURL.indexOf("/teams.html") != -1) {
getTeamInfo();
}
if (currentURL.indexOf("/query.html") != -1) {
queryPageSetup();
}
});
// Listens to content
window.addEventListener("DOMContentLoaded", function() {
// Display/Hide find season range
if (document.getElementById("find-season")) {
document.getElementById("find-season").addEventListener("change", function() {
if (this.checked) {
document.getElementById("find-season-range-block").style.display = "table-row";
}
});
}
if (document.getElementById("find-career")) {
document.getElementById("find-career").addEventListener("change", function() {
if (this.checked) {
document.getElementById("find-season-range-block").style.display = "none";
}
});
}
if (document.getElementById("compare-season")) {
document.getElementById("compare-season").addEventListener("change", function () {
if (this.checked) {
document.getElementById("compare-season-range-block").style.display = "table-row";
}
});
}
if (document.getElementById("compare-career")) {
document.getElementById("compare-career").addEventListener("change", function () {
if (this.checked) {
document.getElementById("compare-season-range-block").style.display = "none";
}
});
}
// Runs on change to checkbox
if (document.getElementById("favorite")) {
document.getElementById("favorite").addEventListener("change", function () {
updateFavoriteQueries(this.checked);
});
}
});
// Website Scriting
// Changes login link depending on user login status
async function loginLink() {
// Users who are logged in
if (sessionStorage.getItem("logged-in") == 'true') {
document.getElementById("login-container").innerHTML = '<a href="account.html">ACCOUNT</a>';
} else {
document.getElementById("login-container").innerHTML = '<a href="login.html">LOGIN</a>';
}
}
// New user signup
async function registerUser() {
username = document.getElementById("login-username").value;
password = document.getElementById("login-password").value;
if (!validUserPass(username, password)) {
return;
}
result = await userSignup(username, password);
document.getElementById("message-box").innerHTML = result;
}
// User login
async function loginUser() {
username = document.getElementById("login-username").value;
password = document.getElementById("login-password").value;
if (!validUserPass(username, password)) {
return;
}
result = await userLogin(username, password);
if (result == "Successful Login"){
window.location.href = "index.html";
} else {
document.getElementById("message-box").innerHTML = result;
}
}
// User logout
function logoutUser() {
sessionStorage.setItem("logged-in", "false");
window.location.href = "index.html";
}
// Get user info
async function getUserInfo() {
let info = await userInfo();
if (info == "No Account Found") {
sessionStorage.setItem("logged-in", "false");
window.location.href = "index.html";
} else {
document.getElementById("display-username").innerHTML = info['result'][0];
document.getElementById("account-created").innerHTML = info['result'][1];
}
}
// Delete user
async function deleteUser() {
if (document.getElementById("delete-account").style.display == "none") {
document.getElementById("delete-account").style.display = "block";
} else {
if (document.getElementById("delete-input").value == "DELETE") {
let result = await userDelete();
if (result == "Account Sucessfully Deleted") {
document.getElementById("account-block").style.display = "none";
document.getElementById("deletion-success").style.display = "block";
sessionStorage.setItem("logged-in", "false");
window.location.href = "index.html";
} else {
document.getElementById("delete-error").innerHTML = result;
}
}
}
}
// Validate username and password
function validUserPass(username, password) {
document.getElementById("input-warning").style.display = "none";
document.getElementById("message-box").innerHTML = "";
if (username.match(/^[A-Za-z0-9]{8,20}$/) == null || password.match(/^[A-Za-z0-9!@#$%&*]{8,20}$/) == null) {
document.getElementById("input-warning").style.display = "block";
return false;
}
return true;
}
// Query page setup
async function queryPageSetup() {
// Get query
let temp = window.location.search;
currentQuery = decodeURIComponent(temp.substring(1));
// Check and update recent
recents = localStorage.getItem("recents");
if (recents != null && recents.includes(currentQuery)) {
updateRecentQueries();
}
// Query display
const queryParams = new URLSearchParams(currentQuery);
subject = queryParams.get('subject');
mode = queryParams.get('mode');
let name1 = queryParams.get('name-1');
let name2 = queryParams.get('name-2');
let careerSeason = queryParams.get('career-season');
let from1 = queryParams.get('from-1');
let to1 = queryParams.get('to-1');
let from2 = queryParams.get('from-2');
let to2 = queryParams.get('to-2');
let seasonType = queryParams.get('season-type');
let timespan1 = null;
let timespan2 = null;
if (from1 != null && to1 != null) {
timespan1 = ((from1 != "None" && to1 != "None") ? (from1 + " to " + to1) : (from1 != "None" && to1 == "None") ? ("Since " + from1) : "All Seasons");
}
if (from2 != null && to2 != null) {
timespan2 = ((from2 != "None" && to2 != "None") ? (from2 + " to " + to2) : (from2 != "None" && to2 == "None") ? ("Since " + from2) : "All Seasons");
}
// Call for player info
await callPlayerInfo();
// Call for team info
await callTeamInfo();
if (subject === "player") {
// Correct names (for potential case change in url)
for (let i = 0; i < playerNames.length; i++) {
if (name1.toLowerCase() == playerNames[i].toLowerCase()) {
name1 = playerNames[i];
}
if (name2 != null && name2.toLowerCase() == playerNames[i].toLowerCase()) {
name2 = playerNames[i];
}
}
// Title
const playerId1 = playerNameToID.get(name1);
const playerId2 = mode == "find" ? null : playerNameToID.get(name2);
const playerImg = (id) => `<img src="https://cdn.nba.com/headshots/nba/latest/1040x760/${id}.png" onerror="this.style.display='none'" style="height:80px; border-radius:50%; margin-right:10px; vertical-align:middle;">`;
document.getElementById("query-title").innerHTML =
mode == "find"
? (playerImg(playerId1) + name1)
: (playerImg(playerId1) + name1 + " vs. " + playerImg(playerId2) + name2);
document.getElementById("query-subtitle").innerHTML =
(careerSeason == "career" ? "Career" : "Season") + " Statistics<br>" +
(seasonType == "all" ? "All" : seasonType == "RegularSeason" ? "Regular" : seasonType == "PostSeason" ? "Post" : seasonType == "AllStarSeason" ? "All-Star" : seasonType == "CollegeSeason" ? "College" : "Showcase") +
(seasonType == "all" ? " Season Types<br>" : " Season<br>") +
(careerSeason == "career" ? "" : (mode == "find" ? timespan1 : (timespan1 + " vs. " + timespan2)));
// Get stats
const stats1 = await callPlayerStats(playerNameToID.get(name1), 0);
const stats2 = mode == "find" ? null : await callPlayerStats(playerNameToID.get(name2), 0);
if (stats1 === "FAIL" || (mode === "compare" && stats2 === "FAIL")) {
document.getElementById("display-stats").innerHTML = "Failed to retrieve data";
return;
}
// Compile and display stats
innerHTML = mode == "find" ? innerHTML = compilePlayerStatistics(name1, null, careerSeason, from1, to1, null, null, seasonType, stats1, null)
: compilePlayerStatistics(name1, name2, careerSeason, from1, to1, from2, to2, seasonType, stats1, stats2);
document.getElementById("display-stats").innerHTML = innerHTML;
// Adjust as needed
manageFooterBuffer(500 - document.getElementById("display-stats").offsetHeight);
} else if (subject === "team") {
// Correct names (for potential case change in url)
for (let i = 0; i < teamNames.length; i++) {
if (name1.toLowerCase() == teamNames[i].toLowerCase()) {
name1 = teamNames[i];
}
if (name2 != null && name2.toLowerCase() == teamNames[i].toLowerCase()) {
name2 = teamNames[i];
}
}
// Title
const teamId1 = teamNameToID.get(name1);
const teamId2 = mode == "find" ? null : teamNameToID.get(name2);
const teamImg = (id) => `<img src="https://cdn.nba.com/logos/nba/${id}/global/L/logo.svg" onerror="this.style.display='none'" style="height:60px; margin-right:10px; vertical-align:middle;">`;
document.getElementById("query-title").innerHTML =
mode == "find"
? (teamImg(teamId1) + name1)
: (teamImg(teamId1) + name1 + " vs. " + teamImg(teamId2) + name2);
document.getElementById("query-subtitle").innerHTML =
(careerSeason == "career" ? "All-Time" : "Season") + " Statistics<br>" +
(careerSeason == "career" ? "" : (mode == "find" ? timespan1 : (timespan1 + " vs. " + timespan2)));
// Get stats
const stats1 = await callTeamStats(teamNameToID.get(name1), 0);
const stats2 = mode == "find" ? null : await callTeamStats(teamNameToID.get(name2), 0);
if (stats1 === "FAIL" || (mode === "compare" && stats2 === "FAIL")) {
document.getElementById("display-stats").innerHTML = "Failed to retrieve data";
return;
}
// Compile stats
innerHTML = mode == "find" ? innerHTML = compileTeamStatistics(name1, null, careerSeason, from1, to1, null, null, stats1, null)
: compileTeamStatistics(name1, name2, careerSeason, from1, to1, from2, to2, stats1, stats2);
document.getElementById("display-stats").innerHTML = innerHTML;
// Adjust as needed
manageFooterBuffer(500 - document.getElementById("display-stats").offsetHeight);
}
// Show/Check favorite if needed
if (sessionStorage.getItem("logged-in") == 'true') {
currentFavorites = await getFavorites();
if (currentFavorites.includes(currentQuery)) {
document.getElementById("favorite").checked = true;
} else {
document.getElementById("favorite").checked = false;
}
document.getElementById("favorite-block").style.display = "block";
} else {
document.getElementById("favorite-block").style.display = "none";
document.getElementById("favorite").checked = false;
}
}
// Updates recents
function updateRecentQueries() {
let recents = localStorage.getItem("recents");
if (recents == null) {
recents = currentQuery;
} else if (!recents.includes(currentQuery)) {
recents = `${currentQuery}|${recents}`;
} else if (recents.includes(currentQuery)) {
recents = recents.substring(0, recents.indexOf(currentQuery)) + recents.substring(recents.indexOf(currentQuery) + currentQuery.length);
while (recents.indexOf('||') != -1) {
recents = recents.replace('||', '|');
}
if (recents.charAt(recents.length - 1) == '|'){
recents = recents.substring(0, recents.length - 1)
}
if (recents.charAt(0) == '|'){
recents = recents.substring(1)
}
if (recents == ""){
recents = currentQuery;
} else {
recents = `${currentQuery}|${recents}`;
}
}
while (recents.split('|').length - 1 >= 10) {
recents = recents.substring(0, recents.lastIndexOf('|'));
}
localStorage.setItem("recents", recents);
}
// Clears recents
function clearRecentQueries() {
localStorage.removeItem("recents");
loadRecentQueries();
}
// Load recents
function loadRecentQueries() {
if (localStorage.getItem("recents") == null) {
document.getElementById("recent-queries").innerHTML = "No recent queries to show.";
} else {
let recents = localStorage.getItem("recents") + '|';
let innerHTML = compileQueriesTable(recents, "clearRecentQueries", "Recents");
document.getElementById("recent-queries").innerHTML = innerHTML;
}
}
// Updates favorite
async function updateFavoriteQueries(makeFavorite) {
let favorites = currentFavorites;
if (makeFavorite) {
if (favorites == "NONE") {
favorites = currentQuery;
} else if (!favorites.includes(currentQuery)) {
favorites = `${currentQuery}|${favorites}`;
}
} else {
if (favorites.includes(currentQuery)) {
favorites = favorites.substring(0, favorites.indexOf(currentQuery)) + favorites.substring(favorites.indexOf(currentQuery) + currentQuery.length);
}
while (favorites.indexOf('||') != -1) {
favorites = favorites.replace('||', '|');
}
if (favorites.charAt(favorites.length - 1) == '|'){
favorites = favorites.substring(0, favorites.length - 1)
}
if (favorites.charAt(0) == '|'){
favorites = favorites.substring(1)
}
if (favorites == ""){
favorites = "NONE";
}
}
// Send updated favorites
await updateFavorites(favorites);
// Set new favorite to current
currentFavorites = await getFavorites();
}
// Clears favorites
async function clearFavoriteQueries() {
await updateFavorites('NONE');
loadFavoriteQueries();
}
// Load favorites
async function loadFavoriteQueries() {
if (sessionStorage.getItem("logged-in") == null || sessionStorage.getItem("logged-in") == 'false') {
document.getElementById("favorite-queries").innerHTML = "Need to make an account or sign in to show favorites.";
} else {
// Get favorites
let favorites = await getFavorites();
if (favorites == 'NONE') {
document.getElementById("favorite-queries").innerHTML = "No favorite queries to show.";
} else {
favorites = favorites + "|";
let innerHTML = compileQueriesTable(favorites, "clearFavoriteQueries", "Favorites");
document.getElementById("favorite-queries").innerHTML = innerHTML;
}
}
}
// Compile queries table
function compileQueriesTable(queryList, clearMethodName, queryType) {
innerHTML = '<table>';
while (queryList.indexOf('|') != -1) {
let query = queryList.substring(0, queryList.indexOf('|'));
const queryParams = new URLSearchParams(query);
let from1 = queryParams.get('from-1');
let to1 = queryParams.get('to-1');
let from2 = queryParams.get('from-2');
let to2 = queryParams.get('to-2');
let timespan1 = null;
let timespan2 = null;
if (from1 != null && to1 != null) {
timespan1 = ((from1 != "None" && to1 != "None") ? (from1 + " to " + to1) : (from1 != "None" && to1 == "None") ? ("Since " + from1) : "All Seasons");
}
if (from2 != null && to2 != null) {
timespan2 = ((from2 != "None" && to2 != "None") ? (from2 + " to " + to2) : (from2 != "None" && to2 == "None") ? ("Since " + from2) : "All Seasons");
}
innerHTML += `<tr><td id="query-link"><a href="query.html?${query}">`;
if (queryParams.get('mode') == 'find') {
innerHTML += `${queryParams.get('name-1')}`;
} else if (queryParams.get('mode') == 'compare') {
innerHTML += `${queryParams.get('name-1')} vs. ${queryParams.get('name-2')}`;
}
innerHTML += '<div class="little-br"></div>';
if (queryParams.get('subject') == 'player') {
innerHTML += ((queryParams.get('career-season') == "career" ? "Career" : "Season") + " Statistics");
let type = ((queryParams.get('season-type') == "all" ? "All" : queryParams.get('season-type') == "RegularSeason" ? "Regular" : queryParams.get('season-type') == "PostSeason" ? "Post" : queryParams.get('season-type') == "AllStarSeason" ? "All-Star" : queryParams.get('season-type') == "CollegeSeason" ? "College" : "Showcase") +
(queryParams.get('season-type') == "all" ? " Season Types" : " Season"));
if (queryParams.get('career-season') == "season") {
innerHTML += (" | " + type);
} else {
innerHTML += (" | " + type);
}
} else if (queryParams.get('subject') == 'team') {
innerHTML += ((queryParams.get('career-season') == "career" ? "All-Time" : "Season") + " Statistics");
}
innerHTML += '<div class="little-br"></div>';
if (queryParams.get('career-season') == "season") {
innerHTML += ((queryParams.get('mode') == "find" ? timespan1 : (timespan1 + " vs. " + timespan2)));
}
innerHTML += '</a></td></tr>';
queryList = queryList.substring(queryList.indexOf('|') + 1);
}
innerHTML += `</table><br><button onclick="${clearMethodName}()">Clear ${queryType}</button>`;
return innerHTML;
}
// Get player info
async function getPlayerInfo() {
// Call for player info
await callPlayerInfo();
// Call for team info
await callTeamInfo();
// Make player input list and allow search
let playerInputList = "";
for (let i = 0; i < playerNames.length; i++) {
playerInputList += (`<option value="${playerNames[i]}"></option>`);
}
document.getElementById("waiting-message").style.display = "none";
document.getElementById("find-player-list").innerHTML = playerInputList;
document.getElementById("compare-player-list-1").innerHTML = playerInputList;
document.getElementById("compare-player-list-2").innerHTML = playerInputList;
mode = "compare";
subject = "player";
switchStatMode();
}
// Get stats for player
async function getPlayerStats() {
// Setup
manageFooterBuffer(500);
document.getElementById("display-player-stats").innerHTML = "Loading...";
document.getElementById("favorite-block").style.display = "none";
let innerHTML = "";
// Get inputs
let inputs = getInput(mode == "find" ? 1 : 2, true, mode == "find" ? 1 : 2, true);
if (inputs[0] !== "") {
document.getElementById("display-player-stats").innerHTML = ("Please fix the following errors:" + inputs[0]);
return;
}
// Gets stats and catch fails
const stats1 = await callPlayerStats(playerNameToID.get(inputs[1][0]), 0);
const stats2 = mode == "find" ? null : await callPlayerStats(playerNameToID.get(inputs[1][1]), 0);
if (stats1 === "FAIL" || (mode === "compare" && stats2 === "FAIL")) {
document.getElementById("display-player-stats").innerHTML = "Failed to retrieve data";
return;
}
// Compile and display stats
innerHTML = mode == "find" ? innerHTML = compilePlayerStatistics(inputs[1][0], null, inputs[2], inputs[3][0], inputs[4][0], null, null, inputs[5], stats1, null)
: compilePlayerStatistics(inputs[1][0], inputs[1][1], inputs[2], inputs[3][0], inputs[4][0], inputs[3][1], inputs[4][1], inputs[5], stats1, stats2);
// Player headshot image(s)
const pid1 = playerNameToID.get(inputs[1][0]);
const pid2 = mode == "find" ? null : playerNameToID.get(inputs[1][1]);
const playerImg = (id, name) => `<img src="https://cdn.nba.com/headshots/nba/latest/1040x760/${id}.png" alt="${name}" onerror="this.style.display='none'" style="height:80px; border-radius:50%; margin-right:8px; vertical-align:middle;">`;
const imageHTML = mode == "find"
? `<div style="margin-bottom:10px;">${playerImg(pid1, inputs[1][0])}<strong>${inputs[1][0]}</strong></div>`
: `<div style="margin-bottom:10px;">${playerImg(pid1, inputs[1][0])}<strong>${inputs[1][0]}</strong> vs. ${playerImg(pid2, inputs[1][1])}<strong>${inputs[1][1]}</strong></div>`;
document.getElementById("display-player-stats").innerHTML = imageHTML + innerHTML;
// Adjust as needed
manageFooterBuffer(500 - document.getElementById("display-player-stats").offsetHeight);
// Set current query
currentQuery = `subject=player&mode=${mode}&name-1=${inputs[1][0]}&name-2=${mode == "find" ? "null" : inputs[1][1]}&career-season=${inputs[2]}&from-1=${inputs[3][0]}&to-1=${inputs[4][0]}&from-2=${inputs[3][1]}&to-2=${inputs[4][1]}&season-type=${inputs[5]}`;
// Add query to recents
updateRecentQueries();
// Show/Check favorite if needed
if (sessionStorage.getItem("logged-in") == 'true') {
currentFavorites = await getFavorites();
if (currentFavorites.includes(currentQuery)){
document.getElementById("favorite").checked = true;
} else {
document.getElementById("favorite").checked = false;
}
document.getElementById("favorite-block").style.display = "block";
} else {
document.getElementById("favorite-block").style.display = "none";
document.getElementById("favorite").checked = false;
}
}
// Compile player statistics for display
function compilePlayerStatistics(playerName1, playerName2, careerSeason, from1, to1, from2, to2, seasonType, stats1, stats2) {
// Variables for easier use
let textHTML = ["", ""];
let seasonHTML = "";
let playerName = [playerName1, playerName2];
let stats = [stats1, stats2];
let from = [from1, from2];
let to = [to1, to2];
// Find career
if (careerSeason === "career") {
for (let s = 0; s < (mode == "find" ? 1 : 2); s++) {
let categories = [];
for (let i = 0; i < stats[s].resultSets.length; i++) {
let statSubset = stats[s].resultSets[i];
if (statSubset.name.indexOf("CareerTotals") != -1 && statSubset.rowSet.length != 0 && (seasonType === "all" || statSubset.name.indexOf(seasonType) != -1)) {
const fgPCT = (statSubset.rowSet[0][8] * 100).toFixed(2);
const fg3PCT = (statSubset.rowSet[0][11] * 100).toFixed(2);
const ftPCT = (statSubset.rowSet[0][14] * 100).toFixed(2);
const cards = [
{ label: "Games Played", value: statSubset.rowSet[0][3] },
{ label: "Games Started", value: statSubset.rowSet[0][4] },
{ label: "Minutes Played", value: statSubset.rowSet[0][5] },
{ label: "FG Made", value: statSubset.rowSet[0][6] },
{ label: "FG Attempted", value: statSubset.rowSet[0][7] },
{ label: "FG%", value: fgPCT + "%" },
{ label: "3PT Made", value: statSubset.rowSet[0][9] },
{ label: "3PT Attempted", value: statSubset.rowSet[0][10] },
{ label: "3PT%", value: fg3PCT + "%" },
{ label: "FT Made", value: statSubset.rowSet[0][12] },
{ label: "FT Attempted", value: statSubset.rowSet[0][13] },
{ label: "FT%", value: ftPCT + "%" },
{ label: "Offensive Reb", value: statSubset.rowSet[0][15] },
{ label: "Defensive Reb", value: statSubset.rowSet[0][16] },
{ label: "Total Rebounds", value: statSubset.rowSet[0][17] },
{ label: "Assists", value: statSubset.rowSet[0][18] },
{ label: "Steals", value: statSubset.rowSet[0][19] },
{ label: "Blocks", value: statSubset.rowSet[0][20] },
{ label: "Turnovers", value: statSubset.rowSet[0][21] },
{ label: "Personal Fouls", value: statSubset.rowSet[0][22] },
{ label: "Points Scored", value: statSubset.rowSet[0][23] },
];
categories.push({ name: playerHeaderMap.get(statSubset.name), cards });
}
}
if (categories.length > 0) {
const uid = `player-tabs-${s}`;
let tabBtns = `<div class="stat-tabs" id="${uid}">`;
categories.forEach((cat, idx) => {
tabBtns += `<button class="stat-tab${idx === 0 ? ' active' : ''}" onclick="switchCareerTab('${uid}', ${idx})">${cat.name}</button>`;
});
tabBtns += `</div>`;
let panels = `<div class="stat-panels">`;
categories.forEach((cat, idx) => {
panels += `<div class="stat-panel${idx === 0 ? ' active' : ''}" data-tab="${uid}-${idx}">`;
panels += `<div class="stat-cards">`;
cat.cards.forEach(card => {
panels += `<div class="stat-card"><span class="stat-card-label">${card.label}</span><span class="stat-card-value">${card.value}</span></div>`;
});
panels += `</div></div>`;
});
panels += `</div>`;
textHTML[s] = tabBtns + panels;
}
}
// Find season
} else if (careerSeason === "season") {
const teamNum = mode == "find" ? 1 : 2;
let seasonTypes = [];
let seasonStats = [[], []];
for (let i = 0; i < stats[0].resultSets.length; i++) {
let count = 0;
let buffer = [[], []];
let type = "";
for (let t = 0; t < teamNum; t++) {
let statSubset = stats[t].resultSets[i];
if (statSubset.name.indexOf("SeasonTotals") != -1 && statSubset.rowSet.length != 0 && (seasonType == "all" || statSubset.name.indexOf(seasonType) != -1)
){
type = statSubset.name;
let seasonData = statSubset.rowSet;
for (let s = 0; s < seasonData.length; s++) {
if ((from[t] <= parseInt(seasonData[s][1].substring(0, 4)) && (to[t] === "None" || to[t] >= parseInt(seasonData[s][1].substring(0, 4))))
|| (from[t] === "None" && to[t] === "None")
) {
buffer[t].push(seasonData[s]);
}
}
count++;
}
}
if (count > 0) {
seasonTypes.push(type);
seasonStats[0].push(buffer[0]);
seasonStats[1].push(buffer[1]);
}
}
const statIndexes = [[1, 4, 5, 6, 7, 8], [1, 9, 11, 12, 14, 15, 17], [1, 18, 20, 21, 22, 23, 24, 25, 26], [1, 20, 21, 22, 23, 24, 25, 26]];
const statWidths = [[64, 42, 32, 20, 20, 26], [64, 50, 32, 60, 40, 48, 30], [64, 62, 28, 26, 24, 26, 28, 20, 26], [64, 32, 30, 30, 30, 30, 40, 32]];
const statNames = [["SEASON", "TEAM", "AGE", "GP", "GS", "MIN"], ["SEASON", "FG-M:A", "FG%", "FG3-M:A", "FG3%", "FT-M:A", "FT%"], ["SEASON", "REB-O:D", "REB", "AST", "STL", "BLK", "TOV", "PF", "PTS"], ["SEASON", "RPG", "APG", "SPG", "BPG", "TPG", "PFPG", "PPG"]];
for (let sType = 0; sType < seasonTypes.length; sType++) {
let typeData = [seasonStats[0][sType], seasonStats[1][sType]];
let seasonCount = [typeData[0].length, typeData[1].length];
let htmlTables = [];
for (let ct = 0; ct < 4; ct++) {
let tempHTML = '<table class="season-table"><tr>';
let statIndex = statIndexes[ct];
let statWidth = statWidths[ct];
let statName = statNames[ct];
let latestSeason = [null, null];
for (let n = 0; n < statName.length; n++) {
tempHTML += `<td>${statName[n]}</td>`;
}
tempHTML += '</tr><tr>';
for (let s = 0; s < statIndex.length; s++) {
tempHTML += '<td><table>';
for (let i = 0; i < (seasonCount[0] > seasonCount[1] ? seasonCount[0] : seasonCount[1]); i++) {
tempHTML += '<tr>';
for (let t = 0; t < teamNum; t++) {
let data = " - ";
if (i < seasonCount[t]) {
data = typeData[t][i][statIndex[s]] != null ? typeData[t][i][statIndex[s]] : " - ";
if (statName[s] == "SEASON") {
data = data == latestSeason[t] ? "^" : data;
latestSeason[t] = typeData[t][i][statIndex[s]];
}
if (statName[s] == "TEAM") {
data = data == "TOT" ? "Total" : data;
}
if (statName[s] == "FG-M:A" || statName[s] == "FG3-M:A" || statName[s] == "FT-M:A" || statName[s] == "REB-O:D") {
data = `${typeData[t][i][statIndex[s]] != null ? typeData[t][i][statIndex[s]] : " - "}:${typeData[t][i][statIndex[s] + 1] != null ? typeData[t][i][statIndex[s] + 1] : " - "}`;
}
if (statName[s] == "FG%" || statName[s] == "FG3%" || statName[s] == "FT%") {
data = (typeData[t][i][statIndex[s]] * 100).toFixed(1) + "%";
}
if (statName[s] == "RPG" || statName[s] == "APG" || statName[s] == "PFPG" || statName[s] == "SPG" || statName[s] == "TPG" || statName[s] == "BPG" || statName[s] == "PPG") {
data = (typeData[t][i][statIndex[s]] != null ? (typeData[t][i][statIndex[s]] / typeData[t][i][6]).toFixed(1) : " - ");
}
}
tempHTML += `<td class=${t == 0 ? '"season-color-1"' : '"season-color-2"'} style="min-width: ${statWidth[s] / teamNum}px">${data}</td>`;
}
tempHTML += '</tr>';
}
tempHTML += '</table></td>';
}
tempHTML += '</tr></table>';
htmlTables.push([tempHTML]);
}
let seasonType = seasonTypes[sType];
let seasonTableName = playerSeasonTypeToSeasonTableName[seasonType];
numSeasonTables[seasonTableName] = 4;
currentSeasonTable[seasonTableName] = 0;
seasonTables[seasonTableName] = htmlTables;
seasonHTML += `<h3>${playerHeaderMap.get(seasonType)}</h3>`;
seasonHTML += `<table class="stat-table"><tr><td class="season-arrow"><button onclick="seasonTablePrevious('${seasonTableName}')"><strong><</strong></button></td>`;
seasonHTML += mode === "find" ?
`<td id="${seasonTableNameToID[seasonTableName]}">${seasonTables[seasonTableName][0]}</td>`
:
`<td><table><tr><td class="season-color-1"> </td><td class="season-key"> ${playerName1}</td></tr><tr><td class="season-color-2"> </td><td class="season-key"> ${playerName2}</td></tr></table></td>`;
seasonHTML += `<td class="season-arrow"><button onclick="seasonTableNext('${seasonTableName}')"><strong>></strong></button></td>`
seasonHTML += mode === "find" ?
"</tr></table>" : `</tr><tr><td></td><td id="${seasonTableNameToID[seasonTableName]}">${seasonTables[seasonTableName][0]}</td><td></td></tr></table>`;
}
}
// Formatting and returning
if (careerSeason === "career") {
for (let s = 0; s < (mode == "find" ? 1 : 2); s++) {
if (textHTML[s] === ""){
textHTML[s] = `<h2>${playerName[s]}</h2>No Data To Show`;
} else {
textHTML[s] = `<h2>${playerName[s]}</h2>` + textHTML[s];
}
}
} else if (careerSeason === "season" && seasonHTML == "") {
seasonHTML = "<h2>No Data To Show</h2>";
}
let innerHTML = null;
if (careerSeason === "season") {
innerHTML = `<table class="stat-table"><tr><td>${seasonHTML}</td></tr></table>`;
}
if (mode === "find" && careerSeason === "career") {
innerHTML = `<table class="stat-table"><tr><td>${textHTML[0]}</td></tr></table>`;
} else if (mode === "compare" && careerSeason === "career") {
innerHTML = `<table class="stat-table"><tr>
<td>${textHTML[0]}</td>
<td>${textHTML[1]}</td>
</tr></table>`;
}
return innerHTML;
}
// Get team info
async function getTeamInfo() {
// Call for team info
await callTeamInfo();
// Make player input list and allow search
let teamInputList = "";
for (let i = 0; i < teamNames.length; i++) {
teamInputList += (`<option value="${teamNames[i]}"></option>`);
}
document.getElementById("waiting-message").style.display = "none";
document.getElementById("find-team-list").innerHTML = teamInputList;
document.getElementById("compare-team-list-1").innerHTML = teamInputList;
document.getElementById("compare-team-list-2").innerHTML = teamInputList;
mode = "compare";
subject = "team";
switchStatMode();
}
// Get stats for team
async function getTeamStats() {
// Setup
manageFooterBuffer(500);
document.getElementById("display-team-stats").innerHTML = "Loading...";
document.getElementById("favorite-block").style.display = "none";
let innerHTML = "";
// Get inputs
let inputs = getInput(mode == "find" ? 1 : 2, true, mode == "find" ? 1 : 2, false);
if (inputs[0] !== "") {
document.getElementById("display-team-stats").innerHTML = ("Please fix the following errors:" + inputs[0]);
return;
}
// Gets stats and catch fails
const stats1 = await callTeamStats(teamNameToID.get(inputs[1][0]), 0);
const stats2 = mode == "find" ? null : await callTeamStats(teamNameToID.get(inputs[1][1]), 0);
if (stats1 === "FAIL" || (mode === "compare" && stats2 === "FAIL")) {
document.getElementById("display-team-stats").innerHTML = "Failed to retrieve data";
return;
}
// Compile stats
innerHTML = mode == "find" ? innerHTML = compileTeamStatistics(inputs[1][0], null, inputs[2], inputs[3][0], inputs[4][0], null, null, stats1, null)
: compileTeamStatistics(inputs[1][0], inputs[1][1], inputs[2], inputs[3][0], inputs[4][0], inputs[3][1], inputs[4][1], stats1, stats2);
// Team logo image(s)
const tid1 = teamNameToID.get(inputs[1][0]);
const tid2 = mode == "find" ? null : teamNameToID.get(inputs[1][1]);
const teamImg = (id, name) => `<img src="https://cdn.nba.com/logos/nba/${id}/global/L/logo.svg" alt="${name}" onerror="this.style.display='none'" style="height:60px; margin-right:8px; vertical-align:middle;">`;
const teamImageHTML = mode == "find"
? `<div style="margin-bottom:10px;">${teamImg(tid1, inputs[1][0])}<strong>${inputs[1][0]}</strong></div>`
: `<div style="margin-bottom:10px;">${teamImg(tid1, inputs[1][0])}<strong>${inputs[1][0]}</strong> vs. ${teamImg(tid2, inputs[1][1])}<strong>${inputs[1][1]}</strong></div>`;
document.getElementById("display-team-stats").innerHTML = teamImageHTML + innerHTML;
// Adjust as needed
manageFooterBuffer(500 - document.getElementById("display-team-stats").offsetHeight);
// Set current query
currentQuery = `subject=team&mode=${mode}&name-1=${inputs[1][0]}&name-2=${mode == "find" ? "null" : inputs[1][1]}&career-season=${inputs[2]}&from-1=${inputs[3][0]}&to-1=${inputs[4][0]}&from-2=${inputs[3][1]}&to-2=${inputs[4][1]}`;
// Add query to recents
updateRecentQueries();
// Show/Check favorite if needed
if (sessionStorage.getItem("logged-in") == 'true') {
currentFavorites = await getFavorites();
if (currentFavorites.includes(currentQuery)){
document.getElementById("favorite").checked = true;
} else {
document.getElementById("favorite").checked = false;
}
document.getElementById("favorite-block").style.display = "block";
} else {
document.getElementById("favorite-block").style.display = "none";
document.getElementById("favorite").checked = false;
}
}
// Compile team statistics for display
function compileTeamStatistics(teamName1, teamName2, careerSeason, from1, to1, from2, to2, stats1, stats2) {
// Variables for easier use
let textHTML = ["", ""];
let tablesHTML = [];
let teamName = [teamName1, teamName2];
let stats = [stats1, stats2];
let from = [from1, from2];
let to = [to1, to2];
// Get overall stats for time period
let allTimeData = [[], []];
let seasons = [[], []];
for (let s = 0; s < (mode == "find" ? 1 : 2); s++) {
for (let i = 0; i < 20; i++) {
allTimeData[s].push(0);
}
for (let i = 0; i < stats[s].resultSets[0].rowSet.length; i++) {
let seasonData = stats[s].resultSets[0].rowSet[i];
if (!(careerSeason === "career" || (from[s] === "None" && to[s] === "None")
|| ((from[s] <= parseInt(seasonData[3].substring(0, 4)) && (to[s] === "None" || to[s] >= parseInt(seasonData[3].substring(0, 4)))))
)) continue;
if (careerSeason === "season") {
seasons[s].push(seasonData);
}
if (seasonData[14] == "LEAGUE CHAMPION") {
allTimeData[s][0] += 1;
allTimeData[s][1] += 1;
} else if (seasonData[14] == "FINALS APPEARANCE") {
allTimeData[s][1] += 1;
}
allTimeData[s][2] += seasonData[4]; // Games Played
allTimeData[s][3] += seasonData[5]; // Games Won
allTimeData[s][4] += seasonData[6]; // Games Lost
allTimeData[s][5] += seasonData[15]; // Field Goals Made
allTimeData[s][6] += seasonData[16]; // Field Goals Attempted
allTimeData[s][7] += seasonData[18]; // 3-Pt Goals Made
allTimeData[s][8] += seasonData[19]; // 3-Pt Goals Attempted
allTimeData[s][9] += seasonData[21]; // Free throws made
allTimeData[s][10] += seasonData[22]; // Free throws attempted
allTimeData[s][11] += seasonData[24]; // Offensive rebounds
allTimeData[s][12] += seasonData[25]; // Defensive rebounds
allTimeData[s][13] += seasonData[26]; // Total rebounds
allTimeData[s][14] += seasonData[27]; // Assists
allTimeData[s][15] += seasonData[28]; // Personal fouls
allTimeData[s][16] += seasonData[29]; // Steals
allTimeData[s][17] += seasonData[30]; // Turnovers
allTimeData[s][18] += seasonData[31]; // Blocks
allTimeData[s][19] += seasonData[32]; // Points Scored
}
}
// All-time stats
if (careerSeason === "career") {
for (let s = 0; s < (mode == "find" ? 1 : 2); s++) {
const winPCT = ((allTimeData[s][3] / allTimeData[s][2]) * 100).toFixed(2);
const cards = [
{ label: "League Champions", value: allTimeData[s][0] },
{ label: "Finals Appearances", value: allTimeData[s][1] },
{ label: "Win %", value: winPCT + "%" },
{ label: "Games Played", value: allTimeData[s][2] },
{ label: "Games Won", value: allTimeData[s][3] },
{ label: "Games Lost", value: allTimeData[s][4] },
{ label: "FG Made", value: allTimeData[s][5] },
{ label: "FG Attempted", value: allTimeData[s][6] },
{ label: "3PT Made", value: allTimeData[s][7] },
{ label: "3PT Attempted", value: allTimeData[s][8] },
{ label: "FT Made", value: allTimeData[s][9] },
{ label: "FT Attempted", value: allTimeData[s][10] },
{ label: "Offensive Reb", value: allTimeData[s][11] },
{ label: "Defensive Reb", value: allTimeData[s][12] },
{ label: "Total Rebounds", value: allTimeData[s][13] },
{ label: "Assists", value: allTimeData[s][14] },
{ label: "Personal Fouls", value: allTimeData[s][15] },
{ label: "Steals", value: allTimeData[s][16] },
{ label: "Turnovers", value: allTimeData[s][17] },
{ label: "Blocks", value: allTimeData[s][18] },
{ label: "Points Scored", value: allTimeData[s][19] },
];
let cardsHTML = '<div class="stat-cards">';
cards.forEach(card => {
cardsHTML += `<div class="stat-card"><span class="stat-card-label">${card.label}</span><span class="stat-card-value">${card.value}</span></div>`;
});
cardsHTML += '</div>';
textHTML[s] = cardsHTML;
}
// Season stats