forked from cbonnet99/jquery-week-calendar
-
Notifications
You must be signed in to change notification settings - Fork 1
/
jquery.weekcalendar.js
1478 lines (1248 loc) · 51.6 KB
/
jquery.weekcalendar.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
/*
* jQuery.weekCalendar v1.2.3-pre
* http://www.redredred.com.au/
*
* Requires:
* - jquery.weekcalendar.css
* - jquery 1.3.x
* - jquery-ui 1.7.x (widget, drag, drop, resize)
*
* Copyright (c) 2009 Rob Monie
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
* If you're after a monthly calendar plugin, check out http://arshaw.com/fullcalendar/
*/
(function($) {
$.widget("ui.weekCalendar", {
options : {
date: new Date(),
timeFormat : "h:i a",
dateFormat : "M d, Y",
alwaysDisplayTimeMinutes: true,
use24Hour : false,
daysToShow : 7,
firstDayOfWeek : 0, // 0 = Sunday, 1 = Monday, 2 = Tuesday, ... , 6 = Saturday
useShortDayNames: false,
timeSeparator : " to ",
startParam : "start",
endParam : "end",
businessHours : {start: 8, end: 18, limitDisplay : false},
newEventText : "New Event",
timeslotHeight: 20,
defaultEventLength : 2,
timeslotsPerHour : 4,
buttons : true,
buttonText : {
today : "today",
lastWeek : " < ",
nextWeek : " > "
},
scrollToHourMillis : 500,
allowCalEventOverlap : false,
overlapEventsSeparate: false,
readonly: false,
draggable : function(calEvent, element) {
return true;
},
resizable : function(calEvent, element) {
return true;
},
eventClick : function() {
},
eventRender : function(calEvent, element) {
return element;
},
eventAfterRender : function(calEvent, element) {
return element;
},
eventDrag : function(calEvent, element) {
},
eventDrop : function(calEvent, element) {
},
eventResize : function(calEvent, element) {
},
eventNew : function(calEvent, element) {
},
eventMouseover : function(calEvent, $event) {
},
eventMouseout : function(calEvent, $event) {
},
calendarBeforeLoad : function(calendar) {
},
calendarAfterLoad : function(calendar) {
},
noEvents : function() {
},
shortMonths : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
longMonths : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
shortDays : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
longDays : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
},
/***********************
* Initialise calendar *
***********************/
_create : function() {
var self = this;
self._computeOptions();
self._setupEventDelegation();
self._renderCalendar();
self._loadCalEvents();
self._resizeCalendar();
self._scrollToHour(self.options.date.getHours());
$(window).unbind("resize.weekcalendar");
$(window).bind("resize.weekcalendar", function() {
self._resizeCalendar();
});
},
/********************
* public functions *
********************/
/*
* Refresh the events for the currently displayed week.
*/
refresh : function() {
this._loadCalEvents(this.element.data("startDate")); //reload with existing week
},
/*
* Clear all events currently loaded into the calendar
*/
clear : function() {
this._clearCalendar();
},
/*
* Go to this week
*/
today : function() {
this._clearCalendar();
this._loadCalEvents(new Date());
},
/*
* Go to the previous week relative to the currently displayed week
*/
prevWeek : function() {
//minus more than 1 day to be sure we're in previous week - account for daylight savings or other anomolies
var newDate = new Date(this.element.data("startDate").getTime() - (MILLIS_IN_WEEK / 6));
this._clearCalendar();
this._loadCalEvents(newDate);
},
/*
* Go to the next week relative to the currently displayed week
*/
nextWeek : function() {
//add 8 days to be sure of being in prev week - allows for daylight savings or other anomolies
var newDate = new Date(this.element.data("startDate").getTime() + MILLIS_IN_WEEK + (MILLIS_IN_WEEK / 7));
this._clearCalendar();
this._loadCalEvents(newDate);
},
/*
* Reload the calendar to whatever week the date passed in falls on.
*/
gotoWeek : function(date) {
this._clearCalendar();
this._loadCalEvents(date);
},
/*
* Remove an event based on it's id
*/
removeEvent : function(eventId) {
var self = this;
self.element.find(".wc-cal-event").each(function() {
if ($(this).data("calEvent").id === eventId) {
$(this).remove();
return false;
}
});
//this could be more efficient rather than running on all days regardless...
self.element.find(".wc-day-column-inner").each(function() {
self._adjustOverlappingEvents($(this));
});
},
/*
* Removes any events that have been added but not yet saved (have no id).
* This is useful to call after adding a freshly saved new event.
*/
removeUnsavedEvents : function() {
var self = this;
self.element.find(".wc-new-cal-event").each(function() {
$(this).remove();
});
//this could be more efficient rather than running on all days regardless...
self.element.find(".wc-day-column-inner").each(function() {
self._adjustOverlappingEvents($(this));
});
},
/*
* update an event in the calendar. If the event exists it refreshes
* it's rendering. If it's a new event that does not exist in the calendar
* it will be added.
*/
updateEvent : function (calEvent) {
this._updateEventInCalendar(calEvent);
},
/*
* Returns an array of timeslot start and end times based on
* the configured grid of the calendar. Returns in both date and
* formatted time based on the 'timeFormat' config option.
*/
getTimeslotTimes : function(date) {
var options = this.options;
var firstHourDisplayed = options.businessHours.limitDisplay ? options.businessHours.start : 0;
var startDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), firstHourDisplayed);
var times = []
var startMillis = startDate.getTime();
for (var i = 0; i < options.timeslotsPerDay; i++) {
var endMillis = startMillis + options.millisPerTimeslot;
times[i] = {
start: new Date(startMillis),
startFormatted: this._formatDate(new Date(startMillis), options.timeFormat),
end: new Date(endMillis),
endFormatted: this._formatDate(new Date(endMillis), options.timeFormat)
};
startMillis = endMillis;
}
return times;
},
formatDate : function(date, format) {
if (format) {
return this._formatDate(date, format);
} else {
return this._formatDate(date, this.options.dateFormat);
}
},
formatTime : function(date, format) {
if (format) {
return this._formatDate(date, format);
} else {
return this._formatDate(date, this.options.timeFormat);
}
},
/*
getData : function(key) {
return this._getData(key);
},
*/
/*********************
* private functions *
*********************/
_setOption: function(key, value) {
var self = this;
if(self.options[key] != value) {
// this could be made more efficient at some stage by caching the
// events array locally in a store but this should be done in conjunction
// with a proper binding model.
var currentEvents = $.map(self.element.find(".wc-cal-event"), function() {
return $(this).data("calEvent");
});
var newOptions = {};
newOptions[key] = value;
self._renderEvents({events:currentEvents, options: newOptions}, self.element.find(".wc-day-column-inner"))
}
},
// compute dynamic options based on other config values
_computeOptions : function() {
var options = this.options;
if (options.businessHours.limitDisplay) {
options.timeslotsPerDay = options.timeslotsPerHour * (options.businessHours.end - options.businessHours.start);
options.millisToDisplay = (options.businessHours.end - options.businessHours.start) * 60 * 60 * 1000;
options.millisPerTimeslot = options.millisToDisplay / options.timeslotsPerDay;
} else {
options.timeslotsPerDay = options.timeslotsPerHour * 24;
options.millisToDisplay = MILLIS_IN_DAY;
options.millisPerTimeslot = MILLIS_IN_DAY / options.timeslotsPerDay;
}
},
/*
* Resize the calendar scrollable height based on the provided function in options.
*/
_resizeCalendar : function () {
var options = this.options;
if (options && $.isFunction(options.height)) {
var calendarHeight = options.height(this.element);
var headerHeight = this.element.find(".wc-header").outerHeight();
var navHeight = this.element.find(".wc-nav").outerHeight();
this.element.find(".wc-scrollable-grid").height(calendarHeight - navHeight - headerHeight);
}
},
/*
* configure calendar interaction events that are able to use event
* delegation for greater efficiency
*/
_setupEventDelegation : function() {
var self = this;
var options = this.options;
this.element.click(function(event) {
var $target = $(event.target);
if ($target.data("preventClick")) {
return;
}
if ($target.hasClass("wc-cal-event")) {
options.eventClick($target.data("calEvent"), $target, event);
} else if ($target.parent().hasClass("wc-cal-event")) {
options.eventClick($target.parent().data("calEvent"), $target.parent(), event);
}
}).mouseover(function(event) {
var $target = $(event.target);
if (self._isDraggingOrResizing($target)) {
return;
}
if ($target.hasClass("wc-cal-event")) {
options.eventMouseover($target.data("calEvent"), $target, event);
}
}).mouseout(function(event) {
var $target = $(event.target);
if (self._isDraggingOrResizing($target)) {
return;
}
if ($target.hasClass("wc-cal-event")) {
if ($target.data("sizing")) return;
options.eventMouseout($target.data("calEvent"), $target, event);
}
});
},
/*
* check if a ui draggable or resizable is currently being dragged or resized
*/
_isDraggingOrResizing : function ($target) {
return $target.hasClass("ui-draggable-dragging") || $target.hasClass("ui-resizable-resizing");
},
/*
* Render the main calendar layout
*/
_renderCalendar : function() {
var $calendarContainer, calendarNavHtml, calendarHeaderHtml, calendarBodyHtml, $weekDayColumns;
var self = this;
var options = this.options;
$calendarContainer = $("<div class=\"wc-container\">").appendTo(self.element);
if (options.buttons) {
calendarNavHtml = "<div class=\"wc-nav\">\
<button class=\"wc-today\">" + options.buttonText.today + "</button>\
<button class=\"wc-prev\">" + options.buttonText.lastWeek + "</button>\
<button class=\"wc-next\">" + options.buttonText.nextWeek + "</button>\
</div>";
$(calendarNavHtml).appendTo($calendarContainer);
$calendarContainer.find(".wc-nav .wc-today").click(function() {
self.element.weekCalendar("today");
return false;
});
$calendarContainer.find(".wc-nav .wc-prev").click(function() {
self.element.weekCalendar("prevWeek");
return false;
});
$calendarContainer.find(".wc-nav .wc-next").click(function() {
self.element.weekCalendar("nextWeek");
return false;
});
}
//render calendar header
calendarHeaderHtml = "<table class=\"wc-header\"><tbody><tr><td class=\"wc-time-column-header\"></td>";
for (var i = 1; i <= options.daysToShow; i++) {
calendarHeaderHtml += "<td class=\"wc-day-column-header wc-day-" + i + "\"></td>";
}
calendarHeaderHtml += "<td class=\"wc-scrollbar-shim\"></td></tr></tbody></table>";
//render calendar body
calendarBodyHtml = "<div class=\"wc-scrollable-grid\">\
<table class=\"wc-time-slots\">\
<tbody>\
<tr>\
<td class=\"wc-grid-timeslot-header\"></td>\
<td colspan=\"" + options.daysToShow + "\">\
<div class=\"wc-time-slot-wrapper\">\
<div class=\"wc-time-slots\">";
var start = options.businessHours.limitDisplay ? options.businessHours.start : 0;
var end = options.businessHours.limitDisplay ? options.businessHours.end : 24;
for (var i = start; i < end; i++) {
for (var j = 0; j < options.timeslotsPerHour - 1; j++) {
calendarBodyHtml += "<div class=\"wc-time-slot\"></div>";
}
calendarBodyHtml += "<div class=\"wc-time-slot wc-hour-end\"></div>";
}
calendarBodyHtml += "</div></div></td></tr><tr><td class=\"wc-grid-timeslot-header\">";
for (var i = start; i < end; i++) {
var bhClass = (options.businessHours.start <= i && options.businessHours.end > i) ? "wc-business-hours" : "";
calendarBodyHtml += "<div class=\"wc-hour-header " + bhClass + "\">"
if (options.use24Hour) {
calendarBodyHtml += "<div class=\"wc-time-header-cell\">" + self._24HourForIndex(i) + "</div>";
} else {
calendarBodyHtml += "<div class=\"wc-time-header-cell\">" + self._hourForIndex(i) + "<span class=\"wc-am-pm\">" + self._amOrPm(i) + "</span></div>";
}
calendarBodyHtml += "</div>";
}
calendarBodyHtml += "</td>";
for (var i = 1; i <= options.daysToShow; i++) {
calendarBodyHtml += "<td class=\"wc-day-column day-" + i + "\"><div class=\"wc-day-column-inner\"></div></td>"
}
calendarBodyHtml += "</tr></tbody></table></div>";
//append all calendar parts to container
$(calendarHeaderHtml + calendarBodyHtml).appendTo($calendarContainer);
$weekDayColumns = $calendarContainer.find(".wc-day-column-inner");
$weekDayColumns.each(function(i, val) {
$(this).height(options.timeslotHeight * options.timeslotsPerDay);
if (!options.readonly) {
self._addDroppableToWeekDay($(this));
self._setupEventCreationForWeekDay($(this));
}
});
$calendarContainer.find(".wc-time-slot").height(options.timeslotHeight - 1); //account for border
$calendarContainer.find(".wc-time-header-cell").css({
height : (options.timeslotHeight * options.timeslotsPerHour) - 11,
padding: 5
});
},
/*
* setup mouse events for capturing new events
*/
_setupEventCreationForWeekDay : function($weekDay) {
var self = this;
var options = this.options;
$weekDay.mousedown(function(event) {
var $target = $(event.target);
if ($target.hasClass("wc-day-column-inner")) {
var $newEvent = $("<div class=\"wc-cal-event wc-new-cal-event wc-new-cal-event-creating\"></div>");
$newEvent.css({lineHeight: (options.timeslotHeight - 2) + "px", fontSize: (options.timeslotHeight / 2) + "px"});
$target.append($newEvent);
var columnOffset = $target.offset().top;
var clickY = event.pageY - columnOffset;
var clickYRounded = (clickY - (clickY % options.timeslotHeight)) / options.timeslotHeight;
var topPosition = clickYRounded * options.timeslotHeight;
$newEvent.css({top: topPosition});
$target.bind("mousemove.newevent", function(event) {
$newEvent.show();
$newEvent.addClass("ui-resizable-resizing");
var height = Math.round(event.pageY - columnOffset - topPosition);
var remainder = height % options.timeslotHeight;
//snap to closest timeslot
if (remainder < (height / 2)) {
var useHeight = height - remainder;
$newEvent.css("height", useHeight < options.timeslotHeight ? options.timeslotHeight : useHeight);
} else {
$newEvent.css("height", height + (options.timeslotHeight - remainder));
}
}).mouseup(function() {
$target.unbind("mousemove.newevent");
$newEvent.addClass("ui-corner-all");
});
}
}).mouseup(function(event) {
var $target = $(event.target);
var $weekDay = $target.closest(".wc-day-column-inner");
var $newEvent = $weekDay.find(".wc-new-cal-event-creating");
if ($newEvent.length) {
//if even created from a single click only, default height
if (!$newEvent.hasClass("ui-resizable-resizing")) {
$newEvent.css({height: options.timeslotHeight * options.defaultEventLength}).show();
}
var top = parseInt($newEvent.css("top"));
var eventDuration = self._getEventDurationFromPositionedEventElement($weekDay, $newEvent, top);
$newEvent.remove();
var newCalEvent = {start: eventDuration.start, end: eventDuration.end, title: options.newEventText};
var $renderedCalEvent = self._renderEvent(newCalEvent, $weekDay);
if (!options.allowCalEventOverlap) {
self._adjustForEventCollisions($weekDay, $renderedCalEvent, newCalEvent, newCalEvent);
self._positionEvent($weekDay, $renderedCalEvent);
} else {
self._adjustOverlappingEvents($weekDay);
}
options.eventNew(eventDuration, $renderedCalEvent);
}
});
},
/*
* load calendar events for the week based on the date provided
*/
_loadCalEvents : function(dateWithinWeek) {
var date, weekStartDate, endDate, $weekDayColumns;
var self = this;
var options = this.options;
date = dateWithinWeek || options.date;
weekStartDate = self._dateFirstDayOfWeek(date);
weekEndDate = self._dateLastMilliOfWeek(date);
options.calendarBeforeLoad(self.element);
self.element.data("startDate", weekStartDate);
self.element.data("endDate", weekEndDate);
$weekDayColumns = self.element.find(".wc-day-column-inner");
self._updateDayColumnHeader($weekDayColumns);
//load events by chosen means
if (typeof options.data == 'string') {
if (options.loading) options.loading(true);
var jsonOptions = {};
jsonOptions[options.startParam || 'start'] = Math.round(weekStartDate.getTime() / 1000);
jsonOptions[options.endParam || 'end'] = Math.round(weekEndDate.getTime() / 1000);
$.getJSON(options.data, jsonOptions, function(data) {
self._renderEvents(data, $weekDayColumns);
if (options.loading) options.loading(false);
});
}
else if ($.isFunction(options.data)) {
options.data(weekStartDate, weekEndDate,
function(data) {
self._renderEvents(data, $weekDayColumns);
});
}
else if (options.data) {
self._renderEvents(options.data, $weekDayColumns);
}
self._disableTextSelect($weekDayColumns);
},
/*
* update the display of each day column header based on the calendar week
*/
_updateDayColumnHeader : function ($weekDayColumns) {
var self = this;
var options = this.options;
var currentDay = self._cloneDate(self.element.data("startDate"));
self.element.find(".wc-header td.wc-day-column-header").each(function(i, val) {
var dayName = options.useShortDayNames ? options.shortDays[currentDay.getDay()] : options.longDays[currentDay.getDay()];
$(this).html(dayName + "<br/>" + self._formatDate(currentDay, options.dateFormat));
if (self._isToday(currentDay)) {
$(this).addClass("wc-today");
} else {
$(this).removeClass("wc-today");
}
currentDay = self._addDays(currentDay, 1);
});
currentDay = self._dateFirstDayOfWeek(self._cloneDate(self.element.data("startDate")));
$weekDayColumns.each(function(i, val) {
$(this).data("startDate", self._cloneDate(currentDay));
$(this).data("endDate", new Date(currentDay.getTime() + (MILLIS_IN_DAY)));
if (self._isToday(currentDay)) {
$(this).parent().addClass("wc-today");
} else {
$(this).parent().removeClass("wc-today");
}
currentDay = self._addDays(currentDay, 1);
});
},
/*
* Render the events into the calendar
*/
_renderEvents : function (data, $weekDayColumns) {
this._clearCalendar();
var self = this;
var options = this.options;
var eventsToRender;
if ($.isArray(data)) {
eventsToRender = self._cleanEvents(data);
} else if (data.events) {
eventsToRender = self._cleanEvents(data.events);
}
if (data.options) {
var updateLayout = false;
//update options
$.each(data.options, function(key, value) {
if (value !== options[key]) {
options[key] = value;
updateLayout = true;
}
});
self._computeOptions();
if (updateLayout) {
self.element.empty();
self._renderCalendar();
$weekDayColumns = self.element.find(".wc-time-slots .wc-day-column-inner");
self._updateDayColumnHeader($weekDayColumns);
self._resizeCalendar();
}
}
$.each(eventsToRender, function(i, calEvent) {
var $weekDay = self._findWeekDayForEvent(calEvent, $weekDayColumns);
if ($weekDay) {
self._renderEvent(calEvent, $weekDay);
}
});
$weekDayColumns.each(function() {
self._adjustOverlappingEvents($(this));
});
options.calendarAfterLoad(self.element);
if (!eventsToRender.length) {
options.noEvents();
}
},
/*
* Render a specific event into the day provided. Assumes correct
* day for calEvent date
*/
_renderEvent: function (calEvent, $weekDay) {
var self = this;
var options = this.options;
if (calEvent.start.getTime() > calEvent.end.getTime()) {
return; // can't render a negative height
}
var eventClass, eventHtml, $calEvent, $modifiedEvent;
eventClass = calEvent.id ? "wc-cal-event" : "wc-cal-event wc-new-cal-event";
eventHtml = "<div class=\"" + eventClass + " ui-corner-all\">\
<div class=\"wc-time ui-corner-all\"></div>\
<div class=\"wc-title\"></div></div>";
$calEvent = $(eventHtml);
$modifiedEvent = options.eventRender(calEvent, $calEvent);
$calEvent = $modifiedEvent ? $modifiedEvent.appendTo($weekDay) : $calEvent.appendTo($weekDay);
$calEvent.css({lineHeight: (options.timeslotHeight - 2) + "px", fontSize: (options.timeslotHeight / 2) + "px"});
self._refreshEventDetails(calEvent, $calEvent);
self._positionEvent($weekDay, $calEvent);
$calEvent.show();
if (!options.readonly && options.resizable(calEvent, $calEvent)) {
self._addResizableToCalEvent(calEvent, $calEvent, $weekDay)
}
if (!options.readonly && options.draggable(calEvent, $calEvent)) {
self._addDraggableToCalEvent(calEvent, $calEvent);
}
options.eventAfterRender(calEvent, $calEvent);
return $calEvent;
},
_adjustOverlappingEvents : function($weekDay) {
var self = this;
if (self.options.allowCalEventOverlap) {
var groupsList = self._groupOverlappingEventElements($weekDay);
$.each(groupsList, function() {
var curGroups = this;
$.each(curGroups, function(groupIndex) {
var curGroup = this;
// do we want events to be displayed as overlapping
if (self.options.overlapEventsSeparate) {
var newWidth = 100 / curGroups.length;
var newLeft = groupIndex * newWidth;
} else {
// TODO what happens when the group has more than 10 elements
var newWidth = 100 - ( (curGroups.length - 1) * 10 );
var newLeft = groupIndex * 10;
}
$.each(curGroup, function() {
// bring mouseovered event to the front
if (!self.options.overlapEventsSeparate) {
$(this).bind("mouseover.z-index", function() {
var $elem = $(this);
$.each(curGroup, function() {
$(this).css({"z-index": "1"});
});
$elem.css({"z-index": "3"});
});
}
$(this).css({width: newWidth + "%", left:newLeft + "%", right: 0});
});
});
});
}
},
/*
* Find groups of overlapping events
*/
_groupOverlappingEventElements : function($weekDay) {
var $events = $weekDay.find(".wc-cal-event:visible");
var sortedEvents = $events.sort(function(a, b) {
return $(a).data("calEvent").start.getTime() - $(b).data("calEvent").start.getTime();
});
var lastEndTime = new Date(0, 0, 0);
var groups = [];
var curGroups = [];
var $curEvent;
$.each(sortedEvents, function() {
$curEvent = $(this);
//checks, if the current group list is not empty, if the overlapping is finished
if (curGroups.length > 0) {
if (lastEndTime.getTime() <= $curEvent.data("calEvent").start.getTime()) {
//finishes the current group list by adding it to the resulting list of groups and cleans it
groups.push(curGroups);
curGroups = [];
}
}
//finds the first group to fill with the event
for (var groupIndex = 0; groupIndex < curGroups.length; groupIndex++) {
if (curGroups[groupIndex].length > 0) {
//checks if the event starts after the end of the last event of the group
if (curGroups[groupIndex][curGroups [groupIndex].length - 1].data("calEvent").end.getTime() <= $curEvent.data("calEvent").start.getTime()) {
curGroups[groupIndex].push($curEvent);
if (lastEndTime.getTime() < $curEvent.data("calEvent").end.getTime()) {
lastEndTime = $curEvent.data("calEvent").end;
}
return;
}
}
}
//if not found, creates a new group
curGroups.push([$curEvent]);
if (lastEndTime.getTime() < $curEvent.data("calEvent").end.getTime()) {
lastEndTime = $curEvent.data("calEvent").end;
}
});
//adds the last groups in result
if (curGroups.length > 0) {
groups.push(curGroups);
}
return groups;
},
/*
* find the weekday in the current calendar that the calEvent falls within
*/
_findWeekDayForEvent : function(calEvent, $weekDayColumns) {
var $weekDay;
$weekDayColumns.each(function() {
if ($(this).data("startDate").getTime() <= calEvent.start.getTime() && $(this).data("endDate").getTime() >= calEvent.end.getTime()) {
$weekDay = $(this);
return false;
}
});
return $weekDay;
},
/*
* update the events rendering in the calendar. Add if does not yet exist.
*/
_updateEventInCalendar : function (calEvent) {
var self = this;
var options = this.options;
self._cleanEvent(calEvent);
if (calEvent.id) {
self.element.find(".wc-cal-event").each(function() {
if ($(this).data("calEvent").id === calEvent.id || $(this).hasClass("wc-new-cal-event")) {
$(this).remove();
return false;
}
});
}
var $weekDay = self._findWeekDayForEvent(calEvent, self.element.find(".wc-time-slots .wc-day-column-inner"));
if ($weekDay) {
var $calEvent = self._renderEvent(calEvent, $weekDay);
self._adjustForEventCollisions($weekDay, $calEvent, calEvent, calEvent);
self._refreshEventDetails(calEvent, $calEvent);
self._positionEvent($weekDay, $calEvent);
self._adjustOverlappingEvents($weekDay);
}
},
/*
* Position the event element within the weekday based on it's start / end dates.
*/
_positionEvent : function($weekDay, $calEvent) {
var options = this.options;
var calEvent = $calEvent.data("calEvent");
var pxPerMillis = $weekDay.height() / options.millisToDisplay;
var firstHourDisplayed = options.businessHours.limitDisplay ? options.businessHours.start : 0;
var startMillis = calEvent.start.getTime() - new Date(calEvent.start.getFullYear(), calEvent.start.getMonth(), calEvent.start.getDate(), firstHourDisplayed).getTime();
var eventMillis = calEvent.end.getTime() - calEvent.start.getTime();
var pxTop = pxPerMillis * startMillis;
var pxHeight = pxPerMillis * eventMillis;
$calEvent.css({top: pxTop, height: pxHeight});
},
/*
* Determine the actual start and end times of a calevent based on it's
* relative position within the weekday column and the starting hour of the
* displayed calendar.
*/
_getEventDurationFromPositionedEventElement : function($weekDay, $calEvent, top) {
var options = this.options;
var startOffsetMillis = options.businessHours.limitDisplay ? options.businessHours.start * 60 * 60 * 1000 : 0;
var start = new Date($weekDay.data("startDate").getTime() + startOffsetMillis + Math.round(top / options.timeslotHeight) * options.millisPerTimeslot);
var end = new Date(start.getTime() + ($calEvent.height() / options.timeslotHeight) * options.millisPerTimeslot);
return {start: start, end: end};
},
/*
* If the calendar does not allow event overlap, adjust the start or end date if necessary to
* avoid overlapping of events. Typically, shortens the resized / dropped event to it's max possible
* duration based on the overlap. If no satisfactory adjustment can be made, the event is reverted to
* it's original location.
*/
_adjustForEventCollisions : function($weekDay, $calEvent, newCalEvent, oldCalEvent, maintainEventDuration) {
var options = this.options;
if (options.allowCalEventOverlap) {
return;
}
var adjustedStart, adjustedEnd;
var self = this;
$weekDay.find(".wc-cal-event").not($calEvent).each(function() {
var currentCalEvent = $(this).data("calEvent");
//has been dropped onto existing event overlapping the end time
if (newCalEvent.start.getTime() < currentCalEvent.end.getTime()
&& newCalEvent.end.getTime() >= currentCalEvent.end.getTime()) {
adjustedStart = currentCalEvent.end;
}
//has been dropped onto existing event overlapping the start time
if (newCalEvent.end.getTime() > currentCalEvent.start.getTime()
&& newCalEvent.start.getTime() <= currentCalEvent.start.getTime()) {
adjustedEnd = currentCalEvent.start;
}
//has been dropped inside existing event with same or larger duration
if (oldCalEvent.resizable == false || (newCalEvent.end.getTime() <= currentCalEvent.end.getTime()
&& newCalEvent.start.getTime() >= currentCalEvent.start.getTime())) {
adjustedStart = oldCalEvent.start;
adjustedEnd = oldCalEvent.end;
return false;
}
});
newCalEvent.start = adjustedStart || newCalEvent.start;
if (adjustedStart && maintainEventDuration) {
newCalEvent.end = new Date(adjustedStart.getTime() + (oldCalEvent.end.getTime() - oldCalEvent.start.getTime()));
self._adjustForEventCollisions($weekDay, $calEvent, newCalEvent, oldCalEvent);
} else {
newCalEvent.end = adjustedEnd || newCalEvent.end;
}
//reset if new cal event has been forced to zero size
if (newCalEvent.start.getTime() >= newCalEvent.end.getTime()) {
newCalEvent.start = oldCalEvent.start;
newCalEvent.end = oldCalEvent.end;
}
$calEvent.data("calEvent", newCalEvent);
},
/*
* Add draggable capabilities to an event
*/
_addDraggableToCalEvent : function(calEvent, $calEvent) {
var self = this;
var options = this.options;
var $weekDay = self._findWeekDayForEvent(calEvent, self.element.find(".wc-time-slots .wc-day-column-inner"));
$calEvent.draggable({
handle : ".wc-time",
containment: ".wc-scrollable-grid",
revert: 'valid',
opacity: 0.5,
grid : [$calEvent.outerWidth() + 1, options.timeslotHeight ],
start : function(event, ui) {
var $calEvent = ui.draggable;
options.eventDrag(calEvent, $calEvent);
}
});
},
/*
* Add droppable capabilites to weekdays to allow dropping of calEvents only
*/
_addDroppableToWeekDay : function($weekDay) {
var self = this;
var options = this.options;
$weekDay.droppable({
accept: ".wc-cal-event",
drop: function(event, ui) {
var $calEvent = ui.draggable;
var top = Math.round(parseInt(ui.position.top));
var eventDuration = self._getEventDurationFromPositionedEventElement($weekDay, $calEvent, top);
var calEvent = $calEvent.data("calEvent");
var newCalEvent = $.extend(true, {}, calEvent, {start: eventDuration.start, end: eventDuration.end});
self._adjustForEventCollisions($weekDay, $calEvent, newCalEvent, calEvent, true);
var $weekDayColumns = self.element.find(".wc-day-column-inner");
//trigger drop callback
options.eventDrop(newCalEvent, calEvent, $newEvent);
var $newEvent = self._renderEvent(newCalEvent, self._findWeekDayForEvent(newCalEvent, $weekDayColumns));
$calEvent.hide();