-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1685 lines (1420 loc) · 58.2 KB
/
Copy pathscript.js
File metadata and controls
1685 lines (1420 loc) · 58.2 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
// Debug mode - set to false to disable console logs
const DEBUG_MODE = true;
function debugLog(...args) {
if (DEBUG_MODE) {
console.log(...args);
}
}
// Global variables to store data
let examData = []; // Add missing examData variable
let filteredData = [];
let selectedCourses = [];
let selectedSections = [];
let courseSectionMap = new Map(); // Track which sections belong to which courses
let availableCourses = [];
let availableSections = [];
// DOM elements
const fileInput = document.getElementById('fileInput');
const uploadArea = document.getElementById('uploadArea');
const filtersSection = document.getElementById('filtersSection');
const routineSection = document.getElementById('routineSection');
const loading = document.getElementById('loading');
const deptSelect = document.getElementById('deptSelect');
const courseInput = document.getElementById('courseInput');
const sectionInput = document.getElementById('sectionInput');
const courseSuggestions = document.getElementById('courseSuggestions');
const sectionSuggestions = document.getElementById('sectionSuggestions');
const selectedCoursesContainer = document.getElementById('selectedCourses');
const selectedSectionsContainer = document.getElementById('selectedSections');
const sectionDropdown = document.getElementById('sectionDropdown');
const availableSectionsSelect = document.getElementById('availableSections');
const sectionAutocomplete = document.getElementById('sectionAutocomplete');
const themeToggle = document.getElementById('themeToggle');
// Initialize the application
document.addEventListener('DOMContentLoaded', function() {
initializeEventListeners();
setCurrentDate();
initializeTheme();
initializeScrollToTop();
updateLastUpdated();
});
function initializeEventListeners() {
// File input event
fileInput.addEventListener('change', handleFileSelect);
// Fix the upload area click to properly trigger file input without double popup
uploadArea.addEventListener('click', (e) => {
// Only trigger if clicking on the upload area itself, not the browse button
if (e.target === uploadArea || e.target.closest('.upload-area') && !e.target.closest('.browse-btn')) {
fileInput.click();
}
});
// Browse button click handler
const browseBtn = uploadArea.querySelector('.browse-btn');
if (browseBtn) {
browseBtn.addEventListener('click', (e) => {
e.stopPropagation(); // Prevent event bubbling
fileInput.click();
});
}
// Drag and drop events
uploadArea.addEventListener('dragover', handleDragOver);
uploadArea.addEventListener('dragleave', handleDragLeave);
uploadArea.addEventListener('drop', handleDrop);
// Theme toggle
themeToggle.addEventListener('click', toggleTheme);
// Filter change events
deptSelect.addEventListener('change', onDepartmentChange);
// Autocomplete events
courseInput.addEventListener('input', onCourseInput);
courseInput.addEventListener('keydown', onCourseKeydown);
courseInput.addEventListener('blur', () => {
setTimeout(() => {
if (!courseSuggestions.matches(':hover')) {
hideSuggestions();
// If input is empty or doesn't match a course, reset
if (!courseInput.value || !courseInput.value.includes(' - ')) {
resetCourseSelection();
}
}
}, 200);
});
sectionInput.addEventListener('input', onSectionInput);
sectionInput.addEventListener('keydown', onSectionKeydown);
sectionInput.addEventListener('blur', () => setTimeout(hideSuggestions, 200));
// Hide suggestions when clicking outside
document.addEventListener('click', (e) => {
if (!e.target.closest('.autocomplete-container')) {
hideSuggestions();
}
});
}
function initializeTheme() {
const savedTheme = localStorage.getItem('examRoutineTheme') || 'light';
setTheme(savedTheme);
}
function toggleTheme() {
const currentTheme = document.documentElement.getAttribute('data-theme');
const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
setTheme(newTheme);
}
function setTheme(theme) {
document.documentElement.setAttribute('data-theme', theme);
localStorage.setItem('examRoutineTheme', theme);
// Update toggle button icon
if (themeToggle) {
themeToggle.textContent = theme === 'dark' ? '☀️' : '🌙';
themeToggle.setAttribute('aria-label', `Switch to ${theme === 'dark' ? 'light' : 'dark'} mode`);
}
}
function setCurrentDate() {
const now = new Date();
const dateString = now.toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
const dateElements = document.querySelectorAll('#currentDate');
dateElements.forEach(element => {
element.textContent = dateString;
});
}
// Drag and drop handlers
function handleDragOver(e) {
e.preventDefault();
uploadArea.classList.add('dragover');
}
function handleDragLeave(e) {
e.preventDefault();
uploadArea.classList.remove('dragover');
}
function handleDrop(e) {
e.preventDefault();
uploadArea.classList.remove('dragover');
const files = e.dataTransfer.files;
if (files.length > 0) {
processFile(files[0]);
}
}
function handleFileSelect(e) {
const file = e.target.files[0];
if (file) {
processFile(file);
}
}
function processFile(file) {
// Validate file type
const validTypes = [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.ms-excel'
];
if (!validTypes.includes(file.type) && !file.name.match(/\.(xlsx|xls)$/i)) {
alert('Please select a valid Excel file (.xlsx or .xls)');
return;
}
// Show loading
showLoading(true);
// Read the file
const reader = new FileReader();
reader.onload = function(e) {
try {
parseExcelData(e.target.result);
} catch (error) {
console.error('Error parsing Excel file:', error);
alert('Error reading the Excel file. Please make sure it\'s a valid Excel file.');
showLoading(false);
}
};
reader.readAsArrayBuffer(file);
}
function parseExcelData(data) {
try {
const workbook = XLSX.read(data, { type: 'array' });
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
// Convert to JSON
const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
if (jsonData.length < 2) {
alert('The Excel file appears to be empty or doesn\'t contain enough data.');
showLoading(false);
return;
}
// Process the data
processExamData(jsonData);
} catch (error) {
console.error('Error parsing Excel data:', error);
alert('Error processing the Excel file. Please check the file format.');
showLoading(false);
}
}
function processExamData(rawData) {
// Assume first row contains headers
const headers = rawData[0].map(header =>
header ? header.toString().toLowerCase().trim() : ''
);
// Find column indices based on comprehensive possible header variations
const columnMap = {
department: findColumnIndex(headers, ['dept.', 'dept', 'department', 'dep', 'dpt']),
courseCode: findColumnIndex(headers, ['course code', 'course_code', 'coursecode', 'code', 'course id', 'course-code']),
courseTitle: findColumnIndex(headers, ['course title', 'course_title', 'coursetitle', 'title', 'course name', 'course-title']),
section: findColumnIndex(headers, ['section', 'sec', 'sect']),
teacher: findColumnIndex(headers, ['teacher', 'instructor', 'faculty', 'prof', 'professor']),
date: findColumnIndex(headers, ['exam date', 'exam_date', 'examdate', 'date', 'exam day', 'exam-date']),
time: findColumnIndex(headers, ['exam time', 'exam_time', 'examtime', 'time', 'exam schedule', 'schedule', 'exam-time']),
room: findColumnIndex(headers, ['room', 'venue', 'location', 'hall', 'classroom'])
};
debugLog('Column mapping detected:', columnMap);
debugLog('Headers found:', headers);
// Validate required columns with helpful error messages
const requiredColumns = ['date', 'courseCode', 'section', 'department'];
const missingColumns = requiredColumns.filter(col => columnMap[col] === -1);
if (missingColumns.length > 0) {
const columnRequirements = {
date: 'Date column (try: "Exam Date", "Date", "Exam Day")',
courseCode: 'Course Code column (try: "Course Code", "Code", "Course ID")',
section: 'Section column (try: "Section", "Sec")',
department: 'Department column (try: "Dept", "Department", "Dept.")'
};
const missingDetails = missingColumns.map(col => columnRequirements[col]).join('\n• ');
alert(`Missing required columns in your Excel file:\n\n• ${missingDetails}\n\nPlease ensure your Excel file has columns with these or similar names. Column names are case-insensitive.`);
showLoading(false);
return;
}
debugLog('All required columns found successfully');
// Process data rows
examData = [];
let processedRows = 0;
let validRows = 0;
for (let i = 1; i < rawData.length; i++) {
const row = rawData[i];
processedRows++;
// Skip empty rows
if (!row || row.every(cell => !cell && cell !== 0)) {
debugLog(`Skipping empty row ${i + 1}`);
continue;
}
try {
const examEntry = {
department: (row[columnMap.department] || '').toString().trim(),
courseCode: (row[columnMap.courseCode] || '').toString().trim(),
courseTitle: (row[columnMap.courseTitle] || '').toString().trim(),
section: (row[columnMap.section] || '').toString().trim(),
teacher: (row[columnMap.teacher] || '').toString().trim(),
date: formatDate(row[columnMap.date]),
time: formatTime(row[columnMap.time]) || (row[columnMap.time] || '').toString().trim(),
room: (row[columnMap.room] || '').toString().trim()
};
debugLog(`Row ${i + 1}:`, examEntry);
// Only add rows with essential data
if (examEntry.courseCode && examEntry.section && examEntry.department) {
examData.push(examEntry);
validRows++;
} else {
debugLog(`Row ${i + 1} missing essential data:`, {
courseCode: examEntry.courseCode,
section: examEntry.section,
department: examEntry.department
});
}
} catch (error) {
console.warn(`Error processing row ${i + 1}:`, error, 'Row data:', row);
}
}
debugLog(`Processed ${processedRows} rows, found ${validRows} valid exam entries`);
if (examData.length === 0) {
alert(`No valid exam data found in the file.
Please ensure your Excel file has:
• Course Code column with valid course codes
• Section column with section information
• Department column with department names
• Date column with exam dates
Processed ${processedRows} rows but none contained all required information.`);
showLoading(false);
return;
}
// Populate filters and show them
populateFilters();
showLoading(false);
showFilters();
// Show detailed success message
const uniqueDepts = [...new Set(examData.map(item => item.department))].length;
const uniqueCourses = [...new Set(examData.map(item => item.courseCode))].length;
const uniqueSections = [...new Set(examData.map(item => item.section))].length;
showSuccessMessage(`✅ Successfully loaded ${examData.length} exam entries from ${processedRows} rows!
📊 Found: ${uniqueDepts} departments, ${uniqueCourses} courses, ${uniqueSections} sections`);
}
function findColumnIndex(headers, possibleNames) {
debugLog('Finding column for names:', possibleNames, 'in headers:', headers);
for (const name of possibleNames) {
const index = headers.findIndex(header => {
const headerLower = header.toLowerCase().trim();
const nameLower = name.toLowerCase().trim();
// Exact match
if (headerLower === nameLower) return true;
// Contains match (both ways)
if (headerLower.includes(nameLower) || nameLower.includes(headerLower)) return true;
// Remove special characters and try again
const cleanHeader = headerLower.replace(/[^a-z0-9]/g, '');
const cleanName = nameLower.replace(/[^a-z0-9]/g, '');
if (cleanHeader === cleanName || cleanHeader.includes(cleanName) || cleanName.includes(cleanHeader)) return true;
return false;
});
if (index !== -1) {
debugLog(`Found column "${possibleNames[0]}" at index ${index} (header: "${headers[index]}")`);
return index;
}
}
debugLog(`Column not found for names:`, possibleNames);
return -1;
}
function formatTime(timeValue) {
if (!timeValue) return '';
const timeStr = timeValue.toString().trim();
debugLog('Formatting time:', timeStr);
// If it's already in a good format, return it
if (timeStr.match(/^\d{1,2}:\d{2}\s*[AP]M(\s*[-–—]\s*\d{1,2}:\d{2}\s*[AP]M)?$/i)) {
return timeStr;
}
// Handle Excel time serial numbers
if (typeof timeValue === 'number' && timeValue < 1) {
try {
const hours = Math.floor(timeValue * 24);
const minutes = Math.floor((timeValue * 24 * 60) % 60);
const ampm = hours >= 12 ? 'PM' : 'AM';
const displayHours = hours === 0 ? 12 : hours > 12 ? hours - 12 : hours;
const formatted = `${displayHours}:${minutes.toString().padStart(2, '0')} ${ampm}`;
debugLog('Converted Excel time serial', timeValue, 'to', formatted);
return formatted;
} catch (error) {
console.warn('Excel time parsing error:', error);
return timeStr;
}
}
// Handle 24-hour format conversion to 12-hour
if (timeStr.match(/^\d{1,2}:\d{2}$/)) {
try {
const [hours, minutes] = timeStr.split(':');
const hour24 = parseInt(hours, 10);
const ampm = hour24 >= 12 ? 'PM' : 'AM';
const displayHours = hour24 === 0 ? 12 : hour24 > 12 ? hour24 - 12 : hour24;
const formatted = `${displayHours}:${minutes} ${ampm}`;
debugLog('Converted 24-hour', timeStr, 'to', formatted);
return formatted;
} catch (error) {
console.warn('24-hour conversion error:', error);
return timeStr;
}
}
// Handle time ranges with different separators
if (timeStr.includes('-') || timeStr.includes('–') || timeStr.includes('—') || timeStr.includes('to')) {
const separators = ['-', '–', '—', 'to'];
let separator = separators.find(sep => timeStr.includes(sep));
if (separator) {
const parts = timeStr.split(separator).map(p => p.trim());
if (parts.length === 2) {
const startTime = formatTime(parts[0]);
const endTime = formatTime(parts[1]);
return `${startTime} - ${endTime}`;
}
}
}
return timeStr;
}
function formatDate(dateValue) {
if (!dateValue) return '';
// Handle Excel date serial numbers (Excel stores dates as numbers)
if (typeof dateValue === 'number') {
try {
const date = XLSX.SSF.parse_date_code(dateValue);
const months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
return `${months[date.m - 1]} ${String(date.d).padStart(2, '0')}, ${date.y}`;
} catch (error) {
console.warn('Excel date parsing error:', error);
return dateValue.toString();
}
}
// Handle string dates
if (typeof dateValue === 'string') {
const dateStr = dateValue.trim();
// If it's already in "Month DD, YYYY" format, keep it
if (dateStr.match(/^\w+ \d{1,2}, \d{4}$/)) {
return dateStr;
}
// Try to parse various date formats
let parsedDate;
try {
// Handle common formats: MM/DD/YYYY, DD/MM/YYYY, YYYY-MM-DD, etc.
parsedDate = new Date(dateStr);
// If that fails, try other parsing methods
if (isNaN(parsedDate.getTime())) {
// Try YYYY-MM-DD format specifically
if (dateStr.match(/^\d{4}-\d{1,2}-\d{1,2}$/)) {
const parts = dateStr.split('-');
parsedDate = new Date(parseInt(parts[0]), parseInt(parts[1]) - 1, parseInt(parts[2]));
}
// Try DD/MM/YYYY or MM/DD/YYYY
else if (dateStr.match(/^\d{1,2}[\/\-]\d{1,2}[\/\-]\d{4}$/)) {
const parts = dateStr.split(/[\/\-]/);
// Assume MM/DD/YYYY format first
parsedDate = new Date(parseInt(parts[2]), parseInt(parts[0]) - 1, parseInt(parts[1]));
// If day > 12, try DD/MM/YYYY format
if (parseInt(parts[0]) > 12) {
parsedDate = new Date(parseInt(parts[2]), parseInt(parts[1]) - 1, parseInt(parts[0]));
}
}
}
if (!isNaN(parsedDate.getTime())) {
const months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
return `${months[parsedDate.getMonth()]} ${String(parsedDate.getDate()).padStart(2, '0')}, ${parsedDate.getFullYear()}`;
}
} catch (error) {
console.warn('Date parsing error:', error, 'for date:', dateStr);
}
}
return dateValue.toString();
}
function populateFilters() {
// Get unique values
const departments = [...new Set(examData.map(item => item.department).filter(d => d))];
// Create course objects with code and title
const courseMap = new Map();
examData.forEach(item => {
if (item.courseCode && item.courseTitle) {
courseMap.set(item.courseCode, {
code: item.courseCode,
title: item.courseTitle,
department: item.department
});
}
});
availableCourses = Array.from(courseMap.values());
const sections = [...new Set(examData.map(item => item.section).filter(s => s))];
availableSections = sections.map(section => ({ section, department: '' }));
// Populate department select
deptSelect.innerHTML = '<option value="">All Departments</option>';
departments.sort().forEach(dept => {
const option = document.createElement('option');
option.value = dept;
option.textContent = dept;
deptSelect.appendChild(option);
});
// Reset selections and hide all dropdowns/autocompletes
selectedCourses = [];
selectedSections = [];
courseSectionMap.clear(); // Clear the course-section mapping
sectionDropdown.style.display = 'none';
sectionAutocomplete.style.display = 'none';
updateSelectedDisplay();
}
function onDepartmentChange() {
const selectedDept = deptSelect.value;
// Filter courses based on department
let filteredCourses;
if (selectedDept) {
const courseMap = new Map();
examData
.filter(item => item.department === selectedDept)
.forEach(item => {
if (item.courseCode && item.courseTitle) {
courseMap.set(item.courseCode, {
code: item.courseCode,
title: item.courseTitle,
department: item.department
});
}
});
availableCourses = Array.from(courseMap.values());
} else {
const courseMap = new Map();
examData.forEach(item => {
if (item.courseCode && item.courseTitle) {
courseMap.set(item.courseCode, {
code: item.courseCode,
title: item.courseTitle,
department: item.department
});
}
});
availableCourses = Array.from(courseMap.values());
}
// Reset selections
selectedCourses = [];
selectedSections = [];
courseSectionMap.clear(); // Clear the course-section mapping
courseInput.value = '';
sectionInput.value = '';
resetCourseSelection();
updateSelectedDisplay();
updateAvailableSections();
// Hide section autocomplete when department changes
sectionAutocomplete.style.display = 'none';
}
// Autocomplete functions
function onCourseInput() {
const query = courseInput.value.toLowerCase().trim();
if (query.length === 0) {
hideSuggestions();
// Hide section-related UI when course input is cleared
sectionDropdown.style.display = 'none';
sectionAutocomplete.style.display = 'none';
return;
}
const selectedDept = deptSelect.value;
let filtered = availableCourses.filter(course => {
const deptMatch = !selectedDept || course.department === selectedDept;
const alreadySelected = selectedCourses.some(selected => selected.code === course.code);
// Enhanced matching: support initials, course code, and full text
const matchesQuery =
course.code.toLowerCase().includes(query) ||
course.title.toLowerCase().includes(query) ||
matchesInitials(course.title, query) ||
matchesInitials(course.code, query);
return deptMatch && !alreadySelected && matchesQuery;
});
showCourseSuggestions(filtered.slice(0, 8));
}
// Helper function to match initials (e.g., "cn" matches "Computer Networks")
function matchesInitials(text, query) {
if (query.length < 2) return false;
const words = text.toLowerCase().split(/[\s\/\-_]+/).filter(word => word.length > 0);
const initials = words.map(word => word.charAt(0)).join('');
return initials.includes(query) || initials.startsWith(query);
}
function onCourseKeydown(e) {
const suggestions = courseSuggestions.querySelectorAll('.suggestion-item');
const highlighted = courseSuggestions.querySelector('.highlighted');
if (e.key === 'ArrowDown') {
e.preventDefault();
const next = highlighted ? highlighted.nextElementSibling : suggestions[0];
if (next) {
if (highlighted) highlighted.classList.remove('highlighted');
next.classList.add('highlighted');
}
} else if (e.key === 'ArrowUp') {
e.preventDefault();
const prev = highlighted ? highlighted.previousElementSibling : suggestions[suggestions.length - 1];
if (prev) {
if (highlighted) highlighted.classList.remove('highlighted');
prev.classList.add('highlighted');
}
} else if (e.key === 'Enter') {
e.preventDefault();
if (highlighted) {
const courseCode = highlighted.dataset.code;
selectCourseForSectionSelection(courseCode);
}
} else if (e.key === 'Escape') {
hideSuggestions();
resetCourseSelection();
}
}
function resetCourseSelection() {
courseInput.value = '';
sectionDropdown.style.display = 'none';
sectionAutocomplete.style.display = 'none'; // Hide section autocomplete when resetting
}
function onSectionInput() {
const query = sectionInput.value.toLowerCase().trim();
if (query.length === 0) {
hideSuggestions();
return;
}
const selectedDept = deptSelect.value;
let sections;
if (selectedCourses.length > 0) {
// Filter sections based on selected courses
sections = [...new Set(examData
.filter(item => {
const deptMatch = !selectedDept || item.department === selectedDept;
const courseMatch = selectedCourses.some(course => course.code === item.courseCode);
return deptMatch && courseMatch;
})
.map(item => item.section)
.filter(s => s))];
} else if (selectedDept) {
sections = [...new Set(examData
.filter(item => item.department === selectedDept)
.map(item => item.section)
.filter(s => s))];
} else {
sections = [...new Set(examData.map(item => item.section).filter(s => s))];
}
const filtered = sections.filter(section => {
const alreadySelected = selectedSections.includes(section);
const matchesQuery = section.toLowerCase().includes(query);
return !alreadySelected && matchesQuery;
});
showSectionSuggestions(filtered.slice(0, 5));
}
function onSectionKeydown(e) {
const suggestions = sectionSuggestions.querySelectorAll('.suggestion-item');
const highlighted = sectionSuggestions.querySelector('.highlighted');
if (e.key === 'ArrowDown') {
e.preventDefault();
const next = highlighted ? highlighted.nextElementSibling : suggestions[0];
if (next) {
if (highlighted) highlighted.classList.remove('highlighted');
next.classList.add('highlighted');
}
} else if (e.key === 'ArrowUp') {
e.preventDefault();
const prev = highlighted ? highlighted.previousElementSibling : suggestions[suggestions.length - 1];
if (prev) {
if (highlighted) highlighted.classList.remove('highlighted');
prev.classList.add('highlighted');
}
} else if (e.key === 'Enter') {
e.preventDefault();
if (highlighted) {
const section = highlighted.dataset.section;
selectSection(section);
}
} else if (e.key === 'Escape') {
hideSuggestions();
}
}
function showCourseSuggestions(courses) {
courseSuggestions.innerHTML = '';
if (courses.length === 0) {
hideSuggestions();
return;
}
courses.forEach(course => {
const item = document.createElement('div');
item.className = 'suggestion-item';
item.dataset.code = course.code;
item.innerHTML = `
<div class="suggestion-code">${course.code}</div>
<div class="suggestion-title">${course.title}</div>
`;
item.addEventListener('click', () => selectCourseForSectionSelection(course.code));
courseSuggestions.appendChild(item);
});
courseSuggestions.style.display = 'block';
}
function selectCourseForSectionSelection(courseCode) {
const course = availableCourses.find(c => c.code === courseCode);
if (!course) return;
// Clear the input but don't add to selected courses yet
courseInput.value = `${course.code} - ${course.title}`;
hideSuggestions();
// Show sections for this course (this will show the dropdown and hide autocomplete)
showSectionsForCourse(courseCode);
// Don't show section autocomplete here - the dropdown is the primary interface
// Section autocomplete is only for additional general section search
}
function showSectionsForCourse(courseCode) {
const selectedDept = deptSelect.value;
// Get sections for this specific course
const courseSections = [...new Set(examData
.filter(item => {
const deptMatch = !selectedDept || item.department === selectedDept;
const courseMatch = item.courseCode === courseCode;
return deptMatch && courseMatch;
})
.map(item => item.section)
.filter(s => s))];
// Populate the dropdown
availableSectionsSelect.innerHTML = '';
if (courseSections.length === 0) {
const option = document.createElement('option');
option.value = '';
option.textContent = 'No sections available for this course';
option.disabled = true;
availableSectionsSelect.appendChild(option);
} else {
courseSections.sort().forEach(section => {
const option = document.createElement('option');
option.value = section;
option.textContent = `Section ${section}`;
availableSectionsSelect.appendChild(option);
});
}
// Clear any previous selection
availableSectionsSelect.selectedIndex = -1;
// Show the section dropdown and hide autocomplete
sectionDropdown.style.display = 'block';
sectionAutocomplete.style.display = 'none';
}
function addSelectedSections() {
const selectedOption = availableSectionsSelect.options[availableSectionsSelect.selectedIndex];
if (!selectedOption || !selectedOption.value) {
alert('Please select a section.');
return;
}
// Get the course from the input
const courseText = courseInput.value;
const courseCode = courseText.split(' - ')[0];
const course = availableCourses.find(c => c.code === courseCode);
if (!course) return;
// Add course to selected courses if not already there
if (!selectedCourses.some(selected => selected.code === courseCode)) {
selectedCourses.push(course);
}
// Track course-section relationships
const section = selectedOption.value;
if (!selectedSections.includes(section)) {
selectedSections.push(section);
}
// Store which course this section was selected for
courseSectionMap.set(courseCode, [section]); // Only one section per course
// Animate fade-out for dropdown
sectionDropdown.classList.add('fade-out');
setTimeout(() => {
sectionDropdown.style.display = 'none';
sectionDropdown.classList.remove('fade-out');
// Reset the interface
courseInput.value = '';
sectionAutocomplete.style.display = 'none'; // Hide section autocomplete after adding sections
// Update display with fade-in
updateSelectedDisplay(true);
updateAvailableSections();
}, 300);
}
function showSectionSuggestions(sections) {
sectionSuggestions.innerHTML = '';
if (sections.length === 0) {
hideSuggestions();
return;
}
sections.forEach(section => {
const item = document.createElement('div');
item.className = 'suggestion-item';
item.dataset.section = section;
item.textContent = section;
item.addEventListener('click', () => selectSection(section));
sectionSuggestions.appendChild(item);
});
sectionSuggestions.style.display = 'block';
}
function hideSuggestions() {
courseSuggestions.style.display = 'none';
sectionSuggestions.style.display = 'none';
}
function selectCourse(courseCode) {
const course = availableCourses.find(c => c.code === courseCode);
if (course && !selectedCourses.some(selected => selected.code === courseCode)) {
selectedCourses.push(course);
courseInput.value = '';
hideSuggestions();
updateSelectedDisplay();
updateAvailableSections();
}
}
function selectSection(section) {
if (!selectedSections.includes(section)) {
selectedSections.push(section);
sectionInput.value = '';
hideSuggestions();
updateSelectedDisplay();
}
}
function removeSelectedCourse(courseCode) {
// Remove the course
selectedCourses = selectedCourses.filter(course => course.code !== courseCode);
// Remove sections that were selected for this course
const courseSections = courseSectionMap.get(courseCode) || [];
courseSections.forEach(section => {
const sectionIndex = selectedSections.indexOf(section);
if (sectionIndex > -1) {
selectedSections.splice(sectionIndex, 1);
}
});
// Remove from course-section mapping
courseSectionMap.delete(courseCode);
updateSelectedDisplay();
updateAvailableSections();
}
function removeSelectedSection(section) {
// Remove the section from selectedSections
selectedSections = selectedSections.filter(s => s !== section);
// Remove from course-section mapping and clean up courses with no sections
for (const [courseCode, sections] of courseSectionMap.entries()) {
const sectionIndex = sections.indexOf(section);
if (sectionIndex > -1) {
sections.splice(sectionIndex, 1);
// If this course has no more sections, remove the course entirely
if (sections.length === 0) {
courseSectionMap.delete(courseCode);
selectedCourses = selectedCourses.filter(course => course.code !== courseCode);
}
}
}
updateSelectedDisplay();
}
function updateSelectedDisplay(fadeIn) {
// Update selected courses display with their sections
const coursesHtml = selectedCourses.map(course => {
const courseSections = courseSectionMap.get(course.code) || [];
const sectionsText = courseSections.length > 0 ? ` (Sections: ${courseSections.join(', ')})` : '';
return `
<div class="selected-item">
<span>${course.code} - ${course.title}${sectionsText}</span>
<button class="remove-btn" onclick="removeSelectedCourse('${course.code}')">×</button>
</div>
`;
}).join('');
selectedCoursesContainer.innerHTML = `
<div class="selected-label">Selected Courses & Sections:</div>
${coursesHtml}
`;
// Fade-in animation
if (fadeIn) {
selectedCoursesContainer.classList.add('fade-in');
setTimeout(() => selectedCoursesContainer.classList.remove('fade-in'), 400);
}
// Update selected sections display (simplified)
const sectionsHtml = selectedSections.map(section => `
<div class="selected-item">
<span>Section ${section}</span>
<button class="remove-btn" onclick="removeSelectedSection('${section}')">×</button>
</div>
`).join('');
selectedSectionsContainer.innerHTML = `
<div class="selected-label">All Selected Sections:</div>
${sectionsHtml}
`;
}
function updateAvailableSections() {
// This function updates available sections based on selected courses
// Implementation is handled in onSectionInput
}
function generateRoutine() {
const selectedDept = deptSelect.value;
const selectedCourseCodes = selectedCourses.map(course => course.code);
if (selectedSections.length === 0) {
alert('Please select at least one section to generate the routine.');
return;
}
debugLog('Generating routine with:');
debugLog('Selected courses:', selectedCourseCodes);
debugLog('Selected sections:', selectedSections);
debugLog('Course-section map:', courseSectionMap);
// Clear previous routine data
filteredData = [];
const routineBody = document.getElementById('routineBody');
if (routineBody) {
routineBody.innerHTML = '';
}
// Filter data based on exact course-section combinations
filteredData = examData.filter(item => {
const deptMatch = !selectedDept || item.department === selectedDept;
// Check if this is an exact course-section combination we selected
let isValidCombination = false;
if (selectedCourseCodes.length === 0) {
// If no specific courses selected, include all sections we selected
isValidCombination = selectedSections.includes(item.section);
} else {
// Check if this course-section combination was specifically selected