Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2459 lines (2104 loc) · 96.6 KB
/
Copy pathscript.js
File metadata and controls
2459 lines (2104 loc) · 96.6 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
// Application State Management
class ExamApp {
constructor() {
// Initialize application state
this.currentQuestionIndex = 0;
this.userAnswers = [];
this.timeRemaining = 5400; // 1.5 hours (90 minutes) in seconds
this.timerInterval = null;
this.examStartTime = null;
this.examEndTime = null;
this.selectedMock = 1;
this.examInProgress = false;
this.mockQuestions = null; // Will hold loaded questions from JSON
this.shuffledQuestions = null; // Will hold shuffled questions for current exam
this.questionMapping = []; // Maps shuffled index to original index
this.answerMapping = []; // Maps shuffled answer options to original indices
this.currentAttempt = null; // Stores the complete attempt state for review
this.tabSwitchCount = 0; // Track tab switches for anti-cheating
this.isTabActive = true; // Track if tab is currently active
this.uniqueSessionId = this.generateSessionId(); // Unique session identifier
// UI Configuration
this.feedbackSuccessDisplayTime = 5000; // Duration to show feedback success message (in milliseconds)
// Initialize the application
this.init();
}
/**
* Initialize the application by setting up event listeners and preparing the UI
*/
async init() {
console.log('Initializing Huawei Mock Exam Application...');
// Wait for DOM to be fully loaded
if (document.readyState === 'loading') {
await new Promise(resolve => {
document.addEventListener('DOMContentLoaded', resolve);
});
}
// Verify essential DOM elements exist
const requiredElements = [
'home-page', 'question-page', 'results-page',
'start-exam-btn', 'question-text', 'answer-options'
];
const missingElements = requiredElements.filter(id => !document.getElementById(id));
if (missingElements.length > 0) {
console.error('Missing required DOM elements:', missingElements);
this.showErrorMessage(`Application initialization failed: Missing elements ${missingElements.join(', ')}`);
return;
}
// Load questions from JSON file
await this.loadMockQuestions();
this.setupEventListeners();
this.setupPageProtection();
this.disableTextSelection();
this.setupAntiCheating();
this.showPage('home-page');
// Setup mobile optimizations
this.setupMobileOptimizations();
console.log('✅ Huawei Mock Exam Application initialized successfully!');
}
/**
* Load mock questions from JSON file
*/
async loadMockQuestions() {
try {
console.log('Loading mock questions from JSON file...');
const response = await fetch('mock-questions.json');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
this.mockQuestions = data.mockExams;
console.log(`Successfully loaded ${Object.keys(this.mockQuestions).length} mock exams`);
// Update the question count display for the default mock
this.updateQuestionCount();
} catch (error) {
console.error('Error loading mock questions:', error);
// Fallback to show error message
this.showErrorMessage('Failed to load exam questions. Please refresh the page and try again.');
}
}
/**
* Generate a unique session ID for tracking
*/
generateSessionId() {
return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
}
/**
* Create attempt state to preserve the exact exam experience for review
*/
createAttemptState(shuffledQuestions) {
const attemptId = Date.now().toString() + Math.random().toString(36).substr(2, 9);
this.currentAttempt = {
attemptId: attemptId,
timestamp: new Date().toISOString(),
selectedMock: this.selectedMock,
questions: shuffledQuestions.map((question, index) => ({
attemptIndex: index,
originalIndex: question.originalIndex,
question: question.question,
options: [...question.options], // Shuffled options as user saw them
correctAnswer: question.correctAnswer, // Mapped to shuffled positions
explanation: question.explanation,
userAnswer: null, // Will be filled when user answers
isMultipleChoice: this.isMultipleChoiceQuestion(question)
})),
userAnswers: new Array(shuffledQuestions.length).fill(null),
examStartTime: this.examStartTime,
examEndTime: null,
tabSwitchCount: 0
};
console.log(`Created attempt state ${attemptId} with ${shuffledQuestions.length} questions`);
// Debug: Log attempt state structure
console.log('Attempt state preview:', {
attemptId: this.currentAttempt.attemptId,
questionCount: this.currentAttempt.questions.length,
firstQuestion: this.currentAttempt.questions[0]?.question?.substring(0, 50) + '...',
firstQuestionOptions: this.currentAttempt.questions[0]?.options?.map((opt, i) => `${String.fromCharCode(65 + i)}. ${opt.substring(0, 30)}...`)
});
return this.currentAttempt;
}
/**
* Update user answer in the attempt state
*/
updateAttemptAnswer(questionIndex, userAnswer) {
if (this.currentAttempt && this.currentAttempt.questions[questionIndex]) {
this.currentAttempt.questions[questionIndex].userAnswer = userAnswer;
this.currentAttempt.userAnswers[questionIndex] = userAnswer;
}
}
/**
* Get questions for the current context (exam or review)
*/
getCurrentMockQuestions() {
// If we have a completed attempt (for review), use that
if (this.currentAttempt && !this.examInProgress) {
return this.currentAttempt.questions;
}
// If exam is in progress and we have shuffled questions, return those
if (this.examInProgress && this.shuffledQuestions) {
return this.shuffledQuestions;
}
// Otherwise return original questions for display/counting
if (!this.mockQuestions) {
console.warn('Mock questions not loaded yet');
return [];
}
const mockData = this.mockQuestions[this.selectedMock];
return mockData ? mockData.questions : [];
}
/**
* Shuffle array using Fisher-Yates algorithm
*/
shuffleArray(array) {
const shuffled = [...array];
for (let i = shuffled.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
}
return shuffled;
}
/**
* Shuffle questions and create mappings
*/
shuffleQuestions(questions) {
console.log('Shuffling questions and answer options...');
// Create array of indices for shuffling
const questionIndices = questions.map((_, index) => index);
const shuffledIndices = this.shuffleArray(questionIndices);
// Create shuffled questions array and mapping
const shuffledQuestions = [];
this.questionMapping = [];
this.answerMapping = [];
shuffledIndices.forEach((originalIndex, shuffledIndex) => {
const originalQuestion = questions[originalIndex];
// Shuffle answer options for this question
const optionIndices = originalQuestion.options.map((_, index) => index);
const shuffledOptionIndices = this.shuffleArray(optionIndices);
// Create shuffled options array
const shuffledOptions = shuffledOptionIndices.map(originalOptionIndex =>
originalQuestion.options[originalOptionIndex]
);
// Map the correct answer(s) to the new shuffled positions
let shuffledCorrectAnswer;
if (Array.isArray(originalQuestion.correctAnswer)) {
// Multiple correct answers
shuffledCorrectAnswer = originalQuestion.correctAnswer.map(correctIndex =>
shuffledOptionIndices.indexOf(correctIndex)
);
} else {
// Single correct answer
shuffledCorrectAnswer = shuffledOptionIndices.indexOf(originalQuestion.correctAnswer);
}
// Create the shuffled question
const shuffledQuestion = {
...originalQuestion,
options: shuffledOptions,
correctAnswer: shuffledCorrectAnswer,
originalIndex: originalIndex
};
shuffledQuestions.push(shuffledQuestion);
this.questionMapping.push(originalIndex);
this.answerMapping.push(shuffledOptionIndices);
});
console.log(`Shuffled ${shuffledQuestions.length} questions with answer options`);
return shuffledQuestions;
}
/**
* Setup tab switching detection for anti-cheating
*/
setupAntiCheating() {
// Track when user switches away from the tab
document.addEventListener('visibilitychange', () => {
if (this.examInProgress) {
if (document.hidden) {
this.isTabActive = false;
this.tabSwitchCount++;
console.warn(`Tab switch detected! Count: ${this.tabSwitchCount}`);
// Show warning for first few switches
if (this.tabSwitchCount <= 2) {
this.showTabSwitchWarning();
} else {
// Auto-submit exam after multiple tab switches
this.showTabSwitchSubmission();
setTimeout(() => {
this.submitExam();
}, 3000);
}
} else {
this.isTabActive = true;
}
}
});
// Also detect focus/blur events
window.addEventListener('blur', () => {
if (this.examInProgress && this.isTabActive) {
this.tabSwitchCount++;
console.warn(`Window blur detected! Count: ${this.tabSwitchCount}`);
if (this.tabSwitchCount <= 2) {
this.showTabSwitchWarning();
} else {
this.showTabSwitchSubmission();
setTimeout(() => {
this.submitExam();
}, 3000);
}
}
});
}
/**
* Show tab switch warning
*/
showTabSwitchWarning() {
const warningDiv = document.createElement('div');
warningDiv.className = 'tab-switch-warning';
warningDiv.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
background: linear-gradient(135deg, #f56565, #e53e3e);
color: white;
padding: 1rem;
text-align: center;
z-index: 10000;
font-weight: 600;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
`;
warningDiv.innerHTML = `
⚠️ WARNING: Tab switching detected! (${this.tabSwitchCount}/3)<br>
<small>Multiple tab switches will result in automatic exam submission</small>
`;
document.body.appendChild(warningDiv);
// Remove warning after 5 seconds
setTimeout(() => {
if (warningDiv.parentNode) {
warningDiv.parentNode.removeChild(warningDiv);
}
}, 5000);
}
/**
* Show tab switch submission notice
*/
showTabSwitchSubmission() {
const submissionDiv = document.createElement('div');
submissionDiv.className = 'tab-switch-submission';
submissionDiv.style.cssText = `
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: linear-gradient(135deg, #e53e3e, #c53030);
color: white;
padding: 2rem;
border-radius: 12px;
text-align: center;
z-index: 10001;
font-weight: 600;
box-shadow: 0 8px 25px rgba(0,0,0,0.5);
max-width: 400px;
`;
submissionDiv.innerHTML = `
<div style="font-size: 2rem; margin-bottom: 1rem;">🚨</div>
<h3 style="margin: 0 0 1rem 0;">Exam Security Violation</h3>
<p style="margin: 0 0 1rem 0;">Multiple tab switches detected. Your exam will be automatically submitted for security reasons.</p>
<div style="background: rgba(255,255,255,0.2); padding: 0.5rem; border-radius: 6px; font-size: 0.9rem;">
Auto-submitting in 3 seconds...
</div>
`;
document.body.appendChild(submissionDiv);
// Create overlay
const overlay = document.createElement('div');
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.7);
z-index: 10000;
`;
document.body.appendChild(overlay);
// Remove after submission
setTimeout(() => {
if (submissionDiv.parentNode) {
submissionDiv.parentNode.removeChild(submissionDiv);
}
if (overlay.parentNode) {
overlay.parentNode.removeChild(overlay);
}
}, 4000);
}
/**
* Show error message to user
*/
showErrorMessage(message) {
const errorDiv = document.createElement('div');
errorDiv.className = 'error-message';
errorDiv.style.cssText = `
position: fixed;
top: 20px;
left: 50%;
transform: translateX(-50%);
background: #e53e3e;
color: white;
padding: 1rem 2rem;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.3);
z-index: 10000;
font-weight: 500;
`;
errorDiv.textContent = message;
document.body.appendChild(errorDiv);
// Remove error message after 5 seconds
setTimeout(() => {
if (errorDiv.parentNode) {
errorDiv.parentNode.removeChild(errorDiv);
}
}, 5000);
}
/**
* Update question count display
*/
updateQuestionCount() {
if (this.mockQuestions && this.mockQuestions[this.selectedMock]) {
const questionCount = document.getElementById('question-count');
if (questionCount) {
questionCount.textContent = this.mockQuestions[this.selectedMock].questions.length;
}
}
}
/**
* Disable text selection and copy functionality
*/
disableTextSelection() {
// Disable right-click context menu
document.addEventListener('contextmenu', (e) => {
e.preventDefault();
return false;
});
// Disable copy shortcuts
document.addEventListener('keydown', (e) => {
// Disable Ctrl+C, Ctrl+A, Ctrl+V, Ctrl+S, F12, Ctrl+Shift+I, Ctrl+U
if ((e.ctrlKey && (e.key === 'c' || e.key === 'a' || e.key === 'v' || e.key === 's' || e.key === 'u')) ||
e.key === 'F12' ||
(e.ctrlKey && e.shiftKey && e.key === 'I')) {
e.preventDefault();
return false;
}
});
// Disable drag and drop
document.addEventListener('dragstart', (e) => {
e.preventDefault();
return false;
});
// Disable selection with mouse
document.addEventListener('selectstart', (e) => {
e.preventDefault();
return false;
});
}
/**
* Setup page refresh and close protection
*/
setupPageProtection() {
window.addEventListener('beforeunload', (e) => {
if (this.examInProgress) {
const message = 'Are you sure you want to leave? Your exam progress will be lost.';
e.returnValue = message;
return message;
}
});
// Also protect against back button during exam
window.addEventListener('popstate', (e) => {
if (this.examInProgress) {
const leave = confirm('Are you sure you want to leave the exam? Your progress will be lost.');
if (!leave) {
window.history.pushState(null, '', window.location.href);
}
}
});
}
/**
* Set up all event listeners for the application
*/
setupEventListeners() {
// Home page - Start exam button
const startExamBtn = document.getElementById('start-exam-btn');
startExamBtn?.addEventListener('click', () => this.startExam());
// Mock selection buttons
document.addEventListener('click', (event) => {
if (event.target.classList.contains('mock-btn')) {
this.selectMock(event.target);
}
});
// Question page - Next question button
const nextQuestionBtn = document.getElementById('next-question-btn');
nextQuestionBtn?.addEventListener('click', () => this.nextQuestion());
// Question page - Previous question button
const prevQuestionBtn = document.getElementById('prev-question-btn');
prevQuestionBtn?.addEventListener('click', () => this.prevQuestion());
// Question page - Submit exam button
const submitExamBtn = document.getElementById('submit-exam-btn');
submitExamBtn?.addEventListener('click', () => this.submitExam());
// Question page - Stop exam button
const stopExamBtn = document.getElementById('stop-exam-btn');
stopExamBtn?.addEventListener('click', () => this.stopExam());
// Stop exam modal buttons
const continueExamBtn = document.getElementById('continue-exam-btn');
continueExamBtn?.addEventListener('click', () => this.hideStopExamModal());
const exitExamBtn = document.getElementById('exit-exam-btn');
exitExamBtn?.addEventListener('click', () => this.confirmExamExit());
// Close modal when clicking backdrop
const stopModal = document.getElementById('stop-exam-modal');
stopModal?.addEventListener('click', (e) => {
if (e.target === stopModal || e.target.classList.contains('stop-modal-backdrop')) {
this.hideStopExamModal();
}
});
// Results page - View answers button
const viewAnswersBtn = document.getElementById('view-answers-btn');
viewAnswersBtn?.addEventListener('click', () => this.toggleDetailedAnswers());
// Results page - Retake exam button
const retakeExamBtn = document.getElementById('retake-exam-btn');
retakeExamBtn?.addEventListener('click', () => this.retakeExam());
// Feedback buttons
const giveFeedbackBtn = document.getElementById('give-feedback-btn');
giveFeedbackBtn?.addEventListener('click', () => this.showFeedbackModal());
const footerFeedbackBtn = document.getElementById('footer-feedback-btn');
footerFeedbackBtn?.addEventListener('click', () => this.showFeedbackModal());
// Report Issue button
const reportIssueLink = document.getElementById('report-issue-link');
reportIssueLink?.addEventListener('click', (e) => {
e.preventDefault();
this.showIssueReportModal();
});
// Issue report modal buttons
const closeIssueBtn = document.getElementById('close-issue-btn');
closeIssueBtn?.addEventListener('click', () => this.hideIssueReportModal());
const cancelIssueBtn = document.getElementById('cancel-issue-btn');
cancelIssueBtn?.addEventListener('click', () => this.hideIssueReportModal());
const submitIssueBtn = document.getElementById('submit-issue-btn');
submitIssueBtn?.addEventListener('click', () => this.submitIssueReport());
// Close issue modal when clicking backdrop
const issueModal = document.getElementById('issue-report-modal');
issueModal?.addEventListener('click', (e) => {
if (e.target === issueModal || e.target.classList.contains('issue-modal-backdrop')) {
this.hideIssueReportModal();
}
});
const closeFeedbackBtn = document.getElementById('close-feedback-btn');
closeFeedbackBtn?.addEventListener('click', () => this.hideFeedbackModal());
const cancelFeedbackBtn = document.getElementById('cancel-feedback-btn');
cancelFeedbackBtn?.addEventListener('click', () => this.hideFeedbackModal());
const submitFeedbackBtn = document.getElementById('submit-feedback-btn');
submitFeedbackBtn?.addEventListener('click', (e) => {
e.preventDefault(); // Prevent form submission
this.submitFeedback();
});
// Also handle form submission directly
const feedbackForm = document.querySelector('.feedback-form');
feedbackForm?.addEventListener('submit', (e) => {
e.preventDefault(); // Prevent form submission
this.submitFeedback();
});
// Star rating functionality
this.setupStarRating();
// Handle answer selection
document.addEventListener('change', (event) => {
if (event.target.name === 'answer') {
this.handleAnswerSelection(event.target.value);
}
});
// Keyboard navigation support
document.addEventListener('keydown', (event) => {
this.handleKeyboardNavigation(event);
});
}
/**
* Select a mock exam
*/
selectMock(mockBtn) {
// Remove active class from all mock buttons
document.querySelectorAll('.mock-btn').forEach(btn => {
btn.classList.remove('active');
});
// Add active class to selected button
mockBtn.classList.add('active');
// Store selected mock
this.selectedMock = parseInt(mockBtn.dataset.mock);
// Update question count display
this.updateQuestionCount();
console.log(`Selected Mock ${this.selectedMock}`);
// Log mock details if available
if (this.mockQuestions && this.mockQuestions[this.selectedMock]) {
const mockData = this.mockQuestions[this.selectedMock];
console.log(`Mock Title: ${mockData.title}`);
console.log(`Question Count: ${mockData.questions.length}`);
}
}
/**
* Handle keyboard navigation for accessibility
*/
handleKeyboardNavigation(event) {
// ESC key to close modals
if (event.key === 'Escape') {
const stopModal = document.getElementById('stop-exam-modal');
const issueModal = document.getElementById('issue-report-modal');
if (stopModal && stopModal.style.display === 'flex') {
this.hideStopExamModal();
return;
}
if (issueModal && issueModal.style.display === 'flex') {
this.hideIssueReportModal();
return;
}
}
const currentPage = document.querySelector('.page.active');
if (currentPage && currentPage.id === 'question-page') {
// Number keys 1-4 for answer selection
if (event.key >= '1' && event.key <= '4') {
const answerIndex = parseInt(event.key) - 1;
const radioButtons = document.querySelectorAll('input[name="answer"]');
if (radioButtons[answerIndex]) {
radioButtons[answerIndex].checked = true;
this.handleAnswerSelection(radioButtons[answerIndex].value);
}
}
// Arrow keys for navigation
if (event.key === 'ArrowLeft') {
const prevBtn = document.getElementById('prev-question-btn');
if (prevBtn && !prevBtn.disabled) {
this.prevQuestion();
}
}
if (event.key === 'ArrowRight') {
const nextBtn = document.getElementById('next-question-btn');
if (nextBtn && !nextBtn.disabled) {
this.nextQuestion();
}
}
// Enter key for next question
if (event.key === 'Enter') {
const nextBtn = document.getElementById('next-question-btn');
const submitBtn = document.getElementById('submit-exam-btn');
if (nextBtn && !nextBtn.disabled) {
this.nextQuestion();
} else if (submitBtn && submitBtn.style.display !== 'none') {
this.submitExam();
}
}
}
}
/**
* Show a specific page and hide others
*/
showPage(pageId) {
console.log(`Showing page: ${pageId}`);
// Hide all pages
document.querySelectorAll('.page').forEach(page => {
page.classList.remove('active');
});
// Show the requested page
const targetPage = document.getElementById(pageId);
if (targetPage) {
targetPage.classList.add('active');
}
// Hide footer on exam and results pages, show otherwise
const footer = document.querySelector('footer.app-footer');
if (footer) {
if (pageId === 'question-page' || pageId === 'results-page') {
footer.style.display = 'none';
} else {
footer.style.display = '';
}
}
}
/**
* Start the exam - initialize timer and show first question
*/
startExam() {
console.log('Starting exam...');
// Check if questions are loaded
if (!this.mockQuestions) {
this.showErrorMessage('Exam questions are still loading. Please wait a moment and try again.');
return;
}
const originalQuestions = this.getCurrentMockQuestions();
if (originalQuestions.length === 0) {
this.showErrorMessage('No questions available for the selected mock exam.');
return;
}
// Set exam in progress flag
this.examInProgress = true;
// Reset tab switch counter
this.tabSwitchCount = 0;
this.isTabActive = true;
// Show loading screen briefly for better UX
this.showLoadingScreen();
setTimeout(() => {
// Shuffle questions and answers for this exam session
this.shuffledQuestions = this.shuffleQuestions(originalQuestions);
console.log('Exam prepared with shuffled questions and options');
// Create attempt state to preserve exact exam experience
this.createAttemptState(this.shuffledQuestions);
// Reset exam state
this.currentQuestionIndex = 0;
this.userAnswers = [];
this.timeRemaining = 5400; // Reset to 1.5 hours
this.examStartTime = new Date();
this.currentAttempt.examStartTime = this.examStartTime;
// Initialize user answers array based on shuffled questions
this.userAnswers = new Array(this.shuffledQuestions.length).fill(null);
// Show question page and start timer
this.showPage('question-page');
this.startTimer();
this.displayQuestion();
this.hideLoadingScreen();
}, 1000);
}
/**
* Show loading screen
*/
showLoadingScreen() {
const loadingScreen = document.getElementById('loading-screen');
if (loadingScreen) {
loadingScreen.style.display = 'flex';
}
}
/**
* Hide loading screen
*/
hideLoadingScreen() {
const loadingScreen = document.getElementById('loading-screen');
if (loadingScreen) {
loadingScreen.style.display = 'none';
}
}
/**
* Start the exam timer
*/
startTimer() {
const timerDisplay = document.getElementById('timer-display');
this.timerInterval = setInterval(() => {
this.timeRemaining--;
// Update timer display
const minutes = Math.floor(this.timeRemaining / 60);
const seconds = this.timeRemaining % 60;
const timeString = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
if (timerDisplay) {
timerDisplay.textContent = timeString;
// Add warning class when time is running low (last 5 minutes)
if (this.timeRemaining <= 300) {
timerDisplay.classList.add('warning');
}
}
// End exam when time runs out
if (this.timeRemaining <= 0) {
console.log('Time\'s up! Auto-submitting exam...');
this.submitExam();
}
}, 1000);
}
/**
* Stop the exam timer
*/
stopTimer() {
if (this.timerInterval) {
clearInterval(this.timerInterval);
this.timerInterval = null;
}
}
/**
* Display the current question and its options
*/
displayQuestion() {
const currentQuestions = this.getCurrentMockQuestions();
// Better error checking
if (!currentQuestions || currentQuestions.length === 0) {
console.error('No questions available for current mock');
return;
}
if (this.currentQuestionIndex >= currentQuestions.length) {
console.error(`Question index ${this.currentQuestionIndex} is out of bounds (total: ${currentQuestions.length})`);
return;
}
const question = currentQuestions[this.currentQuestionIndex];
// Validate question object
if (!question) {
console.error(`Question at index ${this.currentQuestionIndex} is null or undefined`);
return;
}
if (!question.question || !question.options) {
console.error(`Question at index ${this.currentQuestionIndex} is missing required fields:`, question);
return;
}
const questionText = document.getElementById('question-text');
const answerOptions = document.getElementById('answer-options');
const questionCounter = document.getElementById('question-counter');
const progressFill = document.getElementById('progress-fill');
console.log(`Displaying question ${this.currentQuestionIndex + 1}: ${question.question}`);
console.log(`Question has ${question.options.length} options:`, question.options);
// Update question text
if (questionText) {
const isMultipleChoice = this.isMultipleChoiceQuestion(question);
const questionPrefix = isMultipleChoice ?
'<span class="question-type multiple-choice">Multiple Choice</span>' :
'<span class="question-type single-choice">Single Choice</span>';
questionText.innerHTML = questionPrefix + question.question;
}
// Update progress indicator
if (questionCounter) {
questionCounter.textContent = `Question ${this.currentQuestionIndex + 1} of ${currentQuestions.length}`;
}
// Update progress bar
if (progressFill) {
const progress = ((this.currentQuestionIndex + 1) / currentQuestions.length) * 100;
progressFill.style.width = `${progress}%`;
}
// Generate answer options
if (answerOptions) {
answerOptions.innerHTML = '';
if (question.options && Array.isArray(question.options) && question.options.length > 0) {
// Check if this is a multiple choice question
const isMultipleChoice = this.isMultipleChoiceQuestion(question);
question.options.forEach((option, index) => {
const optionDiv = document.createElement('div');
optionDiv.className = 'answer-option';
const inputElement = document.createElement('input');
inputElement.type = isMultipleChoice ? 'checkbox' : 'radio';
inputElement.name = isMultipleChoice ? `answer-${index}` : 'answer';
inputElement.value = index;
inputElement.id = `option-${index}`;
// Check if this option was previously selected
if (isMultipleChoice) {
const userAnswer = this.userAnswers[this.currentQuestionIndex];
if (Array.isArray(userAnswer) && userAnswer.includes(index)) {
inputElement.checked = true;
optionDiv.classList.add('selected');
}
} else {
if (this.userAnswers[this.currentQuestionIndex] === index) {
inputElement.checked = true;
optionDiv.classList.add('selected');
}
}
const label = document.createElement('label');
label.htmlFor = `option-${index}`;
label.textContent = option;
optionDiv.appendChild(inputElement);
optionDiv.appendChild(label);
// Add click handler for the entire option div
optionDiv.addEventListener('click', (e) => {
// Prevent double triggering when clicking the input directly
if (e.target !== inputElement) {
inputElement.checked = !inputElement.checked;
}
this.handleAnswerSelection(index, isMultipleChoice);
});
// Add change handler for the input element
inputElement.addEventListener('change', () => {
this.handleAnswerSelection(index, isMultipleChoice);
});
answerOptions.appendChild(optionDiv);
});
console.log(`Successfully created ${question.options.length} ${isMultipleChoice ? 'multiple choice' : 'single choice'} answer options`);
} else {
console.error('Question options are invalid:', question.options);
answerOptions.innerHTML = '<div class="error-message">Error: No answer options available for this question.</div>';
}
} else {
console.error('answerOptions element not found in DOM');
}
// Update navigation buttons
this.updateNavigationButtons();
}
/**
* Check if a question is multiple choice based on question text patterns
*/
isMultipleChoiceQuestion(question) {
if (!question || !question.question) {
return false;
}
const questionText = question.question.toLowerCase();
// Check for explicit multiple choice indicators
const multipleChoicePatterns = [
/select.*\d+.*answers?/,
/multiple.*choice/,
/\(select.*answers?\)/,
/which.*of.*the.*following.*are.*correct/,
/which.*of.*the.*following.*statements.*are.*correct/,
/which.*of.*the.*following.*are.*true/,
/which.*of.*the.*following.*are.*false/,
/which.*of.*the.*following.*are.*components?/,
/which.*of.*the.*following.*are.*characteristics/,
/which.*of.*the.*following.*are.*filtering/,
/which.*of.*the.*following.*algorithms.*are/,
/which.*of.*the.*following.*ports.*are/,
/which.*of.*the.*following.*modes.*are/,
/which.*of.*the.*following.*technologies.*are/,
/which.*of.*the.*following.*protocols.*are/,
/which.*of.*the.*following.*vpns.*are/,
/which.*of.*the.*following.*authentication.*modes.*are/,
/which.*of.*the.*following.*backup.*modes.*are/,
/which.*of.*the.*following.*statements.*are/
];
// Check if question matches any multiple choice pattern
for (const pattern of multipleChoicePatterns) {
if (pattern.test(questionText)) {
return true;
}
}