-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathcr.js
More file actions
1809 lines (1737 loc) · 57.8 KB
/
cr.js
File metadata and controls
1809 lines (1737 loc) · 57.8 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
/**
* Welcome to the cr.js file!
*/
"use strict";
var WireIt, majors, user, CSRF_token;
var add_new_term, classterm, loggedin, triedlogin;
var Defaults = {
// The count is the zeroth element in a requisite branch. It sets the
// threshold expectations for the success of that branch.
requisiteCount: {
// Threshold count needed to satisfy branch
count: 0,
// Boolean for tracking whether we care about matching all of the following
allOfTheFollowing: false,
// Boolean for checking where we are counting differently
special: 0,
// '' means just count the following, 'total_units' if the threshold is for
// units instead
type: '',
// Displays in the output as "X from:"
desc: 'from',
// Do not add classes to globalMatches
globalMatchesSkip: 0,
// Ignore whether classes are in globalMatches
globalMatchesIgnore: 0,
// Do not short-circuit branch logic once count threshold is met
runinfull: 0,
// Hold onto match information for subtrees
pullmatches: 0
},
requisiteClass: {
// The displayed name of the class. This may be a subject id, or a range,
// or a generalized skipped message
id: '',
// An optional message for display, appended without spacing to the id
desc: '',
// Do not process this as a requisite. Usually used for adding notes to
// a major display inline with other requisites.
skip: 0,
// Set whether the class acts as a corequisite (and can thus be taken in
// the same semester)
coreq: 0,
// Boolean for whether a range is in use
range: 0,
// Regex string to match classes for a range or complex id matching
matchRegex: '',
// Regex string to NOT match classes for a range or complex id matching
excludeRegex: '',
// Do not add classes to globalMatches
globalMatchesSkip: 0,
// Ignore whether classes are in globalMatches
globalMatchesIgnore: 0
},
wireStyleOptions: {
prereq: {
color: '#888888',
bordercolor: '#B8B8B8',
borderwidth: 1,
width: 2,
OK: true
},
coreq: {
color: '#000000',
bordercolor: '#000000',
borderwidth: 1,
width: 1,
OK: true
},
error: {
color: '#ff0000',
bordercolor: '#dd0000',
borderwidth: 1,
width: 1,
OK: false
}
},
callbackArgs: {
LVL: '__lvl__',
OBJ: '__obj__'
},
classData: {
override: false
},
terminalProperties: {
editable: false
},
keyCodes: {
DELETE: 46,
ENTER: 13
},
modalProperties: {
autoOpen: false,
draggable: false,
resizeable: false,
modal: true
}
};
/**
* Builds match parameters object from requisites syntax. Handles when the match
* param is a number and when it is an object. Returns a match params object.
*/
function getMatchParams(arr) {
var matchedElement = arr[0];
var allOfTheFollowing = false;
if (typeof matchedElement === 'number') {
// Shortcut "all of the following" lists with a 0 in front:
// [0, "a", "b"] --> [2, "a", "b"];
if (matchedElement === 0) {
matchedElement = arr.length - 1;
allOfTheFollowing = true;
}
matchedElement = { count: parseInt(matchedElement, 10) };
}
var matchedObject = $.extend({}, Defaults.requisiteCount, matchedElement);
matchedObject.allOfTheFollowing = allOfTheFollowing;
matchedObject.matchesFound = [];
return matchedObject;
}
/**
* Builds match requirement object from requisites syntax. By default, you
* expect something like "18.03", but you must also handle extra information.
* Returns an object with the desired parameters.
*/
function getMatchObject(match) {
var newMatch;
if (typeof match === 'object') {
newMatch = $.extend({}, Defaults.requisiteClass, match);
} else {
newMatch = $.extend({}, Defaults.requisiteClass, {
id: match
});
}
if (newMatch.desc === undefined) {
newMatch.desc = '';
}
return newMatch;
}
/**
* Allows for supplying a callback function to run when a class is found which
* successfully acts as a requisite for the requirements. The arguments can be
* stocked with values from Defaults.callbackArgs to force substitutions.
*/
function applyCallbackFn(obj, callback, callbackArgs, level, i, newMatch) {
// Copy args
var tempArgs = callbackArgs.slice();
// OBJ is replaced with the object provided in this method's
var objPosition = $.inArray(Defaults.callbackArgs.OBJ, tempArgs);
if (~objPosition) {
tempArgs[objPosition] = $.extend({}, newMatch, {div: obj});
}
var lvlPosition = $.inArray(Defaults.callbackArgs.LVL, tempArgs);
if (~lvlPosition) {
tempArgs[lvlPosition] = level.concat([i]);
}
// Calls callback with tempArgs as its arguments.
return callback.apply(null, tempArgs);
}
/**
* The idea here is to make it possible to loop recursively through
* a requisite tree and perform callback actions when a class matches.
*
* Arguments:
* - arr: The array which stores the requisites. Usually recursively called. For
* more information on arr, see majors.js.
* - callback: function to run on sucessfully matched classes, and can define
* further criteria for filtering. Defaults to returning true.
* - callbackArgs: Holds the arguments for callback. "cls" (with quotes) will be
* replaced with the matched course number before being fed into callback.
* - level: Used for recursive calls of checkRequisites. At the top level, it is
* length 0, []. In each level of recursion, that level gets an array of
* index values down through the recursion.
*
* Returns an array, as follows:
* [
* boolean (were reqs met),
* string (information on what requisites are still needed),
* array of matched classes
* ]
*/
var globalMatches = [];
function checkRequisites(arr, callback, callbackArgs, level) {
callback = callback || function emptyCallback() { return true; };
callbackArgs = callbackArgs || [];
if (level === undefined) {
level = [];
globalMatches = [];
}
var matchParams = getMatchParams(arr);
// Holds the unsatisfied requisites in a string for display to the user.
var unsatisfiedRequisitesInfo = [];
var requisiteBranch, callbackResult, newMatch, i, j;
var requisiteBranchMatchParams = function requisiteBranchMatchParams() {
matchParams.count -= $(this).data(matchParams.type);
};
var filterRangeMatches = function filterRangeMatches() {
var data = $(this).data();
var classNames = [data.subject_id].concat(data.joint_subjects || []);
for (j = 0; j < classNames.length; j++) {
if (newMatch.excludeRegex && newMatch.excludeRegex.test(classNames[j])) {
continue;
}
if (newMatch.matchRegex && newMatch.matchRegex.test(classNames[j])) {
return true;
}
}
return false;
};
var iterateRangeMatches = function iterateRangeMatches() {
if (
~$.inArray(this, globalMatches) &&
!matchParams.globalMatchesIgnore &&
!newMatch.globalMatchesIgnore) {
return true;
}
// Calls callback with tempargs as its arguments.
var callbackResult = applyCallbackFn(
$(this), callback, callbackArgs, level, i, newMatch
);
if (callbackResult) {
matchParams.count -= (
matchParams.special ? $(this).data(matchParams.type) : 1
);
matchParams.matchesFound.push(this);
if (!newMatch.globalMatchesSkip && !matchParams.globalMatchesSkip) {
globalMatches.push(this);
}
// newMatch.globalMatchesSkip &&
// console.log('newarrskip', newMatch, matchParams);
// matchParams.globalMatchesSkip &&
// console.log('matchParamsskip', newMatch, matchParams);
}
if (matchParams.count <= 0 && !matchParams.runinfull) {
return [
true, '', level.length ? matchParams.matchesFound : globalMatches
];
}
};
var iterateClassMatches = function iterateClassMatches() {
if (~$.inArray(this, globalMatches) &&
!matchParams.globalMatchesIgnore &&
!newMatch.globalMatchesIgnore) {
return true;
}
// Calls callback with tempargs as its arguments.
var callbackResult = applyCallbackFn(
$(this), callback, callbackArgs, level, i, newMatch
);
if (callbackResult) {
matchParams.count -= (
matchParams.special ? $(this).data(matchParams.type) : 1
);
matchParams.matchesFound.push(this);
if (!newMatch.globalMatchesSkip && !matchParams.globalMatchesSkip) {
globalMatches.push(this);
}
return false;
}
};
for (i = 1; i < arr.length; i++) {
if ($.isArray(arr[i])) {
// In case a sub-branch is inside this branch, we recursively solve that
// branch and use its result.
requisiteBranch = checkRequisites(
arr[i], callback, callbackArgs, level.concat([i])
);
// If the branch is satisfied, or if we need to count something like
// [5, [2, 'foo', 'bar'], [4, 'baz', 'bam', bax', 'bay']] where the 4 from
// will not necessarily be satisfied while the 5 from will be, then count.
if (requisiteBranch[0] || matchParams.pullmatches) {
if (matchParams.special) {
$(requisiteBranch[2]).each(requisiteBranchMatchParams);
} else {
matchParams.count--;
}
}
if (requisiteBranch[0]) {
callbackResult = applyCallbackFn(
arr[i], callback, callbackArgs, level, i, newMatch
);
} else {
unsatisfiedRequisitesInfo.push(requisiteBranch[1]);
}
continue;
}
newMatch = getMatchObject(arr[i]);
if (newMatch.skip ||
(newMatch.id === 'Permission' && !user.needPermission)) {
if (matchParams.allOfTheFollowing) {
matchParams.count--;
}
continue;
}
// Now check for ranges. These are strings of the form 'X.XXX-X.XXX'
if (newMatch.range) {
$('.classdiv:not(.custom)')
.filter(filterRangeMatches)
.each(iterateRangeMatches);
if (matchParams.count <= 0) {
return [
true, '', level.length ? matchParams.matchesFound : globalMatches
];
}
unsatisfiedRequisitesInfo.push(
(newMatch.coreq === 1) ?
('[' + newMatch.id + newMatch.desc + ']') :
(newMatch.id + newMatch.desc)
);
continue;
}
// Now only bona fide classes
var $classmatches = $('.classdiv.' + (
newMatch.id.toUpperCase().replace('.', '_').replace(':', '.')
));
$classmatches.each(iterateClassMatches);
// If it's not a class, or callback failed, then we need to note that.
if (!$classmatches.length || !callbackResult) {
unsatisfiedRequisitesInfo.push(
(newMatch.coreq === 1) ?
('[' + newMatch.id + newMatch.desc + ']') :
(newMatch.id + newMatch.desc)
);
}
if (matchParams.count <= 0 && !matchParams.runinfull) {
return [
true, '', level.length ? matchParams.matchesFound : globalMatches
];
}
}
// return two pieces of info: state and string
if (matchParams.count <= 0) {
return [true, '', level.length ? matchParams.matchesFound : globalMatches];
}
unsatisfiedRequisitesInfo = deGIR(unsatisfiedRequisitesInfo.join(', '));
if (matchParams.special) {
unsatisfiedRequisitesInfo = (
'(' + matchParams.count + ' ' + matchParams.desc + ': ' +
(JSON.stringify(arr.slice(1))) + ')'
);
} else if (level.length || (!level.length && (arr[0] !== arr.length - 1))) {
unsatisfiedRequisitesInfo = (
'(' + matchParams.count + ' ' + matchParams.desc + ': ' +
unsatisfiedRequisitesInfo + ')'
);
}
return [
false,
unsatisfiedRequisitesInfo,
level.length ? matchParams.matchesFound : globalMatches
];
}
/*** Course functions ***/
/**
* Defines new wire's properties (black/grey, straight/curved)
* partially based on the relative semesters and terms of the two
* would-be connected classes.
* from is $() div, to is object with to.div as $() div.
*/
function newWire(from, to) {
if ($.isArray(to.div)) {
return true;
}
// var fromid = from.attr('id');
// var toid = to.div.attr('id');
var fromterm = from.data('classterm');
var toterm = to.div.data('classterm');
var dterm = Math.abs(fromterm - toterm);
var option = 'prereq';
if (to.coreq) {
option = 'coreq';
} else {
toterm += to.div.data('override') ? 0 : 1;
}
if ((fromterm < toterm) && (fromterm || dterm)) {
option = 'error';
}
var wireType = (dterm === 1 || dterm === 2) ? 'Wire' : 'BezierWire';
if (user.viewReqLines) {
from.data('terminals').wires.push(new WireIt[wireType](
from.data('terminals').terminal,
to.div.data('terminals').terminal,
document.body,
Defaults.wireStyleOptions[option]
));
}
return Defaults.wireStyleOptions[option].OK;
}
// Frankly, this function has outgrown its name.
// addWires adds everything for a given class and updates its status.
function addWires(div, addwires) {
if (addwires === undefined) {
addwires = true;
}
var data = div.data();
data.terminals.wires = [];
data.reqstatus = true;
if (/"\(|\)"/.test(JSON.stringify(data.reqs))) {
data.reqstatus = false;
div.find('.reqs').html('Reqs: (hover)').attr(
'title',
'The Registrar changed some requirements unexpectedly, and ' +
'CourseRoad is having trouble parsing ~300 classes. ' +
'Sorry about that. ' + data.reqstr
);
} else if (data.reqs) {
var reqcheck = checkRequisites(
data.reqs,
newWire,
[div, Defaults.callbackArgs.OBJ]
);
data.reqstatus = reqcheck[0];
var tempstr = reqcheck[1];
if (data.reqstatus || data.override || !data.classterm) {
div.find('.reqs').html('Reqs: [X]').removeAttr('title');
} else {
div.find('.reqs').html('Reqs: [ ]').attr('title', 'Need: ' + tempstr);
}
if (data.override) {
div.find('.reqs').attr('title', 'OVERRIDE enabled');
}
}
data.checkterm = (data.classterm === 0) || (([data.fall,
data.iap, data.spring, data.summer])[(data.classterm - 1) % 4]);
data.checkrepeat = true;
if (!~$.inArray(data.grade_rule, ['J', 'U', 'R'])) {
if ($('.classdiv').not(div).filter(function findEarlierClassInstances(j) {
return (
(
$.inArray($(this).data('subject_id'), data.equiv_subjects) !== -1 ||
$(this).hasClass(data.id)
) &&
(j < $(div).index('.classdiv'))
);
}).length) {
data.checkrepeat = false;
}
}
var classReqsMet = data.override || (data.reqstatus && data.checkrepeat);
var classTermOkay = data.checkterm || data.classterm === 0;
data.status = data.offered_this_year && classReqsMet && classTermOkay;
div.removeClass('classdivgood').removeAttr('title');
if (data.status) {
div.addClass('classdivgood');
}
if (!data.checkrepeat) {
div.attr('title', data.subject_id + ' is not counting for credit');
}
if (!data.checkterm) {
div.attr('title', data.subject_id + ' is not available ' +
(['in the Fall term', 'during IAP',
'in the Spring term', 'in the Summer term'])[(data.classterm - 1) %
4]);
}
if (!data.offered_this_year) {
div.attr('title', data.subject_id +
' is not available in this year (' + div.data('year_range') + ')');
}
if (data.override) {
div.find('.coreqs').attr('title', 'OVERRIDE enabled');
}
if ($('.classdivhigh').length === 1) {
$('.WireIt-Wire').addClass('WireIt-Wire-low');
$('.classdivhigh').data('terminals').terminal.wires
.forEach(function removeLowWireClass(wire) {
$(wire.element).removeClass('WireIt-Wire-low');
});
}
return data.status;
}
function updateWires() {
$('.term').each(function adjustTermHeight() {
$(this).find('.termname, .termname span').css(
'width', $(this).height() + 'px'
);
});
$('.year').each(function adjustYearHeight() {
$(this).find('.yearname, .yearname span').css(
'width', $(this).height() + 'px'
);
});
if (preventUpdateWires) {
return false;
}
$('.classdiv').each(function redrawClassWires() {
$(this).data('terminals').terminal.redrawAllWires();
});
}
// This does the work for the left-hand side checklist bar.
function checkClasses() {
var totalUnits = 0;
$('#COREchecker span.checkbox1').removeAttr('title');
$('.corecheck').addClass('unused').removeClass('used');
$('.classdiv').each(function checkClassGIRs(i) {
var self = this;
var $self = $(self);
var data = $self.data();
if (!data.checkrepeat) {
// Repeat classes shouldn't count twice
return true;
}
// Determine whether a class should count for units or not
var forUnits = true;
if (!data.special) {
totalUnits += data.total_units;
return true;
}
var GIR = data.gir;
if (GIR) {
var $effect = $('.corecheck.unused.GIR.' + GIR);
if ($effect.length) {
$effect.eq(0).removeClass('unused').addClass('used')
.attr('title', data.subject_id);
if (GIR === 'LAB') {
if (data.total_units > 6 && $effect.length > 1) {
$effect.eq(1).removeClass('unused').addClass('used')
.attr('title', data.subject_id);
}
totalUnits += data.total_units - 6 * $effect.length;
}
forUnits = false;
}
}
var $otherCIPrecedingInTerm = $('.classdiv.CI:not(.CIM)').not(self)
.filter(function findOtherCIPrecedingInTerm() {
return ($(this).data('classterm') === data.classterm) &&
($(this).index('.classdiv') < i);
});
if (data.ci && !$otherCIPrecedingInTerm.length) {
$effect = $('.corecheck.unused.CI.' + data.ci + ':first');
if ($effect.length) {
$effect.removeClass('unused').addClass('used')
.attr('title', data.subject_id);
forUnits = false;
}
}
if (data.hass) {
var hass = [data.hass];
if (~hass[0].indexOf(',')) {
hass = hass[0].split(',');
}
for (var j = 0; j < hass.length; j++) {
$effect = $('.corecheck.unused.HASS.' + hass[j] + ':first');
if ($effect.length) {
$effect.removeClass('unused').addClass('used')
.attr('title', $self.data('subject_id'));
forUnits = false;
} else {
if ((hass.length > 1) && (j !== (hass.length - 1))) {
continue;
}
$effect = $('.corecheck.unused.HASS.HE:first');
if ($effect.length) {
$effect.removeClass('unused').addClass('used')
.attr('title', data.subject_id);
forUnits = false;
}
}
}
}
if (forUnits) {
totalUnits += data.total_units;
}
});
totalUnits = Math.round(100 * totalUnits) / 100;
$('#totalunits').html(totalUnits);
}
function addAllWires(reloadNotify) {
var status = true;
$('.classdiv').each(function removeClassWires() {
var $this = $(this);
$this.data('terminals').terminal.removeAllWires();
$this.data('classterm', $this.parent().index('.term'));
if ($this.data('substitute')) {
$this.addClass($this.data('substitute')
.replace(/\./g, '_').replace(/,/g, ' '));
}
}).each(function readdClassWires() {
var $this = $(this);
if ($this.data('custom')) {
return true;
}
var temp = addWires($this);
status = status && temp;
});
updateWires();
checkClasses();
$('select.majorminor').each(checkMajor);
// console.log('addAllWires');
if (reloadNotify) {
askBeforeLeaving(true);
}
return status;
}
/*** Course-loading functions ***/
function classFromJSON(json, loadspeed, replacediv) {
if (loadspeed === undefined) {
loadspeed = 'slow';
}
json = $.extend({}, Defaults.classData, json);
if (json.classterm > 16) {
$('.supersenior.hidden').removeClass('hidden', loadspeed);
}
if (json.classterm && json.classterm % 4 === 0) {
$('.term .termname').eq(json.classterm)
.fadeIn(loadspeed).parent().slideDown(loadspeed, updateWires)
.siblings('.yearname').addClass('showsummer', loadspeed);
}
json.info = deGIR(json.info);
if (replacediv === undefined) {
$('.term').eq(json.classterm).append(json.div);
} else {
replacediv.replaceWith(json.div);
}
var $newdiv = $('#' + json.divid);
if (json.reqs === null) {
json.reqs = false;
}
json.reqstatus = true;
if (json.override) {
$newdiv.addClass('classdivoverride');
}
$.extend($newdiv.data(), json);
$newdiv.data('terminals', {
terminal: new WireIt.Terminal($newdiv.get(0), Defaults.terminalProperties),
wires: []
});
return $newdiv;
}
function properYear(classterm) {
return user.classYear -
parseInt(3 - Math.floor((classterm - 1) / 4), 10) - user.supersenior;
}
function fetchClassData(postData, classterm, oldclass) {
if (!(postData.getClass || postData.getCustom)) {
return false;
}
$.post('ajax.php', postData, function fetchClassDataResponse(data) {
if (data.error) {
return false;
}
data.classterm = classterm;
data.override = false;
oldclass ? classFromJSON(data, 0, oldclass) : classFromJSON(data);
addAllWires(true);
}, 'json');
}
function getClass() {
// pulls down and interprets the class data
var classterm = $('#getnewclassterm').val();
var postData;
user.supersenior = (
($('.year.supersenior').is(':visible') || classterm > 16) ? 1 : 0
);
if ($('input[name="getnewclasstype"]:checked').val() === 'custom') {
if (!$('#getnewclassname').val()) {
return false;
}
postData = {
getCustom: 1,
name: $('#getnewclassname').val(),
units: $('#getnewclassunits').val() || 0
};
} else {
if (!$('#getnewclassid').val()) {
return false;
}
postData = {
getClass: 1,
subjectId: $('#getnewclassid').val(),
year: properYear(classterm)
};
}
hideAutocomplete();
$('.getnewclasstypes input').val('');
fetchClassData(postData, classterm);
}
// Used for initial pageload when a hash is present:
// takes in an array containing objects describing the classes.
function getClasses(classList, reloadNotify) {
classList.forEach(function loadEachClassFromJSON(cls) {
classFromJSON(cls, 0);
});
addAllWires(reloadNotify);
}
/*** Major/minor functions ***/
function checkOff(majordiv, lvl, cls) {
var $boxes = $(majordiv + ' .majorchk.majorchk_' + lvl.join('_') +
':not(.chk):first');
$boxes.addClass('chk').attr('title', $.isArray(cls.div) ? null : cls.div.data(
'subject_id'));
return $boxes.length;
}
function checkMajor() {
var $selector = $(this);
var majorId = $selector.val();
var div = $selector.data('div');
var $div = $(div);
var span = $selector.prev('span.majorminor');
span.attr('data-empty', 1).removeAttr('data-value');
var majorData = majors[majorId];
if (!majorData) {
$div.html('');
// Continue checking majors and minors even if this one isn't defined
return true;
}
var majorReqs = majorData.reqs || [0];
span.attr('data-value', $selector.find('option:selected').text())
.removeAttr('data-empty');
$div.html(buildMajor(majorReqs)).append(
'<span class="letmeknow"><br>See an error? Let me know ' +
'<a href="mailto:courseroad@mit.edu?subject=[CourseRoad]%20Error%20in%20' +
majorId + '">here</a>.</span>'
);
draggableChecklist();
checkRequisites(
majorReqs,
checkOff,
[div, Defaults.callbackArgs.LVL, Defaults.callbackArgs.OBJ]
);
}
function buildMajor(branch, level) {
// Helper function to render the checkbox HTML for a given path
function buildCheckbox(arr) {
return (
'<span class="majorchk majorchk_' + arr.join('_') + ' checkbox1">' +
'[<span>✓</span>]</span>'
);
}
// Level keeps track of the recursive path depth and position
if (level === undefined) {
level = [];
}
// Hold the rendered HTML to display in a string
var branchHTML = '<ul>\n';
var matchParams = getMatchParams(branch);
for (var i = 1; i < branch.length; i++) {
// If this branch element is actually a sub-branch, render it recursively
// and append the returned HTML to the current branch
if ($.isArray(branch[i])) {
branchHTML += buildMajor(branch[i], level.concat(i));
continue;
}
var newMatch = getMatchObject(branch[i]);
// Check for ranges
if (newMatch.range) {
branchHTML += '<li>';
for (var j = 0; j < matchParams.count; j++) {
branchHTML += buildCheckbox(level.concat(i));
}
branchHTML += ' The range ' + newMatch.id + newMatch.desc + '</li>\n';
continue;
}
// Now only strings
branchHTML += '<li>';
if (newMatch.skip) {
branchHTML += ' — ' + newMatch.id + newMatch.desc;
} else {
branchHTML += (
buildCheckbox(level.concat(i)) +
' <span class="checkbox1_text" data-id="' + newMatch.id + '">' +
newMatch.id + '</span>' + newMatch.desc
);
}
branchHTML += '</li>\n';
}
branchHTML += '</ul>\n';
if (matchParams.special || level.length) {
branchHTML = (
matchParams.count + ' ' + matchParams.desc + ':\n' + branchHTML
);
} else if (!level.length && (matchParams.count !== branch.length - 1)) {
// If the top level of recursion is looking for something other than
// "all of the following" then we need to display that information
branchHTML = (
matchParams.count + ' ' + matchParams.desc + ':\n' + branchHTML
);
}
if (level.length) {
return '<li>' + buildCheckbox(level) + ' ' + branchHTML + '</li>\n';
}
return '<strong>Requirements:</strong><br>\n' + branchHTML;
}
function draggableChecklist() {
$('.checkbox1_text').draggable({
appendTo: '#rightbar',
// containment: 'body',
// distance: 30,
helper: 'clone',
start: function startDraggingClass(event, ui) {
ui.helper.attr('data-term', '(none)');
$('.term').addClass('notOKterm');
$('.WireIt-Wire').addClass('WireIt-Wire-low');
},
stop: function stopDraggingClass() {
$('.term').removeClass('notOKterm');
unhighlightClasses();
$('.WireIt-Wire').removeClass('WireIt-Wire-low');
},
revert: 'invalid',
zIndex: 2700
});
}
/*** Helper functions ***/
function unhighlightClasses() {
$('#leftbar').addClass('unhighlight');
$('#overridercheck').prop('disabled', true);
$('#overrider span').css('opacity', 0);
$('.classdiv').removeClass('classdivhigh classdivlow');
$('.WireIt-Wire').removeClass('WireIt-Wire-low');
}
function deGIR(str) {
return str.replace(/GIR:PHY1/g, 'Physics I (GIR)')
.replace(/GIR:PHY2/g, 'Physics II (GIR)')
.replace(/GIR:CAL1/g, 'Calculus I (GIR)')
.replace(/GIR:CAL2/g, 'Calculus II (GIR)')
.replace(/GIR:BIOL/g, 'Biology (GIR)')
.replace(/GIR:CHEM/g, 'Chemistry (GIR)')
.replace(/GIR:REST/g, 'REST Requirement')
.replace(/GIR:LAB/g, 'LAB Requirement')
.replace(/GIR:LAB2/g, '1/2 LAB Requirement');
}
/**
* Creates the storable string which holds our precious class data.
* Used primarily in saved classes
*/
function minclass(stringify) {
var minData = $('.classdiv').map(function mapClassToMinData() {
var $this = $(this);
var arr;
if ($this.data('custom')) {
arr = {
name: $this.data('subject_title'),
units: $this.data('total_units'),
custom: true
};
} else {
arr = {
id: $this.data('subject_id'),
year: $this.data('year_desired')
};
}
arr.term = $this.data('classterm');
if ($this.data('override')) {
arr.override = $this.data('override');
}
if ($this.data('substitute')) {
arr.substitute = $this.data('substitute');
}
return arr;
}).get();
return stringify ? JSON.stringify(minData) : minData;
}
function minmajors(stringify) {
var minData = [
$('#choosemajor').val(),
$('#choosemajor2').val(),
$('#chooseminor').val(),
$('#chooseminor2').val(),
$('#chooseneet').val()
];
return stringify ? JSON.stringify(minData) : minData;
}
/*** UI/Page-loading functions ***/
function runBeforeUnload() {
return (
'Are you sure you want to close CourseRoad? ' +
'You\'ll lose any unsaved changes you\'ve made.'
);
}
function askBeforeLeaving(startAsking) {
$(window)[startAsking ? 'on' : 'off']('beforeunload', runBeforeUnload);
}
var userHashChange = true;
window.onhashchange = function onHashChange() {
// userHashChange means that if the user types in a new hash in the URL,
// the browser will reload, but if the hash changes due to saving a new
// version or something it won't.
userHashChange && window.location.reload();
userHashChange = true;
setPageTitle();
};
function swapClassYear(oldclass, newyear) {
if (!oldclass.data('subject_id')) {
return false;
}
oldclass.addClass('classdivlow');
var postData = {
getClass: 1,
subjectId: oldclass.data('subject_id'),
year: newyear
};
fetchClassData(postData, classterm, oldclass);
}
function getCurrentAcademicYear() {
var date = new Date();
return date.getFullYear() + (date.getMonth() > 7);
}
function getCurrentSemesterID() {
// 0 for Fall, 1 for IAP, 2 for Spring, 3 for Summer
var termByMonth = [1, 2, 2, 2, 2, 3, 3, 3, 0, 0, 0, 0];
var term = termByMonth[(new Date()).getMonth()];
return (getCurrentAcademicYear() - user.classYear + 3) * 4 + term;
}
function badCSRF(data) {
return data.csrfError || data === '**csrf**';
}
function alertBadCSRF() {
alert('Whoops! Looks like your session expired. Try refreshing the page.');
}
function getHash() {
return window.location.hash.substr(1);
}
function setNewHash(hash) {
userHashChange = false;
window.location.hash = hash;
setPageTitle();
}
function setPageTitle() {
document.title = 'CourseRoad: ' + getHash();
}
function redirectToAuth() {
window.location.href = (
window.location.origin + ':444' + window.location.pathname + 'secure.php'
);
}
function explainBadLoginHelp() {
alert(
"Sorry you're having trouble. This happens occasionally for reasons " +
"outside my control: browsers do very weird things when they ask for " +
"your certificates, so I can't automatically reset things for you. " +
"Thankfully, there's a workaround: try logging in using your " +
"browser's private browsing/incognito mode. " +
"Ctrl+Shift+N on Chrome, for example, will open a new incognito " +
"chrome window, which has the nice property of not remembering the " +
"certificate weirdness in the other window. " +
"You should be able to navigate to CourseRoad from there and " +
"(hopefully) login with your certificates.\n\n" +
"Please email courseroad@mit.edu if this doesn't work."
);
}
function hideAutocomplete() {
$('#getnewclass .ui-autocomplete').hide();