-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
1873 lines (1603 loc) · 69.3 KB
/
Copy pathapp.js
File metadata and controls
1873 lines (1603 loc) · 69.3 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
/* Load data.xml and build a simple viewer (sections/pages + images).
Works as static site (S3). */
const MODULES = [
// LEVEL I - Growth and Development
// Unit A - Concepts of Physical Growth and Development
{name: "The Study of Physical Growth", id: "studyphysgrowth", level: 1, unit: "A",description:"Timing and variability in growth, as revealed by measurement techniques and experimental studies."},
{name: "The Nature of Craniofacial Growth", id: "naturecfgrowth", level: 1, unit: "A",description:"Overview of embryologic development of the head and face; sites and types of growth in the cranial vault, cranial base, maxilla and mandible."},
{name: "Theories of Craniofacial Growth", id: "theoriescfgrowth", level: 1, unit: "A",description:"Growth theories (Sicher, Scott and Moss) in the context of growth sites, centers, types, mechanism and determinant."},
// Unit B - Early Stages of Development
{name: "Growth and Development During the Preschool Years", id: "preschoolgrowth", level: 1, unit: "B",description:"Physical growth and physiologic development from infancy through the primary dentition."},
{name: "Primary Tooth Eruption and Exfoliation", id: "primarytootheruption", level: 1, unit: "B",description:"The timing of eruption of primary teeth and the pattern of resorption as permanent teeth replace them."},
{name: "The Development of Occlusion in the Primary and Transitional Dentition", id: "primaryocclusaldev", level: 1, unit: "B",description:"Primary molar relationships and the transition in permanent molar relationships as the primary molars are lost, and the importance and fate of spaces in the primary dentition."},
// Unit C - Eruption of the Permanent Teeth and Late Stages of Development
{name: "Eruption of Permanent Teeth", id: "eruptionpermteeth", level: 1, unit: "C",description:"The timing and sequence of eruption of the permanent teeth, and the changes in arch dimensions as this occurs."},
{name: "Process of Tooth Eruption", id: "processtootheruption", level: 1, unit: "C",description:"The process of tooth eruption, and the control of eruption prior to emergence of a tooth and after it enters the oral cavity, using the results of recent human studies."},
{name: "Physical Growth at Adolescence", id: "physgrowthadolescence", level: 1, unit: "C",description:"The hormonal control of adolescent growth, the way sexual development relates to growth of the face and jaws, and the methods of determining growth status."},
{name: "Patterns of Facial Growth", id: "patternsfacialgrowth", level: 1, unit: "C",description:"The concept of growth pattern, jaw rotations as viewed with implant superimpositions and the differences in growth for children with Class II /III and short / long face growth."},
{name: "Maturational Changes", id: "maturationalchanges", level: 1, unit: "C",description:"The decline of growth to slow adult levels at different times for different planes of space, the relationship of late incisor crowding to mandibular growth, and decreasing pulp chambers and tooth wear with aging."},
// Unit D - Psychosocial Growth and Development
{name: "Psychosocial Development", id: "psychosocialdev", level: 1, unit: "D",description:"A discussion of stages in psychosocial development from the perspective of classical and operant conditioning and observational learning, stages of emotional and cognitive development, and their use in communicating with child patients and parents."},
// LEVEL II - Growth and Development
// Unit A - The Nature of Orthodontic Problems
{name: "Malocclusion: Definition and Prevalence", id: "malocclusion", level: 2, unit: "A",description:"Data from the NHANES-III study are used to evaluate types of malocclusion in the United States and the differences in modern American population groups."},
{name: "Known Causes of Malocclusion", id: "malocclusioncauses", level: 2, unit: "A",description:"Types of malocclusion with known causes: fetal molding and birth injuries, syndromes, trauma, disturbances of dental development, genetic influences."},
{name: "Equilibrium Theory and the Etiology of Malocclusion", id: "equilibrium", level: 2, unit: "A",description:"A review of the way in which environmental influences affect jaw relationships and dental occlusion."},
// Unit B - Diagnostic Procedures
{name: "Facial Form Analysis", id: "facialform", level: 2, unit: "B",description:"Evaluating jaw relationships and tooth-lip relationships during clinical examination of a child."},
{name: "Cephalometric Tracing Techniques", id: "cephanalysis", level: 2, unit: "B",description:"How to locate cephalometric landmarks and use them in constructing an accurate cephalometric tracing."},
{name: "Cephalometric Superimposition", id: "cephsuper", level: 2, unit: "B",description:"How to use cranial base, maxillary and mandibular superimpositions to evaluate changes due to growth and/or treatment."},
{name: "Space Analysis and Its Interpretation", id: "spaceanalysis", level: 2, unit: "B",description:"The assumptions that underlie space analysis, the method of using it, and its interpretation in the light of expected changes in dental relationships."},
{name: "Ackerman-Proffit Classification", id: "ackermanproffit", level: 2, unit: "B",description:"A systematic approach to detecting significant deviations from normal jaw and dental relationships, based on the five characteristics of malocclusion."},
// LEVEL III - Biomechanics and Preclinical Orthodontics
// Unit A
{name: "Essentials of Orthodontic Diagnosis", id: "essentialsdx", level: 3, unit: "A",description:"Using systematic description to develop a problem list for individual patients."},
{name: "Concepts of Orthodontic Treatment Planning", id: "conceptstxplan", level: 3, unit: "A",description:"The triage approach to determining the complexity of treatment for orthodontic problems."},
{name: "Biologic Response to Orthodontic Force", id: "biologyorthotx", level: 3, unit: "A",description:"The nature and sequence of events when light vs. heavy pressure is applied to a tooth to induceremodeling of alveolar bone and tooth movement."},
{name: "Mechanical Principles in Controlling Orthodontic Force", id: "controlorthoforce", level: 3, unit: "A",description:"Effects of archwire material, size and beam length; design considerations in contemporary removable and fixed appliances."},
{name: "Orthodontic Anchorage and Controlled Tooth Movement", id: "anchorage", level: 3, unit: "A",description:"Orthodontic anchorage considerations in producing different types of tooth movement."},
// Unit B
{name: "Space Management in Preadolescent Children", id: "spacemgt", level: 3, unit: "B",description:"Interpreting results of mixed dentition space analysis in planning space maintenance, space regaining, space management for mild / moderate crowding, and serial extraction."},
{name: "Crossbites & Vertical Problems in Children", id: "transversevertical", level: 3, unit: "B",description:"Skeletal vs. dental considerations in treatment of anterior crossbite, posterior crossbite, deep bite and open bite."},
{name: "Concepts of Adjunctive Orthodontic Treatment", id: "adjunctconcepts", level: 3, unit: "B",description:"Diagnosis, treatment planning and biomechanical considerations in adjunctive treatment of adults with perio / restorative / other treatment needs."},
{name: "Adjunctive Orthodontic Treatment Procedures", id: "adjunctprocedures", level: 3, unit: "B",description:"Molar uprighting, posterior crossbite correction, forced eruption and incisor alignment in adjunctive treatment."},
// LEVEL IV - Advanced Orthodontics
// Unit A - Orthodontic Treatment Concepts
{name: "Why Do We Do Orthodontics?", id: "whyortho", level: 4, unit: "A",description:"Effects of malocclusion on health, function and psychosocial well-being are reasons for orthodontic treatment."},
{name: "To Extract or Not To Extract, Part 1: Class I Crowding/Protrusion", id: "extract1", level: 4, unit: "A",description:"For crowding and protrusion of incisors, esthetics and stability determine the decision to expand the dental arches vs. reducing tooth mass or number."},
// Unit B - Complex Treatment
{name: "To Extract or Not To Extract, Part 2: Camouflage?", id: "extract2", level: 4, unit: "B",description:"Camouflage (reducing or increasing incisor prominence) vs. surgery in treatment of Class II and Class III problems."},
{name: "Special Considerations In Orthodontics for Adults", id: "adultortho", level: 4, unit: "B",description:"Adults differ from children and adolescents in motivation for orthodontic treatment, periodontal considerations, patient management and use of adjunctive procedures."},
{name: "Complex Adjunctive Treatment", id: "complexadjuncttx", level: 4, unit: "B",description:"A discussion of interactions among specialists in sequencing and carrying out complex treatment for adults with multiple types of dental problems."},
{name: "Orthodontic Retention", id: "retention", level: 4, unit: "B",description:"The reasons for retention: PDL reorganization, gingival fiber effects, and equilibrium changes due to growth."},
// Unit C - Treatment Timing in Complex Problems
{name: "Indications for Orthognathic Surgery", id: "indicationssurgery", level: 4, unit: "C",description:"Orthognathic surgical procedures and the indications for their use in terms of the severity of jaw discrepancies and the limitations of orthodontic camouflage."},
{name: "Orthodontic Management of Patients with Cleft Lip and Palate", id: "clefttx", level: 4, unit: "C",description:"The sequence of care and types of treatment at appropriate ages for cleft lip / palate patients."},
{name: "The Best Time For Orthodontic Treatment", id: "txtiming", level: 4, unit: "C",description:"Considerations in treatment timing and current knowledge about the preferred time for treatment of Class I, II and III problems."},
// Unit D - Professional Interactions
{name: "Interaction with Orthodontists", id: "orthointeract", level: 4, unit: "D",description:"A discussion of what you, the family dentist, should expect from the orthodontist and what he or she should expect from you in referral interactions and coordination of orthodontics with other dental treatment."},
{name: "Meet Your New Young Patient", id: "youngpatient", level: 4, unit: "D",description:"Video of an interview with mother and potential patient daughter, to discuss orthodontic aspects of her treatment plan."},
{name: "Accelerated Tooth Movement?", id: "acceltoothmovement", level: 4, unit: "D",description:"An overview of possible ways to manipulate the biology of tooth movement and reduce treatment time."}
];
function textContentSafe(node){
return node ? (node.textContent || "").trim() : "";
}
function resolveImagePath(path, moduleId){
// XML paths look like: acceltoothmovement/images/xxx.jpg
// In your ZIP, images are in ./images/xxx.jpg
if(!path) return "";
const file = path.split("/").pop();
return `Modules/${moduleId}/images/${file}`;
}
function resolveVideoPath(path, moduleId){
// XML paths look like: youngpatient/video/entering.mp4
if(!path) return "";
const file = path.split("/").pop();
return `Modules/${moduleId}/video/${file}`;
}
function extractRichText(pageTextEl){
// Keep basic formatting from the XML fragments (p, ul, ol, li, etc.)
if(!pageTextEl) return "";
// Build HTML from children by serializing
const parts = [];
for(const child of pageTextEl.childNodes){
if(child.nodeType === Node.ELEMENT_NODE){
parts.push(child.outerHTML);
}else if(child.nodeType === Node.TEXT_NODE){
const t = child.textContent.trim();
if(t) parts.push(`<p>${t}</p>`);
}
}
return parts.join("\n");
}
function buildModel(xml, moduleId){
const pres = xml.querySelector("presentation");
const title = textContentSafe(pres.querySelector(":scope > title"));
const subtitle = textContentSafe(pres.querySelector(":scope > subtitle"));
const sections = [];
const sectionEls = pres.querySelectorAll("sections > section");
sectionEls.forEach((secEl, sIdx) => {
const secTitle = textContentSafe(secEl.querySelector(":scope > title")) || `Section ${sIdx+1}`;
const pages = [];
secEl.querySelectorAll(":scope > pages > page").forEach((pageEl, pIdx) => {
const pageTitle = textContentSafe(pageEl.querySelector(":scope > title")) || `Page ${pIdx+1}`;
const pageType = pageEl.getAttribute("pageType") || "content";
const pageTextEl = pageEl.querySelector(":scope > pageText");
const bodyHtml = extractRichText(pageTextEl);
const resources = [];
pageEl.querySelectorAll(":scope > resources > resource").forEach((resEl) => {
const type = resEl.getAttribute("resourceType") || "";
if(type !== "image" && type !== "video") return;
const loc = resEl.getAttribute("resourceLocation") || "";
const thumb = resEl.getAttribute("thumbnailLocation") || "";
const label = textContentSafe(resEl.querySelector(":scope > label"));
// caption can contain <p> etc.
const capEl = resEl.querySelector(":scope > caption");
const caption = capEl ? capEl.innerHTML.trim() : "";
if(type === "video") {
resources.push({
type,
src: resolveVideoPath(loc, moduleId),
thumb: resolveImagePath(thumb, moduleId),
label,
caption
});
} else {
resources.push({
type,
src: resolveImagePath(loc, moduleId),
thumb: resolveImagePath(thumb, moduleId) || resolveImagePath(loc, moduleId),
label,
caption
});
}
});
// Parse test choices if it's a test page
let testData = null;
if(pageType === "test"){
const choicesEl = pageEl.querySelector(":scope > choices");
if(choicesEl){
const correctChoiceIdx = parseInt(choicesEl.getAttribute("correctChoice") || "1") - 1;
const choices = [];
choicesEl.querySelectorAll(":scope > choice").forEach((choiceEl, cIdx) => {
choices.push({
text: textContentSafe(choiceEl),
isCorrect: cIdx === correctChoiceIdx
});
});
const correctResponseEl = pageEl.querySelector(":scope > correctResponse");
const incorrectResponseEl = pageEl.querySelector(":scope > incorrectResponse");
testData = {
choices,
correctResponse: correctResponseEl ? correctResponseEl.innerHTML.trim() : "",
incorrectResponse: incorrectResponseEl ? incorrectResponseEl.innerHTML.trim() : ""
};
}
}
// A page is a test if pageType attribute is "test"
const isActualTest = pageType === "test";
pages.push({
id: `${sIdx}-${pIdx}`,
sectionIndex: sIdx,
pageIndex: pIdx,
title: pageTitle,
bodyHtml,
resources,
pageType: isActualTest ? "test" : "content",
testData
});
});
sections.push({
title: secTitle,
index: sIdx,
pages
});
});
return { title, subtitle, sections };
}
function flattenPages(model){
const all = [];
model.sections.forEach(sec => sec.pages.forEach(p => all.push(p)));
return all;
}
function areAllPagesInSectionViewed(sectionIndex){
// Check if all non-test pages in the ENTIRE MODULE have been viewed
// (not just in this section, since tests might be in different sections)
const nonTestPages = PAGES.filter(p => p.pageType !== "test");
// If there are no non-test pages, test pages should NOT be locked
if(nonTestPages.length === 0) return false;
// If there are non-test pages, check if all have been viewed
return nonTestPages.every(p => VIEWED_PAGES.has(p.id));
}
function renderTOC(model){
const toc = document.getElementById("moduleTocDesktop");
if(!toc) {
console.warn("TOC element not found");
return;
}
toc.innerHTML = "";
model.sections.forEach((sec) => {
const wrapper = document.createElement("div");
wrapper.className = "section";
const btn = document.createElement("button");
btn.type = "button";
btn.innerHTML = `<span>${sec.title}</span><span class="section-count">${sec.pages.length} page(s)</span>`;
btn.addEventListener("click", () => wrapper.classList.toggle("open"));
wrapper.appendChild(btn);
const pagesDiv = document.createElement("div");
pagesDiv.className = "pages";
sec.pages.forEach((p) => {
const b = document.createElement("button");
b.type = "button";
b.className = "page-link";
b.dataset.pageId = p.id;
// Add lock icon for test pages that require viewing all other pages first
let lockIcon = "";
if(p.pageType === "test"){
lockIcon = ' <span class="lock-icon">🔒</span>';
}
b.innerHTML = `<span class="idx">${String(p.pageIndex+1).padStart(2,"0")}</span><span class="ttl">${p.title}</span>${lockIcon}`;
// Apply styles based on saved progress
// Only mark non-test pages as "viewed" with green indicator
if(VIEWED_PAGES.has(p.id) && p.pageType !== "test"){
b.classList.add("viewed");
}
if(TEST_RESULTS.has(p.id)){
const result = TEST_RESULTS.get(p.id);
if(result === "correct"){
b.classList.add("test-correct");
// Remove lock icon if test is answered
const lockIcon = b.querySelector(".lock-icon");
if(lockIcon) lockIcon.remove();
} else if(result === "incorrect"){
b.classList.add("test-incorrect");
}
}
// Disable test pages until all other pages in section are viewed
if(p.pageType === "test"){
b.classList.add("test-page");
// Always allow access to test pages (no restriction)
b.addEventListener("click", () => selectPage(p.id, {scroll:true}));
// Remove lock icon for test pages
const lockEl = b.querySelector(".lock-icon");
if(lockEl) lockEl.remove();
} else {
// Normal click for non-test pages
b.addEventListener("click", () => selectPage(p.id, {scroll:true}));
}
pagesDiv.appendChild(b);
});
wrapper.appendChild(pagesDiv);
toc.appendChild(wrapper);
});
// Don't open first section by default - let user click to open
}
function setActiveLink(pageId){
document.querySelectorAll(".page-link").forEach(el => {
el.classList.toggle("active", el.dataset.pageId === pageId);
});
// Mark as viewed
VIEWED_PAGES.add(pageId);
// Update the page link to show it's been viewed (but NOT for test pages)
const currentLink = document.querySelector(`[data-page-id="${pageId}"]`);
const currentPage = PAGE_BY_ID.get(pageId);
if(currentLink && currentPage && currentPage.pageType !== "test"){
currentLink.classList.add("viewed");
}
// Find and open the section that contains this page
const page = PAGE_BY_ID.get(pageId);
if(page){
const sectionIndex = page.sectionIndex;
const sections = document.querySelectorAll(".section");
if(sections[sectionIndex]){
sections[sectionIndex].classList.add("open");
}
// Check if all pages in this section are now viewed, and enable test pages if so
if(areAllPagesInSectionViewed(sectionIndex)){
console.log(`All non-test pages viewed! Unlocking all tests...`);
// Find all test pages in the ENTIRE module
const testPageIds = [];
PAGES.forEach(p => {
if(p.pageType === "test"){
testPageIds.push(p.id);
}
});
console.log(`Found ${testPageIds.length} test pages to unlock: ${testPageIds.join(", ")}`);
// Now update each one
testPageIds.forEach(testPageId => {
const link = document.querySelector(`[data-page-id="${testPageId}"]`);
if(link){
console.log(`Found link for test page ${testPageId}, updating it...`);
link.disabled = false;
link.classList.remove("disabled-test");
// Remove the lock icon
const lockIcon = link.querySelector(".lock-icon");
if(lockIcon){
console.log(`Removing lock icon from ${testPageId}`);
lockIcon.remove();
}
// Replace the click handler - remove old one and add new one
const newLink = link.cloneNode(true);
newLink.addEventListener("click", () => {
console.log(`Clicking unlocked test page ${testPageId}`);
selectPage(testPageId, {scroll:true});
});
link.parentNode.replaceChild(newLink, link);
console.log(`Replaced click handler for ${testPageId}`);
} else {
console.log(`Could not find link for test page ${testPageId}`);
}
});
} else {
console.log(`Not all pages viewed yet`);
}
}
}
function updateTestPageLink(pageId, result){
// Update the page link in the sidebar to show test result (correct=green, incorrect=red)
const link = document.querySelector(`[data-page-id="${pageId}"]`);
if(link){
if(result === "correct"){
link.classList.remove("test-incorrect");
link.classList.add("test-correct");
} else if(result === "incorrect"){
link.classList.remove("test-correct");
link.classList.add("test-incorrect");
}
}
// Save progress after test answer
saveModuleProgress();
}
function renderPage(pageData){
document.getElementById("pageTitle").textContent = pageData.title;
const pageBody = document.getElementById("pageBody");
// Check if this is a test page
if(pageData.pageType === "test" && pageData.testData){
// Check if this test has already been answered
const previousResult = TEST_RESULTS.get(pageData.id);
if(previousResult){
// Test already answered, show the result again
pageBody.innerHTML = `
<div class="test-question">
${pageData.bodyHtml}
<div class="test-choices">
${pageData.testData.choices.map((choice, idx) => `
<button class="test-choice" data-choice-idx="${idx}" disabled ${choice.isCorrect ? 'data-correct="true"' : ''}>
${choice.text}
</button>
`).join('')}
</div>
<div class="test-feedback" id="testFeedback"></div>
</div>
`;
// Show the previous result
const feedbackDiv = document.getElementById("testFeedback");
if(previousResult === "correct"){
feedbackDiv.innerHTML = `
<div class="feedback correct">
<strong>✓ Correct!</strong>
<div>${pageData.testData.correctResponse}</div>
</div>
`;
const correctBtn = pageBody.querySelector('[data-correct="true"]');
if(correctBtn) correctBtn.classList.add("correct");
} else {
feedbackDiv.innerHTML = `
<div class="feedback incorrect">
<strong>✗ Incorrect</strong>
<div>${pageData.testData.incorrectResponse}</div>
</div>
`;
}
// Disable all buttons
pageBody.querySelectorAll(".test-choice").forEach(b => {
b.disabled = true;
});
} else {
// Test not yet answered, show interactive buttons
pageBody.innerHTML = `
<div class="test-question">
${pageData.bodyHtml}
<div class="test-choices">
${pageData.testData.choices.map((choice, idx) => `
<button class="test-choice" data-choice-idx="${idx}">
${choice.text}
</button>
`).join('')}
</div>
<div class="test-feedback" id="testFeedback"></div>
</div>
`;
// Add event listeners to choices
pageBody.querySelectorAll(".test-choice").forEach((btn, idx) => {
btn.addEventListener("click", () => {
const choice = pageData.testData.choices[idx];
const feedbackDiv = document.getElementById("testFeedback");
if(choice.isCorrect){
feedbackDiv.innerHTML = `
<div class="feedback correct">
<strong>✓ Correct!</strong>
<div>${pageData.testData.correctResponse}</div>
</div>
`;
btn.classList.add("correct");
// Save result as correct
TEST_RESULTS.set(pageData.id, "correct");
// Update the page link in sidebar to show green
updateTestPageLink(pageData.id, "correct");
} else {
feedbackDiv.innerHTML = `
<div class="feedback incorrect">
<strong>✗ Incorrect</strong>
<div>${pageData.testData.incorrectResponse}</div>
</div>
<div class="feedback correct-answer">
<strong>The correct answer was:</strong>
<div>${pageData.testData.choices.find(c => c.isCorrect).text}</div>
</div>
`;
btn.classList.add("incorrect");
// Mark correct answer button
const correctBtn = pageBody.querySelector('[data-correct="true"]');
if(correctBtn) correctBtn.classList.add("correct");
// Save result as incorrect
TEST_RESULTS.set(pageData.id, "incorrect");
// Update the page link in sidebar to show red
updateTestPageLink(pageData.id, "incorrect");
}
// Disable all choices after answering
pageBody.querySelectorAll(".test-choice").forEach(b => {
b.disabled = true;
});
});
});
}
} else {
// Regular content page
pageBody.innerHTML = pageData.bodyHtml || "<p>(No content)</p>";
}
const media = document.getElementById("pageMedia");
media.innerHTML = "";
pageData.resources.forEach((r, idx) => {
const card = document.createElement("div");
card.className = "thumb";
if(r.type === "video") {
// Video resource - show thumbnail with play overlay
if(r.thumb) {
const img = document.createElement("img");
img.src = r.thumb;
img.alt = (r.label || ("Video " + (idx+1)));
img.loading = "lazy";
img.onerror = function(){
// If thumbnail fails, show a generic video placeholder
img.style.display = "none";
};
card.appendChild(img);
}
// Play button overlay
const playOverlay = document.createElement("div");
playOverlay.className = "thumb-play-overlay";
playOverlay.innerHTML = "▶";
card.appendChild(playOverlay);
const label = document.createElement("div");
label.className = "label";
label.textContent = r.label || ("Video " + (idx+1));
card.appendChild(label);
card.addEventListener("click", () => openVideoModal(r.src, r.caption || r.label || ""));
} else {
// Image resource
const img = document.createElement("img");
img.src = r.thumb;
img.alt = (r.label || ("Image " + (idx+1)));
img.loading = "lazy";
img.onerror = function(){ card.style.display = "none"; };
const label = document.createElement("div");
label.className = "label";
label.textContent = r.label || ("Image " + (idx+1));
card.appendChild(img);
card.appendChild(label);
card.addEventListener("click", () => openModal(r.src, r.caption || r.label || ""));
}
media.appendChild(card);
});
if(pageData.resources.length === 0){
media.innerHTML = "";
}
// Add navigation buttons at the end
let pageNavigation = document.getElementById("pageNavigation");
if(!pageNavigation){
// Create it if it doesn't exist
const page = document.getElementById("page");
pageNavigation = document.createElement("div");
pageNavigation.id = "pageNavigation";
page.appendChild(pageNavigation);
}
pageNavigation.innerHTML = `
<div class="page-navigation">
<button id="prevBtn" class="nav-btn nav-prev">← Previous</button>
<span id="pageProgress" class="page-progress">Page 1/1</span>
<button id="nextBtn" class="nav-btn nav-next">Next →</button>
</div>
`;
document.getElementById("prevBtn").addEventListener("click", prevPage);
document.getElementById("nextBtn").addEventListener("click", nextPage);
updateNavigationButtons();
updatePageProgress();
}
function renderHomeModule(moduleInfo){
const page = document.getElementById("page");
page.innerHTML = `
<div class="page-title">${moduleInfo.name}</div>
<div class="page-body" style="padding: 20px;">
<p>Module loaded. Use the table of contents on the left to navigate.</p>
</div>
`;
}
async function getModuleStats(moduleId){
// Get stats from saved progress
const saved = localStorage.getItem(`module_${moduleId}`);
// Get total non-test pages and test page IDs from XML
// Only count pages with actual test choices as "tests"
let totalNonTestPages = 0;
const testPageIds = new Set();
try {
const res = await fetch(`Modules/${moduleId}/data.xml`, {cache:"no-store"});
if(res.ok){
const xmlText = await res.text();
const xml = new DOMParser().parseFromString(xmlText, "application/xml");
// Count pages based on whether they have choices
let sectionIndex = 0;
xml.querySelectorAll("sections > section").forEach(secEl => {
let pageIndex = 0;
secEl.querySelectorAll(":scope > pages > page").forEach(pageEl => {
const pageId = `${sectionIndex}-${pageIndex}`;
const pageType = pageEl.getAttribute("pageType") || "content";
// Only treat as test if it's marked as test AND has choices
if(pageType === "test"){
const choicesEl = pageEl.querySelector(":scope > choices");
if(choicesEl){
testPageIds.add(pageId);
} else {
// No choices = treat as regular content
totalNonTestPages++;
}
} else {
totalNonTestPages++;
}
pageIndex++;
});
sectionIndex++;
});
}
} catch(e) {
console.error("Error loading module stats:", e);
}
if(!saved) return {
viewedCount: 0,
totalNonTestPages,
correctTests: 0,
totalTests: 0,
score: 0
};
const progress = JSON.parse(saved);
// Count only non-test pages in viewed pages
const viewedNonTestPages = progress.viewedPages.filter(pageId => {
// Only count if it's NOT a test page (doesn't have choices)
return !testPageIds.has(pageId);
}).length;
const testResults = Object.entries(progress.testResults || {});
const correctTests = testResults.filter(([_, result]) => result === "correct").length;
const totalTests = testResults.length;
const score = totalTests > 0 ? Math.round((correctTests / totalTests) * 100) : 0;
return {
viewedCount: viewedNonTestPages,
totalNonTestPages,
correctTests,
totalTests,
score
};
}
async function renderHomePage(){
const sidebar = document.getElementById("sidebar");
const layout = document.querySelector(".layout");
const content = document.getElementById("content");
const page = document.getElementById("page");
const toc = document.getElementById("toc");
// Show sidebar on home page for level navigation (if it exists)
if(sidebar) sidebar.style.display = "block";
layout.classList.add("home-view");
// Make content adjust to sidebar
if(content) content.style.maxWidth = "100%";
// Change menu titles to "Modules" on home page
const sidebarTitle = document.querySelector(".sidebar-title");
if(sidebarTitle) sidebarTitle.textContent = "Modules";
const levelsMenuToggle = document.getElementById("levelsMenuToggle");
if(levelsMenuToggle) levelsMenuToggle.textContent = "Modules";
// Group modules by Level and Unit
const grouped = {};
MODULES.forEach(mod => {
if (!grouped[mod.level]) grouped[mod.level] = {};
if (!grouped[mod.level][mod.unit]) grouped[mod.level][mod.unit] = [];
grouped[mod.level][mod.unit].push(mod);
});
// Build HTML structure by Level and Unit
let levelsHtml = "";
for(let level = 1; level <= 4; level++){
if(!grouped[level]) continue;
const levelUnits = grouped[level];
const unitKeys = Object.keys(levelUnits).sort();
let unitsHtml = "";
unitKeys.forEach(unit => {
const mods = levelUnits[unit];
let moduleCardsHtml = mods.map(mod => `
<button class="module-card" data-module-id="${mod.id}" data-module-name="${mod.name.toLowerCase()}">
<div class="module-card-inner">
<div class="module-name">${mod.name}</div>
<div class="module-description">${mod.description}</div>
<div class="module-stats-placeholder">Loading...</div>
</div>
</button>
`).join('');
unitsHtml += `
<div class="unit-group">
<div class="unit-header">Unit ${unit}</div>
<div class="unit-modules">
${moduleCardsHtml}
</div>
</div>
`;
});
levelsHtml += `
<div class="level-section">
<div class="level-header">Level ${level}</div>
<div class="level-units">
${unitsHtml}
</div>
</div>
`;
}
// Render home page with hierarchical structure
page.innerHTML = `
<div class="modules-hierarchy" id="modulesHierarchy">
${levelsHtml}
</div>
`;
// Add home-page class to remove constraining styles
page.classList.add("home-page");
// Add click handlers to module cards
document.querySelectorAll(".module-card").forEach(btn => {
btn.addEventListener("click", () => {
const moduleId = btn.dataset.moduleId;
loadModule(moduleId);
});
});
// Setup search functionality using the topbar search
const search = document.getElementById("search");
search.value = ""; // Clear search
// Remove old search handler if exists
if(window._homeSearchHandler){
search.removeEventListener("input", window._homeSearchHandler);
}
// Add new search handler for home page
window._homeSearchHandler = (e) => {
const query = e.target.value.toLowerCase().trim();
const cards = document.querySelectorAll(".module-card");
const levelSections = document.querySelectorAll(".level-section");
const unitGroups = document.querySelectorAll(".unit-group");
// Hide/show cards based on search
cards.forEach(card => {
const moduleName = card.dataset.moduleName;
if(query === "" || moduleName.includes(query)){
card.style.display = "";
} else {
card.style.display = "none";
}
});
// Show/hide unit groups if they have visible cards
unitGroups.forEach(unit => {
const visibleCards = Array.from(unit.querySelectorAll(".module-card"))
.filter(card => card.style.display !== "none");
unit.style.display = visibleCards.length > 0 ? "" : "none";
});
// Show/hide level sections if they have visible units
levelSections.forEach(level => {
const visibleUnits = Array.from(level.querySelectorAll(".unit-group"))
.filter(unit => unit.style.display !== "none");
level.style.display = visibleUnits.length > 0 ? "" : "none";
});
};
search.addEventListener("input", window._homeSearchHandler);
// Load stats for each module asynchronously
for(const mod of MODULES){
const stats = await getModuleStats(mod.id);
const card = document.querySelector(`[data-module-id="${mod.id}"]`);
if(card){
const hasProgress = stats.viewedCount > 0 || stats.totalTests > 0;
if(hasProgress){
card.classList.add("in-progress");
}
let statsHtml = "";
// Always show pages count, tests if they exist
statsHtml = `
<div class="module-stats">
${stats.totalNonTestPages > 0 ? `<span class="stat-item">📖 ${stats.viewedCount}/${stats.totalNonTestPages} pages</span>` : ""}
${stats.totalTests > 0 ? `
<span class="stat-item ${stats.correctTests === stats.totalTests ? 'completed' : 'in-progress'}">
✓ ${stats.correctTests}/${stats.totalTests} tests
</span>
` : ""}
</div>
`;
const placeholder = card.querySelector(".module-stats-placeholder");
if(placeholder){
placeholder.outerHTML = statsHtml || "";
}
}
}
}
let MODEL = null;
let PAGES = [];
let PAGE_BY_ID = new Map();
let CURRENT_PAGE_ID = null;
let CURRENT_MODULE = null;
let CURRENT_PAGE_INDEX = -1;
let CURRENT_LEVEL = 'all'; // Track currently selected level
let VIEWED_PAGES = new Set();
let TEST_RESULTS = new Map(); // Track test results: pageId -> "correct" or "incorrect"
let MODAL_ZOOM = 100; // Track modal zoom level
let MODAL_PAN_X = 0; // Track pan position
let MODAL_PAN_Y = 0;
let HOME_SCROLL_POSITION = 0; // Track home page scroll position
// Initialize modal controls
function initializeModalControls(){
const modal = document.getElementById("imgModal");
const modalImg = document.getElementById("modalImg");
const zoomLevel = document.getElementById("zoomLevel");
const zoomInBtn = document.getElementById("zoomInBtn");
const zoomOutBtn = document.getElementById("zoomOutBtn");
const resetBtn = document.getElementById("resetBtn");
const closeBtn = document.getElementById("modalClose");
// Close modal only with the close button, not by clicking outside
// Zoom in
if(zoomInBtn){
zoomInBtn.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
MODAL_ZOOM = Math.min(MODAL_ZOOM + 20, 300);
const baseWidth = parseFloat(modalImg.dataset.baseWidth);
const baseHeight = parseFloat(modalImg.dataset.baseHeight);
const newWidth = baseWidth * (MODAL_ZOOM / 100);
const newHeight = baseHeight * (MODAL_ZOOM / 100);
modalImg.style.width = newWidth + "px";
modalImg.style.height = newHeight + "px";
zoomLevel.textContent = MODAL_ZOOM + "%";
};
}
// Zoom out
if(zoomOutBtn){
zoomOutBtn.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
MODAL_ZOOM = Math.max(MODAL_ZOOM - 20, 50);
const baseWidth = parseFloat(modalImg.dataset.baseWidth);
const baseHeight = parseFloat(modalImg.dataset.baseHeight);
const newWidth = baseWidth * (MODAL_ZOOM / 100);
const newHeight = baseHeight * (MODAL_ZOOM / 100);
modalImg.style.width = newWidth + "px";
modalImg.style.height = newHeight + "px";
zoomLevel.textContent = MODAL_ZOOM + "%";
};
}
// Reset zoom
if(resetBtn){
resetBtn.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
MODAL_ZOOM = 100;
MODAL_PAN_X = 0;
MODAL_PAN_Y = 0;
const baseWidth = parseFloat(modalImg.dataset.baseWidth);
const baseHeight = parseFloat(modalImg.dataset.baseHeight);
const container = document.querySelector(".modal-image-container");
container.scrollLeft = 0;
container.scrollTop = 0;
modalImg.style.width = baseWidth + "px";
modalImg.style.height = baseHeight + "px";
modalImg.style.transform = `none`;
zoomLevel.textContent = "100%";
};
}
// Close button - must work reliably
if(closeBtn){
closeBtn.onclick = (e) => {
e.preventDefault();
e.stopPropagation();
closeModal();
return false;
};
}
// Prevent modal closing when clicking on controls area
const controls = document.querySelector(".modal-controls");
if(controls){
controls.onclick = (e) => {
e.stopPropagation();
};
}
// Panning
let isDragging = false;
let startX, startY;
modalImg.addEventListener('mousedown', (e) => {
isDragging = true;
startX = e.clientX;
startY = e.clientY;
modalImg.style.cursor = 'grabbing';
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
const scale = MODAL_ZOOM / 100;
const deltaX = e.clientX - startX;
const deltaY = e.clientY - startY;
MODAL_PAN_X += deltaX;
MODAL_PAN_Y += deltaY;
startX = e.clientX;
startY = e.clientY;
const container = document.querySelector(".modal-image-container");
container.scrollLeft -= deltaX;
container.scrollTop -= deltaY;
});
document.addEventListener('mouseup', () => {
isDragging = false;
modalImg.style.cursor = 'grab';
});
modalImg.addEventListener('dragstart', (e) => e.preventDefault());
// Handle image container resize
const container = document.querySelector(".modal-image-container");
let isResizing = false;
let resizeStartY = 0;
let resizeStartX = 0;
let resizeStartHeight = 0;
let resizeStartWidth = 0;
container.addEventListener('mousedown', (e) => {
// Check if mouse is in the bottom-right corner (resize handle area)
const rect = container.getBoundingClientRect();
const distFromRight = rect.right - e.clientX;
const distFromBottom = rect.bottom - e.clientY;
// Enable resize if in the bottom-right 20px corner
if(distFromRight < 20 && distFromBottom < 20){
isResizing = true;
resizeStartY = e.clientY;
resizeStartX = e.clientX;
resizeStartHeight = container.offsetHeight;
resizeStartWidth = container.offsetWidth;
document.body.style.cursor = 'se-resize';
e.preventDefault();
}
});
document.addEventListener('mousemove', (e) => {
if (!isResizing) return;
const deltaY = e.clientY - resizeStartY;
const deltaX = e.clientX - resizeStartX;
const newHeight = Math.max(200, Math.min(resizeStartHeight + deltaY, window.innerHeight * 0.8));
const newWidth = Math.max(300, Math.min(resizeStartWidth + deltaX, window.innerWidth * 0.9));
container.style.height = newHeight + 'px';
container.style.width = newWidth + 'px';
// Adjust modal width to fit the image container
const modal = document.getElementById("imgModal");
const modalPadding = 24; // padding on each side
const newModalWidth = newWidth + modalPadding;
modal.style.width = newModalWidth + 'px';
});
document.addEventListener('mouseup', () => {
isResizing = false;
document.body.style.cursor = 'auto';
});