forked from hmc-tools/hmc-scheduler
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathscheduler.js
executable file
·1611 lines (1388 loc) · 47.6 KB
/
scheduler.js
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
var globalCourseData = {};
var globalCourseSearch = [];
var globalCourses;
var globalFavCourses;
var globalTerm;
var globalShowMoreIndex;
var globalCourseAreas = {};
fetch('/data/main.json').then(function(response){
return response.json();
}).then(function(json) {
globalTerm = json['selected'];
globalCourseData[globalTerm] = json['selected_data'];
createDropdownBlock("Course Term:", "course-terms", globalTerm);
createDropdownBlock("Course Area:", "course-areas", "All");
var terms = json['terms']; // TODO: implement all
var areas = json['areas'];
areas.unshift("All")
createDropdown("#course-terms", terms);
createDropdown("#course-areas", areas);
$(".dropdown-menu li a").click(function() {
$(this).parents(".dropdown").find(".btn").html($(this).text() + getCaret());
$(this).parents(".dropdown").find(".btn").attr('realVal', $(this).text());
updateSearch();
})
fetchCourseAreas();
//getAllDepartments();
addExtraAttributes();
updateSearch();
})
function fetchCourseAreas() {
term = globalTerm;
if(!(term in globalCourseAreas)) {
fetch('/data/'+term+'_infomap.json').then(function(response) {
return response.json();
}, function(error) {
globalCourseAreas[term] = {}
}).then(function(json){
globalCourseAreas[term] = json;
area = $("#course-areas_btn").attr('realVal');
if(area != "All") updateSearch();
}, function(error) {
globalCourseAreas[term] = {}
})
}
}
function getAllDepartments() {
var depts = {};
for (key of globalCourseData) {
//TODO: Get rid of this later
var dept = "";
if (key['departments']) {
jQuery.each(key['departments'], function() {
if (this['Name']) {
dept += this['Name'] + ' ';
}
})
if (!(dept in depts)) {
depts[dept] = 1;
} else {
depts[dept] = depts[dept] + 1;
}
}
}
}
function addExtraAttributes() {
for (var id in globalCourseData[globalTerm]) {
key = globalCourseData[globalTerm][id]
//Add the campus the course is on to its attributes
//Currently, courses which are jointly taught (JT) will not show up no matter which college you select.
var courseCode = id.slice(-2);
var college = "";
switch (courseCode) {
case 'HM':
college = "Harvey Mudd";
break;
case 'CG':
college = "Claremont Graduate University";
break;
case 'CM':
college = "Claremont McKenna";
break;
case 'SC':
college = "Scripps";
break;
case 'PO':
college = "Pomona";
break;
case 'PZ':
college = "Pitzer";
break;
case 'KS':
college = "Keck Science";
break;
case 'JM':
college = "Joint Music";
break;
case 'JP':
college = "CMS PE";
break;
default:
college = "Other";
break;
}
key.campus = college;
// Add its filled status (whether or not there are empty seats left)
// Currently, full is false if there is even 1 unfilled section
// Default: starts out as true (and will remain that way if there is no data on fullness)
//sectionTimeMap = {};
for (var i in key['sections']) {
section = key['sections'][i];
//var term = session['designator'];
var full = true;
if (section['capacity'] && section['currentEnrollment'] && (section['currentEnrollment'] < section['capacity'])) {
full = false;
}
section.full = full;
}
}
}
function updateSearch() {
globalTerm = $("#course-terms_btn").attr('realVal');
if (!globalTerm) {
return;
}
if (globalTerm == 'All') {
globalTerm = "";
} else {
if(!(globalTerm in globalCourseData)) {
fetchCourseAreas();
globalCourseData[globalTerm] = null;
term = globalTerm
fetch('/data/' + term + '.json').then(function(response){
return response.json();
}).then(function(json) {
globalCourseData[term] = json
}).then(updateSearch);
return
} else if(globalCourseData[globalTerm] == null) {
return
}
}
var code = document.getElementById("course-code").value;
var title = document.getElementById("course-title").value;
var useTitleRegex = document.getElementById("title-regex").checked;
var useCodeRegex = document.getElementById("code-regex").checked;
var instructor = document.getElementById("instructor").value;
var useInstructorRegex = document.getElementById("prof-regex").checked;
var campus = $("#campus_btn").attr('realVal') || false;
var coursearea = $("#course-areas_btn").attr('realVal') || false;
var filled = document.getElementById("filled-regex").checked;
var department = $("#department_btn").attr('realVal') || false;
if (campus === "All") {
campus = false;
}
if (department === "All") {
department = false;
}
// Implement title, code, and instructor regex
var titleRe = implementRegex(useTitleRegex, title);
var codeRe = implementRegex(useCodeRegex, code);
var instructorRe = implementRegex(useInstructorRegex, instructor);
validCourses = []
for(var id in globalCourseData[globalTerm]) {
validCourses.push(globalCourseData[globalTerm][id])
}
validCourses = getCoursesFromAttributeRegex(validCourses, "name", titleRe);
validCourses = getCoursesFromAttributeRegex(validCourses, "id", codeRe);
validCourses = getInstructorRegex(validCourses, instructorRe);
if (campus != false) {
validCourses = getCoursesFromAttribute(validCourses, "campus", campus);
}
if (filled) {
validCourses = getCoursesFilled(validCourses);
}
if (department != false) {
validCourses = getCoursesFromDept(validCourses, department);
}
if (coursearea != "All" && term in globalCourseAreas) {
validCourses = getCoursesFromArea(validCourses, coursearea);
}
// if (globalTerm != "") {
// validCourses = filterCoursesByCalendar(validCourses, "designator", globalTerm);
// }
globalCourseSearch = validCourses;
repopulateChart();
}
function implementRegex(useRegex, term) {
if (!useRegex) { //TODO: Why did we get rid of the excalmation point... used to be (!useRegex)
term = term.replace(/[\-\[\]\/\{\}\(\)\+\.\\\^\$\|]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".").replace(/\s+/g, "\\s+");
return RegExp(".*" + term + ".*", "i");
} else {
return RegExp(term, "i");
}
}
function toAmPmTime(timestring) {
if (timestring.length === 3) {
timestring = '0' + timestring;
}
hours = timestring.substring(0, 2);
ispm = hours > 12;
if (ispm) hours = '' + (hours - 12);
if (hours.length === 1) {
hours = '0' + hours;
}
if (timestring[2] === ':') {
minutes = timestring.substring(3,5);
} else {
minutes = timestring.substring(2, 4);
}
return hours + ':' + minutes + (ispm ? 'PM' : 'AM');
}
function toCourseObject(courseJson) {
var courseName = courseJson['name'];
var timeslots = '';
var isfirsttimeslot = true;
for (var sectionId in courseJson['sections']) {
section = courseJson['sections'][sectionId]
if (!isfirsttimeslot) {
timeslots += '\n';
}
var instructorName = '';
if (section['instructors'] && section['instructors'].length > 0) {
var instructor = section['instructors'][0];
instructorName = instructor.split(',')[0];
} else {
instructorName = 'Unknown';
}
var timeslot = '';
timeslot += section['section_id'];
timeslot += ' (';
timeslot += instructorName;
timeslot += '): ';
var isFirstTime = true;
for (var schedule of section['schedule']) {
if (!isFirstTime) {
timeslot += ', ';
}
isFirstTime = false;
timeslot += schedule['days'];
timeslot += ' ';
timeslot += toAmPmTime(schedule['start_time']);
timeslot += '-';
timeslot += toAmPmTime(schedule['end_time']);
timeslot += '; ';
timeslot += schedule['site'];
}
timeslots += timeslot;
isfirsttimeslot = false;
}
return {
name: courseName,
times: timeslots,
selected: true,
data: courseJson
};
}
var options = {
'showSections': false,
'allowConflicts': false
};
function randomColor(seed) {
if (!seed)
seed = '' + Math.random();
// Use a hash function (djb2) to generate a deterministic but "random" color.
var hash = 5381 % 359;
for (var i = 0; i < seed.length; i++)
hash = (((hash << 5) + hash) + seed.charCodeAt(i)) % 359;
return 'hsl(' + hash + ', 73%, 90%)'
// Even though we should use "% 360" for all possible values, using 359 makes for fewer hash collisions.
}
var openNode = false;
var tabIndex = 0;
function addCourse(course, courses, favoriteCourses, fc) {
// Make a new course node
var courseNode = document.getElementById('course-template').cloneNode(true);
courseNode.classList.remove('template');
course._node = courseNode;
course._node.toJSON = function() {
return undefined;
};
// Fill in the values
if (course.name) courseNode.querySelector('input[type="text"]').value = course.name;
courseNode.querySelector('input[type="checkbox"]').checked = course.selected;
if (course.times) courseNode.querySelector('textarea').value = course.times;
courseNode.querySelector('input[type="text"]').style.backgroundColor = course.color || randomColor(course.name);
// Collapsing and expanding
courseNode.querySelector('input[type="text"]').onfocus = function() {
if (openNode && openNode != courseNode)
openNode.classList.add('collapsed');
openNode = courseNode;
openNode.classList.remove('collapsed');
};
/*courseNode.querySelector('input[type="text"]').ondblclick = function () {
openNode.classList.add('collapsed');
openNode = false;
};*/
// Data updating
courseNode.querySelector('input[type="text"]').onchange = function() {
course.name = this.value;
save('courses', courses);
document.getElementById('button-generate').disabled = false;
};
courseNode.querySelector('textarea').onchange = function() {
course.times = this.value.trim();
// Add a trailing line break to facilitate copy/paste
if (this.value[this.value.length - 1] != '\n')
this.value += '\n';
save('courses', courses);
document.getElementById('button-generate').disabled = false;
};
courseNode.querySelector('input[type="checkbox"]').onchange = function() {
course.selected = !!this.checked;
save('courses', courses);
document.getElementById('button-generate').disabled = false;
};
// Tabbing
courseNode.querySelector('input[type="text"]').setAttribute('tabindex', ++tabIndex);
courseNode.querySelector('textarea').setAttribute('tabindex', ++tabIndex);
// Deleting
courseNode.querySelector('.x').onclick = function() {
if (confirm('Are you sure you want to delete ' + (course.name || 'this class') + '?')) {
courses.splice(courses.indexOf(course), 1);
courseNode.parentNode.removeChild(courseNode);
save('courses', courses);
document.getElementById('button-generate').disabled = false;
if (courses.length == 0) {
document.getElementById('courses-container').classList.add('empty');
document.getElementById('courses-container').classList.remove('not-empty');
}
}
return false;
};
// Change colors
courseNode.querySelector('.c').onclick = function() {
var color = course.color || randomColor(course.name);
courseNode.querySelector('input[type="text"]').style.backgroundColor = course.color = color.replace(/\d+/, function(hue) {
return (+hue + 24) % 360;
});
save('courses', courses);
document.getElementById('button-generate').disabled = false;
return false;
};
if (fc) {
courseNode.getElementsByClassName('atf')[0].style = 'display: none;';
courseNode.getElementsByClassName('fta')[0].style = '';
document.getElementById('favorite-courses').appendChild(courseNode);
document.getElementById('favorite-courses-container').classList.remove('empty');
document.getElementById('favorite-courses-container').classList.add('not-empty');
} else {
document.getElementById('courses').appendChild(courseNode);
document.getElementById('courses-container').classList.remove('empty');
document.getElementById('courses-container').classList.add('not-empty');
document.getElementById('button-generate').disabled = false;
}
}
function timeToHours(h, m, pm) {
return h + m / 60 + (pm && h != 12 ? 12 : 0);
}
function formatHours(hours) {
var h = Math.floor(hours) % 12 || 12;
var m = Math.round((hours % 1) * 60);
return h + ':' + ('0' + m).substr(-2) + (hours >= 12 ? 'pm' : 'am');
}
function loadSchedule(schedules, i) {
i = Math.min(schedules.length - 1, Math.max(i, 0));
// Some UI
document.getElementById('button-left').disabled = i <= 0;
document.getElementById('button-right').disabled = i + 1 >= schedules.length;
document.getElementById('page-number').innerHTML = i + 1;
document.getElementById('page-count').innerHTML = schedules.length;
document.getElementById('button-save').disabled = schedules.length == 0;
document.getElementById('button-export').disabled = schedules.length == 0;
document.getElementById('button-print').disabled = schedules.length == 0;
document.getElementById('page-counter').classList.add(schedules.length ? 'not-empty' : 'empty');
document.getElementById('page-counter').classList.remove(schedules.length ? 'empty' : 'not-empty');
setCreditCounter(schedules[i] || []);
drawSchedule(schedules[i] || []);
return i;
}
function setCreditCounter(schedule) {
var seenSoFar = new Set();
var count = schedule.filter(function(timeSlot) {
if (seenSoFar.has(timeSlot.section)) return false;
seenSoFar.add(timeSlot.section);
return true;
}).map(function(course) {
if (!course.sectionData) {
return NaN;
}
return getCredits(course.sectionData);
}).reduce(function(a, b) {
return a + b;
}, 0);
document.getElementById('credit-counter').innerHTML = isNaN(count) ? '' : '(' + count.toFixed(1) + ' credits)';
}
function getCredits(sectionData) {
if (!('credits' in sectionData)) {
return NaN;
}
switch(sectionData['campus']) {
case 'HM':
// Mudd courses are worth their full value.
return sectionData['credits'];
case 'JM':
// Joint music courses seems to be halved?
return sectionData['credits'] * 2;
default:
switch(sectionData['credits']) {
case 0.25:
// Usually quarter-credit off-campus becomes 1-credit.
return 1
default:
// Other colleges' courses usually need to be multiplied by three.
return sectionData['credits'] * 3;
}
}
}
function drawSchedule(schedule) {
var days = Array.prototype.slice.call(document.querySelectorAll('.day'));
var beginHour = 8 - 0.5; // Starts at 8am
var hourHeight = document.querySelector('#schedule li').offsetHeight;
// Clear the schedule
days.forEach(function(day) {
while (day.firstChild)
day.removeChild(day.firstChild);
});
// Add each time slot
schedule.forEach(function(timeSlot) {
var div = document.createElement('div');
div.classList.add('classDiv')
div.style.top = hourHeight * (timeSlot.from - beginHour) + 'px';
div.style.setProperty('background-color', 'unset');
var bgColor = timeSlot.course.color || randomColor(timeSlot.course.name);
// this way, color is maintained even when printing
div.style.setProperty('box-shadow', 'inset 0 0 0 1000px '+bgColor, 'important')
//div.style.setProperty('background-color', bgColor, 'important');
div.innerHTML = (options.showSections && timeSlot.section ?
timeSlot.section.replace(/^([^(]+)\((.*)\)/, function(_, code, profs) {
return '<b>' + code + '</b><br />' + profs;
}) :
'<b>' + timeSlot.course.name + '</b>') +
'<br />' + formatHours(timeSlot.from) + ' - ' + formatHours(timeSlot.to);
days[timeSlot.weekday].appendChild(div);
// Vertically center
var supposedHeight = (timeSlot.to - timeSlot.from) * hourHeight;
var paddingHeight = (supposedHeight - div.offsetHeight) / 2;
div.style.padding = paddingHeight + 'px 0';
div.style.height = (supposedHeight /*- paddingHeight * 2*/ ) + 'px';
});
}
function addSavedSchedule(name, schedule, savedSchedules) {
var div = document.createElement('div');
var scheduleLink = document.createElement('a');
scheduleLink.href = '#';
scheduleLink.onclick = function() {
drawSchedule(schedule);
document.getElementById('button-generate').disabled = false;
return false;
};
scheduleLink.appendChild(document.createTextNode(name));
var removeLink = document.createElement('a');
removeLink.href = '#';
removeLink.className = 'x';
removeLink.onclick = function() {
if (confirm('Are you sure you want to delete this saved schedule?')) {
div.parentNode.removeChild(div);
delete savedSchedules[name];
if (document.getElementById('saved-schedules').children.length == 0) {
document.getElementById('saved-schedules-container').classList.add('empty');
document.getElementById('saved-schedules-container').classList.remove('not-empty');
}
save('savedSchedules', savedSchedules);
}
return false;
};
removeLink.appendChild(document.createTextNode('x'));
div.appendChild(scheduleLink);
div.appendChild(document.createTextNode(' '));
div.appendChild(removeLink);
document.getElementById('saved-schedules-container').classList.remove('empty');
document.getElementById('saved-schedules-container').classList.add('not-empty');
document.getElementById('saved-schedules').appendChild(div);
}
function download(filename, text) {
var a = document.createElement('a');
a.href = 'data:text/plain;charset=utf-8,' + encodeURIComponent(text);
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
function exportSchedule(mapOfCourses) {
var header = 'BEGIN:VCALENDAR\nVERSION:2.0\nPRODID:-//HMC Scheduler//EN\n';
var footer = 'END:VCALENDAR\n';
var result = '';
result += header;
for (i in mapOfCourses) {
var vevent = new VEventObject(mapOfCourses[i]);
result += vevent.toString();
}
result += footer;
return result;
}
function padZero(n, pad) {
var s = '' + n;
while (s.length < pad)
s = '0' + s;
return s;
}
function formatDate(date) {
return [
padZero(date.getFullYear(), 4),
padZero(date.getMonth() + 1, 2),
padZero(date.getDate(), 2),
'T',
padZero(date.getHours(), 2),
padZero(date.getMinutes(), 2),
padZero(date.getSeconds(), 2)
].join('');
}
function VEventObject(timeBlocks) {
this.weekdays = [];
for (i in timeBlocks) {
this.weekdays.push(timeBlocks[i].weekday);
}
this.startTime = timeBlocks[0].from;
this.endTime = timeBlocks[0].to;
this.startDate = new Date(Date.parse(timeBlocks[0].sectionData.startDate));
// Update the start date of the class to the first day where there is
// actually a class (according to the MTWRF flags)
var startDay = this.startDate.getDay();
var daysTillClasses = this.weekdays.map(function(weekday) {
var day = weekday + 1;
return (7 + day - startDay) % 7;
});
var daysTillFirstClass = Math.min.apply(null, daysTillClasses);
this.startDate.setDate(this.startDate.getDate() + daysTillFirstClass);
this.endDate = new Date(Date.parse(timeBlocks[0].sectionData.endDate));
this.name = timeBlocks[0].course.name;
this.loc = timeBlocks[0].loc;
this.toString = function() {
var days = ['MO', 'TU', 'WE', 'TH', 'FR'];
var startDateFull = dateAddHoursAndMinutes(this.startDate, this.startTime);
var endDateFull = dateAddHoursAndMinutes(this.startDate, this.endTime); //no "overnight" classes
var header = 'BEGIN:VEVENT\n';
var footer = 'END:VEVENT\n';
var uid = 'UID:' + this.startDate + this.startTime + '-' + (new Date()).getTime() + '\n';
var dtstart = 'DTSTART:' + formatDate(startDateFull) + '\n';
var dtend = 'DTEND:' + formatDate(endDateFull) + '\n';
var dtstamp = 'DTSTAMP:' + formatDate(new Date()) + '\n';
var place = 'LOCATION:' + this.loc.replace(/,/g, '\\,').replace(/\n/g, '') + '\n';
var rrule = 'RRULE:FREQ=WEEKLY;BYDAY=' + this.weekdays.map(function(day) {
return days[day];
}).join(',') + ';UNTIL=' + formatDate(this.endDate) + '\n';
var title = 'SUMMARY:' + this.name.replace(/,/g, '\\,') + '\n';
return header + uid + dtstart + dtend + dtstamp + place + rrule + title + footer;
};
}
function dateAddHoursAndMinutes(date, fracHours) {
var hours = Math.floor(fracHours);
var minutes = (fracHours - hours) * 60;
var newDate = new Date(date);
newDate.setHours(hours);
newDate.setMinutes(minutes);
return newDate;
}
function mapCourses(schedules) {
var mapOfCourses = {};
for (var i = 0; i < schedules.length; i++) {
var timeBlock = schedules[i];
var key = timeBlock.course.name + timeBlock.loc + (' ' + timeBlock.from + ' ' + timeBlock.to);
if (!mapOfCourses[key])
mapOfCourses[key] = [];
mapOfCourses[key].push(timeBlock);
}
return mapOfCourses;
}
function generateSchedules(courses) {
// Parse all the courses from text form into a list of courses, each a list of time slots
var classes = courses.filter(function(course) {
return course.selected && course.times;
}).map(function(course) {
// Parse every line separately
return course.times.split('\n').map(function(timeSlot, index) {
// Extract the section info from the string, if it's there.
var section = timeSlot.indexOf(': ') > -1 ? timeSlot.split(': ')[0] : '';
var sectionNumber = parseInt(section.slice(12,14)); // courseids are a fixed length
var sectionData = course.data && section? course.data.sections[sectionNumber]: null;
// Split it into a list of each day's time slot
var args = [];
// The lookahead at the end is because meeting times are delimited by commas (oops), but the location may contain commas.
timeSlot.replace(/([MTWRF]+) (\d?\d):(\d\d)\s*(AM|PM)?\s*\-\s?(\d?\d):(\d\d)\s*(AM|PM)?;([^;]*?)(?=$|, \w+ \d?\d:\d{2})/gi, function(_, daylist, h1, m1, pm1, h2, m2, pm2, loc) {
daylist.split('').forEach(function(day) {
args.push({
'course': course,
'section': section,
'sectionData': sectionData,
'loc': loc.trim(),
'weekday': 'MTWRF'.indexOf(day),
'from': timeToHours(+h1, +m1, (pm1 || pm2).toUpperCase() == 'PM'),
'to': timeToHours(+h2, +m2, (pm2 || pm1).toUpperCase() == 'PM'),
});
});
});
return args;
});
});
// Generate all possible combinations
var combos = [];
var state = classes.map(function() {
return 0;
}); // Array of the same length
while (true) {
// Add this possibility
combos.push(classes.map(function(course, i) {
return course[state[i]];
}));
// Increment state
var incremented = false;
for (var i = 0; i < classes.length; i++) {
if (state[i] < classes[i].length - 1) {
state[i]++;
incremented = true;
break;
} else
state[i] = 0;
}
// We're done.
if (!incremented)
break;
}
// Concatenate all the timeslots
var concatted = combos.map(function(combo) {
return Array.prototype.concat.apply([], combo);
});
// And remove conflicting schedules
return options.allowConflicts ? concatted : concatted.filter(function(timeSlots) {
// Loop over every six minute interval and make sure no two classes occupy it
for (var day = 0; day < 5; day++) {
var todaySlots = timeSlots.filter(function(timeSlot) {
return timeSlot.weekday == day;
});
for (var t = 0; t < 24; t += 0.1) {
var classesThen = todaySlots.filter(function(timeSlot) {
return timeSlot.from < t && t < timeSlot.to;
});
var uniqueClassesThen = unique_classes(classesThen);
if (uniqueClassesThen.length > 1) {
// check to see if their dates are all disjoint
for(var i = 0; i < uniqueClassesThen.length-1; i++) {
for(var j = i+1; j < uniqueClassesThen.length; j++) {
if(sectionDatesOverlap(uniqueClassesThen[i]['sectionData'], uniqueClassesThen[j]['sectionData'])) {
return false;
}
}
}
return true;
}
}
}
return true;
});
}
function sectionDatesOverlap(sectionData_a, sectionData_b) {
a_start = new Date(sectionData_a['startDate'])
a_end = new Date(sectionData_a['endDate'])
b_start = new Date(sectionData_b['startDate'])
b_end = new Date(sectionData_b['endDate'])
if (a_start <= b_start && b_start <= a_end) return true; // b starts in a
if (a_start <= b_end && b_end <= a_end) return true; // b ends in a
if (b_start < a_start && a_end < b_end) return true; // a in b
if (a_start == b_start && a_end == b_end) return true; // a is b
return false;
}
// This function takes a list of courses and reduces it - removing any
// two timeSlots that have the same course name
function unique_classes(timeSlots) {
slots = []
alreadyAdded = {}
for (slotIdx in timeSlots) {
var timeSlot = timeSlots[slotIdx];
if (!(timeSlot.course.name in alreadyAdded)) {
slots.push(timeSlot);
alreadyAdded[timeSlot.course.name] = true;
}
}
return slots;
}
// Store stuff
var lastModified = localStorage.lastModified;
function save(type, arr) {
if (localStorage.lastModified != lastModified)
if (!confirm('It looks like the data has been modified from another window. Do you want to overwrite those changes? If not, refresh this page to update its data.')) {
return;
}
lastModified = localStorage.lastModified = Date.now();
localStorage[type] = JSON.stringify(arr);
}
function messageOnce(str) {
if (localStorage['message_' + str])
return false;
localStorage['message_' + str] = true;
return true;
}
(function() {
// Load data
var courses = localStorage.courses ? JSON.parse(localStorage.courses) : [];
var favoriteCourses = localStorage.favoriteCourses ? JSON.parse(localStorage.favoriteCourses) : [];
globalCourses = courses;
globalFavCourses = favoriteCourses;
var savedSchedules = localStorage.savedSchedules ? JSON.parse(localStorage.savedSchedules) : {};
var schedules = [];
var schedulePosition = 0;
// Attach events
/*document.getElementById('button-add').onclick = function () {
var course = {
'name': '',
'selected': true,
'times': ''
};
courses.push(course);
addCourse(course, courses, favoriteCourses);
save('courses', courses);
};*/
document.getElementById('button-save').onclick = function() {
var name = prompt('What would you like to call this schedule?', '');
if (name) {
savedSchedules[name] = JSON.parse(JSON.stringify(schedules[schedulePosition]));
addSavedSchedule(name, savedSchedules[name], savedSchedules);
save('savedSchedules', savedSchedules);
}
};
document.getElementById('button-generate').onclick = function() {
schedules = generateSchedules(courses);
// Display them all
schedulePosition = loadSchedule(schedules, 0);
console.log(schedules, schedulePosition);
this.disabled = true;
};
document.getElementById('button-sections').checked = options.showSections = localStorage.showSections;
document.getElementById('button-sections').onclick = function() {
localStorage.showSections = options.showSections = this.checked;
document.getElementById('button-generate').onclick();
};
document.getElementById('button-conflicts').checked = options.allowConflicts = localStorage.allowConflicts;
document.getElementById('button-conflicts').onclick = function() {
localStorage.allowConflicts = options.allowConflicts = this.checked;
document.getElementById('button-generate').onclick();
};
// Navigating schedules
document.getElementById('button-left').onclick = function() {
schedulePosition = loadSchedule(schedules, schedulePosition - 1);
};
document.getElementById('button-right').onclick = function() {
schedulePosition = loadSchedule(schedules, schedulePosition + 1);
this.classList.add('clicked');
};
document.onkeydown = function(e) {
if (e.keyCode == 39)
document.getElementById('button-right').onclick();
else if (e.keyCode == 37)
document.getElementById('button-left').onclick();
};
// Display all the courses
if (courses.length) {
for (var i = 0; i < courses.length; i++) {
addCourse(courses[i], courses, favoriteCourses, false);
}
document.getElementById('button-generate').onclick();
}
// Display all the favorite courses
if (favoriteCourses.length) {
for (var i = 0; i < favoriteCourses.length; i++) {
addCourse(favoriteCourses[i], courses, favoriteCourses, true);
}
document.getElementById('button-generate').onclick();
}
// Display all the saved schedules
for (var name in savedSchedules)
addSavedSchedule(name, savedSchedules[name], savedSchedules);
// Sigh, browser detection
var detection = {
'chrome': !!window.chrome,
'webkit': navigator.userAgent.toLowerCase().indexOf('safari') > -1,
'firefox': navigator.userAgent.toLowerCase().indexOf('firefox') > -1,
'mac': navigator.userAgent.toLowerCase().indexOf('mac os') > -1
};
// Firefox printing is ugly
if (detection['firefox'])
document.getElementById('button-print').style.display = 'none';
document.getElementById('button-print').onclick = function() {
if (detection['chrome'] && messageOnce('print-tip'))
alert('Pro-tip: Chrome has an option on the Print dialog to disable Headers and Footers, which makes for a prettier schedule!');
window.print();
};
document.getElementById('button-clear').onclick = function() {
if (confirm('Are you sure you want to delete all the courses you\'ve added?')) {
save('courses', courses = []);
save('favoriteCourses', favoriteCourses = []);
window.location.reload();
}
return false;
};
document.getElementById('button-export').onclick = function() {
var mapOfCourses = mapCourses(schedules[schedulePosition]);
var scheduleText = exportSchedule(mapOfCourses);
download("schedule.ics", scheduleText);
};
// Silly workaround to circumvent crossdomain policy
if (window.opener)
window.opener.postMessage('loaded', '*');
}());
///////////////////// START PARSER /////////////////////////////////////
function getCourseSections(course) {
return course["courseSections"];
}
function filterCoursesByCalendar(courses, calendarAttribute, expected) {
var filteredCourses = [];
for (course of courses) {
var correctedCourse = JSON.parse(JSON.stringify(course));
var sectionsForCourse = filterSectionsByCalendar(getCourseSections(course),
calendarAttribute, expected);
correctedCourse["courseSections"] = sectionsForCourse;
if (sectionsForCourse.length != 0) {
filteredCourses.push(correctedCourse);
}
}
return filteredCourses;
}
function filterSectionsByCalendar(sections, attribute, expected) {
var filteredSections = []; // Has invalid sections removed.
for (section of sections) {
var correctedSection = JSON.parse(JSON.stringify(section)); // Has invalid calendar sessions removed.
var filteredCalendarSessions = []; // Valid calendar session array.
if(!section['calendarSessions']) continue;
for (calendarSession of section["calendarSessions"]) {
if (calendarSession[attribute].startsWith(expected)) {
filteredCalendarSessions.push(calendarSession);
}
}
correctedSection["calendarSessions"] = filteredCalendarSessions;
// If there are no calendar sections left for this section,
// remove the section.
if (filteredCalendarSessions.length != 0) {
filteredSections.push(correctedSection);
}
}
return filteredSections;
}
function getCoursesFromAttribute(response, attribute, expected) {
var possibleCourses = [];
for (key of response) {
if (key[attribute] === expected) {
possibleCourses.push(key);
}
}
return possibleCourses;
}
function getCoursesFromAttributeRegex(response, attribute, expression) {
var possibleCourses = [];
for (key of response) {
if (key[attribute]) {
if (key[attribute].match(expression)) {
possibleCourses.push(key);
}
}
}
return possibleCourses;
}
function getInstructorRegex(response, expression) {