-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscript.js
More file actions
893 lines (742 loc) · 29 KB
/
Copy pathscript.js
File metadata and controls
893 lines (742 loc) · 29 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
// Theme Toggle Functions
function toggleTheme() {
const html = document.documentElement;
const themeToggle = document.querySelector('.theme-toggle i');
if (html.getAttribute('data-theme') === 'dark') {
html.setAttribute('data-theme', 'light');
if (themeToggle) themeToggle.className = 'fas fa-moon';
localStorage.setItem('theme', 'light');
} else {
html.setAttribute('data-theme', 'dark');
if (themeToggle) themeToggle.className = 'fas fa-sun';
localStorage.setItem('theme', 'dark');
}
}
function loadSavedTheme() {
const savedTheme = localStorage.getItem('theme') || 'light';
const html = document.documentElement;
const themeToggle = document.querySelector('.theme-toggle i');
html.setAttribute('data-theme', savedTheme);
if (themeToggle) {
themeToggle.className = savedTheme === 'dark' ? 'fas fa-sun' : 'fas fa-moon';
}
}
// Mobile Navigation Functions
function toggleMobileNav() {
const navMenu = document.querySelector('.nav-menu');
const navToggle = document.querySelector('.nav-toggle i');
if (navMenu) {
navMenu.classList.toggle('active');
if (navToggle) {
navToggle.className = navMenu.classList.contains('active') ? 'fas fa-times' : 'fas fa-bars';
}
}
}
function closeMobileNav() {
const navMenu = document.querySelector('.nav-menu');
const navToggle = document.querySelector('.nav-toggle i');
if (navMenu) {
navMenu.classList.remove('active');
if (navToggle) {
navToggle.className = 'fas fa-bars';
}
}
}
// Smooth Scrolling for Navigation Links
function smoothScrollToSection(sectionId) {
const section = document.getElementById(sectionId);
if (section) {
section.scrollIntoView({ behavior: 'smooth' });
}
}
// Password Toggle Functions
function togglePasswordVisibility(inputId) {
const input = document.getElementById(inputId);
const toggleBtn = input?.nextElementSibling;
if (input && toggleBtn) {
if (input.type === 'password') {
input.type = 'text';
toggleBtn.querySelector('i').className = 'fas fa-eye-slash';
} else {
input.type = 'password';
toggleBtn.querySelector('i').className = 'fas fa-eye';
}
}
}
// Experiment Functions (placeholders for future implementation)
function startQuickExperiment(experimentType) {
showToast(`Starting ${experimentType} experiment...`, 'info');
// TODO: Implement experiment logic
}
function startExperiment(experimentType) {
showToast(`Loading ${experimentType} experiment...`, 'info');
// TODO: Implement experiment logic
}
function showToast(message, type = 'info') {
// Remove existing toasts
document.querySelectorAll('.toast').forEach(toast => toast.remove());
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.innerHTML = `
<i class="fas fa-${getToastIcon(type)}"></i>
<span>${message}</span>
`;
document.body.appendChild(toast);
// Auto remove after 3 seconds
setTimeout(() => {
toast.style.animation = 'slideOutRight 0.3s ease';
setTimeout(() => toast.remove(), 300);
}, 3000);
}
function getToastIcon(type) {
switch(type) {
case 'success': return 'check-circle';
case 'error': return 'exclamation-circle';
case 'warning': return 'exclamation-triangle';
default: return 'info-circle';
}
}
// Auth Modal Functions
function showAuthModal() {
const modal = document.getElementById('authModal');
if (modal) {
modal.style.display = 'flex';
switchTab('login');
}
}
function showRegisterForm() {
const modal = document.getElementById('authModal');
if (modal) {
modal.style.display = 'flex';
switchTab('register');
}
}
function switchTab(tabName) {
document.querySelectorAll('.auth-tab').forEach(t => t.classList.remove('active'));
document.querySelectorAll('.auth-form').forEach(f => f.classList.remove('active'));
const activeTab = document.querySelector(`[data-tab="${tabName}"]`);
const activeForm = document.getElementById(`${tabName}Form`);
if (activeTab) activeTab.classList.add('active');
if (activeForm) activeForm.classList.add('active');
}
function hideAuthModal() {
const modal = document.getElementById('authModal');
if (modal) {
modal.style.display = 'none';
}
}
// Tutorial Modal Functions
function showTutorial() {
const modal = document.getElementById('tutorialModal');
if (modal) {
modal.style.display = 'flex';
resetTutorial();
}
}
function hideTutorial() {
const modal = document.getElementById('tutorialModal');
if (modal) {
modal.style.display = 'none';
}
}
function prevTutorialStep() {
const steps = document.querySelectorAll('.tutorial-step');
let currentStep = 0;
steps.forEach((step, index) => {
if (step.classList.contains('active')) {
currentStep = index;
}
});
if (currentStep > 0) {
steps[currentStep].classList.remove('active');
steps[currentStep - 1].classList.add('active');
updateTutorialButtons();
}
}
function nextTutorialStep() {
const steps = document.querySelectorAll('.tutorial-step');
let currentStep = 0;
steps.forEach((step, index) => {
if (step.classList.contains('active')) {
currentStep = index;
}
});
if (currentStep < steps.length - 1) {
steps[currentStep].classList.remove('active');
steps[currentStep + 1].classList.add('active');
updateTutorialButtons();
} else {
hideTutorial();
}
}
function resetTutorial() {
const steps = document.querySelectorAll('.tutorial-step');
steps.forEach(step => step.classList.remove('active'));
steps[0].classList.add('active');
updateTutorialButtons();
}
function updateTutorialButtons() {
const steps = document.querySelectorAll('.tutorial-step');
let currentStep = 0;
steps.forEach((step, index) => {
if (step.classList.contains('active')) {
currentStep = index;
}
});
const prevBtn = document.getElementById('prevStep');
const nextBtn = document.getElementById('nextStep');
if (prevBtn) prevBtn.disabled = currentStep === 0;
if (nextBtn) nextBtn.textContent = currentStep === steps.length - 1 ? 'Finish' : 'Next';
}
// Form Handling Functions
async function handleLogin(form) {
const formData = new FormData(form);
const data = Object.fromEntries(formData);
try {
const response = await fetch('login.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(data)
});
const result = await response.json();
if (result.status === 'success') {
showToast('Login successful!', 'success');
setTimeout(() => {
window.location.href = result.redirect || 'index.php';
}, 1000);
} else {
showToast(result.message || 'Invalid credentials', 'error');
}
} catch (error) {
showToast('Network error. Please try again.', 'error');
console.error('Login error:', error);
}
}
async function handleRegister(form) {
const formData = new FormData(form);
const data = Object.fromEntries(formData);
const confirmPassword = document.getElementById('regConfirmPassword')?.value;
if (!confirmPassword || data.password !== confirmPassword) {
showToast('Passwords do not match!', 'error');
return;
}
if (data.password.length < 6) {
showToast('Password must be at least 6 characters long', 'error');
return;
}
try {
const response = await fetch('register.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(data)
});
const result = await response.json();
if (result.status === 'success') {
showToast('Registration successful! Please login.', 'success');
setTimeout(() => {
switchTab('login');
}, 1500);
} else {
showToast('Registration failed. Username may already exist.', 'error');
}
} catch (error) {
showToast('Network error. Please try again.', 'error');
console.error('Registration error:', error);
}
}
// Initialize functions when DOM is loaded
document.addEventListener('DOMContentLoaded', function() {
// Initialize auth modal
const authModal = document.getElementById('authModal');
const tutorialModal = document.getElementById('tutorialModal');
// Close modal on X click
document.querySelectorAll('.close-modal, .close-tutorial').forEach(closeBtn => {
closeBtn.addEventListener('click', function() {
if (authModal && authModal.contains(this)) hideAuthModal();
if (tutorialModal && tutorialModal.contains(this)) hideTutorial();
});
});
// Close modal when clicking outside
window.addEventListener('click', function(e) {
if (authModal && e.target === authModal) hideAuthModal();
if (tutorialModal && e.target === tutorialModal) hideTutorial();
});
// Auth tab switching
document.querySelectorAll('.auth-tab').forEach(tab => {
tab.addEventListener('click', function() {
switchTab(this.dataset.tab);
});
});
// Login form submission
const loginForm = document.getElementById('loginForm');
if (loginForm) {
loginForm.addEventListener('submit', function(e) {
e.preventDefault();
handleLogin(this);
});
}
// Register form submission
const registerForm = document.getElementById('registerForm');
if (registerForm) {
registerForm.addEventListener('submit', function(e) {
e.preventDefault();
handleRegister(this);
});
}
// Tutorial navigation
const prevStepBtn = document.getElementById('prevStep');
const nextStepBtn = document.getElementById('nextStep');
if (prevStepBtn) prevStepBtn.addEventListener('click', prevTutorialStep);
if (nextStepBtn) nextStepBtn.addEventListener('click', nextTutorialStep);
// Initialize tutorial buttons state
updateTutorialButtons();
// Hero buttons for guest users
const heroLoginBtn = document.getElementById('heroLoginBtn');
const heroTutorialBtn = document.getElementById('heroTutorialBtn');
if (heroLoginBtn) heroLoginBtn.addEventListener('click', showAuthModal);
if (heroTutorialBtn) heroTutorialBtn.addEventListener('click', showTutorial);
// Nav login/register buttons
const navLoginBtn = document.querySelector('.btn-login');
const navRegisterBtn = document.querySelector('.btn-register');
if (navLoginBtn) navLoginBtn.addEventListener('click', showAuthModal);
if (navRegisterBtn) navRegisterBtn.addEventListener('click', showRegisterForm);
// Theme toggle
const themeToggle = document.querySelector('.theme-toggle');
if (themeToggle) {
themeToggle.addEventListener('click', toggleTheme);
}
// Mobile navigation toggle
const navToggle = document.querySelector('.nav-toggle');
if (navToggle) {
navToggle.addEventListener('click', toggleMobileNav);
}
// Close mobile nav when clicking nav links
document.querySelectorAll('.nav-link').forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
const href = this.getAttribute('href');
if (href && href.startsWith('#')) {
smoothScrollToSection(href.substring(1));
}
closeMobileNav();
});
});
// Password visibility toggles
document.querySelectorAll('.toggle-password').forEach(btn => {
btn.addEventListener('click', function() {
const input = this.previousElementSibling;
if (input) {
togglePasswordVisibility(input.id);
}
});
});
// Load saved theme on page load
loadSavedTheme();
// Initialize chatbot
initializeChatbot();
// Grading Modal Functions
const gradingModal = document.getElementById('gradingModal');
const gradingForm = document.getElementById('gradingForm');
if (gradingModal) {
// Close modal when clicking outside
window.addEventListener('click', function(e) {
if (e.target === gradingModal) {
closeGradingModal();
}
});
// Close modal with X button
const closeBtn = gradingModal.querySelector('.close-modal');
if (closeBtn) {
closeBtn.addEventListener('click', closeGradingModal);
}
}
if (gradingForm) {
gradingForm.addEventListener('submit', handleGradeSubmission);
}
// Grade slider sync
const gradeInput = document.getElementById('grade');
const gradeSlider = document.getElementById('gradeSlider');
if (gradeInput && gradeSlider) {
gradeInput.addEventListener('input', function() {
gradeSlider.value = this.value;
});
gradeSlider.addEventListener('input', function() {
gradeInput.value = this.value;
});
}
// Results Modal Functions
const resultsModal = document.getElementById('resultsModal');
if (resultsModal) {
const repeatBtn = resultsModal.querySelector('.btn-secondary');
const saveBtn = resultsModal.querySelector('.btn-primary');
if (repeatBtn) {
repeatBtn.addEventListener('click', repeatExperiment);
}
if (saveBtn) {
saveBtn.addEventListener('click', saveResults);
}
}
});
// Grading Modal Functions
function openGradingModal(studentName, experimentName, date, submissionId) {
const modal = document.getElementById('gradingModal');
if (!modal) return;
// Populate modal with student data
document.getElementById('gradingStudentName').textContent = studentName;
document.getElementById('gradingExperimentName').textContent = experimentName;
document.getElementById('gradingDate').textContent = `Submitted on: ${date}`;
// Store submission ID for grading
modal.dataset.submissionId = submissionId;
// Set video source (fetch from server or use placeholder)
const video = document.getElementById('studentVideo');
if (video) {
// For now, use placeholder. In production, fetch video path from server
video.src = `get_submission_video.php?id=${submissionId}`;
video.load();
}
// Reset form
const form = document.getElementById('gradingForm');
if (form) {
form.reset();
}
// Show modal
modal.style.display = 'flex';
}
function closeGradingModal() {
const modal = document.getElementById('gradingModal');
if (modal) {
modal.style.display = 'none';
}
}
async function handleGradeSubmission(e) {
e.preventDefault();
const formData = new FormData(e.target);
const data = Object.fromEntries(formData);
// Get submission ID from modal
const modal = document.getElementById('gradingModal');
const submissionId = modal ? modal.dataset.submissionId : null;
if (!submissionId) {
showToast('Error: Submission ID not found', 'error');
return;
}
// Add submission ID to data
data.submission_id = submissionId;
try {
// Send grade to server
const response = await fetch('grade_submission.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(data)
});
const result = await response.json();
if (result.status === 'success') {
showToast(`Grade submitted successfully!`, 'success');
// Update the submission status on the page
updateSubmissionStatus(document.getElementById('gradingStudentName').textContent, data.grade);
// Close modal
closeGradingModal();
// Optionally reload the page to refresh data
setTimeout(() => {
window.location.reload();
}, 1500);
} else {
showToast(result.message || 'Error submitting grade', 'error');
}
} catch (error) {
showToast('Error submitting grade', 'error');
console.error('Grade submission error:', error);
}
}
function updateSubmissionStatus(studentName, grade) {
// Find and update the submission card
const cards = document.querySelectorAll('.submission-card');
cards.forEach(card => {
const cardStudentName = card.querySelector('h4').textContent;
if (cardStudentName === studentName) {
const statusElement = card.querySelector('.submission-status .status');
const buttonElement = card.querySelector('.btn-review');
if (statusElement) {
statusElement.className = 'status graded';
statusElement.textContent = `Grade: ${grade}%`;
}
if (buttonElement) {
buttonElement.innerHTML = '<i class="fas fa-eye"></i> View Submission';
}
}
});
// Update table row as well
const tableRows = document.querySelectorAll('.data-table tbody tr');
tableRows.forEach(row => {
const studentCell = row.querySelector('.student-cell span');
if (studentCell && studentCell.textContent === studentName) {
const statusCell = row.querySelector('td:nth-child(5) .status');
const gradeCell = row.querySelector('td:nth-child(6)');
const actionCell = row.querySelector('td:nth-child(7) .btn-view');
if (statusCell) {
statusCell.className = 'status graded';
statusCell.textContent = 'Graded';
}
if (gradeCell) {
gradeCell.textContent = `${grade}%`;
}
if (actionCell) {
actionCell.textContent = 'View';
}
}
});
}
// Additional Lab Functions
function resetLab() {
showToast('Resetting laboratory...', 'info');
// TODO: Implement lab reset logic
// Clear canvas, reset equipment positions, clear chemicals, etc.
}
function repeatExperiment() {
const modal = document.getElementById('resultsModal');
if (modal) {
modal.style.display = 'none';
}
showToast('Repeating experiment...', 'info');
// TODO: Implement experiment repeat logic
}
function saveResults() {
showToast('Results saved successfully!', 'success');
const modal = document.getElementById('resultsModal');
if (modal) {
modal.style.display = 'none';
}
// TODO: Implement results saving logic
}
// AI Assistant Chatbot
function initializeChatbot() {
const chatbotToggle = document.getElementById('chatbot-toggle');
const chatbot = document.getElementById('chatbot');
const chatbotClose = document.getElementById('chatbot-close');
const chatbotInput = document.getElementById('chatbot-input');
const chatbotSend = document.getElementById('chatbot-send');
const chatbotMessages = document.getElementById('chatbot-messages');
// Return early if elements don't exist
if (!chatbotToggle || !chatbot || !chatbotClose || !chatbotInput || !chatbotSend || !chatbotMessages) {
console.warn('Chatbot elements not found');
return;
}
let speechSynthesis = null;
let speechRecognition = null;
const knowledgeBase = {
greetings: [
"Hello! I'm your ChemLab assistant. How can I help you today?",
"Hi there! Welcome to ChemLab 3D 👋",
"Hey! Ready to run a virtual experiment?"
],
about:
"ChemLab 3D is an interactive virtual chemistry laboratory where students perform experiments using realistic 3D equipment in a safe environment.",
getting_started:
"To begin, log in, choose an experiment, and enter the 3D lab. Drag equipment from the toolbox and follow the guided steps.",
experiments:
"Available experiments include acid–base titration, pH measurement, calorimetry, electrochemistry, precipitation reactions, and gas laws.",
experiment_steps:
"Each experiment follows these steps: set up equipment, add chemicals, observe reactions, record results, and submit your work.",
equipment:
"You can use beakers, flasks, burettes, pipettes, thermometers, balances, hot plates, and stands. All tools are fully interactive in 3D.",
chemicals:
"ChemLab includes chemicals such as HCl, NaOH, H2SO4, NaCl, AgNO3, CuSO4, and indicators like phenolphthalein.",
safety:
"Always follow the instructions and use the correct equipment. Virtual lab safety helps build real laboratory habits.",
results:
"Your observations and measurements are recorded automatically. Some experiments require written analysis.",
grading:
"Grading is based on correct setup, procedure, results, and submitted analysis. Check the rubric before submitting.",
submit_work:
"You can submit your work in the Submit section under the lab page. Upload your screen recording of the experiment and add notes or comments if you want, then click submit.",
contact:
"For technical issues or feedback, please contact the support team through the website contact page.",
default:
"I'm not sure about that 🤔 I can help with experiments, submission, equipment, theory, or safety. What would you like to know?"
};
// Initialize speech synthesis
function initSpeechSynthesis() {
if ('speechSynthesis' in window) {
speechSynthesis = window.speechSynthesis;
// Load voices
speechSynthesis.onvoiceschanged = () => {
console.log('Speech synthesis voices loaded');
};
}
}
// Initialize speech recognition
function initSpeechRecognition() {
if ('webkitSpeechRecognition' in window || 'SpeechRecognition' in window) {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
speechRecognition = new SpeechRecognition();
speechRecognition.continuous = false;
speechRecognition.interimResults = false;
speechRecognition.lang = 'en-US';
speechRecognition.onresult = (event) => {
const transcript = event.results[0][0].transcript;
chatbotInput.value = transcript;
processMessage(transcript);
};
speechRecognition.onerror = (event) => {
console.error('Speech recognition error:', event.error);
};
}
}
function speak(text) {
if (!speechSynthesis) return;
const utterance = new SpeechSynthesisUtterance(text);
utterance.rate = 1; // Speed (0.5 to 2)
utterance.pitch = 1; // Pitch (0 to 2, 1 is normal)
utterance.volume = 1; // Volume (0 to 1)
// Get available voices
const voices = speechSynthesis.getVoices();
// Try to find a female voice
let femaleVoice = voices.find(voice => {
// Different ways to identify female voices
return (
voice.name.toLowerCase().includes('female') ||
voice.name.toLowerCase().includes('woman') ||
voice.name.toLowerCase().includes('samantha') || // Common female voice name
voice.name.toLowerCase().includes('google uk female') ||
voice.name.toLowerCase().includes('microsoft zira') || // Windows female
voice.name.toLowerCase().includes('microsoft hazel') || // Windows female
voice.name.toLowerCase().includes('karen') || // macOS female
voice.name.toLowerCase().includes('ava') || // macOS female
voice.name.toLowerCase().includes('tessa') // macOS female
);
});
// If no female voice found, use any available voice
if (femaleVoice) {
utterance.voice = femaleVoice;
console.log('Using female voice:', femaleVoice.name);
} else if (voices.length > 0) {
// Fallback to first available voice
utterance.voice = voices[0];
console.log('Female voice not found, using:', voices[0].name);
}
// Adjust voice characteristics for more feminine sound
utterance.pitch = 1.2; // Higher pitch (more feminine)
utterance.rate = 0.95; // Slightly slower for clarity
speechSynthesis.speak(utterance);
}
// Process incoming message
function processMessage(message) {
const msg = message.toLowerCase().trim();
addMessage(message, 'user');
let response = knowledgeBase.default;
if (msg.match(/\b(hi|hello|hey)\b/)) {
response = knowledgeBase.greetings[Math.floor(Math.random() * knowledgeBase.greetings.length)];
} else if (msg.includes('about') || msg.includes('what is')) {
response = knowledgeBase.about;
} else if (msg.includes('start') || msg.includes('begin')) {
response = knowledgeBase.getting_started;
} else if (msg.includes('step')) {
response = knowledgeBase.experiment_steps;
} else if (
msg.includes('submit') ||
msg.includes('upload') ||
msg.includes('screen') ||
msg.includes('recording') ||
msg.includes('notes')
) {
response = knowledgeBase.submit_work;
} else if (msg.includes('experiment')) {
response = knowledgeBase.experiments;
} else if (msg.includes('equipment')) {
response = knowledgeBase.equipment;
} else if (msg.includes('chemical')) {
response = knowledgeBase.chemicals;
} else if (msg.includes('safety')) {
response = knowledgeBase.safety;
} else if (msg.includes('grade')) {
response = knowledgeBase.grading;
} else if (msg.includes('result')) {
response = knowledgeBase.results;
} else if (msg.includes('contact') || msg.includes('support')) {
response = knowledgeBase.contact;
}
// Add slight delay for natural conversation feel
setTimeout(() => {
addMessage(response, 'bot');
speak(response);
}, 500);
}
// Add message to chat
function addMessage(text, sender) {
const messageElement = document.createElement('div');
messageElement.className = `chat-message ${sender}`;
messageElement.textContent = text;
messageElement.setAttribute('role', 'status');
chatbotMessages.appendChild(messageElement);
chatbotMessages.scrollTop = chatbotMessages.scrollHeight;
}
// Toggle chatbot
chatbotToggle.addEventListener('click', () => {
const isOpen = chatbot.classList.toggle('open');
chatbotToggle.classList.toggle('active', isOpen);
chatbotToggle.setAttribute('aria-expanded', isOpen);
chatbotToggle.setAttribute('aria-label', isOpen ? 'Close AI assistant' : 'Open AI assistant');
if (isOpen) {
chatbotInput.focus();
// Initialize speech features when first opened
if (!speechSynthesis) initSpeechSynthesis();
if (!speechRecognition) initSpeechRecognition();
}
});
// Close chatbot
chatbotClose.addEventListener('click', () => {
chatbot.classList.remove('open');
chatbotToggle.classList.remove('active');
chatbotToggle.setAttribute('aria-expanded', 'false');
chatbotToggle.setAttribute('aria-label', 'Open AI assistant');
});
// Send message on button click
chatbotSend.addEventListener('click', () => {
const message = chatbotInput.value.trim();
if (message) {
processMessage(message);
chatbotInput.value = '';
}
});
// Send message on Enter key
chatbotInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
const message = chatbotInput.value.trim();
if (message) {
processMessage(message);
chatbotInput.value = '';
}
}
});
// Voice input button
const voiceButton = document.createElement('button');
voiceButton.innerHTML = '<i class="fas fa-microphone"></i>';
voiceButton.className = 'accessibility-btn';
voiceButton.style.position = 'absolute';
voiceButton.style.right = '70px';
voiceButton.style.top = '50%';
voiceButton.style.transform = 'translateY(-50%)';
voiceButton.style.background = 'transparent';
voiceButton.style.border = 'none';
voiceButton.style.color = 'var(--text-secondary)';
voiceButton.style.cursor = 'pointer';
voiceButton.setAttribute('aria-label', 'Voice input');
chatbotInput.parentElement.style.position = 'relative';
chatbotInput.parentElement.appendChild(voiceButton);
voiceButton.addEventListener('click', () => {
if (speechRecognition) {
speechRecognition.start();
voiceButton.innerHTML = '<i class="fas fa-microphone-slash"></i>';
voiceButton.style.color = '#ef4444';
speechRecognition.onend = () => {
voiceButton.innerHTML = '<i class="fas fa-microphone"></i>';
voiceButton.style.color = 'var(--text-secondary)';
};
}
});
}