-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcaseada.html
More file actions
938 lines (857 loc) · 50 KB
/
caseada.html
File metadata and controls
938 lines (857 loc) · 50 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="color-scheme" content="light"/>
<title>TV Movie Ratings Case Study</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/simple-statistics/7.8.3/simple-statistics.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstat/1.9.5/jstat.min.js"></script>
<style>
/* -----------------------------
Purdue palette + accessibility
Sources (brand): Boilermaker Gold #CFB991, Black #000000; supporting Rush #DAAA00, Aged #8E6F3E, Dark Gray #373A36
We keep your calculations 100% intact and focus on semantics, contrast, focus, and keyboard UX.
------------------------------*/
:root{
/* Purdue brand core */
--p-black:#000000;
--p-gold:#CFB991; /* Boilermaker Gold */
--p-rush:#DAAA00; /* supporting gold (bolder) */
--p-aged:#8E6F3E; /* deeper gold/brown */
--p-dark:#373A36; /* dark gray */
--p-gray:#9D968D; /* medium gray */
/* App neutrals */
--card:#ffffff; --panel:#f7f7f7; --line:#e5e7eb;
--ink:#111827; --muted:#4b5563;
/* Map existing theme tokens to Purdue tones for minimal code churn */
--bg1:#f0f2f4; --bg2:#f0f2f4; /* remove bright gradient */
--green1:var(--p-dark); --green2:var(--p-black); /* used for table head in data-display */
--blue1:var(--p-gold); --blue2:var(--p-black); /* accents and active tab text */
--orange1:var(--p-gold); --orange2:var(--p-aged);/* callouts and CTA */
--purple1:var(--p-dark); --purple2:var(--p-black);/* secondary CTA */
--danger:var(--p-black); /* avoid red/green-only cues */
--focus-ring: var(--p-rush);
}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
/* Skip link for keyboard users */
.skip-link{position:absolute;left:-999px;top:auto;width:1px;height:1px;overflow:hidden}
.skip-link:focus{left:16px;top:16px;width:auto;height:auto;background:#fff;color:#000;padding:.5rem .75rem;border:2px solid var(--p-black);z-index:9999}
body{
font-family: system-ui, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell, Noto Sans, Helvetica, Arial, "Apple Color Emoji","Segoe UI Emoji";
max-width:1200px;margin:0 auto;padding:20px;
background:linear-gradient(135deg,var(--bg1) 0%,var(--bg2) 100%);
min-height:100vh;
color:var(--ink);
}
main{display:block}
.container{background:var(--card);border-radius:15px;padding:30px;box-shadow:0 20px 40px rgba(0,0,0,.06)}
h1{color:var(--ink);text-align:center;margin-bottom:10px;font-size:2.2em}
.subtitle{text-align:center;color:var(--muted);margin-bottom:30px;font-size:1.1em}
/* Info banner with not-red/green emphasis and good contrast */
.data-info{background:#fff;border:3px solid var(--p-gold);border-radius:10px;padding:16px;margin:20px 0;color:var(--ink)}
/* Controls */
.data-controls{display:flex;justify-content:center;gap:15px;margin:20px 0;flex-wrap:wrap}
.btn{padding:12px 20px;border:2px solid transparent;border-radius:12px;font-size:1em;font-weight:700;cursor:pointer;transition:transform .15s ease, box-shadow .15s ease;min-width:170px;line-height:1.2}
.btn:hover{transform:translateY(-2px);box-shadow:0 6px 12px rgba(0,0,0,.14)}
.btn:focus-visible{outline:3px solid var(--focus-ring);outline-offset:2px}
.btn:disabled{opacity:.6;cursor:not-allowed;transform:none;box-shadow:none}
/* Map existing button classes to Purdue colors while keeping names intact */
.btn-green{background:var(--p-black);color:#fff;border-color:var(--p-black)} /* primary */
.btn-orange{background:var(--p-gold);color:#000;border-color:var(--p-dark)} /* secondary on gold */
.btn-purple{background:var(--p-dark);color:#fff;border-color:var(--p-dark)} /* tertiary */
.btn-red{background:var(--p-black);color:#fff;border-color:var(--p-gold);min-width:260px;border-radius:14px;letter-spacing:.02em;text-transform:none}
.data-display{background:var(--panel);border-radius:10px;padding:20px;margin:20px 0;border:2px solid #e5e7eb}
.data-display:focus{outline:3px solid var(--focus-ring);outline-offset:3px}
.data-display h3{color:var(--ink);margin-bottom:15px;text-align:center}
.data-table-container{max-height:400px;overflow-y:auto;border-radius:8px;box-shadow:0 2px 4px rgba(0,0,0,.06)}
/* Tabs */
.tabs-container{margin-top:30px}
.tabs{display:flex;border-bottom:3px solid #e5e7eb;margin-bottom:30px;border-radius:10px 10px 0 0;overflow:hidden}
.tab-button{flex:1;padding:18px 22px;background:var(--panel);border:none;cursor:pointer;font-size:1.05em;font-weight:800;color:var(--muted);transition:background .15s ease;text-transform:none;letter-spacing:.3px;border-bottom:4px solid transparent}
.tab-button:hover{background:#e9ecef;color:var(--ink)}
.tab-button[aria-selected="true"]{background:#fff;color:var(--p-black);border-bottom-color:var(--p-gold)}
.tab-button:focus-visible{outline:3px solid var(--focus-ring);outline-offset:2px}
.tab-content{display:none;animation:fadeIn .3s ease-in}
.tab-content.active{display:block}
@keyframes fadeIn{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:translateY(0)}}
/* Case + questions */
.case-content{font-size:1.05em;line-height:1.6;color:var(--ink);background:#fff;padding:25px;border-radius:10px;border-left:6px solid var(--p-gold)}
.question-section{margin:30px 0;padding:25px;background:var(--panel);border-radius:10px;border-left:6px solid var(--p-aged)}
.question-section h3{color:var(--p-dark);margin-bottom:14px;font-size:1.1em}
.question-option{display:flex;align-items:flex-start;gap:12px;padding:15px;background:#fff;border-radius:10px;border:2px solid var(--line);cursor:pointer;transition:box-shadow .15s ease}
.question-option:hover{box-shadow:0 2px 4px rgba(0,0,0,.06)}
.question-option input[type="radio"],
.variable-option input[type="checkbox"],
.comparison-option input[type="radio"]{transform:scale(1.2);accent-color:var(--p-black)}
.question-submit{text-align:center;margin:18px 0}
/* Feedback: avoid color-only cues; add strong borders and icons via content */
.feedback{margin-top:16px;padding:14px 16px;border-radius:10px;border:2px solid var(--p-dark);background:#fff;font-weight:700}
.feedback.correct{border-left:8px solid var(--p-gold)}
.feedback.incorrect{border-left:8px solid var(--p-black)}
/* Analysis sections */
.analysis-section,.hypothesis-section{margin:30px 0;padding:25px;background:var(--panel);border-radius:10px;border-left:6px solid var(--p-gold)}
.hypothesis-section{border-left-color:var(--p-dark)}
h2{color:var(--p-black);margin-bottom:16px;font-size:1.35em}
table{width:100%;border-collapse:collapse;margin:20px 0;background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 4px 6px rgba(0,0,0,.06)}
caption{caption-side:top;text-align:left;font-weight:800;padding:10px 12px;color:var(--muted)}
th,td{padding:14px;text-align:left;border-bottom:1px solid var(--line)}
th{background:var(--p-black);color:#fff;font-weight:800;letter-spacing:.3px}
.data-display th{position:sticky;top:0;z-index:10}
tr:hover{background:#f9fafb;transition:background .15s ease}
.numeric{text-align:right;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-weight:600}
fieldset{border:0;margin:0;padding:0;min-inline-size:0}
.variable-selection{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px;margin:18px 0;border:0;padding:0}
.comparison-selection{display:grid;grid-template-columns:repeat(auto-fit,minmax(300px,1fr));gap:12px;margin:18px 0;border:0;padding:0}
.variable-option,.comparison-option{display:flex;align-items:center;gap:12px;padding:14px;background:#fff;border-radius:10px;border:2px solid var(--line)}
.selection-info{background:#fff;border:2px solid var(--p-dark);border-left:8px solid var(--p-gold);border-radius:10px;padding:12px;margin:15px 0;color:var(--ink);text-align:center;font-weight:800}
#dataTable{font-size:.95em}
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}
/* Visible focus for interactive elements */
a:focus-visible, button:focus-visible, input:focus-visible{outline:3px solid var(--focus-ring);outline-offset:2px}
/* Reduced motion support */
@media (prefers-reduced-motion: reduce){
*{animation:none!important;transition:none!important}
}
</style>
</head>
<body>
<a class="skip-link" href="#main">Skip to main content</a>
<main id="main" role="main">
<div class="container" role="region" aria-labelledby="page-title">
<h1 id="page-title">TV Movie Ratings Case Study</h1>
<p class="subtitle">An analytical exercise activity by Dr. Altinoz. Please send all feedback to caltinoz@purdueglobal.edu</p>
<div class="data-info" role="note" aria-label="Analysis Scope">
<strong>Analysis Scope:</strong> CBC Network movies (<span id="observationCount">30</span> observations)<br/>
<strong>Dependent Variable:</strong> Rating (<span id="avgRating">—</span> avg)<br/>
</div>
<div class="data-controls" role="group" aria-label="Data controls">
<button class="btn btn-green" id="btnNew" type="button"><span aria-hidden="true">🎲</span> Generate New Dataset</button>
<button class="btn btn-green" id="btnToggle" type="button" aria-expanded="false" aria-controls="dataDisplay"><span aria-hidden="true">📊</span> <span id="dataToggleText">Show Data</span></button>
<button class="btn btn-green" id="btnCSV" type="button"><span aria-hidden="true">💾</span> Download CSV</button>
</div>
<div id="datasetStatus" class="sr-only" aria-live="polite"></div>
<div id="dataDisplay" class="data-display" aria-live="polite" hidden tabindex="-1">
<h3>Current Dataset</h3>
<div class="data-table-container">
<table id="dataTable" aria-label="dataset table">
<caption>Generated or original monthly observations for ratings and factors</caption>
<thead>
<tr>
<th scope="col">Month</th>
<th scope="col">Rating</th>
<th scope="col">Fact</th>
<th scope="col">Stars</th>
<th scope="col">Previous Rating</th>
<th scope="col">Competition</th>
</tr>
</thead>
<tbody id="dataTableBody"></tbody>
</table>
</div>
</div>
<div class="tabs-container" aria-label="Analysis Tabs">
<div class="tabs" id="tabs" role="tablist">
<button class="tab-button" role="tab" aria-selected="true" aria-controls="case-questions" id="tab-case" tabindex="0">The Case and the Questions</button>
<button class="tab-button" role="tab" aria-selected="false" aria-controls="ab-comparisons" id="tab-ab" tabindex="-1">A/B Comparisons</button>
<button class="tab-button" role="tab" aria-selected="false" aria-controls="impact-analysis" id="tab-impact" tabindex="-1">Impact Analysis of Various Factors</button>
</div>
<div id="case-questions" class="tab-content active" role="tabpanel" aria-labelledby="tab-case">
<div class="case-content" role="region" aria-labelledby="case-title">
<h2 id="case-title" style="margin-bottom:16px;">The Case and the Questions</h2>
<p>The Network has collected data on the ratings of their TV movies. They have kept track of whether the movies had stars, if the plots were based on real-life situations, what the ratings were for the lead-in show to the movie and what the ratings were for the competition at the same time.</p>
<p>You can generate a new data set, then download it to do your own analysis. You can also use the two analysis tabs to use the metrics calculated by the tool. The executives have the following questions:</p>
<div class="question-section" role="group" aria-labelledby="q1-legend" aria-describedby="q1-help">
<h3 id="q1-legend">Question 1: Should the network choose to hire stars to improve their ratings or not?</h3>
<p id="q1-help" class="sr-only">Choose yes if the one-tailed t-test shows a significant positive effect of stars.</p>
<fieldset>
<legend class="sr-only">Q1 options</legend>
<label class="question-option">
<input type="radio" name="q1" value="yes"/>
<span>Yes, the network should hire stars because they significantly improve ratings</span>
</label>
<label class="question-option">
<input type="radio" name="q1" value="no"/>
<span>No, the network should not prioritize hiring stars because they do not significantly improve ratings</span>
</label>
</fieldset>
<div class="question-submit">
<button class="btn btn-orange" id="submitQ1" type="button">Submit Answer</button>
</div>
<div id="q1-feedback" class="feedback" role="status" aria-live="polite" style="display:none;"></div>
</div>
<div class="question-section" role="group" aria-labelledby="q2-legend" aria-describedby="q2-help">
<h3 id="q2-legend">Question 2: Should the network choose plot-lines based on real life situations or not?</h3>
<p id="q2-help" class="sr-only">Choose yes if the one-tailed t-test shows a significant positive effect of reality-based plots.</p>
<fieldset>
<legend class="sr-only">Q2 options</legend>
<label class="question-option">
<input type="radio" name="q2" value="yes"/>
<span>Yes, the network should choose real-life plot-lines because they significantly improve ratings</span>
</label>
<label class="question-option">
<input type="radio" name="q2" value="no"/>
<span>No, the network should not prioritize real-life plot-lines because they do not significantly improve ratings</span>
</label>
</fieldset>
<div class="question-submit">
<button class="btn btn-orange" id="submitQ2" type="button">Submit Answer</button>
</div>
<div id="q2-feedback" class="feedback" role="status" aria-live="polite" style="display:none;"></div>
</div>
<div class="question-section" role="group" aria-labelledby="q3-legend" aria-describedby="q3-help">
<h3 id="q3-legend">Question 3: Which strategy increases ratings more — hiring stars or using reality-based plot-lines?</h3>
<p id="q3-help" class="sr-only">Select the factor with the larger estimated effect size in a two-variable regression.</p>
<fieldset>
<legend class="sr-only">Q3 options</legend>
<label class="question-option">
<input type="radio" name="q3" value="stars"/>
<span>Hiring stars increases ratings more than reality-based plot-lines</span>
</label>
<label class="question-option">
<input type="radio" name="q3" value="fact"/>
<span>Reality-based plot-lines increase ratings more than hiring stars</span>
</label>
</fieldset>
<div class="question-submit">
<button class="btn btn-orange" id="submitQ3" type="button">Submit Answer</button>
</div>
<div id="q3-feedback" class="feedback" role="status" aria-live="polite" style="display:none;"></div>
</div>
<div class="question-section" role="group" aria-labelledby="q4-legend" aria-describedby="q4-help">
<h3 id="q4-legend">Question 4 [Advanced]: Which single factor should the network prioritize as their primary programming strategy?</h3>
<div id="q4-help" style="font-size:.95em;color:#374151;margin-bottom:15px;">
<p><em>Suggested Strategy:</em></p>
<ol style="margin:0 0 0 1.25rem; padding-left:0;">
<li>Run the regression with all four variables using the “Impact Analysis of Various Factors” tab (Tab 3).</li>
<li>Identify the independent variable with the largest coefficient and compare its t-statistic to the two-tailed 95% t-critical value.</li>
<li>If that variable is significant (|t| ≥ t-critical) and has the highest coefficient, declare it the best choice and confirm it matches your answer.</li>
<li>If the highest-coefficient variable is not significant, remove it, rerun the regression with the remaining variables, and repeat the comparison.</li>
<li>Continue until a variable is both significant and has the highest coefficient among those left. If all independent variables are not significant, the answer should be “none of the variables are significant so programming strategy must target something else.”</li>
</ol>
</div>
<fieldset>
<legend class="sr-only">Q4 options</legend>
<label class="question-option">
<input type="radio" name="q4" value="stars"/>
<span>Prioritize hiring stars for shows</span>
</label>
<label class="question-option">
<input type="radio" name="q4" value="fact"/>
<span>Prioritize reality-based plot-lines</span>
</label>
<label class="question-option">
<input type="radio" name="q4" value="previousRating"/>
<span>Prioritize pairing with high-rated lead-in shows</span>
</label>
<label class="question-option">
<input type="radio" name="q4" value="competition"/>
<span>Prioritize counter-programming against weak competition</span>
</label>
<label class="question-option">
<input type="radio" name="q4" value="None of the factors should be prioritized, look for other factors."/>
<span>None of the variables are significant so programming strategy must target something else.</span>
</label>
</fieldset>
<div class="question-submit">
<button class="btn btn-orange" id="submitQ4" type="button">Submit Answer</button>
</div>
<div id="q4-feedback" class="feedback" role="status" aria-live="polite" style="display:none;"></div>
</div>
</div>
</div>
<div id="ab-comparisons" class="tab-content" role="tabpanel" aria-labelledby="tab-ab">
<div class="hypothesis-section" role="region" aria-labelledby="ab-title">
<h2 id="ab-title">A/B Comparison using One-Tailed T-Tests</h2>
<p>Test whether one group gets higher ratings than another using one-tailed t-tests (equal variances assumed, 95% confidence). Uses <strong>sample</strong> variances and df-based critical values.</p>
<h3>Select Comparison:</h3>
<fieldset class="comparison-selection" aria-labelledby="comparison-legend">
<legend id="comparison-legend" class="sr-only">Comparison options</legend>
<label class="comparison-option">
<input type="radio" name="comparison" value="stars" checked/>
<span>Do movies with Stars get better ratings than those without Stars?</span>
</label>
<label class="comparison-option">
<input type="radio" name="comparison" value="fact"/>
<span>Do Fact-based movies get better ratings than Fiction movies?</span>
</label>
</fieldset>
<div class="question-submit">
<button class="btn btn-purple" id="runTest" type="button" aria-controls="hypothesis-results">Run One-Tailed T-Test</button>
</div>
</div>
<div id="hypothesis-results" class="results" aria-live="polite" role="region" aria-label="Hypothesis test results"></div>
</div>
<div id="impact-analysis" class="tab-content" role="tabpanel" aria-labelledby="tab-impact">
<div class="analysis-section" role="region" aria-labelledby="impact-title">
<h2 id="impact-title">Multiple Linear Regression Analysis</h2>
<p>Select which independent variables to include in your regression model:</p>
<fieldset class="variable-selection" aria-describedby="selectionInfo" aria-label="Variable selection">
<legend class="sr-only">Toggle variables for regression analysis</legend>
<label class="variable-option">
<input type="checkbox" id="fact" checked/>
<span>Fact (Documentary vs Fiction)</span>
</label>
<label class="variable-option">
<input type="checkbox" id="stars" checked/>
<span>Stars (Celebrity Cast)</span>
</label>
<label class="variable-option">
<input type="checkbox" id="previousRating" checked/>
<span>Previous Rating</span>
</label>
<label class="variable-option">
<input type="checkbox" id="competition" checked/>
<span>Competition Rating</span>
</label>
</fieldset>
<div class="selection-info" id="selectionInfo" aria-live="polite">Selected: Fact, Stars, Previous Rating, Competition (4 variables)</div>
<div class="question-submit">
<button class="btn btn-red" id="runRegression" type="button" aria-controls="results">Run Regression Analysis</button>
</div>
</div>
<div id="results" class="results" aria-live="polite" role="region" aria-label="Regression analysis results"></div>
</div>
</div>
</div>
</main>
<script>
// ---------- Data ----------
let cbcData = [
{month:1, rating:14, fact:0, stars:1, previousRating:8.2, competition:14.8},
{month:2, rating:11.3, fact:1, stars:0, previousRating:13, competition:13.2},
{month:3, rating:13.6, fact:0, stars:0, previousRating:13.7, competition:15.1},
{month:4, rating:12.9, fact:1, stars:0, previousRating:8.8, competition:16},
{month:5, rating:13.2, fact:1, stars:0, previousRating:13.1, competition:17},
{month:6, rating:16, fact:1, stars:0, previousRating:6.9, competition:15.8},
{month:7, rating:14.6, fact:1, stars:1, previousRating:13.8, competition:17.4},
{month:8, rating:16.6, fact:0, stars:1, previousRating:16.8, competition:14.4},
{month:9, rating:17.5, fact:1, stars:0, previousRating:14.8, competition:14.2},
{month:10,rating:11.6, fact:0, stars:0, previousRating:10, competition:14},
{month:11,rating:8.9, fact:0, stars:0, previousRating:8.6, competition:13},
{month:12,rating:15.6, fact:0, stars:0, previousRating:13.3, competition:16.8},
{month:1, rating:9.2, fact:0, stars:1, previousRating:6.8, competition:12.1},
{month:2, rating:11.8, fact:0, stars:0, previousRating:12.9, competition:12},
{month:3, rating:11, fact:0, stars:0, previousRating:5.3, competition:14.7},
{month:4, rating:9.5, fact:1, stars:0, previousRating:13, competition:17.3},
{month:5, rating:11.6, fact:0, stars:0, previousRating:10.1, competition:12.8},
{month:6, rating:13.3, fact:1, stars:0, previousRating:13.1, competition:20.3},
{month:7, rating:13.6, fact:1, stars:0, previousRating:14.1, competition:18.3},
{month:8, rating:12.4, fact:0, stars:0, previousRating:13.6, competition:20.2},
{month:9, rating:13.8, fact:1, stars:0, previousRating:10.2, competition:16.6},
{month:10,rating:11.9, fact:1, stars:0, previousRating:11.8, competition:12.2},
{month:11,rating:14.6, fact:0, stars:0, previousRating:14.9, competition:14.9},
{month:12,rating:15.8, fact:1, stars:1, previousRating:13.4, competition:17.2},
{month:1, rating:15.4, fact:0, stars:1, previousRating:13.6, competition:16.8},
{month:2, rating:12.8, fact:0, stars:0, previousRating:12.7, competition:14.6},
{month:3, rating:12.8, fact:0, stars:0, previousRating:12, competition:18.6},
{month:4, rating:15.1, fact:0, stars:0, previousRating:14.1, competition:15.5},
{month:5, rating:11.4, fact:0, stars:1, previousRating:11.2, competition:16.4},
{month:6, rating:19.1, fact:1, stars:0, previousRating:12.6, competition:15.4}
].map((r, i) => ({ id: i + 1, ...r }));
let currentDataInfo = { isGenerated:false, correlatedFactors:[], targetRSquared:0 };
// ---------- Cached nodes ----------
const $ = (sel) => document.querySelector(sel);
const $$ = (sel) => Array.from(document.querySelectorAll(sel));
const nodes = {
tbody: $('#dataTableBody'),
obsCount: $('#observationCount'),
avgRating: $('#avgRating'),
dataDisplay: $('#dataDisplay'),
dataToggleText: $('#dataToggleText'),
datasetStatus: $('#datasetStatus'),
selectionInfo: $('#selectionInfo'),
results: $('#results'),
hypoResults: $('#hypothesis-results'),
q1Feedback: $('#q1-feedback'),
q2Feedback: $('#q2-feedback'),
q3Feedback: $('#q3-feedback'),
q4Feedback: $('#q4-feedback'),
};
// ---------- Labels & helpers ----------
const LABELS = { fact:'Fact', stars:'Stars', previousRating:'Previous Rating', competition:'Competition' };
const by = (k, v) => d => d[k] === v;
const pick = k => d => d[k];
const ratings = (k, v) => cbcData.filter(by(k, v)).map(pick('rating'));
const getSelected = () => ['fact','stars','previousRating','competition'].filter(v => document.getElementById(v)?.checked);
function updateInfo(){
const sel = getSelected();
if (sel.length === 0){
nodes.selectionInfo.textContent = 'Please select at least one variable';
nodes.selectionInfo.setAttribute('aria-live','assertive');
} else {
nodes.selectionInfo.textContent = `Selected: ${sel.map(v => LABELS[v]).join(', ')} (${sel.length} variables)`;
nodes.selectionInfo.setAttribute('aria-live','polite');
}
}
function updateDataDisplay(){
const rows = cbcData.map(r => `
<tr>
<td>${r.month}</td>
<td class="numeric">${r.rating}</td>
<td class="numeric">${r.fact}</td>
<td class="numeric">${r.stars}</td>
<td class="numeric">${r.previousRating}</td>
<td class="numeric">${r.competition}</td>
</tr>`).join('');
nodes.tbody.innerHTML = rows;
}
function updateTopStats(){
nodes.obsCount.textContent = cbcData.length;
const avg = ss.mean(cbcData.map(r => r.rating));
nodes.avgRating.textContent = isFinite(avg) ? avg.toFixed(2) : '—';
}
function announceDataset(message){
if (nodes.datasetStatus){
nodes.datasetStatus.textContent = message;
}
}
// ---------- Data generation ----------
function generateDataPoint(month, correlatedFactors, targetRSquared, id){
const baseRating = 12 + Math.random()*6;
const fact = Math.random()<0.5 ? 1 : 0;
const stars = Math.random()<0.3 ? 1 : 0;
const previousRating = 5 + Math.random()*12;
const competition = 12 + Math.random()*9;
let rating = baseRating, totalEffect = 0;
if (correlatedFactors.includes('fact')){
const effect = fact * (1 + Math.random()*2);
rating += effect; totalEffect += Math.abs(effect);
}
if (correlatedFactors.includes('stars')){
const effect = stars * (0.5 + Math.random()*2.5);
rating += effect; totalEffect += Math.abs(effect);
}
if (correlatedFactors.includes('previousRating')){
const effect = (previousRating - 11) * (0.1 + Math.random()*0.3);
rating += effect; totalEffect += Math.abs(effect);
}
if (correlatedFactors.includes('competition')){
const effect = (competition - 15) * (-0.05 - Math.random()*0.15);
rating += effect; totalEffect += Math.abs(effect);
}
const noiseLevel = totalEffect > 0 && targetRSquared > 0
? totalEffect * Math.sqrt((1 - targetRSquared) / targetRSquared)
: 2.0;
rating += (Math.random()-0.5)*2*noiseLevel;
rating = Math.max(8, Math.min(20, rating));
return {
id,
month,
rating: Math.round(rating*10)/10,
fact,
stars,
previousRating: Math.round(previousRating*10)/10,
competition: Math.round(competition*10)/10
};
}
function generateNewDataset(){
const numCorrelated = Math.floor(Math.random()*5);
const all = ['fact','stars','previousRating','competition'];
const correlated = numCorrelated>0 ? [...all].sort(()=>Math.random()-0.5).slice(0,numCorrelated) : [];
const targetR2 = numCorrelated>0 ? 0.3 + Math.random()*0.5 : 0.1 + Math.random()*0.1;
cbcData = [];
let id = 1;
for (let month=1; month<=12; month++){
const obs = 2 + Math.floor(Math.random()*3);
for (let i=0;i<obs;i++) cbcData.push(generateDataPoint(month, correlated, targetR2, id++));
}
currentDataInfo = { isGenerated:true, correlatedFactors:correlated, targetRSquared:targetR2 };
updateDataDisplay();
updateTopStats();
resetAllQuestions();
nodes.results.style.display = 'none';
nodes.hypoResults.style.display = 'none';
const correlatedLabels = correlated.map(f => LABELS[f] || f);
const factorText = correlatedLabels.length
? `Correlated factors: ${correlatedLabels.join(', ')}.`
: 'No individual factors were emphasized in this sample.';
announceDataset(`New dataset generated with ${cbcData.length} observations. ${factorText} Target R-squared approximately ${targetR2.toFixed(2)}.`);
}
// ---------- CSV ----------
function downloadCSV(){
let csv = 'Month,Rating,Fact,Stars,Previous_Rating,Competition\n';
cbcData.forEach(r => { csv += `${r.month},${r.rating},${r.fact},${r.stars},${r.previousRating},${r.competition}\n`; });
const blob = new Blob([csv], {type:'text/csv'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
const ts = new Date().toISOString().slice(0,19).replace(/:/g,'-');
a.href = url;
const filename = `${currentDataInfo.isGenerated ? 'cbc_generated' : 'cbc_original'}_${ts}.csv`;
a.download = filename;
a.setAttribute('aria-label', `Download CSV file ${filename}`);
document.body.appendChild(a); a.click(); document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// ---------- Tabs ----------
function setTabState(btn, selected){
btn.setAttribute('aria-selected', String(selected));
btn.tabIndex = selected ? 0 : -1;
}
function showTab(button, tabId){
$$('.tab-content').forEach(c => c.classList.remove('active'));
$$('.tab-button').forEach(b => { setTabState(b, false); });
document.getElementById(tabId).classList.add('active');
setTabState(button, true);
const h = document.querySelector(`#${tabId} h2, #${tabId} h3`);
if (h) h.setAttribute('tabindex','-1'), h.focus();
}
function onTabKeydown(e){
const keys = ['ArrowLeft','ArrowRight','Home','End'];
if (!keys.includes(e.key)) return;
const tabs = $$('.tab-button');
const currentIndex = tabs.indexOf(document.activeElement);
let nextIndex = currentIndex;
if (e.key === 'ArrowRight') nextIndex = (currentIndex + 1) % tabs.length;
if (e.key === 'ArrowLeft') nextIndex = (currentIndex - 1 + tabs.length) % tabs.length;
if (e.key === 'Home') nextIndex = 0;
if (e.key === 'End') nextIndex = tabs.length - 1;
tabs[nextIndex].focus();
e.preventDefault();
}
// ---------- T-test ----------
function calculateTStat(g1, g2){
const n1 = g1.length, n2 = g2.length;
const mean1 = ss.mean(g1), mean2 = ss.mean(g2);
const v1 = ss.sampleVariance(g1), v2 = ss.sampleVariance(g2);
const pooled = ((n1-1)*v1 + (n2-1)*v2) / (n1 + n2 - 2);
return (mean1 - mean2) / Math.sqrt(pooled*(1/n1 + 1/n2));
}
function tCritical95OneTailed(df){
const table = [
[6,1.943],[8,1.860],[10,1.812],[12,1.782],[15,1.753],
[20,1.725],[25,1.708],[30,1.697],[40,1.684],[60,1.671],[120,1.658]
];
if (df <= 5) return 2.015;
for (let i=0;i<table.length;i++){
if (df <= table[i][0]) return table[i][1];
}
return 1.645;
}
function runOneTailedTest(a, b){
const t = calculateTStat(a,b);
const df = a.length + b.length - 2;
const tcrit = tCritical95OneTailed(df);
return { t, df, tcrit, significant: t > tcrit };
}
function showFeedback(questionId, isCorrect, tStat, tCritical){
const el = document.getElementById(`${questionId}-feedback`);
el.innerHTML = (isCorrect
? `✅ <strong>Correct.</strong> T-statistic: ${tStat.toFixed(3)}, T-critical (95%, one-tailed): ${tCritical}`
: `⚠️ <strong>Incorrect.</strong> T-statistic: ${tStat.toFixed(3)}, T-critical (95%, one-tailed): ${tCritical}`
);
el.className = `feedback ${isCorrect ? 'correct' : 'incorrect'}`;
el.style.display = 'block';
}
function resetAllQuestions(){
['q1','q2','q3','q4'].forEach(q => {
$$(`input[name="${q}"]`).forEach(r => r.checked = false);
const f = document.getElementById(`${q}-feedback`);
f.style.display = 'none'; f.textContent = '';
});
['submitQ1','submitQ2','submitQ3','submitQ4'].forEach(id => { const b = document.getElementById(id); if (b) b.disabled = false; });
}
// ---------- Real OLS multiple regression ----------
function transpose(A){ const m=A.length,n=A[0].length; const T=Array.from({length:n},()=>Array(m).fill(0)); for(let i=0;i<m;i++) for(let j=0;j<n;j++) T[j][i]=A[i][j]; return T; }
function matMul(A,B){ const m=A.length,n=A[0].length,p=B[0].length; const C=Array.from({length:m},()=>Array(p).fill(0)); for(let i=0;i<m;i++) for(let k=0;k<n;k++){ const aik=A[i][k]; for(let j=0;j<p;j++) C[i][j]+=aik*B[k][j]; } return C; }
function identity(n){ const I=Array.from({length:n},()=>Array(n).fill(0)); for(let i=0;i<n;i++) I[i][i]=1; return I; }
function invert(A){
const n = A.length;
const M = A.map(row => row.slice());
const I = identity(n);
for (let col=0; col<n; col++){
let pivot = col;
for (let r=col+1;r<n;r++) if (Math.abs(M[r][col]) > Math.abs(M[pivot][col])) pivot = r;
if (Math.abs(M[pivot][col]) < 1e-12) throw new Error('Matrix not invertible');
if (pivot !== col){ [M[col], M[pivot]] = [M[pivot], M[col]]; [I[col], I[pivot]] = [I[pivot], I[col]]; }
const div = M[col][col];
for (let j=0;j<n;j++){ M[col][j] /= div; I[col][j] /= div; }
for (let r=0;r<n;r++){
if (r===col) continue;
const factor = M[r][col];
for (let j=0;j<n;j++){ M[r][j] -= factor*M[col][j]; I[r][j] -= factor*I[col][j]; }
}
}
return I;
}
function ols(y, X){
const XT = transpose(X);
const XTX = matMul(XT, X);
const XTX_inv = invert(XTX);
const XTy = matMul(XT, y);
const beta = matMul(XTX_inv, XTy);
const yhat = matMul(X, beta);
const resid = y.map((v,i)=>[v[0]-yhat[i][0]]);
const n = y.length, p = X[0].length;
const sse = resid.reduce((a,[e])=>a+e*e,0);
const sst = (()=>{ const meanY = y.reduce((a,[v])=>a+v,0)/n; return y.reduce((a,[v])=>a+(v-meanY)*(v-meanY),0); })();
const sigma2 = sse / (n - p);
const varBeta = XTX_inv.map(row=>row.map(v=>v*sigma2));
const seBeta = varBeta.map((row,i)=>Math.sqrt(row[i]));
const tVals = beta.map((b,i)=> b[0]/seBeta[i]);
const r2 = 1 - (sse/sst);
return { beta: beta.map(b=>b[0]), se: seBeta, t: tVals, r2, n, p, sse };
}
function buildDesignMatrix(selected){
const X = []; const y = [];
for (const r of cbcData){
const row = [1];
if (selected.includes('fact')) row.push(r.fact);
if (selected.includes('stars')) row.push(r.stars);
if (selected.includes('previousRating')) row.push(r.previousRating);
if (selected.includes('competition')) row.push(r.competition);
X.push(row);
y.push([r.rating]);
}
const cols = ['Intercept'].concat(selected.map(v => LABELS[v]));
return { X, y, cols };
}
// ---------- UI actions ----------
function onSubmitQ1(e){
const selected = document.querySelector('input[name="q1"]:checked');
if (!selected){ alert('Please select an answer.'); return; }
const a = ratings('stars',1), b = ratings('stars',0);
const { t, tcrit, significant } = runOneTailedTest(a,b);
const correct = significant ? 'yes' : 'no';
showFeedback('q1', selected.value === correct, t, tcrit.toFixed(3));
e.currentTarget.type='button'; e.currentTarget.disabled = true;
}
function onSubmitQ2(e){
const selected = document.querySelector('input[name="q2"]:checked');
if (!selected){ alert('Please select an answer.'); return; }
const a = ratings('fact',1), b = ratings('fact',0);
const { t, tcrit, significant } = runOneTailedTest(a,b);
const correct = significant ? 'yes' : 'no';
showFeedback('q2', selected.value === correct, t, tcrit.toFixed(3));
e.currentTarget.type='button'; e.currentTarget.disabled = true;
}
function onSubmitQ3(e){
const selected = document.querySelector('input[name="q3"]:checked');
if (!selected){ alert('Please select an answer.'); return; }
const selectedVars = ['fact','stars'];
const { X, y } = buildDesignMatrix(selectedVars);
let starsCoeff = 0, factCoeff = 0;
try {
const { beta } = ols(y, X);
factCoeff = beta[1] ?? 0;
starsCoeff = beta[2] ?? 0;
} catch(err){
const a = ratings('stars',1), b = ratings('stars',0);
starsCoeff = ss.mean(a) - ss.mean(b);
const af = ratings('fact',1), bf = ratings('fact',0);
factCoeff = ss.mean(af) - ss.mean(bf);
}
const correct = Math.abs(starsCoeff) > Math.abs(factCoeff) ? 'stars' : 'fact';
const fb = nodes.q3Feedback;
const isCorrect = selected.value === correct;
fb.innerHTML = (isCorrect
? `✅ <strong>Correct.</strong> Stars coefficient: ${starsCoeff.toFixed(3)}, Fact coefficient: ${factCoeff.toFixed(3)}`
: `⚠️ <strong>Incorrect.</strong> Stars coefficient: ${starsCoeff.toFixed(3)}, Fact coefficient: ${factCoeff.toFixed(3)}`);
fb.className = `feedback ${isCorrect ? 'correct' : 'incorrect'}`;
fb.style.display = 'block';
e.currentTarget.type='button'; e.currentTarget.disabled = true;
}
function evaluatePriorityVariable(){
const remaining = ['fact','stars','previousRating','competition'];
const removed = [];
while (remaining.length > 0){
const { X, y, cols } = buildDesignMatrix(remaining);
const fit = ols(y, X);
const df = fit.n - fit.p;
const tcrit = jStat.studentt.inv(0.975, df);
let best = null;
for (const key of remaining){
const label = LABELS[key];
const colIndex = cols.indexOf(label);
if (colIndex === -1) continue;
const coeff = fit.beta[colIndex];
const tVal = fit.t[colIndex];
if (!Number.isFinite(coeff) || !Number.isFinite(tVal)) continue;
if (!best || coeff > best.coeff){
best = { key, label, coeff, t: tVal, tcrit };
}
}
if (!best) break;
if (Math.abs(best.t) >= best.tcrit){
return { best, removed };
}
removed.push(best);
const idx = remaining.indexOf(best.key);
if (idx === -1) break;
remaining.splice(idx, 1);
}
return { best: null, removed };
}
function onSubmitQ4(e){
const selected = document.querySelector('input[name="q4"]:checked');
if (!selected){ alert('Please select an answer.'); return; }
let msg = '';
try {
const { best, removed } = evaluatePriorityVariable();
const noneValue = 'None of the factors should be prioritized, look for other factors.';
if (best){
const coeffStr = Number.isFinite(best.coeff) ? best.coeff.toFixed(3) : '—';
const absT = Number.isFinite(best.t) ? Math.abs(best.t).toFixed(2) : '—';
const tcritStr = Number.isFinite(best.tcrit) ? best.tcrit.toFixed(2) : '—';
const correctKey = best.key;
const isCorrect = selected.value === correctKey;
const removalNote = removed.length
? ` After removing ${removed.map(r => `<em>${r.label}</em> (coefficient ${Number.isFinite(r.coeff) ? r.coeff.toFixed(3) : '—'}, |t|≈${Number.isFinite(r.t) ? Math.abs(r.t).toFixed(2) : '—'} < t-critical≈${Number.isFinite(r.tcrit) ? r.tcrit.toFixed(2) : '—'})`).join(', ')} for lacking significance, the regression was rerun with the remaining variables.`
: '';
msg = isCorrect
? `✅ <strong>Correct.</strong> Following the coefficient-first check, <em>${best.label}</em> has the largest coefficient (${coeffStr}) and is significant because |t|≈${absT} exceeds t-critical≈${tcritStr}.${removalNote}`
: `⚠️ <strong>Incorrect.</strong> Following the coefficient-first check, <em>${best.label}</em> has the largest coefficient (${coeffStr}) and is significant because |t|≈${absT} exceeds t-critical≈${tcritStr}.${removalNote}`;
nodes.q4Feedback.className = `feedback ${isCorrect ? 'correct' : 'incorrect'}`;
} else {
const removalNote = removed.length
? ` Removed ${removed.map(r => `<em>${r.label}</em> (coefficient ${Number.isFinite(r.coeff) ? r.coeff.toFixed(3) : '—'}, |t|≈${Number.isFinite(r.t) ? Math.abs(r.t).toFixed(2) : '—'} < t-critical≈${Number.isFinite(r.tcrit) ? r.tcrit.toFixed(2) : '—'})`).join(', ')} during the step-down process.`
: '';
const isCorrect = selected.value === noneValue;
msg = isCorrect
? `✅ <strong>Correct.</strong> None of the variables are significant so programming strategy must target something else.${removalNote}`
: `⚠️ <strong>Incorrect.</strong> None of the variables are significant so programming strategy must target something else.${removalNote}`;
nodes.q4Feedback.className = `feedback ${isCorrect ? 'correct' : 'incorrect'}`;
}
} catch(err){
msg = '⚠️ Regression failed (matrix not invertible). Try changing selected variables or generating a new dataset.';
nodes.q4Feedback.className = 'feedback incorrect';
}
nodes.q4Feedback.innerHTML = msg;
nodes.q4Feedback.style.display = 'block';
e.currentTarget.type='button'; e.currentTarget.disabled = true;
}
function onRunTest(){
const selected = document.querySelector('input[name="comparison"]:checked').value;
let g1, g2, lab1, lab2, title;
if (selected === 'stars'){
g1 = ratings('stars',1); g2 = ratings('stars',0);
lab1='With Stars'; lab2='Without Stars'; title='Movies with Stars vs. Without Stars';
} else {
g1 = ratings('fact',1); g2 = ratings('fact',0);
lab1='Fact-based'; lab2='Fiction'; title='Fact-based vs. Fiction Movies';
}
const n1=g1.length, n2=g2.length;
const mean1=ss.mean(g1), mean2=ss.mean(g2);
const std1=ss.sampleStandardDeviation(g1), std2=ss.sampleStandardDeviation(g2);
const { t, df, tcrit } = runOneTailedTest(g1,g2);
nodes.hypoResults.innerHTML = `
<div class="hypothesis-section">
<h2>One-Tailed T-Test: ${title}</h2>
<table>
<thead><tr><th>Group</th><th>Size</th><th>Mean</th><th>Std Dev (sample)</th></tr></thead>
<tbody>
<tr><td>${lab1}</td><td class="numeric">${n1}</td><td class="numeric">${mean1.toFixed(3)}</td><td class="numeric">${std1.toFixed(3)}</td></tr>
<tr><td>${lab2}</td><td class="numeric">${n2}</td><td class="numeric">${mean2.toFixed(3)}</td><td class="numeric">${std2.toFixed(3)}</td></tr>
</tbody>
</table>
<table>
<thead><tr><th>Statistic</th><th>Value</th></tr></thead>
<tbody>
<tr><td>Degrees of Freedom</td><td class="numeric">${df}</td></tr>
<tr><td>T-Statistic</td><td class="numeric">${t.toFixed(4)}</td></tr>
<tr><td>T-Critical (95%, one-tailed)</td><td class="numeric">${tcrit.toFixed(3)}</td></tr>
</tbody>
</table>
</div>`;
nodes.hypoResults.style.display = 'block';
}
// Format p-values in standard notation with ~3 significant digits (no scientific notation)
function formatP(p, sig = 3) {
if (!isFinite(p)) return '—';
p = Math.max(0, Math.min(1, p)); // clamp to [0,1]
if (p === 0) return '0.' + '0'.repeat(sig); // e.g., "0.000"
const magnitude = Math.floor(Math.log10(p)); // negative for 0<p<1
const decimals = Math.max(0, sig - 1 - magnitude);
return p.toFixed(Math.min(12, decimals)); // cap decimals to avoid super long strings
}
function onRunRegression(){
const selected = getSelected();
if (selected.length === 0){ alert('Select at least one variable.'); return; }
const { X, y, cols } = buildDesignMatrix(selected);
try{
const fit = ols(y, X);
const df = fit.n - fit.p; // for coefficient t-stats
const tcritTwoTailed95 = jStat.studentt.inv(0.975, df); // precise critical value via jStat
const rows = cols.map((name, i)=>{
const t = fit.t[i];
const p = 2 * (1 - jStat.studentt.cdf(Math.abs(t), df)); // two-tailed p-value
const pStr = formatP(p, 3); // standard notation, ~3 sig figs
return `
<tr>
<td>${name}</td>
<td class="numeric">${fit.beta[i].toFixed(3)}</td>
<td class="numeric">${fit.se[i].toFixed(3)}</td>
<td class="numeric">${t.toFixed(2)}</td>
<td class="numeric">${pStr}</td>
</tr>`;
}).join('');
nodes.results.innerHTML = `
<div class="analysis-section">
<h2>Regression Analysis Results</h2>
<table>
<thead><tr><th>Statistic</th><th>Value</th></tr></thead>
<tbody>
<tr><td>Observations</td><td class="numeric">${fit.n}</td></tr>
<tr><td>Variables (incl. intercept)</td><td class="numeric">${fit.p}</td></tr>
<tr><td>Degrees of Freedom</td><td class="numeric">${df}</td></tr>
<tr><td>R-Squared</td><td class="numeric">${fit.r2.toFixed(3)}</td></tr>
<tr><td>T-Critical (95%, two-tailed)</td><td class="numeric">${tcritTwoTailed95.toFixed(3)}</td></tr>
<tr><td>Assumptions</td><td>OLS, standard errors from σ²(X'X)<sup>-1</sup>; p-values via Student's t CDF (jStat)</td></tr>
</tbody>
</table>
<table>
<thead><tr><th>Variable</th><th>Coefficient</th><th>Std. Error</th><th>T-Value</th><th>P-Value</th></tr></thead>
<tbody>${rows}</tbody>
</table>
</div>`;
nodes.results.style.display = 'block';
} catch(err){
nodes.results.innerHTML = `<div class="analysis-section"><h2>Regression Analysis Results</h2>
<div class="feedback incorrect" style="display:block;">⚠️ Regression failed (matrix not invertible). Try different variable selection or generate a new dataset.</div></div>`;
nodes.results.style.display = 'block';
}
}
function toggleDataDisplay(){
const toggleButton = document.getElementById('btnToggle');
const showing = !nodes.dataDisplay.hasAttribute('hidden');
if (showing){
nodes.dataDisplay.setAttribute('hidden','');
nodes.dataToggleText.textContent = 'Show Data';
toggleButton.setAttribute('aria-expanded','false');
} else {
updateDataDisplay();
nodes.dataDisplay.removeAttribute('hidden');
setTimeout(() => nodes.dataDisplay.focus(), 0);
nodes.dataToggleText.textContent = 'Hide Data';
toggleButton.setAttribute('aria-expanded','true');
}
}
// ---------- Init ----------
document.addEventListener('DOMContentLoaded', () => {
// Checkbox info announcer
$$('input[type="checkbox"]').forEach(cb => cb.addEventListener('change', updateInfo));
updateInfo();
updateDataDisplay();
updateTopStats();
document.getElementById('btnNew').addEventListener('click', generateNewDataset);
document.getElementById('btnToggle').addEventListener('click', toggleDataDisplay);
document.getElementById('btnCSV').addEventListener('click', downloadCSV);
document.getElementById('submitQ1').addEventListener('click', onSubmitQ1);
document.getElementById('submitQ2').addEventListener('click', onSubmitQ2);
document.getElementById('submitQ3').addEventListener('click', onSubmitQ3);
document.getElementById('submitQ4').addEventListener('click', onSubmitQ4);
document.getElementById('runTest').addEventListener('click', onRunTest);
document.getElementById('runRegression').addEventListener('click', onRunRegression);
document.getElementById('tab-case').addEventListener('click', (e)=>showTab(e.currentTarget,'case-questions'));
document.getElementById('tab-ab').addEventListener('click', (e)=>showTab(e.currentTarget,'ab-comparisons'));
document.getElementById('tab-impact').addEventListener('click', (e)=>showTab(e.currentTarget,'impact-analysis'));
// Keyboard navigation for tabs
document.getElementById('tabs').addEventListener('keydown', onTabKeydown);
// Set initial aria-expanded for data toggle
document.getElementById('btnToggle').setAttribute('aria-expanded','false');
announceDataset(`Loaded original dataset with ${cbcData.length} observations. Use the controls above to review or download the data.`);
});
</script>
</body>
</html>