forked from HarkerDev/bellschedule
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
1233 lines (1073 loc) · 41.6 KB
/
script.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
/**
* Primary script for the Harker Bell Schedule
* Hosted at http://harkerdev.github.io/bellschedule
**/
/**
* CSS things
*/
addEventListener("scroll", function(event) {
document.getElementById("header").style.left = scrollX + "px";
});
/**
* Returns an array of values in the array that aren't in a.
*/
Array.prototype.diff = function(a) {
return this.filter(function(i) {return a.indexOf(i) < 0;});
};
/**
* Constants
*/
var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]; //days of the week in string form
var schedules; //array of schedules (each schedule is an array in this array
var mobile = isMobile();
/**
* Globals
*/
var displayDate; //beginning of time period currently being displayed by the schedule
var updateScheduleID; //ID of interval of updateSchedule
var hasFocus = true; //document.hasFocus() seems to be unreliable; assumes window has focus on page load
var options = {};
var urlParams; //object with GET variables as properties and their respective values as values
var inputStr = "";
var KEY_LEFT = 37;
var KEY_UP = 38;
var KEY_RIGHT = 39;
var KEY_DOWN = 40;
var KEY_A = 65;
var KEY_B = 66;
var KONAMI = "" + KEY_UP + KEY_UP + KEY_DOWN + KEY_DOWN + KEY_LEFT + KEY_RIGHT + KEY_LEFT + KEY_RIGHT + KEY_B + KEY_A;
var isDoge;
var START_DATE = new Date('August 22, 2016'); //The start day of the school year. This should be a weekday.
var START_SCHEDULE = 1; //The schedule on the first day
//On a given day, independent of rotation, after school has a fixed function. This array maps the day (0 for Monday, etc.)
//to the particular function (e.g. Extra Help). This ultimately piggybacks on the replacement system.
var COLLABORATION_REPLACEMENTS = [
"Collaboration -> Office Hours",
"Collaboration -> Office Hours",
"Collaboration -> Faculty Meeting",
"Collaboration -> Office Hours",
"Collaboration -> After School"
]
var TOTAL_SCHEDULES = 8; //The number of schedules to be cycled
var SCHEDULES = ["A", "B", "C", "D", "A", "B", "C", "D"]
var MILLIS_PER_DAY = 1000 * 60 * 60 * 24;
/**
* Gets GET variables from URL and sets them as properties of the urlParams object.
* Then updates the state of the current history entry with the appropriate week.
*/
(function() {
//decode GET vars in URL
updateUrlParams();
//update history state
window.history.replaceState(getDateFromUrlParams(), document.title, document.location);
}());
/**
* Event listeners
*/
document.addEventListener("visibilitychange", function(event) {
if(!document.hidden) { //only slightly redundant; on un-minimize, document gains visibility without focus
updateSchedule();
// updateClock();
}
updateUpdateInterval();
});
addEventListener("focus", function(event) {
updateSchedule();
//updateClock();
hasFocus = true;
updateUpdateInterval();
});
addEventListener("blur", function(event) {
hasFocus = false;
updateUpdateInterval();
});
/**
* Event listener for navigating through history.
* (onload event will not fire when navigating through history items pushed by history.pushState, because the page does not reload)
*/
addEventListener("popstate", function(event) {
updateUrlParams();
updateSchedule(event.state);
});
/**
* Updates urlParams object based on the GET variables in the URL.
* (variables as properties and values as values)
*/
function updateUrlParams() {
urlParams = {};
var match,
pl = /(?!^)\+/g, //regex for replacing non-leading + with space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
}
/**
* Parses schedules, creates schedule for correct week, sets title title on page load.
*/
addEventListener("load", function(event) {
initViewport();
initTitle();
parseRawSchedule();
//updateSchedule();
//updateClock();
download("options.json", createOptions, displayOptionsError);
isDoge = false;
});
function initViewport() {
if(mobile) {
var meta = document.createElement("meta");
meta.name = "viewport";
meta.content = 'user-scalable=no, initial-scale=1.0, maximum-scale=1.0';
document.getElementsByTagName("head")[0].appendChild(meta);
document.getElementsByTagName("body")[0].class = "mobile";
}
}
/**
* Adds appropriate event listeners to items in the schedule title.
*/
function initTitle() {
document.getElementById("header").addEventListener("click", setTitleTitle);
document.getElementById("leftArrow").addEventListener("click", goLast);
document.getElementById("rightArrow").addEventListener("click", goNext);
document.getElementById("refresh").addEventListener("click", function(){ updateSchedule(null,true) });
setTitleTitle();
}
/**
* Parses raw schedule in body of page into schedule array
* Code is questionable
*/
function parseRawSchedule() {
var rawSchedules=document.getElementById("schedules").textContent.split("\n"); //get raw schedule text
schedules = new Array();
var x=0; //index in schedules
schedules[0] = new Array(); //create array of special schedule days
while(rawSchedules.length>0){
//loop through all lines in raw schedule text
if(rawSchedules[0].length==0){
//if line is empty, move to next index in schedules
schedules[++x] = new Array(); //could probably use id as index instead, or just properties
rawSchedules.shift();
} else{
//if line has text, save in current location in schedules
var str = rawSchedules.shift();
if(x==0 && str.indexOf("|")>=0){
//behavior for blocks of dates with the same schedule
var start = new Date(str.substring(0,str.indexOf("|")));
var end = new Date(str.substring(str.indexOf("|")+1,str.indexOf("\t")));
for(;start<=end;start.setDate(start.getDate()+1)){
schedules[0].push(start.getMonth().valueOf()+1+"/"+start.getDate()+"/"+start.getFullYear().toString().substr(-2)+str.substring(str.indexOf("\t")));
}
}
else schedules[x].push(str);
}
}
}
/**
* Displays schedule of the week of the given date/time
*/
function setDisplayDate(time, force) {
var date = (time ? new Date(time) : getDateFromUrlParams()); //variable to keep track of current day in loop
setDayBeginning(date);
if(force || !displayDate || (date.valueOf()!=displayDate.valueOf())) {
var schedule = document.getElementById("schedule"); //get schedule table
displayDate = new Date(date);
displayMessage = "Welcome back! Tell a freshman about <a href='http://tiny.cc/bellschedule'>tiny.cc/bellschedule</a>.";
if(getMonday(date) > getMonday(new Date()))
displayMessage += "<br>This is a future date, so the schedule may be incorrect. (In particular, special/alternate schedules may be missing.)"; //display warning if date is in the future
warn(displayMessage)
/*warn("<b style='color:#FF8020'>UPDATE FROM STUCO!</b> Find out what Harker Student Council is working on for YOU at <a style='font-weight:bold' href='http://tiny.cc/harkerstuco'>tiny.cc/harkerstuco</a>!"
+ "<br><b>Submit Honor Council Feedback: </b><a style='font-weight:bold' href=http://bit.ly/harkerfeedback>bit.ly/harkerfeedback</a>"
+ "<br>Use this link <b>only</b> if you have concerns about possible breaches of academic integrity or wish to report Code of Conduct violations."
+ "<br><b>Submit StuCo Feedback:</b> Email <a style='font-weight:bold' href=mailto:[email protected]>[email protected]</a>"
+ "<br>Otherwise, direct your suggestions and concerns here."
+"<br><b>Dowload the new iOS app <a href='http://goo.gl/ZDMMRp'>here</a> to get live push notifications.</b>"); //else display message*/
/*
if(date.valueOf()==getMonday(new Date()).valueOf()) document.getElementById("currWeek").style.display = "none"; //hide back to current week button on current week
else document.getElementById("currWeek").style.display = "inline"; //else show the button
*/
while(schedule.rows.length) schedule.deleteRow(-1); //clear existing weeks (rows); there should only be one, but just in case...
var week = schedule.insertRow(-1); //create new week (row)
if(!options.enableDayView) {
date = getMonday(date);
for(var d=0;d<5;d++) {
//for each day Monday through Friday (inclusive)
createDay(week, date);
date.setDate(date.getDate()+1); //increment day
}
} else createDay(week, date);
}
}
/**
* Returns a Date object based on the current urlParams (GET variables in the URL).
* If any part of the date is not specified, defaults to the current date/month/year.
* If in week view, uses the Monday of the week instead of the day.
*/
function getDateFromUrlParams() {
var date = new Date();
if(urlParams["y"]>0) date.setFullYear("20" + urlParams["y"]);
if(urlParams["m"]>0) date.setMonth(urlParams["m"]-1);
if(urlParams["d"]>0) date.setDate(urlParams["d"]);
if(!options.enableDayView) date = getMonday(date);
return date;
}
/**
* Displays the given warning or hides the warning div if no warning text is given.
*/
function warn(text) {
var warning = document.getElementById("warning")
if(text) warning.style.display = "block";
else warning.style.display = "none";
warning.innerHTML = text;
}
/**
* Creates the day for the given date and appends it to the given week
*/
function createDay(week, date) {
var daySchedule = getDayInfo(date); //get schedule for that day
var col = week.insertCell(-1); //create cell for day
col.date = date.valueOf(); //store date in cell element
if(date.getMonth()==9 && date.getDate()==31) //check Halloween
col.classList.add("halloween");
var head = document.createElement("div"); //create header div in cell
head.classList.add("head");
var headWrapper = document.createElement("div");
headWrapper.classList.add("headWrapper");
var scheduleString = ""; //Should we display the schedule id (e.g. A) next to the date
//Make sure not to display anything if daySchedule is empty
if (typeof daySchedule.name != 'undefined' || daySchedule.name != null){
//Not a weekend, so add
scheduleString = "(" + daySchedule.name + ")";
}
if (scheduleString === "()") {
//It's a holiday so delete the extra parenthesis
scheduleString = "";}
headWrapper.innerHTML = days[date.getDay()] + "<div class=\"headDate\">" + daySchedule.dateString + " " + scheduleString + "</div>"; //Portion commented out represents schedule id of that day
head.appendChild(headWrapper);
col.appendChild(head);
var prevEnd = "8:00"; //set start of day to 8:00AM
// for sub periods, passing periods are already handled and do not need to be added in the next iteration
if(daySchedule.index > 0) { //populates cell with day's schedule (a bit messily)
for(var i=1;i<schedules[daySchedule.index].length;i++) {
var text = schedules[daySchedule.index][i];
var periodName = makePeriodNameReplacements(text.substring(0,text.indexOf("\t")), daySchedule.replacements);
var periodTime = text.substring(text.indexOf("\t")+1);
var start = periodTime.substring(0,periodTime.indexOf("-"));
var end = periodTime.substring(periodTime.lastIndexOf("-")+1);
// only creates a new passing period before the period if either 1) it's a split lunch period in the new schedule or
// 2) the date is not within the bounds of the new schedule
if(options.showPassingPeriods) {
var passing = document.createElement("div");
passing.classList.add("period");
createPeriod(passing,"",prevEnd,start,date);
col.appendChild(passing);
}
prevEnd = end;
var period = document.createElement("div");
period.classList.add("period");
if(periodName.indexOf("|") >= 0) {
//handle split periods (i.e. lunches)
var table = document.createElement("table");
table.classList.add("lunch");
var row = table.insertRow(-1);
var period1 = row.insertCell(-1);
var period2 = row.insertCell(-1);
var period1Time = periodTime.substring(0,periodTime.indexOf("||"));
var period2Time = periodTime.substring(periodTime.indexOf("||")+2);
var period1Name = periodName.substring(0, periodName.indexOf("||"));
var period2Name = periodName.substring(periodName.indexOf("||")+2);
//If there are two sets of subperiods (i.e. a|b||c|d) there should be 4 "|"s
if (findNumberOfOccurences(periodName, "|") == 4) {
show1Time = true;
show2Time = true;
createSubPeriods(
period1,
period1Name,
start,
period1Time.substring(period1Time.indexOf("-")+1,period1Time.indexOf("|")),
period1Time.substring(period1Time.indexOf("|")+1,period1Time.lastIndexOf("-")),
end,
date,
show1Time,
show2Time
);
createSubPeriods(
period2,
period2Name,
start,
period2Time.substring(period2Time.indexOf("-")+1,period2Time.indexOf("|")),
period2Time.substring(period2Time.indexOf("|")+1,period2Time.lastIndexOf("-")),
end,
date,
show1Time,
show2Time
);
}
else {
//parent, name, start, end, date
createPeriod(
period1,
period1Name,
start,
end,
date
)
show1Time = daySchedule.id == 4 || daySchedule.id == "ReCreate";
show2Time = !(show1Time);
//parent, name, start1, end1, start2, end2, date, show 1st, show 2nd
createSubPeriods(
period2,
period2Name,
start,
period2Time.substring(period2Time.indexOf("-")+1,period2Time.indexOf("|")),
period2Time.substring(period2Time.indexOf("|")+1,period2Time.lastIndexOf("-")),
end,
date,
show1Time,
show2Time
);
}
period.appendChild(table);
} else {
createPeriod(period,periodName,start,end,date);
//parent, name, start, end, date
//createSubPeriods(
//lunch2,
//periodName.substring(periodName.indexOf("||")+2),
//start,
//lunch2Time.substring(lunch2Time.indexOf("-")+1,lunch2Time.indexOf("|")),
//lunch2Time.substring(lunch2Time.indexOf("|")+1,lunch2Time.lastIndexOf("-")),
//end,
//date
//);
}
col.appendChild(period);
}
}
}
/**
* Returns new name for period based on array of replacements.
* If the current period name is listed in the array of replacements, returns the new, replaced name; otherwise, returns current name.
* replacements is an array of strings of the form "OldName->NewName"
*/
function makePeriodNameReplacements(periodName, replacements) {
if(replacements.length > 0) {
for(var i=0;i<replacements.length;i++) {
if(!replacements[i].indexOf(periodName))
return replacements[i].substring(replacements[i].indexOf("->")+2);
}
}
return periodName;
}
/**
* Sets the title of the title to a random line from the title titles list
*/
function setTitleTitle() {
var titles = document.getElementById("titleTitles").textContent.split("\n");
document.getElementById("title").title=titles[Math.floor(Math.random()*titles.length)];
}
/**
* Returns the Monday of next week if date is Saturday; else returns the Monday of that week
*/
function getMonday(d) {
var date = new Date(d);
if(date.getDay()>=6) date.setDate(date.getDate()+2); //set date to next Monday if today is Saturday
else date.setDate(date.getDate()-date.getDay()+1); //else set date Monday of this week
setDayBeginning(date); //set to beginning of day
return date;
}
/**
* Sets given date to beginning of the day (12:00 AM).
*/
function setDayBeginning(date) {
date.setHours(0,0,0,0);
}
/**
* Takes in a date and a string of form "hh:MM" and turns it into a time on the day of the given date.
* Assumes hours less than 7 are PM and hours 7 or greater are AM.
*/
function getDateFromString(string, date) {
var hour = string.substring(0,string.indexOf(":"));
var min = string.substring(string.indexOf(":")+1);
if(hour<7) hour = parseInt(hour,10)+12; //assumes hours less than seven are PM and hours 7 or greater are AM
return new Date(date.getFullYear(),date.getMonth(),date.getDate(),hour,min);
}
/**
* For given day, returns index of schedule id in schedules, schedule id, and formatted date (mm/dd/yy).
* Schedule id index is 0 if not found in schedules.
*/
function getDayInfo(day) {
var dateString = day.getMonth().valueOf()+1 + "/" + day.getDate().valueOf() + "/" + day.getFullYear().toString().substr(-2); //format in mm/dd/YY
var id;
var index = 0;
var replacements = [];
for(var i=0;i<schedules[0].length;i++) //search for special schedule on day
if(!schedules[0][i].indexOf(dateString)){
//found special schedule
if(schedules[0][i].indexOf("[") >= 0) { //check for period replacements
//cut replacements and space character out of id and save separately
id = schedules[0][i].substring(schedules[0][i].indexOf("\t")+1,schedules[0][i].indexOf("[")-1)
replacements = schedules[0][i].substring(schedules[0][i].indexOf("[")+1,schedules[0][i].indexOf("]")).split(",");
} else {
// no replacements to be made
id = schedules[0][i].substring(schedules[0][i].indexOf("\t")+1);
}
index = getScheduleIndex(id);
}
if(id === undefined) { //no special schedule found
id = day.getDay();
if(id==0 || id==6) index = id = 0; //no school on weekends
else { //default schedule for that day
id = calculateScheduleRotationID(day);
index = getScheduleIndex(id);
//Utilizes the replacement system and the fixed mapping to determine
//and display the particular after school function on a given day.
//Note that this is completely independent of the rotation of the
//schdule.
replacements = [COLLABORATION_REPLACEMENTS[day.getDay() - 1]];
}
}
var name = "";
if (id <= TOTAL_SCHEDULES) {
name = SCHEDULES[id - 1];
}
return { "index": index, "id": id, "dateString": dateString, "replacements": replacements, "name": name };
}
/**
* Gets the index in the list of schedules of the schedule with the given schedule id (or 0 if no matching schedules were found)
*/
function getScheduleIndex(id) {
if(id==0) return 0; //schedule id 0 represents no school
for(var i=1;i<schedules.length;i++) { //find index of schedule id
if(id==schedules[i][0]) return i; //found specified schedule id
}
return 0; //couldn't find specified schedule
}
/**
* Determines which schedule should be displayed given the four block rotation.
* This futher factors out weekends and holidays when
* considering which day to display. Relies on a known starting anchor day with
* a given schedule and continues the cycle from there.
*/
function calculateScheduleRotationID(date) {
var daysDifference = (date.getTime() - START_DATE.getTime()) / MILLIS_PER_DAY;
var weeksDifference = Math.floor(daysDifference / 7);
//Factor out weekends (2 days per week)
daysDifference -= weeksDifference * 2;
//Factor out holidays
var dateExp = /\d{1,2}\/\d{1,2}\/\d{2}/ //Finds dates of the format M(M)/D(D)/YY
for (var i = 0; i < schedules[0].length; i++) {
var entry = schedules[0][i];
if (entry.search(dateExp) != -1) {
//Parse entry into date and id
var dateString = entry.split("\t")[0];
//Convert the date to format M(M)/D(D)/YYYY because Date defaults to 1900s
dateString = dateString.substring(0, dateString.length - 2) + "20" + dateString.substring(dateString.length - 2);
var entryDate = new Date(dateString);
var entryId = entry.split("\t")[1];
//If the checked schedule "entry" is a holiday in the future that occurs
//before the date that is being calculated "date" but after the start of
//pilot program, don't consider it in the cycle
if (getScheduleIndex(entryId) == 0 && date > entryDate && entryDate > START_DATE) {
daysDifference--;
}
}
}
var id;
if (daysDifference < 0) //Different formula needed for events before start day
id = START_SCHEDULE + Math.floor(daysDifference % TOTAL_SCHEDULES) + TOTAL_SCHEDULES;
else
id = START_SCHEDULE + Math.floor(daysDifference % TOTAL_SCHEDULES);
//Even schedules repeat (2 and 6 are the same and 4 and 8 are the same)
if (id > 4 && id % 2 == 0)
id = id - 4;
return id;
}
/**
* Creates and returns a new period wrapper with the given content and start/end times.
* Also applies any special properties based on period length (text on single line if too short, block period if longer than regular).
*/
function createPeriod(parent, name, start, end, date, showTime) {
//Do not show time for very small periods (e.g. class meetings)
if(typeof(showTime) === "undefined") showTime = true;
startDate = getDateFromString(start,date);
endDate = getDateFromString(end,date);
var periodWrapper = document.createElement("div");
periodWrapper.classList.add("periodWrapper");
periodWrapper.periodName = name;
periodWrapper.start = startDate;
periodWrapper.end = endDate;
var length = (endDate-startDate)/60000;
if (options.color==true)
{
if (periodWrapper.periodName == "P1")
{
periodWrapper.classList.add("periodone");
}
if (periodWrapper.periodName =="P2")
{
periodWrapper.classList.add("periodtwo");
}
if (periodWrapper.periodName =="P3")
{
periodWrapper.classList.add("periodthree");
}
if (periodWrapper.periodName == "P4")
{
periodWrapper.classList.add("periodfour");
}
if (periodWrapper.periodName == "P5" ||periodWrapper.periodName == "P6")
{
periodWrapper.classList.add("lunchperiod");
}
if (periodWrapper.periodName == "Lunch")
{
periodWrapper.classList.add("lunchtime");
}
if (periodWrapper.periodName == "P7")
{
periodWrapper.classList.add("periodseven");
}
if (periodWrapper.periodName == "P8")
{
periodWrapper.classList.add("periodeight");
}
if (periodWrapper.periodName == "School Meeting" || periodWrapper.periodName == "Advisory")
{
periodWrapper.classList.add("meeting");
}
if (periodWrapper.periodName == "Extra Help")
{
periodWrapper.classList.add("extrahelp");
}
}
if(length > 0) {
periodWrapper.style.height = (length-1) + "px"; //minus 1 to account for 1px border
if(length >= 15) {
if(name) periodWrapper.innerHTML = name;
//Force long periods (30 minutes and up) to have a time
if(showTime) periodWrapper.innerHTML += (length<30 ? " " : "<br />") + start + " – " + end;
//if(length>50 && !name.indexOf("P")) //handle block periods (class=long, i.e. bold text)
//periodWrapper.classList.add("long");
}
return parent.appendChild(periodWrapper);
}
}
/**
* Creates and appends two new sub-periods and passing period to parent period with given start and end times.
*/
function createSubPeriods(parent, name, start1, end1, start2, end2, date, showFirstTime, showSecondTime) {
console.log(showSecondTime);
if (typeof(showFirstTime) === "undefined") showFirstTime = true;
if (typeof(showSecondTime) === "undefined") showSecondTime = true;
var p1 = document.createElement("div");
p1.classList.add("period");
createPeriod(
p1,
name.substring(0,name.indexOf("|")),
start1,
end1,
date,
showFirstTime);
parent.appendChild(p1);
if(options.showPassingPeriods) {
var lunchPassing = document.createElement("div");
lunchPassing.classList.add("period");
createPeriod(lunchPassing,"",end1,start2,date);
parent.appendChild(lunchPassing);
}
var p2 = document.createElement("div");
p2.classList.add("period");
//var w2 = document.createElement("div");
//w2.classList.add("periodWrapper");
createPeriod(
p2,
name.substring(name.indexOf("|")+1),
start2,
end2,
date,
showSecondTime);
parent.appendChild(p2);
}
/**
* Creates and appends just three new sub-periods (passing periods added manually) with given start and end times.
*/
function create3SubPeriods(parent, name1, start1, end1, name2, start2, end2, name3, start3, end3, date) {
var p1 = document.createElement("div");
p1.classList.add("period");
createPeriod(
p1,
name1,
start1,
end1,
date);
parent.appendChild(p1);
var p2 = document.createElement("div");
p2.classList.add("period");
//var w2 = document.createElement("div");
//w2.classList.add("periodWrapper");
createPeriod(
p2,
name2,
start2,
end2,
date);
parent.appendChild(p2);
var p3 = document.createElement("div");
p3.classList.add("period");
createPeriod(
p3,
name3,
start3,
end3,
date);
parent.appendChild(p3);
}
/**
* Navigates schedule to previous date.
*/
function goLast() {
var date = new Date(displayDate);
date.setDate(date.getDate() - (options.enableDayView ? 1 : 7));
updateSchedule(date);
updateSearch(date);
}
/**
* Navigates schedule to next date.
*/
function goNext() {
var date = new Date(displayDate);
date.setDate(date.getDate() + (options.enableDayView ? 1 : 7));
updateSchedule(date);
updateSearch(date);
}
/**
* Navigates schedule to current date.
*/
function goCurr() {
var date = new Date();
updateSchedule(date);
updateSearch(date);
}
/**
* Updates GET variables and urlParams to reflect date in week and pushes corresponding history state.
*/
function updateSearch(week, noHistory) {
var curr = new Date();
if(!options.enableDayView) curr = getMonday(curr);
if(week.getDate() != curr.getDate()) {
urlParams["m"] = week.getMonth()+1;
urlParams["d"] = week.getDate();
} else {
delete urlParams["m"];
delete urlParams["d"];
}
if(week.getYear() != curr.getYear()) urlParams["y"] = week.getFullYear().toString().substr(-2);
else delete urlParams["y"];
var search = "?";
for(var param in urlParams) search += param + "=" + urlParams[param] + "&";
search = search.slice(0,-1);
history.pushState(week, document.title, location.protocol + "//" + location.host + location.pathname + search + location.hash);
}
/**
* Highlights given date/time on the schedule; defaults to now if none is given
*/
function setHighlightedPeriod(time) {
//set default time argument
if(!time) time = Date.now();
//set date based on time (for finding day to highlight)
var date = new Date(time);
date.setHours(0,0,0,0);
//clear previous highlighted day/periods
//TODO: maybe it would be better to not clear highlights when nothing needs to be changed.
var prevDay = document.getElementById("today");
var prevPeriods = [];
if(prevDay){
//clear previous highlighted periods
prevPeriods = Array.prototype.slice.call(prevDay.getElementsByClassName("now")); //get copy of array, not reference to it (needed to check for period changes later)
for(var i=prevPeriods.length-1;i>=0;i--){
var prevPeriod = prevPeriods[i];
prevPeriod.classList.remove("now");
//remove period length
var periodLength = prevPeriod.getElementsByClassName("periodLength")[0];
if(periodLength) prevPeriod.removeChild(periodLength);
}
//clear previous highlighted day
//needs to be done after getting prevPeriods, or else prevDay no longer points anywhere
prevDay.id = "";
}
//set new highlighted day/period
var days = document.getElementById("schedule").rows[0].cells;
for(var d=0;d<days.length;d++){
var day = days[d];
if(date.valueOf() == day.date){ //test if date should be highlighted
//set new highlighted day
day.id = "today";
//set new highlighted periods
var periods = day.getElementsByClassName("periodWrapper");
for(var p=0;p<periods.length;p++)
{
var period = periods[p];
if(time-period.start>=0 && time-period.end<0){ //test if period should be highlighted
period.classList.add("now");
//add period length if it fits
if((period.end-period.start)/60000>=40){
var length = (period.end - time) / 60000;
period.innerHTML += "<div class=\"periodLength\">" +
(length>1 ?
Math.round(length) + " min. left</div>" :
Math.round(length*60) + " sec. left</div>");
}
}
}
}
}
if(options.enablePeriodNotifications) {
var currPeriods = Array.prototype.slice.call(document.getElementsByClassName("now")); //needs to be an array and not an HTML
var diff1 = currPeriods.diff(prevPeriods);
var diff2 = prevPeriods.diff(currPeriods);
for(var i=0; i<diff1.length; i++) {
var name = currPeriods[i].periodName;
if(name && !hasFocus) sendNotification(name + " has started.", options.notificationDuration);
}
for(var i=0; i<diff2.length; i++) {
var name = prevPeriods[i].periodName;
if(name && !hasFocus) sendNotification(name + " has ended.", options.notificationDuration);
}
}
}
/**
* Updates schedule to display as it would on the given date/time; defaults to now if none is given.
* Also updates
*/
function updateSchedule(time,force) {
setDisplayDate(time,force);
setHighlightedPeriod();
}
/**
* Expands the options div and changes the options arrow to point down and to the right.
*/
function expandOptions() {
document.getElementById("options").classList.add("expanded");
document.getElementById("optionsArrow").innerHTML = "↘";
}
/**
* Contracts the options div and changes the options arrow to point up and to the left.
*/
function contractOptions() {
document.getElementById("options").classList.remove("expanded");
document.getElementById("optionsArrow").innerHTML = "↖";
}
/**
* Toggles the options div between extended and contracted and updates options arrow accordingly.
*/
function toggleOptions() {
if(document.getElementById("options").classList.contains("expanded"))
contractOptions();
else expandOptions();
}
/**
* Initializes automatic option saving and sets options to previously-saved values, if any.
* If no previous saved value exists, sets current (default) value as saved value.
*/
function initOptions() {
var opt = document.getElementById("options");
opt.addEventListener("mouseover", expandOptions);
opt.addEventListener("mouseout", contractOptions);
if(mobile) opt.classList.add("mobile");
document.getElementById("optionsArrow").addEventListener("click", toggleOptions);
var inputs = opt.getElementsByTagName("input");
if(localStorage.updateScheduleInterval) {
//rename key
localStorage.activeUpdateInterval=localStorage.updateScheduleInterval;
localStorage.removeItem("updateScheduleInterval");
}
for(var i=0; i<inputs.length; i++)
{
var input = inputs[i];
//special cases because localStorage saves values as strings
if(input.type=="checkbox") { //booleans
input.addEventListener("change", function(event) {
options[event.target.name] = localStorage[event.target.name] = event.target.checked;
});
if(localStorage[input.name]) options[input.name] = input.checked = localStorage[input.name]=="true";
else options[input.name] = localStorage[input.name] = input.checked;
}
else if(input.type=="number") { //numbers
input.addEventListener("change", function(event) {
options[event.target.name] = parseInt(localStorage[event.target.name] = event.target.value);
});
if(localStorage[input.name]) options[input.name] = parseInt(input.value = localStorage[input.name]);
else options[input.name] = parseInt(localStorage[input.name] = input.value);
}
else { //strings
input.addEventListener("change", function(event) {
options[event.target.name] = localStorage[event.target.name] = event.target.value;
});
if(localStorage[input.name]) options[input.name] = input.value = localStorage[input.name];
else options[input.name] = localStorage[input.name] = input.value;
}
}
}
/**
* Creates options in the options div.
*/
function createOptions(data) {
// just assume the file has everything for now
JSON.parse(data).sections.forEach(function(section) {
if(!section.hasOwnProperty("platforms") ||
((mobile && section.platforms.indexOf("mobile") >= 0) || !mobile)) {
createOptionSection(section);
}
});
initOptions();
attachOptionActions();
updateSchedule(null, true);
}
/**
* Displays error about retrieving schedule.
*/
function displayOptionsError(timeout, status) {
updateSchedule();
if(timeout) {
warn("Retrieval of options.json timed out!");
} else {
warn("Something went wrong while retrieving options.json!");
}
}
/**
* Create and insert options section.
*/
function createOptionSection(section) {
createOptionSectionTitle(section);
section.options.forEach(function(option) {
if(!option.hasOwnProperty("platforms") ||
((mobile && option.platforms.indexOf("mobile") >= 0) || !mobile)) {
createOption(option);
}
});
}
/**
* Create and insert options section title.
*/
function createOptionSectionTitle(section) {
var tr = document.createElement("tr");
var th = document.createElement("th");
th.colspan = 2;