-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
2272 lines (1980 loc) · 99 KB
/
app.js
File metadata and controls
2272 lines (1980 loc) · 99 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
// Import Firebase modules
import { database, auth } from './firebase-config.js';
import { ref, set, get, onValue } from 'firebase/database';
import { signInAnonymously } from 'firebase/auth';
import Chart from 'chart.js/auto';
import glossaryData from './public/glossary.json';
import rubricData from './public/rubric.json';
import papersData from './public/papers.json';
// Application State
let firebaseUid = null; // Set after anonymous auth on init
let currentPage = 0;
let papers = [];
let glossary = [];
let rubric = [];
let sessionId = null;
let userRatings = {}; // Personal ratings
let userPredictions = {}; // Predicted average ratings
let paperScores = {}; // Individual scores per paper (for restoring after refresh)
let totalScore = 0;
let userName = '';
let hasUsedBackButton = false; // Track if user has used their one-time back navigation
let celebratedPapers = new Set(); // Track papers where 90%+ was achieved
let pageDisplayTimestamps = {}; // Track when each paper page is displayed for response time calculation
let isViewingResults = false; // Flag to indicate viewing someone else's results (read-only mode)
// Criterion token allocation (20 tokens distributed across 6 criteria)
let criterionTokens = { title: 0, access: 0, source: 0, theory: 0, methods: 0, conclusion: 0 };
const CRITERIA = [
{ key: 'title', label: '📰 Title' },
{ key: 'access', label: '📚 Access' },
{ key: 'source', label: '🏛️ Source' },
{ key: 'theory', label: '🔬 Theory' },
{ key: 'methods', label: '📊 Methods & Data' },
{ key: 'conclusion', label: '📝 Conclusion' }
];
// Session timeout configuration — inactivity-based disconnect
const INACTIVITY_TIMEOUT = 30 * 60 * 1000; // Disconnect after 30 minutes of inactivity
const INACTIVITY_WARNING = 5 * 60 * 1000; // Warn when 5 minutes of inactivity remain
const ABSOLUTE_MAX_DURATION = 120 * 60 * 1000; // Hard cap: disconnect after 2 hours regardless
const ACTIVITY_RESET_DEBOUNCE = 5000; // Avoid resetting timers too frequently
const ACTIVITY_EVENTS = ['click', 'keydown', 'touchstart', 'scroll', 'mousemove'];
let lastActivityTime = null;
let sessionTimeoutId = null;
let warningTimeoutId = null;
let absoluteTimeoutId = null;
let inactivityWarningShown = false;
let firebaseListeners = []; // Track all Firebase listeners for cleanup
// Seed scores (vetted expert ratings) - weighted as 100 participants each
// Distribution: ~7 papers per quality score (1-7) for balanced assessment
const seedScores = {
// Score 1 (Predatory/Pseudoscience) - 8 papers
'STUDY-1': 1, // Chocolate boosts math scores - predatory journal, tiny sample
'STUDY-4': 1, // Herbal tea prevents Alzheimer's - predatory journal, folk medicine
'STUDY-29': 1, // Vaccine injury conspiracy - misinterprets data, dangerous
'STUDY-32': 1, // 5G causes cancer/autism - physics-defying conspiracy
'STUDY-34': 1, // Alkaline foods - pure pseudoscience, no research
'STUDY-40': 1, // Chemtrails mind control - pure fabrication
'STUDY-46': 1, // Detox tea - fraudulent marketing, no study
'STUDY-48': 1, // Magnet arthritis - pseudoscience, product website, testimonials only
// Score 2 (Marketing/Severe Conflicts) - 9 papers
'STUDY-7': 2, // AI hiring tool - corporate white paper, biased data
'STUDY-11': 2, // Tall men as CEOs - preprint, evolutionary psych overreach
'STUDY-17': 2, // Remote work - corporate marketing report, major conflict of interest
'STUDY-20': 2, // Bitcoin stabilizes economy - non-peer-reviewed, crypto advocacy
'STUDY-28': 2, // Energy drink performance - corporate funded, cherry-picked
'STUDY-36': 2, // Probiotic yogurt - company press release, vague claims
'STUDY-38': 2, // GMO safety panel - industry bias, cherry-picked literature
'STUDY-42': 2, // Testosterone therapy - clinic advertising, profit motive
'STUDY-44': 2, // Organic diet - organic trade association, industry-funded, no controls
// Score 3 (Weak but Legitimate Attempt) - 5 papers
'STUDY-9': 3, // Violent video games - small sample, not preregistered
'STUDY-12': 3, // Lavender insomnia - small trial, weak controls, aromatherapy basis
'STUDY-15': 3, // Classical music raises IQ - Mozart effect rehash, tiny effect
'STUDY-23': 3, // Peptide cream - company trial, self-assessment, no blinding
'STUDY-25': 3, // Crystal water - alternative medicine trial, weak methodology
// Score 4 (Decent but Limited) - 5 papers
'STUDY-6': 4, // Instagram anxiety - large survey but correlation not causation
'STUDY-18': 4, // Gut bacteria depression - good mouse study, overblown conclusions
'STUDY-26': 4, // Alzheimer's drug - high dropout rate, pharma funded
'STUDY-30': 4, // Mediterranean diet - good observational study, self-reported
'STUDY-35': 4, // Green space mental health - correlation only, income confounders
// Score 5 (Good Methods with Limitations) - 8 papers
'STUDY-3': 5, // Screens delay sleep - good theory, large sample, self-reported
'STUDY-5': 5, // Pesticide bees - field trial, preregistered, specific claims
'STUDY-13': 5, // Urban foxes diet - rigorous methods, respected journal
'STUDY-14': 5, // Mars soil crops - rigorous methods, open data, cautious conclusion
'STUDY-16': 5, // EV battery cold - solid physics, government research
'STUDY-21': 5, // Vertical farms - life-cycle assessment, trade-offs acknowledged
'STUDY-27': 5, // Income inequality health - top-tier journal, pre-registered, public data
'STUDY-45': 5, // Sitting breaks - randomized crossover, short-term only
// Score 6 (Rigorous, Top Journals) - 9 papers
'STUDY-2': 6, // Aircraft alloy - rigorous testing, patent data withheld, cautious conclusion
'STUDY-8': 6, // Solar cells - independent replication, top journal, but key data withheld pending patent
'STUDY-10': 6, // Microplastics blood - novel method, contamination controls, alarming but careful
'STUDY-22': 6, // Smartphone sleep tracking - objective measures, preregistered, top journal
'STUDY-31': 6, // Reading to infants - cluster RCT, blinded assessment, open data
'STUDY-33': 6, // AI cancer detection - external validation, appropriately cautious
'STUDY-37': 6, // Psilocybin therapy - double-blind RCT, standardized protocol, conservative
'STUDY-41': 6, // PrEP HIV prevention - prospective cohort, emphasizes adherence
'STUDY-43': 6, // CRISPR sickle cell - N=15 single-arm, off-target edits detected, overclaiming title
// Score 7 (Gold Standard) - 4 papers
'STUDY-19': 7, // Climate reconstruction - thousands of datasets, rigorous stats, NOAA archived
'STUDY-24': 7, // Mindfulness pain - Cochrane systematic review, meta-analysis, gold standard
'STUDY-39': 7, // Sea level rise - multi-model ensemble, uncertainty quantified, archived
'STUDY-47': 7 // Participatory budgeting - mixed methods, preregistered, nuanced conclusions
};
const seedWeight = 100; // Each seed score counts as 100 participants
function extractValidRatings(ratingsData) {
if (!ratingsData || typeof ratingsData !== 'object') {
return [];
}
return Object.values(ratingsData)
.map(entry => {
if (typeof entry === 'number') return entry;
if (entry && typeof entry === 'object') return entry.rating;
return null;
})
.filter(rating => Number.isFinite(rating) && rating >= 1 && rating <= 7);
}
// Helper function to get performance icon based on percentage
function getPerformanceIcon(percentage) {
if (percentage >= 90) return '🏆'; // Trophy/Cup
if (percentage >= 75) return '🥇'; // Gold medal
if (percentage >= 60) return '🥈'; // Silver medal
return '🥉'; // Bronze medal
}
// Setup animation for a single logo
function setupLogoAnimation(logoId) {
const logo = document.getElementById(logoId);
if (!logo) return;
let isAnimating = false;
let hoverTimer = null;
// Define drop types
const dropTypes = ['droplet', 'droplet-star', 'droplet-heart', 'droplet-sparkle', 'droplet-bubble'];
// Trigger animation after 900ms of hover (desktop)
logo.addEventListener('mouseenter', () => {
if (isAnimating) return;
hoverTimer = setTimeout(() => {
startAnimation(logo);
}, 900);
});
logo.addEventListener('mouseleave', () => {
if (hoverTimer) {
clearTimeout(hoverTimer);
hoverTimer = null;
}
});
// Trigger animation on click (desktop)
logo.addEventListener('click', (e) => {
if (isAnimating) return;
e.preventDefault();
if (hoverTimer) {
clearTimeout(hoverTimer);
hoverTimer = null;
}
startAnimation(logo);
});
// Trigger animation immediately on touch/tap (mobile)
logo.addEventListener('touchstart', (e) => {
if (isAnimating) return;
e.preventDefault(); // Prevent double firing with mouse events
startAnimation(logo);
}, { passive: false });
// Listen for celebration event (triggered when score >= 90%)
logo.addEventListener('celebrate', () => {
startAnimation(logo, 'celebration');
});
// Periodic shake increase every 8 seconds for 2 seconds (for main logo and navbar logo)
if (logoId === 'logo-icon' || logoId === 'navbar-logo') {
setInterval(() => {
if (!isAnimating) {
logo.classList.add('shake-intense');
setTimeout(() => {
logo.classList.remove('shake-intense');
}, 2000);
}
}, 8000);
}
function startAnimation(logoElement, dropType = 'mixed') {
if (isAnimating && dropType !== 'celebration') return; // Allow celebration to override
isAnimating = true;
// Define drop types
const dropTypes = ['droplet', 'droplet-star', 'droplet-heart', 'droplet-sparkle', 'droplet-bubble'];
// Check if this is a celebration animation
const isCelebration = dropType === 'celebration';
// Add flip animation with accelerated shake to logo
logoElement.classList.add('flipping');
// Store original src and swap to inverted version when upside down
const originalSrc = logoElement.src;
const invertedSrc = originalSrc.replace('unlock-lab-icon.svg', 'unlock-lab-icon-inverted.svg');
// Swap to inverted image when logo is upside down (at 15% of 4s animation = 600ms)
setTimeout(() => {
logoElement.src = invertedSrc;
}, 600);
// Refill step: drops rain from top into logo (starts at 2500ms, before final rotation)
// Skip refill for celebration animations
if (!isCelebration) {
setTimeout(() => {
const refillRect = logoElement.getBoundingClientRect();
const targetX = refillRect.left + refillRect.width; // Upper right corner X
const targetY = refillRect.top; // Upper right corner Y
const refillDropCount = dropType === 'celebration' ? 20 : 12;
const startTopPosition = 0; // Start from top of viewport
for (let i = 0; i < refillDropCount; i++) {
const refillDrop = document.createElement('div');
// For celebration refills, use a special class that does not repeat the main animation
if (isCelebration) {
refillDrop.className = 'droplet droplet-celebration-refill droplet-refill';
} else if (dropType === 'mixed') {
const randomType = dropTypes[Math.floor(Math.random() * dropTypes.length)];
refillDrop.className = `droplet ${randomType} droplet-refill`;
} else {
refillDrop.className = `droplet ${dropType} droplet-refill`;
}
// Start from random positions at top of screen, spread horizontally
const startX = targetX + (Math.random() - 0.5) * window.innerWidth * 0.4;
const jitterTargetX = (Math.random() - 0.5) * 20;
const jitterTargetY = (Math.random() - 0.5) * 20;
// Calculate distance drop needs to travel from top to logo
const travelDistance = targetY - startTopPosition + jitterTargetY;
refillDrop.style.left = `${startX}px`;
refillDrop.style.top = `${startTopPosition}px`;
refillDrop.style.width = `${2 + Math.random() * 0.5}vw`;
refillDrop.style.height = `${(2 + Math.random() * 0.5) * 1.2}vw`;
refillDrop.style.setProperty('--travel-distance', `${travelDistance}px`);
refillDrop.style.animationDelay = `${i * 45}ms`;
dropletContainer.appendChild(refillDrop);
}
}, 2500);
} // End of refill section (skipped for celebration)
// Swap back to original after refill completes (at 3800ms, before final rotation)
// This happens for both regular and celebration animations
setTimeout(() => {
logoElement.src = originalSrc;
}, 3800);
// Create droplet container
const dropletContainer = document.createElement('div');
dropletContainer.className = 'droplet-container';
document.body.appendChild(dropletContainer);
// Get logo position
const logoRect = logoElement.getBoundingClientRect();
// Adjust drop count and size for celebration
const dropCount = dropType === 'celebration' ? 15 : 8;
// For celebration, drops fall from top center of screen
// For regular animations, drops come from logo position
const upperRightX = isCelebration ? window.innerWidth / 2 : logoRect.left + logoRect.width;
const upperRightY = isCelebration ? 0 : logoRect.top;
// Create drops boiling out from upper right corner
for (let i = 0; i < dropCount; i++) {
const droplet = document.createElement('div');
// Assign drop class based on type
if (isCelebration) {
droplet.className = 'droplet droplet-celebration';
} else if (dropType === 'mixed') {
// Randomly pick a drop type
const randomType = dropTypes[Math.floor(Math.random() * dropTypes.length)];
droplet.className = `droplet ${randomType}`;
} else {
droplet.className = `droplet ${dropType}`;
}
// Small random spread around upper right corner
// For celebration, spread drops across full viewport width
const jitterX = isCelebration
? (Math.random() - 0.5) * window.innerWidth * 1.5
: (Math.random() - 0.5) * 20;
const jitterY = (Math.random() - 0.5) * (isCelebration ? 40 : 20);
// Use viewport-relative sizing for growth
const size = isCelebration ? 1.5 + Math.random() : 1 + Math.random() * 0.5;
const delay = i * (isCelebration ? 40 : 50); // Faster stagger for celebration
droplet.style.left = `${upperRightX + jitterX}px`;
droplet.style.top = `${upperRightY + jitterY}px`;
droplet.style.width = `${size}vw`;
droplet.style.height = `${size * 1.2}vw`;
droplet.style.animationDelay = `${delay}ms`;
dropletContainer.appendChild(droplet);
}
// After flip (600ms), create drops from bottom left corner
setTimeout(() => {
const updatedRect = logoElement.getBoundingClientRect();
const bottomLeftX = updatedRect.left;
const bottomLeftY = updatedRect.top + updatedRect.height;
for (let i = 0; i < dropCount; i++) {
const droplet = document.createElement('div');
// Assign drop class based on type
if (isCelebration) {
droplet.className = 'droplet droplet-celebration';
} else if (dropType === 'mixed') {
const randomType = dropTypes[Math.floor(Math.random() * dropTypes.length)];
droplet.className = `droplet ${randomType}`;
} else {
droplet.className = `droplet ${dropType}`;
}
const jitterX = isCelebration
? (Math.random() - 0.5) * window.innerWidth * 1.5
: (Math.random() - 0.5) * 20;
const jitterY = (Math.random() - 0.5) * (isCelebration ? 40 : 20);
// Use viewport-relative sizing for growth
const size = isCelebration ? 1.5 + Math.random() : 1 + Math.random() * 0.5;
droplet.style.left = `${bottomLeftX + jitterX}px`;
droplet.style.top = `${bottomLeftY + jitterY}px`;
droplet.style.width = `${size}vw`;
droplet.style.height = `${size * 1.2}vw`;
dropletContainer.appendChild(droplet);
}
}, 600);
// Clean up after animation completes
setTimeout(() => {
logoElement.classList.remove('flipping');
dropletContainer.remove();
if (dropType !== 'celebration') {
isAnimating = false;
} else {
// Allow immediate new animation after celebration
setTimeout(() => { isAnimating = false; }, 500);
}
}, 4000);
}
}
// Initialize animations for main logos
function initLogoAnimation() {
const logos = ['logo-icon', 'navbar-logo', 'guide-logo', 'final-logo'];
logos.forEach(logoId => setupLogoAnimation(logoId));
}
// Initialize app
document.addEventListener('DOMContentLoaded', async () => {
// Initialize logo animation
initLogoAnimation();
// Check if viewing results from URL parameter
const urlParams = new URLSearchParams(window.location.search);
const sessionParam = urlParams.get('session');
if (sessionParam) {
// Hide welcome page immediately to prevent flash
document.getElementById('page-welcome').classList.remove('active');
// Load and display results for specified session
await loadSessionResults(sessionParam);
return;
}
// Load saved state first
const hasState = loadState();
// Generate or restore session ID
if (!sessionId) {
sessionId = generateSessionId();
}
// Load content and build all pages SYNCHRONOUSLY before any async work.
// This ensures papers[], glossary, and rubric are ready before the page is
// shown and before any user interaction can occur.
await loadContent();
generatePaperPages();
// Initialize animations for all paper page logos
papers.forEach((paper, index) => {
setupLogoAnimation(`paper-logo-${index}`);
});
// Render guide-page content (glossary + rubric)
renderGlossary();
renderRubric();
// Restore previously submitted ratings if resuming
if (hasState && Object.keys(userRatings).length > 0) {
restoreSubmittedRatings();
}
// Update score display if resuming with existing score
if (totalScore > 0) {
const scoreDisplay = document.getElementById('total-score-header');
if (scoreDisplay) {
const ratedCount = Object.keys(userRatings).length;
const percentageScore = ratedCount > 0 ? Math.round(totalScore / ratedCount) : 0;
const icon = getPerformanceIcon(percentageScore);
scoreDisplay.innerHTML = `<span class="medal-icon">${icon}</span> ${percentageScore}%`;
document.getElementById('score-banner').style.display = 'flex';
}
}
// Show the correct page NOW — content is ready, no race condition possible
const pageToShow = (hasState && currentPage > 0) ? currentPage : 0;
showPage(pageToShow);
// === Async work that must not block page display ===
// Sign in anonymously so all subsequent Firebase writes carry a verified auth token.
// auth.currentUser persists across page reloads via Firebase's local persistence.
if (auth.currentUser) {
firebaseUid = auth.currentUser.uid;
} else {
const cred = await signInAnonymously(auth);
firebaseUid = cred.user.uid;
}
// Generate or retrieve username (may require a Firebase round-trip)
userName = localStorage.getItem('userName');
if (!userName) {
userName = await generateUniqueUsername();
localStorage.setItem('userName', userName);
}
// Update username placeholders now that the value is known
displayUsername();
// Start session timeout
startSessionTimeout();
// Track active participants
trackParticipant();
// Update participant count
updateParticipantCount();
});
// Expose functions to global scope for HTML onclick handlers
window.nextPage = nextPage;
window.previousPage = previousPage;
window.enableSubmit = enableSubmit;
window.submitRating = submitRating;
window.showHelp = showHelp;
window.closeHelp = closeHelp;
window.showTab = showTab;
window.finishEarly = finishEarly;
// Generate unique session ID
function generateSessionId() {
return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
// Generate child-friendly username with two-digit number
function generateUsername() {
const adjectives = [
'Red', 'Blue', 'Green', 'Yellow', 'Purple', 'Orange', 'Pink', 'Teal',
'Brave', 'Wise', 'Swift', 'Tall', 'Happy', 'Clever', 'Bright', 'Quick',
'Mighty', 'Gentle', 'Bold', 'Cheerful', 'Curious', 'Friendly', 'Kind', 'Peaceful'
];
const animals = [
'Fox', 'Raccoon', 'Owl', 'Sparrow', 'Robin', 'Falcon', 'Eagle', 'Hawk',
'Rabbit', 'Squirrel', 'Deer', 'Bear', 'Wolf', 'Otter', 'Badger', 'Hedgehog',
'Dolphin', 'Seal', 'Penguin', 'Panda', 'Koala', 'Tiger', 'Lion', 'Leopard'
];
const adjective = adjectives[Math.floor(Math.random() * adjectives.length)];
const animal = animals[Math.floor(Math.random() * animals.length)];
const number = Math.floor(Math.random() * 100).toString().padStart(2, '0'); // 00-99
return `${adjective} ${animal} ${number}`;
}
// Generate a unique username by checking against existing leaderboard usernames
async function generateUniqueUsername() {
const leaderboardRef = ref(database, 'leaderboard');
try {
const snapshot = await get(leaderboardRef);
const existingUsernames = new Set();
if (snapshot.exists()) {
const leaderboardData = snapshot.val();
Object.values(leaderboardData).forEach(entry => {
if (entry.userName) {
existingUsernames.add(entry.userName);
}
});
}
// Reserve 'Anonymous' so it can never be assigned to a real user
existingUsernames.add('Anonymous');
// Attempt to generate a unique username (max 500 attempts)
let attempts = 0;
let username;
do {
username = generateUsername();
attempts++;
// Fallback: if maximum attempts reached, append a counter to ensure uniqueness
if (attempts >= 500) {
const baseUsername = generateUsername();
let counter = 1;
username = `${baseUsername}-${counter}`;
while (existingUsernames.has(username)) {
counter++;
username = `${baseUsername}-${counter}`;
}
break;
}
} while (existingUsernames.has(username));
return username;
} catch (error) {
console.error('Error checking username uniqueness:', error);
// Fallback to regular generation if Firebase check fails
return generateUsername();
}
}
// Save application state to localStorage
function saveState() {
const state = {
currentPage,
userRatings,
userPredictions,
paperScores,
totalScore,
sessionId,
hasUsedBackButton,
celebratedPapers: Array.from(celebratedPapers),
pageDisplayTimestamps,
criterionTokens
};
localStorage.setItem('workshopState', JSON.stringify(state));
}
// Load application state from localStorage
function loadState() {
try {
const saved = localStorage.getItem('workshopState');
if (saved) {
const state = JSON.parse(saved);
currentPage = state.currentPage || 0;
userRatings = state.userRatings || {};
userPredictions = state.userPredictions || {};
paperScores = state.paperScores || {};
totalScore = state.totalScore || 0;
sessionId = state.sessionId || null;
hasUsedBackButton = state.hasUsedBackButton || false;
celebratedPapers = new Set(state.celebratedPapers || []);
pageDisplayTimestamps = state.pageDisplayTimestamps || {};
criterionTokens = state.criterionTokens || { title: 0, access: 0, source: 0, theory: 0, methods: 0, conclusion: 0 };
return true; // State was loaded
}
} catch (error) {
console.error('Error loading state:', error);
}
return false; // No state to load
}
// Restore submitted ratings UI for previously rated papers
function restoreSubmittedRatings() {
Object.keys(userRatings).forEach(paperId => {
// Find paper index
const paperIndex = papers.findIndex(p => p.id === paperId);
if (paperIndex >= 0) {
// Hide rating section, show results
const ratingSection = document.getElementById(`rating-section-${paperIndex}`);
const resultsBox = document.getElementById(`results-${paperIndex}`);
if (ratingSection) ratingSection.style.display = 'none';
if (resultsBox) {
resultsBox.style.display = 'block';
// Restore the score display if we have it saved
const savedScore = paperScores[paperId];
if (savedScore !== undefined) {
const scoreElement = document.getElementById(`score-${paperIndex}`);
if (scoreElement) {
scoreElement.textContent = `${savedScore}%`;
scoreElement.style.fontSize = '2rem';
scoreElement.style.fontWeight = 'bold';
}
}
// Re-fetch and show results
const rating = userRatings[paperId];
const prediction = userPredictions[paperId];
if (rating && prediction) {
showResults(paperIndex, paperId, rating, prediction, true);
}
}
}
});
}
// Display username only on results page
function displayUsername() {
// Update navbar username display (will be shown/hidden by showPage)
const navbarUsername = document.getElementById('navbar-username');
if (navbarUsername) {
navbarUsername.textContent = userName;
}
// Update username in Save Your Results section
const usernameSaveDisplay = document.getElementById('username-display-save');
if (usernameSaveDisplay) {
usernameSaveDisplay.textContent = userName;
}
// Also update the inline username reference
const usernameInline = document.getElementById('username-display-inline');
if (usernameInline) {
usernameInline.textContent = userName;
}
}
// Start session timeout to prevent excessive Firebase usage
function startSessionTimeout() {
lastActivityTime = Date.now();
resetInactivityTimer();
// Listen for user activity to reset the inactivity timer
ACTIVITY_EVENTS.forEach(event => {
document.addEventListener(event, onUserActivity, { passive: true });
});
// Hard cap: end session after 50 minutes regardless of activity
absoluteTimeoutId = setTimeout(() => {
endSession();
}, ABSOLUTE_MAX_DURATION);
// Update timer display every 30 seconds
setInterval(updateTimerDisplay, 30000);
updateTimerDisplay();
}
// Called on any user interaction — resets the inactivity countdown
function onUserActivity() {
const now = Date.now();
if (lastActivityTime && (now - lastActivityTime) < ACTIVITY_RESET_DEBOUNCE) {
return;
}
lastActivityTime = now;
inactivityWarningShown = false;
resetInactivityTimer();
}
function getRemainingInactivityMs() {
if (!lastActivityTime) return INACTIVITY_TIMEOUT;
return INACTIVITY_TIMEOUT - (Date.now() - lastActivityTime);
}
// (Re)start the inactivity disconnect timer
function resetInactivityTimer() {
if (sessionTimeoutId) clearTimeout(sessionTimeoutId);
if (warningTimeoutId) clearTimeout(warningTimeoutId);
// Warn at 5 minutes of inactivity
warningTimeoutId = setTimeout(() => {
const remaining = getRemainingInactivityMs();
if (!inactivityWarningShown && remaining > 0 && remaining <= INACTIVITY_WARNING) {
inactivityWarningShown = true;
alert('⏰ 5 minutes until your session disconnects due to inactivity.');
}
}, INACTIVITY_TIMEOUT - INACTIVITY_WARNING);
// Disconnect at 10 minutes of inactivity
sessionTimeoutId = setTimeout(() => {
endSession();
}, INACTIVITY_TIMEOUT);
}
// Update timer display
function updateTimerDisplay() {
const remaining = getRemainingInactivityMs();
const minutes = Math.max(0, Math.floor(remaining / 60000));
// Calculate papers remaining
const papersRated = Object.keys(userRatings).length;
const totalPapers = papers.length || 48;
const papersRemaining = Math.max(0, totalPapers - papersRated);
const timerEl = document.getElementById('session-timer');
if (timerEl) {
if (remaining > 0) {
timerEl.textContent = `${minutes} min | ${papersRemaining} paper${papersRemaining !== 1 ? 's' : ''} left`;
timerEl.style.color = remaining <= 5 * 60000 ? '#f56565' : '';
} else {
timerEl.textContent = 'Session ending...';
timerEl.style.color = '#f56565';
}
}
}
function endSession() {
// Stop all Firebase listeners
firebaseListeners.forEach(unsubscribe => {
if (typeof unsubscribe === 'function') {
unsubscribe();
}
});
firebaseListeners = [];
// Remove from active participants
if (sessionId) {
const participantRef = ref(database, `active/${sessionId}`);
set(participantRef, null);
}
// Clear all timeouts
if (sessionTimeoutId) clearTimeout(sessionTimeoutId);
if (warningTimeoutId) clearTimeout(warningTimeoutId);
if (absoluteTimeoutId) clearTimeout(absoluteTimeoutId);
// Remove activity listeners
ACTIVITY_EVENTS.forEach(event => {
document.removeEventListener(event, onUserActivity);
});
// Show message and disable interaction
const overlay = document.createElement('div');
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.9);
display: flex;
align-items: center;
justify-content: center;
z-index: 10000;
color: white;
text-align: center;
padding: 20px;
`;
overlay.innerHTML = `
<div>
<h2 style="margin-bottom: 20px; color: white;">⏰ Session Disconnected</h2>
<p style="margin-bottom: 20px; color: white;">
Your session ended due to inactivity.<br>
Thank you for participating!
</p>
<button onclick="location.reload()" style="
background: #667eea;
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
">Start New Session</button>
</div>
`;
document.body.appendChild(overlay);
}
// Track active participants
function trackParticipant() {
const participantRef = ref(database, `active/${sessionId}`);
// Mark as active
set(participantRef, {
joinedAt: Date.now(),
lastActive: Date.now(),
uid: firebaseUid
});
// Update activity every 30 seconds
setInterval(() => {
set(participantRef, {
joinedAt: Date.now(),
lastActive: Date.now(),
uid: firebaseUid
});
}, 30000);
// Remove on page unload
window.addEventListener('beforeunload', () => {
set(participantRef, null);
});
}
// Update participant count display
function updateParticipantCount() {
const counter = document.getElementById('participant-counter');
// Hide counter initially
if (counter) {
counter.style.display = 'none';
}
const activeRef = ref(database, 'active');
const unsubscribe = onValue(activeRef, (snapshot) => {
const active = snapshot.val();
if (counter) {
if (active && Object.keys(active).length > 0) {
// Count only participants active in the last 60 seconds
const activeCount = Object.keys(active).filter(key => {
const timestamp = active[key].timestamp;
return timestamp && (Date.now() - timestamp < 60000);
}).length;
if (activeCount > 0) {
counter.textContent = `${activeCount} participant${activeCount !== 1 ? 's' : ''} active`;
counter.style.display = 'inline-block';
} else {
counter.style.display = 'none';
}
} else {
counter.style.display = 'none';
}
}
}, (error) => {
// Handle Firebase connection errors - hide counter
console.error('Error updating participant count:', error);
if (counter) {
counter.style.display = 'none';
}
});
// Track listener for cleanup
firebaseListeners.push(unsubscribe);
}
// Shuffle papers array using Fisher-Yates algorithm with seeded randomization
function shufflePapers() {
// Safety check
if (!papers || !papers.length || !sessionId) {
console.warn('Cannot shuffle papers: papers or sessionId not initialized');
return;
}
// Use session ID as seed for consistent randomization per participant
let seed = 0;
for (let i = 0; i < sessionId.length; i++) {
seed = ((seed << 5) - seed) + sessionId.charCodeAt(i);
seed = seed & seed; // Convert to 32-bit integer
}
// Seeded random number generator
function seededRandom() {
seed = (seed * 9301 + 49297) % 233280;
return seed / 233280;
}
// Fisher-Yates shuffle with seeded random
for (let i = papers.length - 1; i > 0; i--) {
const j = Math.floor(seededRandom() * (i + 1));
[papers[i], papers[j]] = [papers[j], papers[i]];
}
}
// Load content from bundled JSON imports
async function loadContent(shouldShuffle = true) {
try {
glossary = glossaryData;
rubric = rubricData;
papers = [...papersData]; // spread to avoid mutating the import
// Shuffle papers for this participant (consistent across page reloads)
// Skip shuffling if loading session results (no sessionId yet)
if (shouldShuffle && sessionId) {
shufflePapers();
}
// Update total papers count on final page (will be updated when results load)
const totalPapersElement = document.getElementById('total-papers');
if (totalPapersElement) {
totalPapersElement.textContent = Object.keys(userRatings).length || 0;
}
} catch (error) {
console.error('Error loading content:', error);
alert(`Error loading workshop content: ${error.message}\n\nPlease try:\n1. Hard refresh (Ctrl+Shift+R or Cmd+Shift+R)\n2. Clear browser cache\n3. Contact support if issue persists`);
}
}
// Render glossary
function renderGlossary() {
console.log('renderGlossary called');
const glossaryContent = document.getElementById('glossary-content');
const modalGlossary = document.getElementById('modal-glossary');
console.log('Glossary content element:', glossaryContent);
console.log('Modal glossary element:', modalGlossary);
console.log('Glossary data:', glossary);
if (!glossary || glossary.length === 0) {
console.error('Glossary data not loaded or empty', glossary);
const errorHTML = '<p style="color: red;">Error: Glossary data failed to load. Please refresh the page.</p>';
if (glossaryContent) glossaryContent.innerHTML = errorHTML;
if (modalGlossary) modalGlossary.innerHTML = errorHTML;
return;
}
const glossaryHTML = glossary.map(item => `
<div class="glossary-item">
<div class="glossary-term">${item.term}</div>
<div class="glossary-definition">${item.definition}</div>
</div>
`).join('');
console.log('Generated glossary HTML length:', glossaryHTML.length);
console.log('Generated glossary HTML (first 200 chars):', glossaryHTML.substring(0, 200));
if (glossaryContent) {
glossaryContent.innerHTML = glossaryHTML;
console.log('Glossary content updated. Element now contains:', glossaryContent.innerHTML.substring(0, 200));
} else {
console.error('glossary-content element not found in DOM');
}
if (modalGlossary) {
modalGlossary.innerHTML = glossaryHTML;
console.log('Modal glossary updated');
} else {
console.warn('modal-glossary element not found in DOM (this is OK if modal not on current page)');
}
}
// Render rubric
function renderRubric() {
console.log('renderRubric called');
const rubricContent = document.getElementById('rubric-content');
const modalRubric = document.getElementById('modal-rubric');
console.log('Rubric content element:', rubricContent);
console.log('Modal rubric element:', modalRubric);
console.log('Rubric data:', rubric);
if (!rubric || rubric.length === 0) {
console.error('Rubric data not loaded or empty', rubric);
const errorHTML = '<p style="color: red;">Error: Rubric data failed to load. Please refresh the page.</p>';
if (rubricContent) rubricContent.innerHTML = errorHTML;
if (modalRubric) modalRubric.innerHTML = errorHTML;
return;
}
// Helper function to bold text up to and including the first colon
const boldUpToColon = (text) => {
const colonIndex = text.indexOf(':');
if (colonIndex === -1) return text; // No colon found, return as is
const beforeColon = text.substring(0, colonIndex + 1); // Include the colon
const afterColon = text.substring(colonIndex + 1);
return `<strong>${beforeColon}</strong>${afterColon}`;
};
const rubricHTML = `
<div class="info-box" style="margin-bottom: 1rem; background: #f3e5f5; border-left: 4px solid #9c27b0;">
<p style="margin: 0;"><strong>💡 Scoring Strategy:</strong> You can freely weigh some criteria more strongly than others when forming your overall rating.</p>
</div>
<div style="overflow-x: auto; -webkit-overflow-scrolling: touch;">
<table class="rubric-table">
<thead>
<tr>
<th>Category</th>
<th>Low (1-2)</th>
<th>Medium (3-5)</th>
<th>High (6-7)</th>
</tr>
</thead>
<tbody>