source: src/main/resources/static/js/fullcalendar.js

Last change on this file was 77205be, checked in by gjoko kostadinov <gjokokostadinov@…>, 11 months ago

Add entire code

  • Property mode set to 100755
File size: 148.1 KB
Line 
1/*!
2 * FullCalendar v1.6.4
3 * Docs & License: http://arshaw.com/fullcalendar/
4 * (c) 2013 Adam Shaw
5 */
6
7/*
8 * Use fullcalendar.css for basic styling.
9 * For event drag & drop, requires jQuery UI draggable.
10 * For event resizing, requires jQuery UI resizable.
11 */
12
13(function($, undefined) {
14
15
16;;
17
18var defaults = {
19
20 // display
21 defaultView: 'month',
22 aspectRatio: 1.35,
23 header: {
24 left: 'title',
25 center: '',
26 right: 'today prev,next'
27 },
28 weekends: true,
29 weekNumbers: false,
30 weekNumberCalculation: 'iso',
31 weekNumberTitle: 'W',
32
33 // editing
34 //editable: false,
35 //disableDragging: false,
36 //disableResizing: false,
37
38 allDayDefault: true,
39 ignoreTimezone: true,
40
41 // event ajax
42 lazyFetching: true,
43 startParam: 'start',
44 endParam: 'end',
45
46 // time formats
47 titleFormat: {
48 month: 'MMMM yyyy',
49 week: "MMM d[ yyyy]{ '&#8212;'[ MMM] d yyyy}",
50 day: 'dddd, MMM d, yyyy'
51 },
52 columnFormat: {
53 month: 'ddd',
54 week: 'ddd M/d',
55 day: 'dddd M/d'
56 },
57 timeFormat: { // for event elements
58 '': 'h(:mm)t' // default
59 },
60
61 // locale
62 isRTL: false,
63 firstDay: 0,
64 monthNames: ['January','February','March','April','May','June','July','August','September','October','November','December'],
65 monthNamesShort: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
66 dayNames: ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],
67 dayNamesShort: ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],
68 buttonText: {
69 prev: "<span class='fc-text-arrow'>&lsaquo;</span>",
70 next: "<span class='fc-text-arrow'>&rsaquo;</span>",
71 prevYear: "<span class='fc-text-arrow'>&laquo;</span>",
72 nextYear: "<span class='fc-text-arrow'>&raquo;</span>",
73 today: 'today',
74 month: 'month',
75 week: 'week',
76 day: 'day'
77 },
78
79 // jquery-ui theming
80 theme: false,
81 buttonIcons: {
82 prev: 'circle-triangle-w',
83 next: 'circle-triangle-e'
84 },
85
86 //selectable: false,
87 unselectAuto: true,
88
89 dropAccept: '*',
90
91 handleWindowResize: true
92
93};
94
95// right-to-left defaults
96var rtlDefaults = {
97 header: {
98 left: 'next,prev today',
99 center: '',
100 right: 'title'
101 },
102 buttonText: {
103 prev: "<span class='fc-text-arrow'>&rsaquo;</span>",
104 next: "<span class='fc-text-arrow'>&lsaquo;</span>",
105 prevYear: "<span class='fc-text-arrow'>&raquo;</span>",
106 nextYear: "<span class='fc-text-arrow'>&laquo;</span>"
107 },
108 buttonIcons: {
109 prev: 'circle-triangle-e',
110 next: 'circle-triangle-w'
111 }
112};
113
114
115
116;;
117
118var fc = $.fullCalendar = { version: "1.6.4" };
119var fcViews = fc.views = {};
120
121
122$.fn.fullCalendar = function(options) {
123
124
125 // method calling
126 if (typeof options == 'string') {
127 var args = Array.prototype.slice.call(arguments, 1);
128 var res;
129 this.each(function() {
130 var calendar = $.data(this, 'fullCalendar');
131 if (calendar && $.isFunction(calendar[options])) {
132 var r = calendar[options].apply(calendar, args);
133 if (res === undefined) {
134 res = r;
135 }
136 if (options == 'destroy') {
137 $.removeData(this, 'fullCalendar');
138 }
139 }
140 });
141 if (res !== undefined) {
142 return res;
143 }
144 return this;
145 }
146
147 options = options || {};
148
149 // would like to have this logic in EventManager, but needs to happen before options are recursively extended
150 var eventSources = options.eventSources || [];
151 delete options.eventSources;
152 if (options.events) {
153 eventSources.push(options.events);
154 delete options.events;
155 }
156
157
158 options = $.extend(true, {},
159 defaults,
160 (options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {},
161 options
162 );
163
164
165 this.each(function(i, _element) {
166 var element = $(_element);
167 var calendar = new Calendar(element, options, eventSources);
168 element.data('fullCalendar', calendar); // TODO: look into memory leak implications
169 calendar.render();
170 });
171
172
173 return this;
174
175};
176
177
178// function for adding/overriding defaults
179function setDefaults(d) {
180 $.extend(true, defaults, d);
181}
182
183
184
185;;
186
187
188function Calendar(element, options, eventSources) {
189 var t = this;
190
191
192 // exports
193 t.options = options;
194 t.render = render;
195 t.destroy = destroy;
196 t.refetchEvents = refetchEvents;
197 t.reportEvents = reportEvents;
198 t.reportEventChange = reportEventChange;
199 t.rerenderEvents = rerenderEvents;
200 t.changeView = changeView;
201 t.select = select;
202 t.unselect = unselect;
203 t.prev = prev;
204 t.next = next;
205 t.prevYear = prevYear;
206 t.nextYear = nextYear;
207 t.today = today;
208 t.gotoDate = gotoDate;
209 t.incrementDate = incrementDate;
210 t.formatDate = function(format, date) { return formatDate(format, date, options) };
211 t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) };
212 t.getDate = getDate;
213 t.getView = getView;
214 t.option = option;
215 t.trigger = trigger;
216
217
218 // imports
219 EventManager.call(t, options, eventSources);
220 var isFetchNeeded = t.isFetchNeeded;
221 var fetchEvents = t.fetchEvents;
222
223
224 // locals
225 var _element = element[0];
226 var header;
227 var headerElement;
228 var content;
229 var tm; // for making theme classes
230 var currentView;
231 var elementOuterWidth;
232 var suggestedViewHeight;
233 var resizeUID = 0;
234 var ignoreWindowResize = 0;
235 var date = new Date();
236 var events = [];
237 var _dragElement;
238
239
240
241 /* Main Rendering
242 -----------------------------------------------------------------------------*/
243
244
245 setYMD(date, options.year, options.month, options.date);
246
247
248 function render(inc) {
249 if (!content) {
250 initialRender();
251 }
252 else if (elementVisible()) {
253 // mainly for the public API
254 calcSize();
255 _renderView(inc);
256 }
257 }
258
259
260 function initialRender() {
261 tm = options.theme ? 'ui' : 'fc';
262 element.addClass('fc');
263 if (options.isRTL) {
264 element.addClass('fc-rtl');
265 }
266 else {
267 element.addClass('fc-ltr');
268 }
269 if (options.theme) {
270 element.addClass('ui-widget');
271 }
272
273 content = $("<div class='fc-content' style='position:relative'/>")
274 .prependTo(element);
275
276 header = new Header(t, options);
277 headerElement = header.render();
278 if (headerElement) {
279 element.prepend(headerElement);
280 }
281
282 changeView(options.defaultView);
283
284 if (options.handleWindowResize) {
285 $(window).resize(windowResize);
286 }
287
288 // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
289 if (!bodyVisible()) {
290 lateRender();
291 }
292 }
293
294
295 // called when we know the calendar couldn't be rendered when it was initialized,
296 // but we think it's ready now
297 function lateRender() {
298 setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
299 if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
300 renderView();
301 }
302 },0);
303 }
304
305
306 function destroy() {
307
308 if (currentView) {
309 trigger('viewDestroy', currentView, currentView, currentView.element);
310 currentView.triggerEventDestroy();
311 }
312
313 $(window).unbind('resize', windowResize);
314
315 header.destroy();
316 content.remove();
317 element.removeClass('fc fc-rtl ui-widget');
318 }
319
320
321 function elementVisible() {
322 return element.is(':visible');
323 }
324
325
326 function bodyVisible() {
327 return $('body').is(':visible');
328 }
329
330
331
332 /* View Rendering
333 -----------------------------------------------------------------------------*/
334 function changeView(newViewName) {
335 if (!currentView || newViewName != currentView.name) {
336 _changeView(newViewName);
337 }
338 }
339
340
341 function _changeView(newViewName) {
342 ignoreWindowResize++;
343
344 if (currentView) {
345 trigger('viewDestroy', currentView, currentView, currentView.element);
346 unselect();
347 currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
348 freezeContentHeight();
349 currentView.element.remove();
350 header.deactivateButton(currentView.name);
351 }
352
353 header.activateButton(newViewName);
354
355 currentView = new fcViews[newViewName](
356 $("<div class='fc-view fc-view-" + newViewName + "' style='position:relative'/>")
357 .appendTo(content),
358 t // the calendar object
359 );
360
361 renderView();
362 unfreezeContentHeight();
363
364 ignoreWindowResize--;
365 }
366
367
368 function renderView(inc) {
369 if (
370 !currentView.start || // never rendered before
371 inc || date < currentView.start || date >= currentView.end // or new date range
372 ) {
373 if (elementVisible()) {
374 _renderView(inc);
375 }
376 }
377 }
378
379
380 function _renderView(inc) { // assumes elementVisible
381 ignoreWindowResize++;
382
383 if (currentView.start) { // already been rendered?
384 trigger('viewDestroy', currentView, currentView, currentView.element);
385 unselect();
386 clearEvents();
387 }
388
389 freezeContentHeight();
390 currentView.render(date, inc || 0); // the view's render method ONLY renders the skeleton, nothing else
391 setSize();
392 unfreezeContentHeight();
393 (currentView.afterRender || noop)();
394
395 updateTitle();
396 updateTodayButton();
397
398 trigger('viewRender', currentView, currentView, currentView.element);
399 currentView.trigger('viewDisplay', _element); // deprecated
400
401 ignoreWindowResize--;
402
403 getAndRenderEvents();
404 }
405
406
407
408 /* Resizing
409 -----------------------------------------------------------------------------*/
410
411
412 function updateSize() {
413 if (elementVisible()) {
414 unselect();
415 clearEvents();
416 calcSize();
417 setSize();
418 renderEvents();
419 }
420 }
421
422
423 function calcSize() { // assumes elementVisible
424 if (options.contentHeight) {
425 suggestedViewHeight = options.contentHeight;
426 }
427 else if (options.height) {
428 suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
429 }
430 else {
431 suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
432 }
433 }
434
435
436 function setSize() { // assumes elementVisible
437
438 if (suggestedViewHeight === undefined) {
439 calcSize(); // for first time
440 // NOTE: we don't want to recalculate on every renderView because
441 // it could result in oscillating heights due to scrollbars.
442 }
443
444 ignoreWindowResize++;
445 currentView.setHeight(suggestedViewHeight);
446 currentView.setWidth(content.width());
447 ignoreWindowResize--;
448
449 elementOuterWidth = element.outerWidth();
450 }
451
452
453 function windowResize() {
454 if (!ignoreWindowResize) {
455 if (currentView.start) { // view has already been rendered
456 var uid = ++resizeUID;
457 setTimeout(function() { // add a delay
458 if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
459 if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
460 ignoreWindowResize++; // in case the windowResize callback changes the height
461 updateSize();
462 currentView.trigger('windowResize', _element);
463 ignoreWindowResize--;
464 }
465 }
466 }, 200);
467 }else{
468 // calendar must have been initialized in a 0x0 iframe that has just been resized
469 lateRender();
470 }
471 }
472 }
473
474
475
476 /* Event Fetching/Rendering
477 -----------------------------------------------------------------------------*/
478 // TODO: going forward, most of this stuff should be directly handled by the view
479
480 function refetchEvents() { // can be called as an API method
481 clearEvents();
482 fetchAndRenderEvents();
483 }
484
485
486 function rerenderEvents(modifiedEventID) { // can be called as an API method
487 clearEvents();
488 renderEvents(modifiedEventID);
489 }
490
491
492 function renderEvents(modifiedEventID) { // TODO: remove modifiedEventID hack
493 if (elementVisible()) {
494 currentView.setEventData(events); // for View.js, TODO: unify with renderEvents
495 currentView.renderEvents(events, modifiedEventID); // actually render the DOM elements
496 currentView.trigger('eventAfterAllRender');
497 }
498 }
499
500
501 function clearEvents() {
502 currentView.triggerEventDestroy(); // trigger 'eventDestroy' for each event
503 currentView.clearEvents(); // actually remove the DOM elements
504 currentView.clearEventData(); // for View.js, TODO: unify with clearEvents
505 }
506
507
508 function getAndRenderEvents() {
509 if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) {
510 fetchAndRenderEvents();
511 }
512 else {
513 renderEvents();
514 }
515 }
516
517
518 function fetchAndRenderEvents() {
519 fetchEvents(currentView.visStart, currentView.visEnd);
520 // ... will call reportEvents
521 // ... which will call renderEvents
522 }
523
524
525 // called when event data arrives
526 function reportEvents(_events) {
527 events = _events;
528 renderEvents();
529 }
530
531
532 // called when a single event's data has been changed
533 function reportEventChange(eventID) {
534 rerenderEvents(eventID);
535 }
536
537 /* Header Updating
538 -----------------------------------------------------------------------------*/
539 function updateTitle() {
540 header.updateTitle(currentView.title);
541 }
542
543
544 function updateTodayButton() {
545 var today = new Date();
546 if (today >= currentView.start && today < currentView.end) {
547 header.disableButton('today');
548 }
549 else {
550 header.enableButton('today');
551 }
552 }
553
554
555
556 /* Selection
557 -----------------------------------------------------------------------------*/
558
559
560 function select(start, end, allDay) {
561 currentView.select(start, end, allDay===undefined ? true : allDay);
562 }
563
564
565 function unselect() { // safe to be called before renderView
566 if (currentView) {
567 currentView.unselect();
568 }
569 }
570
571
572
573 /* Date
574 -----------------------------------------------------------------------------*/
575
576
577 function prev() {
578 renderView(-1);
579 }
580
581
582 function next() {
583 renderView(1);
584 }
585
586
587 function prevYear() {
588 addYears(date, -1);
589 renderView();
590 }
591
592
593 function nextYear() {
594 addYears(date, 1);
595 renderView();
596 }
597
598
599 function today() {
600 date = new Date();
601 renderView();
602 }
603
604
605 function gotoDate(year, month, dateOfMonth) {
606 if (year instanceof Date) {
607 date = cloneDate(year); // provided 1 argument, a Date
608 }else{
609 setYMD(date, year, month, dateOfMonth);
610 }
611 renderView();
612 }
613
614
615 function incrementDate(years, months, days) {
616 if (years !== undefined) {
617 addYears(date, years);
618 }
619 if (months !== undefined) {
620 addMonths(date, months);
621 }
622 if (days !== undefined) {
623 addDays(date, days);
624 }
625 renderView();
626 }
627
628
629 function getDate() {
630 return cloneDate(date);
631 }
632
633
634
635 /* Height "Freezing"
636 -----------------------------------------------------------------------------*/
637
638
639 function freezeContentHeight() {
640 content.css({
641 width: '100%',
642 height: content.height(),
643 overflow: 'hidden'
644 });
645 }
646
647
648 function unfreezeContentHeight() {
649 content.css({
650 width: '',
651 height: '',
652 overflow: ''
653 });
654 }
655
656
657
658 /* Misc
659 -----------------------------------------------------------------------------*/
660
661
662 function getView() {
663 return currentView;
664 }
665
666
667 function option(name, value) {
668 if (value === undefined) {
669 return options[name];
670 }
671 if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
672 options[name] = value;
673 updateSize();
674 }
675 }
676
677
678 function trigger(name, thisObj) {
679 if (options[name]) {
680 return options[name].apply(
681 thisObj || _element,
682 Array.prototype.slice.call(arguments, 2)
683 );
684 }
685 }
686
687
688
689 /* External Dragging
690 ------------------------------------------------------------------------*/
691
692 if (options.droppable) {
693 $(document)
694 .bind('dragstart', function(ev, ui) {
695 var _e = ev.target;
696 var e = $(_e);
697 if (!e.parents('.fc').length) { // not already inside a calendar
698 var accept = options.dropAccept;
699 if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
700 _dragElement = _e;
701 currentView.dragStart(_dragElement, ev, ui);
702 }
703 }
704 })
705 .bind('dragstop', function(ev, ui) {
706 if (_dragElement) {
707 currentView.dragStop(_dragElement, ev, ui);
708 _dragElement = null;
709 }
710 });
711 }
712
713
714}
715
716;;
717
718function Header(calendar, options) {
719 var t = this;
720
721
722 // exports
723 t.render = render;
724 t.destroy = destroy;
725 t.updateTitle = updateTitle;
726 t.activateButton = activateButton;
727 t.deactivateButton = deactivateButton;
728 t.disableButton = disableButton;
729 t.enableButton = enableButton;
730
731
732 // locals
733 var element = $([]);
734 var tm;
735
736
737
738 function render() {
739 tm = options.theme ? 'ui' : 'fc';
740 var sections = options.header;
741 if (sections) {
742 element = $("<table class='fc-header' style='width:100%'/>")
743 .append(
744 $("<tr/>")
745 .append(renderSection('left'))
746 .append(renderSection('center'))
747 .append(renderSection('right'))
748 );
749 return element;
750 }
751 }
752
753
754 function destroy() {
755 element.remove();
756 }
757
758
759 function renderSection(position) {
760 var e = $("<td class='fc-header-" + position + "'/>");
761 var buttonStr = options.header[position];
762 if (buttonStr) {
763 $.each(buttonStr.split(' '), function(i) {
764 if (i > 0) {
765 e.append("<span class='fc-header-space'/>");
766 }
767 var prevButton;
768 $.each(this.split(','), function(j, buttonName) {
769 if (buttonName == 'title') {
770 e.append("<span class='fc-header-title'><h2>&nbsp;</h2></span>");
771 if (prevButton) {
772 prevButton.addClass(tm + '-corner-right');
773 }
774 prevButton = null;
775 }else{
776 var buttonClick;
777 if (calendar[buttonName]) {
778 buttonClick = calendar[buttonName]; // calendar method
779 }
780 else if (fcViews[buttonName]) {
781 buttonClick = function() {
782 button.removeClass(tm + '-state-hover'); // forget why
783 calendar.changeView(buttonName);
784 };
785 }
786 if (buttonClick) {
787 var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here?
788 var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here?
789 var button = $(
790 "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" +
791 (icon ?
792 "<span class='fc-icon-wrap'>" +
793 "<span class='ui-icon ui-icon-" + icon + "'/>" +
794 "</span>" :
795 text
796 ) +
797 "</span>"
798 )
799 .click(function() {
800 if (!button.hasClass(tm + '-state-disabled')) {
801 buttonClick();
802 }
803 })
804 .mousedown(function() {
805 button
806 .not('.' + tm + '-state-active')
807 .not('.' + tm + '-state-disabled')
808 .addClass(tm + '-state-down');
809 })
810 .mouseup(function() {
811 button.removeClass(tm + '-state-down');
812 })
813 .hover(
814 function() {
815 button
816 .not('.' + tm + '-state-active')
817 .not('.' + tm + '-state-disabled')
818 .addClass(tm + '-state-hover');
819 },
820 function() {
821 button
822 .removeClass(tm + '-state-hover')
823 .removeClass(tm + '-state-down');
824 }
825 )
826 .appendTo(e);
827 disableTextSelection(button);
828 if (!prevButton) {
829 button.addClass(tm + '-corner-left');
830 }
831 prevButton = button;
832 }
833 }
834 });
835 if (prevButton) {
836 prevButton.addClass(tm + '-corner-right');
837 }
838 });
839 }
840 return e;
841 }
842
843
844 function updateTitle(html) {
845 element.find('h2')
846 .html(html);
847 }
848
849
850 function activateButton(buttonName) {
851 element.find('span.fc-button-' + buttonName)
852 .addClass(tm + '-state-active');
853 }
854
855
856 function deactivateButton(buttonName) {
857 element.find('span.fc-button-' + buttonName)
858 .removeClass(tm + '-state-active');
859 }
860
861
862 function disableButton(buttonName) {
863 element.find('span.fc-button-' + buttonName)
864 .addClass(tm + '-state-disabled');
865 }
866
867
868 function enableButton(buttonName) {
869 element.find('span.fc-button-' + buttonName)
870 .removeClass(tm + '-state-disabled');
871 }
872
873
874}
875
876;;
877
878fc.sourceNormalizers = [];
879fc.sourceFetchers = [];
880
881var ajaxDefaults = {
882 dataType: 'json',
883 cache: false
884};
885
886var eventGUID = 1;
887
888
889function EventManager(options, _sources) {
890 var t = this;
891
892
893 // exports
894 t.isFetchNeeded = isFetchNeeded;
895 t.fetchEvents = fetchEvents;
896 t.addEventSource = addEventSource;
897 t.removeEventSource = removeEventSource;
898 t.updateEvent = updateEvent;
899 t.renderEvent = renderEvent;
900 t.removeEvents = removeEvents;
901 t.clientEvents = clientEvents;
902 t.normalizeEvent = normalizeEvent;
903
904
905 // imports
906 var trigger = t.trigger;
907 var getView = t.getView;
908 var reportEvents = t.reportEvents;
909
910
911 // locals
912 var stickySource = { events: [] };
913 var sources = [ stickySource ];
914 var rangeStart, rangeEnd;
915 var currentFetchID = 0;
916 var pendingSourceCnt = 0;
917 var loadingLevel = 0;
918 var cache = [];
919
920
921 for (var i=0; i<_sources.length; i++) {
922 _addEventSource(_sources[i]);
923 }
924
925
926
927 /* Fetching
928 -----------------------------------------------------------------------------*/
929
930
931 function isFetchNeeded(start, end) {
932 return !rangeStart || start < rangeStart || end > rangeEnd;
933 }
934
935
936 function fetchEvents(start, end) {
937 rangeStart = start;
938 rangeEnd = end;
939 cache = [];
940 var fetchID = ++currentFetchID;
941 var len = sources.length;
942 pendingSourceCnt = len;
943 for (var i=0; i<len; i++) {
944 fetchEventSource(sources[i], fetchID);
945 }
946 }
947
948
949 function fetchEventSource(source, fetchID) {
950 _fetchEventSource(source, function(events) {
951 if (fetchID == currentFetchID) {
952 if (events) {
953
954 if (options.eventDataTransform) {
955 events = $.map(events, options.eventDataTransform);
956 }
957 if (source.eventDataTransform) {
958 events = $.map(events, source.eventDataTransform);
959 }
960 // TODO: this technique is not ideal for static array event sources.
961 // For arrays, we'll want to process all events right in the beginning, then never again.
962
963 for (var i=0; i<events.length; i++) {
964 events[i].source = source;
965 normalizeEvent(events[i]);
966 }
967 cache = cache.concat(events);
968 }
969 pendingSourceCnt--;
970 if (!pendingSourceCnt) {
971 reportEvents(cache);
972 }
973 }
974 });
975 }
976
977
978 function _fetchEventSource(source, callback) {
979 var i;
980 var fetchers = fc.sourceFetchers;
981 var res;
982 for (i=0; i<fetchers.length; i++) {
983 res = fetchers[i](source, rangeStart, rangeEnd, callback);
984 if (res === true) {
985 // the fetcher is in charge. made its own async request
986 return;
987 }
988 else if (typeof res == 'object') {
989 // the fetcher returned a new source. process it
990 _fetchEventSource(res, callback);
991 return;
992 }
993 }
994 var events = source.events;
995 if (events) {
996 if ($.isFunction(events)) {
997 pushLoading();
998 events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) {
999 callback(events);
1000 popLoading();
1001 });
1002 }
1003 else if ($.isArray(events)) {
1004 callback(events);
1005 }
1006 else {
1007 callback();
1008 }
1009 }else{
1010 var url = source.url;
1011 if (url) {
1012 var success = source.success;
1013 var error = source.error;
1014 var complete = source.complete;
1015
1016 // retrieve any outbound GET/POST $.ajax data from the options
1017 var customData;
1018 if ($.isFunction(source.data)) {
1019 // supplied as a function that returns a key/value object
1020 customData = source.data();
1021 }
1022 else {
1023 // supplied as a straight key/value object
1024 customData = source.data;
1025 }
1026
1027 // use a copy of the custom data so we can modify the parameters
1028 // and not affect the passed-in object.
1029 var data = $.extend({}, customData || {});
1030
1031 var startParam = firstDefined(source.startParam, options.startParam);
1032 var endParam = firstDefined(source.endParam, options.endParam);
1033 if (startParam) {
1034 data[startParam] = Math.round(+rangeStart / 1000);
1035 }
1036 if (endParam) {
1037 data[endParam] = Math.round(+rangeEnd / 1000);
1038 }
1039
1040 pushLoading();
1041 $.ajax($.extend({}, ajaxDefaults, source, {
1042 data: data,
1043 success: function(events) {
1044 events = events || [];
1045 var res = applyAll(success, this, arguments);
1046 if ($.isArray(res)) {
1047 events = res;
1048 }
1049 callback(events);
1050 },
1051 error: function() {
1052 applyAll(error, this, arguments);
1053 callback();
1054 },
1055 complete: function() {
1056 applyAll(complete, this, arguments);
1057 popLoading();
1058 }
1059 }));
1060 }else{
1061 callback();
1062 }
1063 }
1064 }
1065
1066
1067
1068 /* Sources
1069 -----------------------------------------------------------------------------*/
1070
1071
1072 function addEventSource(source) {
1073 source = _addEventSource(source);
1074 if (source) {
1075 pendingSourceCnt++;
1076 fetchEventSource(source, currentFetchID); // will eventually call reportEvents
1077 }
1078 }
1079
1080
1081 function _addEventSource(source) {
1082 if ($.isFunction(source) || $.isArray(source)) {
1083 source = { events: source };
1084 }
1085 else if (typeof source == 'string') {
1086 source = { url: source };
1087 }
1088 if (typeof source == 'object') {
1089 normalizeSource(source);
1090 sources.push(source);
1091 return source;
1092 }
1093 }
1094
1095
1096 function removeEventSource(source) {
1097 sources = $.grep(sources, function(src) {
1098 return !isSourcesEqual(src, source);
1099 });
1100 // remove all client events from that source
1101 cache = $.grep(cache, function(e) {
1102 return !isSourcesEqual(e.source, source);
1103 });
1104 reportEvents(cache);
1105 }
1106
1107
1108
1109 /* Manipulation
1110 -----------------------------------------------------------------------------*/
1111
1112
1113 function updateEvent(event) { // update an existing event
1114 var i, len = cache.length, e,
1115 defaultEventEnd = getView().defaultEventEnd, // getView???
1116 startDelta = event.start - event._start,
1117 endDelta = event.end ?
1118 (event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end
1119 : 0; // was null and event was just resized
1120 for (i=0; i<len; i++) {
1121 e = cache[i];
1122 if (e._id == event._id && e != event) {
1123 e.start = new Date(+e.start + startDelta);
1124 if (event.end) {
1125 if (e.end) {
1126 e.end = new Date(+e.end + endDelta);
1127 }else{
1128 e.end = new Date(+defaultEventEnd(e) + endDelta);
1129 }
1130 }else{
1131 e.end = null;
1132 }
1133 e.title = event.title;
1134 e.url = event.url;
1135 e.allDay = event.allDay;
1136 e.className = event.className;
1137 e.editable = event.editable;
1138 e.color = event.color;
1139 e.backgroundColor = event.backgroundColor;
1140 e.borderColor = event.borderColor;
1141 e.textColor = event.textColor;
1142 normalizeEvent(e);
1143 }
1144 }
1145 normalizeEvent(event);
1146 reportEvents(cache);
1147 }
1148
1149
1150 function renderEvent(event, stick) {
1151 normalizeEvent(event);
1152 if (!event.source) {
1153 if (stick) {
1154 stickySource.events.push(event);
1155 event.source = stickySource;
1156 }
1157 cache.push(event);
1158 }
1159 reportEvents(cache);
1160 }
1161
1162
1163 function removeEvents(filter) {
1164 if (!filter) { // remove all
1165 cache = [];
1166 // clear all array sources
1167 for (var i=0; i<sources.length; i++) {
1168 if ($.isArray(sources[i].events)) {
1169 sources[i].events = [];
1170 }
1171 }
1172 }else{
1173 if (!$.isFunction(filter)) { // an event ID
1174 var id = filter + '';
1175 filter = function(e) {
1176 return e._id == id;
1177 };
1178 }
1179 cache = $.grep(cache, filter, true);
1180 // remove events from array sources
1181 for (var i=0; i<sources.length; i++) {
1182 if ($.isArray(sources[i].events)) {
1183 sources[i].events = $.grep(sources[i].events, filter, true);
1184 }
1185 }
1186 }
1187 reportEvents(cache);
1188 }
1189
1190
1191 function clientEvents(filter) {
1192 if ($.isFunction(filter)) {
1193 return $.grep(cache, filter);
1194 }
1195 else if (filter) { // an event ID
1196 filter += '';
1197 return $.grep(cache, function(e) {
1198 return e._id == filter;
1199 });
1200 }
1201 return cache; // else, return all
1202 }
1203
1204
1205
1206 /* Loading State
1207 -----------------------------------------------------------------------------*/
1208
1209
1210 function pushLoading() {
1211 if (!loadingLevel++) {
1212 trigger('loading', null, true, getView());
1213 }
1214 }
1215
1216
1217 function popLoading() {
1218 if (!--loadingLevel) {
1219 trigger('loading', null, false, getView());
1220 }
1221 }
1222
1223
1224
1225 /* Event Normalization
1226 -----------------------------------------------------------------------------*/
1227
1228
1229 function normalizeEvent(event) {
1230 var source = event.source || {};
1231 var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone);
1232 event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + '');
1233 if (event.date) {
1234 if (!event.start) {
1235 event.start = event.date;
1236 }
1237 delete event.date;
1238 }
1239 event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone));
1240 event.end = parseDate(event.end, ignoreTimezone);
1241 if (event.end && event.end <= event.start) {
1242 event.end = null;
1243 }
1244 event._end = event.end ? cloneDate(event.end) : null;
1245 if (event.allDay === undefined) {
1246 event.allDay = firstDefined(source.allDayDefault, options.allDayDefault);
1247 }
1248 if (event.className) {
1249 if (typeof event.className == 'string') {
1250 event.className = event.className.split(/\s+/);
1251 }
1252 }else{
1253 event.className = [];
1254 }
1255 // TODO: if there is no start date, return false to indicate an invalid event
1256 }
1257
1258
1259
1260 /* Utils
1261 ------------------------------------------------------------------------------*/
1262
1263
1264 function normalizeSource(source) {
1265 if (source.className) {
1266 // TODO: repeat code, same code for event classNames
1267 if (typeof source.className == 'string') {
1268 source.className = source.className.split(/\s+/);
1269 }
1270 }else{
1271 source.className = [];
1272 }
1273 var normalizers = fc.sourceNormalizers;
1274 for (var i=0; i<normalizers.length; i++) {
1275 normalizers[i](source);
1276 }
1277 }
1278
1279
1280 function isSourcesEqual(source1, source2) {
1281 return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
1282 }
1283
1284
1285 function getSourcePrimitive(source) {
1286 return ((typeof source == 'object') ? (source.events || source.url) : '') || source;
1287 }
1288
1289
1290}
1291
1292;;
1293
1294
1295fc.addDays = addDays;
1296fc.cloneDate = cloneDate;
1297fc.parseDate = parseDate;
1298fc.parseISO8601 = parseISO8601;
1299fc.parseTime = parseTime;
1300fc.formatDate = formatDate;
1301fc.formatDates = formatDates;
1302
1303
1304
1305/* Date Math
1306-----------------------------------------------------------------------------*/
1307
1308var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
1309 DAY_MS = 86400000,
1310 HOUR_MS = 3600000,
1311 MINUTE_MS = 60000;
1312
1313
1314function addYears(d, n, keepTime) {
1315 d.setFullYear(d.getFullYear() + n);
1316 if (!keepTime) {
1317 clearTime(d);
1318 }
1319 return d;
1320}
1321
1322
1323function addMonths(d, n, keepTime) { // prevents day overflow/underflow
1324 if (+d) { // prevent infinite looping on invalid dates
1325 var m = d.getMonth() + n,
1326 check = cloneDate(d);
1327 check.setDate(1);
1328 check.setMonth(m);
1329 d.setMonth(m);
1330 if (!keepTime) {
1331 clearTime(d);
1332 }
1333 while (d.getMonth() != check.getMonth()) {
1334 d.setDate(d.getDate() + (d < check ? 1 : -1));
1335 }
1336 }
1337 return d;
1338}
1339
1340
1341function addDays(d, n, keepTime) { // deals with daylight savings
1342 if (+d) {
1343 var dd = d.getDate() + n,
1344 check = cloneDate(d);
1345 check.setHours(9); // set to middle of day
1346 check.setDate(dd);
1347 d.setDate(dd);
1348 if (!keepTime) {
1349 clearTime(d);
1350 }
1351 fixDate(d, check);
1352 }
1353 return d;
1354}
1355
1356
1357function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes
1358 if (+d) { // prevent infinite looping on invalid dates
1359 while (d.getDate() != check.getDate()) {
1360 d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS);
1361 }
1362 }
1363}
1364
1365
1366function addMinutes(d, n) {
1367 d.setMinutes(d.getMinutes() + n);
1368 return d;
1369}
1370
1371
1372function clearTime(d) {
1373 d.setHours(0);
1374 d.setMinutes(0);
1375 d.setSeconds(0);
1376 d.setMilliseconds(0);
1377 return d;
1378}
1379
1380
1381function cloneDate(d, dontKeepTime) {
1382 if (dontKeepTime) {
1383 return clearTime(new Date(+d));
1384 }
1385 return new Date(+d);
1386}
1387
1388
1389function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1
1390 var i=0, d;
1391 do {
1392 d = new Date(1970, i++, 1);
1393 } while (d.getHours()); // != 0
1394 return d;
1395}
1396
1397
1398function dayDiff(d1, d2) { // d1 - d2
1399 return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS);
1400}
1401
1402
1403function setYMD(date, y, m, d) {
1404 if (y !== undefined && y != date.getFullYear()) {
1405 date.setDate(1);
1406 date.setMonth(0);
1407 date.setFullYear(y);
1408 }
1409 if (m !== undefined && m != date.getMonth()) {
1410 date.setDate(1);
1411 date.setMonth(m);
1412 }
1413 if (d !== undefined) {
1414 date.setDate(d);
1415 }
1416}
1417
1418
1419
1420/* Date Parsing
1421-----------------------------------------------------------------------------*/
1422
1423
1424function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true
1425 if (typeof s == 'object') { // already a Date object
1426 return s;
1427 }
1428 if (typeof s == 'number') { // a UNIX timestamp
1429 return new Date(s * 1000);
1430 }
1431 if (typeof s == 'string') {
1432 if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp
1433 return new Date(parseFloat(s) * 1000);
1434 }
1435 if (ignoreTimezone === undefined) {
1436 ignoreTimezone = true;
1437 }
1438 return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null);
1439 }
1440 // TODO: never return invalid dates (like from new Date(<string>)), return null instead
1441 return null;
1442}
1443
1444
1445function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false
1446 // derived from http://delete.me.uk/2005/03/iso8601.html
1447 // TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html
1448 var m = s.match(/^([0-9]{4})(-([0-9]{2})(-([0-9]{2})([T ]([0-9]{2}):([0-9]{2})(:([0-9]{2})(\.([0-9]+))?)?(Z|(([-+])([0-9]{2})(:?([0-9]{2}))?))?)?)?)?$/);
1449 if (!m) {
1450 return null;
1451 }
1452 var date = new Date(m[1], 0, 1);
1453 if (ignoreTimezone || !m[13]) {
1454 var check = new Date(m[1], 0, 1, 9, 0);
1455 if (m[3]) {
1456 date.setMonth(m[3] - 1);
1457 check.setMonth(m[3] - 1);
1458 }
1459 if (m[5]) {
1460 date.setDate(m[5]);
1461 check.setDate(m[5]);
1462 }
1463 fixDate(date, check);
1464 if (m[7]) {
1465 date.setHours(m[7]);
1466 }
1467 if (m[8]) {
1468 date.setMinutes(m[8]);
1469 }
1470 if (m[10]) {
1471 date.setSeconds(m[10]);
1472 }
1473 if (m[12]) {
1474 date.setMilliseconds(Number("0." + m[12]) * 1000);
1475 }
1476 fixDate(date, check);
1477 }else{
1478 date.setUTCFullYear(
1479 m[1],
1480 m[3] ? m[3] - 1 : 0,
1481 m[5] || 1
1482 );
1483 date.setUTCHours(
1484 m[7] || 0,
1485 m[8] || 0,
1486 m[10] || 0,
1487 m[12] ? Number("0." + m[12]) * 1000 : 0
1488 );
1489 if (m[14]) {
1490 var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0);
1491 offset *= m[15] == '-' ? 1 : -1;
1492 date = new Date(+date + (offset * 60 * 1000));
1493 }
1494 }
1495 return date;
1496}
1497
1498
1499function parseTime(s) { // returns minutes since start of day
1500 if (typeof s == 'number') { // an hour
1501 return s * 60;
1502 }
1503 if (typeof s == 'object') { // a Date object
1504 return s.getHours() * 60 + s.getMinutes();
1505 }
1506 var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/);
1507 if (m) {
1508 var h = parseInt(m[1], 10);
1509 if (m[3]) {
1510 h %= 12;
1511 if (m[3].toLowerCase().charAt(0) == 'p') {
1512 h += 12;
1513 }
1514 }
1515 return h * 60 + (m[2] ? parseInt(m[2], 10) : 0);
1516 }
1517}
1518
1519
1520
1521/* Date Formatting
1522-----------------------------------------------------------------------------*/
1523// TODO: use same function formatDate(date, [date2], format, [options])
1524
1525
1526function formatDate(date, format, options) {
1527 return formatDates(date, null, format, options);
1528}
1529
1530
1531function formatDates(date1, date2, format, options) {
1532 options = options || defaults;
1533 var date = date1,
1534 otherDate = date2,
1535 i, len = format.length, c,
1536 i2, formatter,
1537 res = '';
1538 for (i=0; i<len; i++) {
1539 c = format.charAt(i);
1540 if (c == "'") {
1541 for (i2=i+1; i2<len; i2++) {
1542 if (format.charAt(i2) == "'") {
1543 if (date) {
1544 if (i2 == i+1) {
1545 res += "'";
1546 }else{
1547 res += format.substring(i+1, i2);
1548 }
1549 i = i2;
1550 }
1551 break;
1552 }
1553 }
1554 }
1555 else if (c == '(') {
1556 for (i2=i+1; i2<len; i2++) {
1557 if (format.charAt(i2) == ')') {
1558 var subres = formatDate(date, format.substring(i+1, i2), options);
1559 if (parseInt(subres.replace(/\D/, ''), 10)) {
1560 res += subres;
1561 }
1562 i = i2;
1563 break;
1564 }
1565 }
1566 }
1567 else if (c == '[') {
1568 for (i2=i+1; i2<len; i2++) {
1569 if (format.charAt(i2) == ']') {
1570 var subformat = format.substring(i+1, i2);
1571 var subres = formatDate(date, subformat, options);
1572 if (subres != formatDate(otherDate, subformat, options)) {
1573 res += subres;
1574 }
1575 i = i2;
1576 break;
1577 }
1578 }
1579 }
1580 else if (c == '{') {
1581 date = date2;
1582 otherDate = date1;
1583 }
1584 else if (c == '}') {
1585 date = date1;
1586 otherDate = date2;
1587 }
1588 else {
1589 for (i2=len; i2>i; i2--) {
1590 if (formatter = dateFormatters[format.substring(i, i2)]) {
1591 if (date) {
1592 res += formatter(date, options);
1593 }
1594 i = i2 - 1;
1595 break;
1596 }
1597 }
1598 if (i2 == i) {
1599 if (date) {
1600 res += c;
1601 }
1602 }
1603 }
1604 }
1605 return res;
1606};
1607
1608
1609var dateFormatters = {
1610 s : function(d) { return d.getSeconds() },
1611 ss : function(d) { return zeroPad(d.getSeconds()) },
1612 m : function(d) { return d.getMinutes() },
1613 mm : function(d) { return zeroPad(d.getMinutes()) },
1614 h : function(d) { return d.getHours() % 12 || 12 },
1615 hh : function(d) { return zeroPad(d.getHours() % 12 || 12) },
1616 H : function(d) { return d.getHours() },
1617 HH : function(d) { return zeroPad(d.getHours()) },
1618 d : function(d) { return d.getDate() },
1619 dd : function(d) { return zeroPad(d.getDate()) },
1620 ddd : function(d,o) { return o.dayNamesShort[d.getDay()] },
1621 dddd: function(d,o) { return o.dayNames[d.getDay()] },
1622 M : function(d) { return d.getMonth() + 1 },
1623 MM : function(d) { return zeroPad(d.getMonth() + 1) },
1624 MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] },
1625 MMMM: function(d,o) { return o.monthNames[d.getMonth()] },
1626 yy : function(d) { return (d.getFullYear()+'').substring(2) },
1627 yyyy: function(d) { return d.getFullYear() },
1628 t : function(d) { return d.getHours() < 12 ? 'a' : 'p' },
1629 tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' },
1630 T : function(d) { return d.getHours() < 12 ? 'A' : 'P' },
1631 TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' },
1632 u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") },
1633 S : function(d) {
1634 var date = d.getDate();
1635 if (date > 10 && date < 20) {
1636 return 'th';
1637 }
1638 return ['st', 'nd', 'rd'][date%10-1] || 'th';
1639 },
1640 w : function(d, o) { // local
1641 return o.weekNumberCalculation(d);
1642 },
1643 W : function(d) { // ISO
1644 return iso8601Week(d);
1645 }
1646};
1647fc.dateFormatters = dateFormatters;
1648
1649
1650/* thanks jQuery UI (https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js)
1651 *
1652 * Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
1653 * `date` - the date to get the week for
1654 * `number` - the number of the week within the year that contains this date
1655 */
1656function iso8601Week(date) {
1657 var time;
1658 var checkDate = new Date(date.getTime());
1659
1660 // Find Thursday of this week starting on Monday
1661 checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
1662
1663 time = checkDate.getTime();
1664 checkDate.setMonth(0); // Compare with Jan 1
1665 checkDate.setDate(1);
1666 return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
1667}
1668
1669
1670;;
1671
1672fc.applyAll = applyAll;
1673
1674
1675/* Event Date Math
1676-----------------------------------------------------------------------------*/
1677
1678
1679function exclEndDay(event) {
1680 if (event.end) {
1681 return _exclEndDay(event.end, event.allDay);
1682 }else{
1683 return addDays(cloneDate(event.start), 1);
1684 }
1685}
1686
1687
1688function _exclEndDay(end, allDay) {
1689 end = cloneDate(end);
1690 return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end);
1691 // why don't we check for seconds/ms too?
1692}
1693
1694
1695
1696/* Event Element Binding
1697-----------------------------------------------------------------------------*/
1698
1699
1700function lazySegBind(container, segs, bindHandlers) {
1701 container.unbind('mouseover').mouseover(function(ev) {
1702 var parent=ev.target, e,
1703 i, seg;
1704 while (parent != this) {
1705 e = parent;
1706 parent = parent.parentNode;
1707 }
1708 if ((i = e._fci) !== undefined) {
1709 e._fci = undefined;
1710 seg = segs[i];
1711 bindHandlers(seg.event, seg.element, seg);
1712 $(ev.target).trigger(ev);
1713 }
1714 ev.stopPropagation();
1715 });
1716}
1717
1718
1719
1720/* Element Dimensions
1721-----------------------------------------------------------------------------*/
1722
1723
1724function setOuterWidth(element, width, includeMargins) {
1725 for (var i=0, e; i<element.length; i++) {
1726 e = $(element[i]);
1727 e.width(Math.max(0, width - hsides(e, includeMargins)));
1728 }
1729}
1730
1731
1732function setOuterHeight(element, height, includeMargins) {
1733 for (var i=0, e; i<element.length; i++) {
1734 e = $(element[i]);
1735 e.height(Math.max(0, height - vsides(e, includeMargins)));
1736 }
1737}
1738
1739
1740function hsides(element, includeMargins) {
1741 return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0);
1742}
1743
1744
1745function hpadding(element) {
1746 return (parseFloat($.css(element[0], 'paddingLeft', true)) || 0) +
1747 (parseFloat($.css(element[0], 'paddingRight', true)) || 0);
1748}
1749
1750
1751function hmargins(element) {
1752 return (parseFloat($.css(element[0], 'marginLeft', true)) || 0) +
1753 (parseFloat($.css(element[0], 'marginRight', true)) || 0);
1754}
1755
1756
1757function hborders(element) {
1758 return (parseFloat($.css(element[0], 'borderLeftWidth', true)) || 0) +
1759 (parseFloat($.css(element[0], 'borderRightWidth', true)) || 0);
1760}
1761
1762
1763function vsides(element, includeMargins) {
1764 return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0);
1765}
1766
1767
1768function vpadding(element) {
1769 return (parseFloat($.css(element[0], 'paddingTop', true)) || 0) +
1770 (parseFloat($.css(element[0], 'paddingBottom', true)) || 0);
1771}
1772
1773
1774function vmargins(element) {
1775 return (parseFloat($.css(element[0], 'marginTop', true)) || 0) +
1776 (parseFloat($.css(element[0], 'marginBottom', true)) || 0);
1777}
1778
1779
1780function vborders(element) {
1781 return (parseFloat($.css(element[0], 'borderTopWidth', true)) || 0) +
1782 (parseFloat($.css(element[0], 'borderBottomWidth', true)) || 0);
1783}
1784
1785
1786
1787/* Misc Utils
1788-----------------------------------------------------------------------------*/
1789
1790
1791//TODO: arraySlice
1792//TODO: isFunction, grep ?
1793
1794
1795function noop() { }
1796
1797
1798function dateCompare(a, b) {
1799 return a - b;
1800}
1801
1802
1803function arrayMax(a) {
1804 return Math.max.apply(Math, a);
1805}
1806
1807
1808function zeroPad(n) {
1809 return (n < 10 ? '0' : '') + n;
1810}
1811
1812
1813function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
1814 if (obj[name] !== undefined) {
1815 return obj[name];
1816 }
1817 var parts = name.split(/(?=[A-Z])/),
1818 i=parts.length-1, res;
1819 for (; i>=0; i--) {
1820 res = obj[parts[i].toLowerCase()];
1821 if (res !== undefined) {
1822 return res;
1823 }
1824 }
1825 return obj[''];
1826}
1827
1828
1829function htmlEscape(s) {
1830 return s.replace(/&/g, '&amp;')
1831 .replace(/</g, '&lt;')
1832 .replace(/>/g, '&gt;')
1833 .replace(/'/g, '&#039;')
1834 .replace(/"/g, '&quot;')
1835 .replace(/\n/g, '<br />');
1836}
1837
1838
1839function disableTextSelection(element) {
1840 element
1841 .attr('unselectable', 'on')
1842 .css('MozUserSelect', 'none')
1843 .bind('selectstart.ui', function() { return false; });
1844}
1845
1846
1847/*
1848function enableTextSelection(element) {
1849 element
1850 .attr('unselectable', 'off')
1851 .css('MozUserSelect', '')
1852 .unbind('selectstart.ui');
1853}
1854*/
1855
1856
1857function markFirstLast(e) {
1858 e.children()
1859 .removeClass('fc-first fc-last')
1860 .filter(':first-child')
1861 .addClass('fc-first')
1862 .end()
1863 .filter(':last-child')
1864 .addClass('fc-last');
1865}
1866
1867
1868function setDayID(cell, date) {
1869 cell.each(function(i, _cell) {
1870 _cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]);
1871 // TODO: make a way that doesn't rely on order of classes
1872 });
1873}
1874
1875
1876function getSkinCss(event, opt) {
1877 var source = event.source || {};
1878 var eventColor = event.color;
1879 var sourceColor = source.color;
1880 var optionColor = opt('eventColor');
1881 var backgroundColor =
1882 event.backgroundColor ||
1883 eventColor ||
1884 source.backgroundColor ||
1885 sourceColor ||
1886 opt('eventBackgroundColor') ||
1887 optionColor;
1888 var borderColor =
1889 event.borderColor ||
1890 eventColor ||
1891 source.borderColor ||
1892 sourceColor ||
1893 opt('eventBorderColor') ||
1894 optionColor;
1895 var textColor =
1896 event.textColor ||
1897 source.textColor ||
1898 opt('eventTextColor');
1899 var statements = [];
1900 if (backgroundColor) {
1901 statements.push('background-color:' + backgroundColor);
1902 }
1903 if (borderColor) {
1904 statements.push('border-color:' + borderColor);
1905 }
1906 if (textColor) {
1907 statements.push('color:' + textColor);
1908 }
1909 return statements.join(';');
1910}
1911
1912
1913function applyAll(functions, thisObj, args) {
1914 if ($.isFunction(functions)) {
1915 functions = [ functions ];
1916 }
1917 if (functions) {
1918 var i;
1919 var ret;
1920 for (i=0; i<functions.length; i++) {
1921 ret = functions[i].apply(thisObj, args) || ret;
1922 }
1923 return ret;
1924 }
1925}
1926
1927
1928function firstDefined() {
1929 for (var i=0; i<arguments.length; i++) {
1930 if (arguments[i] !== undefined) {
1931 return arguments[i];
1932 }
1933 }
1934}
1935
1936
1937;;
1938
1939fcViews.month = MonthView;
1940
1941function MonthView(element, calendar) {
1942 var t = this;
1943
1944
1945 // exports
1946 t.render = render;
1947
1948
1949 // imports
1950 BasicView.call(t, element, calendar, 'month');
1951 var opt = t.opt;
1952 var renderBasic = t.renderBasic;
1953 var skipHiddenDays = t.skipHiddenDays;
1954 var getCellsPerWeek = t.getCellsPerWeek;
1955 var formatDate = calendar.formatDate;
1956
1957
1958 function render(date, delta) {
1959
1960 if (delta) {
1961 addMonths(date, delta);
1962 date.setDate(1);
1963 }
1964
1965 var firstDay = opt('firstDay');
1966
1967 var start = cloneDate(date, true);
1968 start.setDate(1);
1969
1970 var end = addMonths(cloneDate(start), 1);
1971
1972 var visStart = cloneDate(start);
1973 addDays(visStart, -((visStart.getDay() - firstDay + 7) % 7));
1974 skipHiddenDays(visStart);
1975
1976 var visEnd = cloneDate(end);
1977 addDays(visEnd, (7 - visEnd.getDay() + firstDay) % 7);
1978 skipHiddenDays(visEnd, -1, true);
1979
1980 var colCnt = getCellsPerWeek();
1981 var rowCnt = Math.round(dayDiff(visEnd, visStart) / 7); // should be no need for Math.round
1982
1983 if (opt('weekMode') == 'fixed') {
1984 addDays(visEnd, (6 - rowCnt) * 7); // add weeks to make up for it
1985 rowCnt = 6;
1986 }
1987
1988 t.title = formatDate(start, opt('titleFormat'));
1989
1990 t.start = start;
1991 t.end = end;
1992 t.visStart = visStart;
1993 t.visEnd = visEnd;
1994
1995 renderBasic(rowCnt, colCnt, true);
1996 }
1997
1998
1999}
2000
2001;;
2002
2003fcViews.basicWeek = BasicWeekView;
2004
2005function BasicWeekView(element, calendar) {
2006 var t = this;
2007
2008
2009 // exports
2010 t.render = render;
2011
2012
2013 // imports
2014 BasicView.call(t, element, calendar, 'basicWeek');
2015 var opt = t.opt;
2016 var renderBasic = t.renderBasic;
2017 var skipHiddenDays = t.skipHiddenDays;
2018 var getCellsPerWeek = t.getCellsPerWeek;
2019 var formatDates = calendar.formatDates;
2020
2021
2022 function render(date, delta) {
2023
2024 if (delta) {
2025 addDays(date, delta * 7);
2026 }
2027
2028 var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
2029 var end = addDays(cloneDate(start), 7);
2030
2031 var visStart = cloneDate(start);
2032 skipHiddenDays(visStart);
2033
2034 var visEnd = cloneDate(end);
2035 skipHiddenDays(visEnd, -1, true);
2036
2037 var colCnt = getCellsPerWeek();
2038
2039 t.start = start;
2040 t.end = end;
2041 t.visStart = visStart;
2042 t.visEnd = visEnd;
2043
2044 t.title = formatDates(
2045 visStart,
2046 addDays(cloneDate(visEnd), -1),
2047 opt('titleFormat')
2048 );
2049
2050 renderBasic(1, colCnt, false);
2051 }
2052
2053
2054}
2055
2056;;
2057
2058fcViews.basicDay = BasicDayView;
2059
2060
2061function BasicDayView(element, calendar) {
2062 var t = this;
2063
2064
2065 // exports
2066 t.render = render;
2067
2068
2069 // imports
2070 BasicView.call(t, element, calendar, 'basicDay');
2071 var opt = t.opt;
2072 var renderBasic = t.renderBasic;
2073 var skipHiddenDays = t.skipHiddenDays;
2074 var formatDate = calendar.formatDate;
2075
2076
2077 function render(date, delta) {
2078
2079 if (delta) {
2080 addDays(date, delta);
2081 }
2082 skipHiddenDays(date, delta < 0 ? -1 : 1);
2083
2084 var start = cloneDate(date, true);
2085 var end = addDays(cloneDate(start), 1);
2086
2087 t.title = formatDate(date, opt('titleFormat'));
2088
2089 t.start = t.visStart = start;
2090 t.end = t.visEnd = end;
2091
2092 renderBasic(1, 1, false);
2093 }
2094
2095
2096}
2097
2098;;
2099
2100setDefaults({
2101 weekMode: 'fixed'
2102});
2103
2104
2105function BasicView(element, calendar, viewName) {
2106 var t = this;
2107
2108
2109 // exports
2110 t.renderBasic = renderBasic;
2111 t.setHeight = setHeight;
2112 t.setWidth = setWidth;
2113 t.renderDayOverlay = renderDayOverlay;
2114 t.defaultSelectionEnd = defaultSelectionEnd;
2115 t.renderSelection = renderSelection;
2116 t.clearSelection = clearSelection;
2117 t.reportDayClick = reportDayClick; // for selection (kinda hacky)
2118 t.dragStart = dragStart;
2119 t.dragStop = dragStop;
2120 t.defaultEventEnd = defaultEventEnd;
2121 t.getHoverListener = function() { return hoverListener };
2122 t.colLeft = colLeft;
2123 t.colRight = colRight;
2124 t.colContentLeft = colContentLeft;
2125 t.colContentRight = colContentRight;
2126 t.getIsCellAllDay = function() { return true };
2127 t.allDayRow = allDayRow;
2128 t.getRowCnt = function() { return rowCnt };
2129 t.getColCnt = function() { return colCnt };
2130 t.getColWidth = function() { return colWidth };
2131 t.getDaySegmentContainer = function() { return daySegmentContainer };
2132
2133
2134 // imports
2135 View.call(t, element, calendar, viewName);
2136 OverlayManager.call(t);
2137 SelectionManager.call(t);
2138 BasicEventRenderer.call(t);
2139 var opt = t.opt;
2140 var trigger = t.trigger;
2141 var renderOverlay = t.renderOverlay;
2142 var clearOverlays = t.clearOverlays;
2143 var daySelectionMousedown = t.daySelectionMousedown;
2144 var cellToDate = t.cellToDate;
2145 var dateToCell = t.dateToCell;
2146 var rangeToSegments = t.rangeToSegments;
2147 var formatDate = calendar.formatDate;
2148
2149
2150 // locals
2151
2152 var table;
2153 var head;
2154 var headCells;
2155 var body;
2156 var bodyRows;
2157 var bodyCells;
2158 var bodyFirstCells;
2159 var firstRowCellInners;
2160 var firstRowCellContentInners;
2161 var daySegmentContainer;
2162
2163 var viewWidth;
2164 var viewHeight;
2165 var colWidth;
2166 var weekNumberWidth;
2167
2168 var rowCnt, colCnt;
2169 var showNumbers;
2170 var coordinateGrid;
2171 var hoverListener;
2172 var colPositions;
2173 var colContentPositions;
2174
2175 var tm;
2176 var colFormat;
2177 var showWeekNumbers;
2178 var weekNumberTitle;
2179 var weekNumberFormat;
2180
2181
2182
2183 /* Rendering
2184 ------------------------------------------------------------*/
2185
2186
2187 disableTextSelection(element.addClass('fc-grid'));
2188
2189
2190 function renderBasic(_rowCnt, _colCnt, _showNumbers) {
2191 rowCnt = _rowCnt;
2192 colCnt = _colCnt;
2193 showNumbers = _showNumbers;
2194 updateOptions();
2195
2196 if (!body) {
2197 buildEventContainer();
2198 }
2199
2200 buildTable();
2201 }
2202
2203
2204 function updateOptions() {
2205 tm = opt('theme') ? 'ui' : 'fc';
2206 colFormat = opt('columnFormat');
2207
2208 // week # options. (TODO: bad, logic also in other views)
2209 showWeekNumbers = opt('weekNumbers');
2210 weekNumberTitle = opt('weekNumberTitle');
2211 if (opt('weekNumberCalculation') != 'iso') {
2212 weekNumberFormat = "w";
2213 }
2214 else {
2215 weekNumberFormat = "W";
2216 }
2217 }
2218
2219
2220 function buildEventContainer() {
2221 daySegmentContainer =
2222 $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
2223 .appendTo(element);
2224 }
2225
2226
2227 function buildTable() {
2228 var html = buildTableHTML();
2229
2230 if (table) {
2231 table.remove();
2232 }
2233 table = $(html).appendTo(element);
2234
2235 head = table.find('thead');
2236 headCells = head.find('.fc-day-header');
2237 body = table.find('tbody');
2238 bodyRows = body.find('tr');
2239 bodyCells = body.find('.fc-day');
2240 bodyFirstCells = bodyRows.find('td:first-child');
2241
2242 firstRowCellInners = bodyRows.eq(0).find('.fc-day > div');
2243 firstRowCellContentInners = bodyRows.eq(0).find('.fc-day-content > div');
2244
2245 markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's
2246 markFirstLast(bodyRows); // marks first+last td's
2247 bodyRows.eq(0).addClass('fc-first');
2248 bodyRows.filter(':last').addClass('fc-last');
2249
2250 bodyCells.each(function(i, _cell) {
2251 var date = cellToDate(
2252 Math.floor(i / colCnt),
2253 i % colCnt
2254 );
2255 trigger('dayRender', t, date, $(_cell));
2256 });
2257
2258 dayBind(bodyCells);
2259 }
2260
2261
2262
2263 /* HTML Building
2264 -----------------------------------------------------------*/
2265
2266
2267 function buildTableHTML() {
2268 var html =
2269 "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" +
2270 buildHeadHTML() +
2271 buildBodyHTML() +
2272 "</table>";
2273
2274 return html;
2275 }
2276
2277
2278 function buildHeadHTML() {
2279 var headerClass = tm + "-widget-header";
2280 var html = '';
2281 var col;
2282 var date;
2283
2284 html += "<thead><tr>";
2285
2286 if (showWeekNumbers) {
2287 html +=
2288 "<th class='fc-week-number " + headerClass + "'>" +
2289 htmlEscape(weekNumberTitle) +
2290 "</th>";
2291 }
2292
2293 for (col=0; col<colCnt; col++) {
2294 date = cellToDate(0, col);
2295 html +=
2296 "<th class='fc-day-header fc-" + dayIDs[date.getDay()] + " " + headerClass + "'>" +
2297 htmlEscape(formatDate(date, colFormat)) +
2298 "</th>";
2299 }
2300
2301 html += "</tr></thead>";
2302
2303 return html;
2304 }
2305
2306
2307 function buildBodyHTML() {
2308 var contentClass = tm + "-widget-content";
2309 var html = '';
2310 var row;
2311 var col;
2312 var date;
2313
2314 html += "<tbody>";
2315
2316 for (row=0; row<rowCnt; row++) {
2317
2318 html += "<tr class='fc-week'>";
2319
2320 if (showWeekNumbers) {
2321 date = cellToDate(row, 0);
2322 html +=
2323 "<td class='fc-week-number " + contentClass + "'>" +
2324 "<div>" +
2325 htmlEscape(formatDate(date, weekNumberFormat)) +
2326 "</div>" +
2327 "</td>";
2328 }
2329
2330 for (col=0; col<colCnt; col++) {
2331 date = cellToDate(row, col);
2332 html += buildCellHTML(date);
2333 }
2334
2335 html += "</tr>";
2336 }
2337
2338 html += "</tbody>";
2339
2340 return html;
2341 }
2342
2343
2344 function buildCellHTML(date) {
2345 var contentClass = tm + "-widget-content";
2346 var month = t.start.getMonth();
2347 var today = clearTime(new Date());
2348 var html = '';
2349 var classNames = [
2350 'fc-day',
2351 'fc-' + dayIDs[date.getDay()],
2352 contentClass
2353 ];
2354
2355 if (date.getMonth() != month) {
2356 classNames.push('fc-other-month');
2357 }
2358 if (+date == +today) {
2359 classNames.push(
2360 'fc-today',
2361 tm + '-state-highlight'
2362 );
2363 }
2364 else if (date < today) {
2365 classNames.push('fc-past');
2366 }
2367 else {
2368 classNames.push('fc-future');
2369 }
2370
2371 html +=
2372 "<td" +
2373 " class='" + classNames.join(' ') + "'" +
2374 " data-date='" + formatDate(date, 'yyyy-MM-dd') + "'" +
2375 ">" +
2376 "<div>";
2377
2378 if (showNumbers) {
2379 html += "<div class='fc-day-number'>" + date.getDate() + "</div>";
2380 }
2381
2382 html +=
2383 "<div class='fc-day-content'>" +
2384 "<div style='position:relative'>&nbsp;</div>" +
2385 "</div>" +
2386 "</div>" +
2387 "</td>";
2388
2389 return html;
2390 }
2391
2392
2393
2394 /* Dimensions
2395 -----------------------------------------------------------*/
2396
2397
2398 function setHeight(height) {
2399 viewHeight = height;
2400
2401 var bodyHeight = viewHeight - head.height();
2402 var rowHeight;
2403 var rowHeightLast;
2404 var cell;
2405
2406 if (opt('weekMode') == 'variable') {
2407 rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6));
2408 }else{
2409 rowHeight = Math.floor(bodyHeight / rowCnt);
2410 rowHeightLast = bodyHeight - rowHeight * (rowCnt-1);
2411 }
2412
2413 bodyFirstCells.each(function(i, _cell) {
2414 if (i < rowCnt) {
2415 cell = $(_cell);
2416 cell.find('> div').css(
2417 'min-height',
2418 (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell)
2419 );
2420 }
2421 });
2422
2423 }
2424
2425
2426 function setWidth(width) {
2427 viewWidth = width;
2428 colPositions.clear();
2429 colContentPositions.clear();
2430
2431 weekNumberWidth = 0;
2432 if (showWeekNumbers) {
2433 weekNumberWidth = head.find('th.fc-week-number').outerWidth();
2434 }
2435
2436 colWidth = Math.floor((viewWidth - weekNumberWidth) / colCnt);
2437 setOuterWidth(headCells.slice(0, -1), colWidth);
2438 }
2439
2440
2441
2442 /* Day clicking and binding
2443 -----------------------------------------------------------*/
2444
2445
2446 function dayBind(days) {
2447 days.click(dayClick)
2448 .mousedown(daySelectionMousedown);
2449 }
2450
2451
2452 function dayClick(ev) {
2453 if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
2454 var date = parseISO8601($(this).data('date'));
2455 trigger('dayClick', this, date, true, ev);
2456 }
2457 }
2458
2459
2460
2461 /* Semi-transparent Overlay Helpers
2462 ------------------------------------------------------*/
2463 // TODO: should be consolidated with AgendaView's methods
2464
2465
2466 function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
2467
2468 if (refreshCoordinateGrid) {
2469 coordinateGrid.build();
2470 }
2471
2472 var segments = rangeToSegments(overlayStart, overlayEnd);
2473
2474 for (var i=0; i<segments.length; i++) {
2475 var segment = segments[i];
2476 dayBind(
2477 renderCellOverlay(
2478 segment.row,
2479 segment.leftCol,
2480 segment.row,
2481 segment.rightCol
2482 )
2483 );
2484 }
2485 }
2486
2487
2488 function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive
2489 var rect = coordinateGrid.rect(row0, col0, row1, col1, element);
2490 return renderOverlay(rect, element);
2491 }
2492
2493
2494
2495 /* Selection
2496 -----------------------------------------------------------------------*/
2497
2498
2499 function defaultSelectionEnd(startDate, allDay) {
2500 return cloneDate(startDate);
2501 }
2502
2503
2504 function renderSelection(startDate, endDate, allDay) {
2505 renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time???
2506 }
2507
2508
2509 function clearSelection() {
2510 clearOverlays();
2511 }
2512
2513
2514 function reportDayClick(date, allDay, ev) {
2515 var cell = dateToCell(date);
2516 var _element = bodyCells[cell.row*colCnt + cell.col];
2517 trigger('dayClick', _element, date, allDay, ev);
2518 }
2519
2520
2521
2522 /* External Dragging
2523 -----------------------------------------------------------------------*/
2524
2525
2526 function dragStart(_dragElement, ev, ui) {
2527 hoverListener.start(function(cell) {
2528 clearOverlays();
2529 if (cell) {
2530 renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
2531 }
2532 }, ev);
2533 }
2534
2535
2536 function dragStop(_dragElement, ev, ui) {
2537 var cell = hoverListener.stop();
2538 clearOverlays();
2539 if (cell) {
2540 var d = cellToDate(cell);
2541 trigger('drop', _dragElement, d, true, ev, ui);
2542 }
2543 }
2544
2545
2546
2547 /* Utilities
2548 --------------------------------------------------------*/
2549
2550
2551 function defaultEventEnd(event) {
2552 return cloneDate(event.start);
2553 }
2554
2555
2556 coordinateGrid = new CoordinateGrid(function(rows, cols) {
2557 var e, n, p;
2558 headCells.each(function(i, _e) {
2559 e = $(_e);
2560 n = e.offset().left;
2561 if (i) {
2562 p[1] = n;
2563 }
2564 p = [n];
2565 cols[i] = p;
2566 });
2567 p[1] = n + e.outerWidth();
2568 bodyRows.each(function(i, _e) {
2569 if (i < rowCnt) {
2570 e = $(_e);
2571 n = e.offset().top;
2572 if (i) {
2573 p[1] = n;
2574 }
2575 p = [n];
2576 rows[i] = p;
2577 }
2578 });
2579 p[1] = n + e.outerHeight();
2580 });
2581
2582
2583 hoverListener = new HoverListener(coordinateGrid);
2584
2585 colPositions = new HorizontalPositionCache(function(col) {
2586 return firstRowCellInners.eq(col);
2587 });
2588
2589 colContentPositions = new HorizontalPositionCache(function(col) {
2590 return firstRowCellContentInners.eq(col);
2591 });
2592
2593
2594 function colLeft(col) {
2595 return colPositions.left(col);
2596 }
2597
2598
2599 function colRight(col) {
2600 return colPositions.right(col);
2601 }
2602
2603
2604 function colContentLeft(col) {
2605 return colContentPositions.left(col);
2606 }
2607
2608
2609 function colContentRight(col) {
2610 return colContentPositions.right(col);
2611 }
2612
2613
2614 function allDayRow(i) {
2615 return bodyRows.eq(i);
2616 }
2617
2618}
2619
2620;;
2621
2622function BasicEventRenderer() {
2623 var t = this;
2624
2625
2626 // exports
2627 t.renderEvents = renderEvents;
2628 t.clearEvents = clearEvents;
2629
2630
2631 // imports
2632 DayEventRenderer.call(t);
2633
2634
2635 function renderEvents(events, modifiedEventId) {
2636 t.renderDayEvents(events, modifiedEventId);
2637 }
2638
2639
2640 function clearEvents() {
2641 t.getDaySegmentContainer().empty();
2642 }
2643
2644
2645 // TODO: have this class (and AgendaEventRenderer) be responsible for creating the event container div
2646
2647}
2648
2649;;
2650
2651fcViews.agendaWeek = AgendaWeekView;
2652
2653function AgendaWeekView(element, calendar) {
2654 var t = this;
2655
2656
2657 // exports
2658 t.render = render;
2659
2660
2661 // imports
2662 AgendaView.call(t, element, calendar, 'agendaWeek');
2663 var opt = t.opt;
2664 var renderAgenda = t.renderAgenda;
2665 var skipHiddenDays = t.skipHiddenDays;
2666 var getCellsPerWeek = t.getCellsPerWeek;
2667 var formatDates = calendar.formatDates;
2668
2669
2670 function render(date, delta) {
2671
2672 if (delta) {
2673 addDays(date, delta * 7);
2674 }
2675
2676 var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
2677 var end = addDays(cloneDate(start), 7);
2678
2679 var visStart = cloneDate(start);
2680 skipHiddenDays(visStart);
2681
2682 var visEnd = cloneDate(end);
2683 skipHiddenDays(visEnd, -1, true);
2684
2685 var colCnt = getCellsPerWeek();
2686
2687 t.title = formatDates(
2688 visStart,
2689 addDays(cloneDate(visEnd), -1),
2690 opt('titleFormat')
2691 );
2692
2693 t.start = start;
2694 t.end = end;
2695 t.visStart = visStart;
2696 t.visEnd = visEnd;
2697
2698 renderAgenda(colCnt);
2699 }
2700
2701}
2702
2703;;
2704
2705fcViews.agendaDay = AgendaDayView;
2706
2707
2708function AgendaDayView(element, calendar) {
2709 var t = this;
2710
2711
2712 // exports
2713 t.render = render;
2714
2715
2716 // imports
2717 AgendaView.call(t, element, calendar, 'agendaDay');
2718 var opt = t.opt;
2719 var renderAgenda = t.renderAgenda;
2720 var skipHiddenDays = t.skipHiddenDays;
2721 var formatDate = calendar.formatDate;
2722
2723
2724 function render(date, delta) {
2725
2726 if (delta) {
2727 addDays(date, delta);
2728 }
2729 skipHiddenDays(date, delta < 0 ? -1 : 1);
2730
2731 var start = cloneDate(date, true);
2732 var end = addDays(cloneDate(start), 1);
2733
2734 t.title = formatDate(date, opt('titleFormat'));
2735
2736 t.start = t.visStart = start;
2737 t.end = t.visEnd = end;
2738
2739 renderAgenda(1);
2740 }
2741
2742
2743}
2744
2745;;
2746
2747setDefaults({
2748 allDaySlot: true,
2749 allDayText: 'all-day',
2750 firstHour: 8,
2751 lastHour: 10,
2752 slotMinutes: 30,
2753 defaultEventMinutes: 120,
2754 axisFormat: 'h(:mm)tt',
2755 timeFormat: {
2756 agenda: 'h:mm{ - h:mm}'
2757 },
2758 dragOpacity: {
2759 agenda: .5
2760 },
2761 minTime: 0,
2762 maxTime: 24,
2763 slotEventOverlap: false
2764});
2765
2766
2767// TODO: make it work in quirks mode (event corners, all-day height)
2768// TODO: test liquid width, especially in IE6
2769
2770
2771function AgendaView(element, calendar, viewName) {
2772 var t = this;
2773
2774
2775 // exports
2776 t.renderAgenda = renderAgenda;
2777 t.setWidth = setWidth;
2778 t.setHeight = setHeight;
2779 t.afterRender = afterRender;
2780 t.defaultEventEnd = defaultEventEnd;
2781 t.timePosition = timePosition;
2782 t.getIsCellAllDay = getIsCellAllDay;
2783 t.allDayRow = getAllDayRow;
2784 t.getCoordinateGrid = function() { return coordinateGrid }; // specifically for AgendaEventRenderer
2785 t.getHoverListener = function() { return hoverListener };
2786 t.colLeft = colLeft;
2787 t.colRight = colRight;
2788 t.colContentLeft = colContentLeft;
2789 t.colContentRight = colContentRight;
2790 t.getDaySegmentContainer = function() { return daySegmentContainer };
2791 t.getSlotSegmentContainer = function() { return slotSegmentContainer };
2792 t.getMinMinute = function() { return minMinute };
2793 t.getMaxMinute = function() { return maxMinute };
2794 t.getSlotContainer = function() { return slotContainer };
2795 t.getRowCnt = function() { return 1 };
2796 t.getColCnt = function() { return colCnt };
2797 t.getColWidth = function() { return colWidth };
2798 t.getSnapHeight = function() { return snapHeight };
2799 t.getSnapMinutes = function() { return snapMinutes };
2800 t.defaultSelectionEnd = defaultSelectionEnd;
2801 t.renderDayOverlay = renderDayOverlay;
2802 t.renderSelection = renderSelection;
2803 t.clearSelection = clearSelection;
2804 t.reportDayClick = reportDayClick; // selection mousedown hack
2805 t.dragStart = dragStart;
2806 t.dragStop = dragStop;
2807
2808
2809 // imports
2810 View.call(t, element, calendar, viewName);
2811 OverlayManager.call(t);
2812 SelectionManager.call(t);
2813 AgendaEventRenderer.call(t);
2814 var opt = t.opt;
2815 var trigger = t.trigger;
2816 var renderOverlay = t.renderOverlay;
2817 var clearOverlays = t.clearOverlays;
2818 var reportSelection = t.reportSelection;
2819 var unselect = t.unselect;
2820 var daySelectionMousedown = t.daySelectionMousedown;
2821 var slotSegHtml = t.slotSegHtml;
2822 var cellToDate = t.cellToDate;
2823 var dateToCell = t.dateToCell;
2824 var rangeToSegments = t.rangeToSegments;
2825 var formatDate = calendar.formatDate;
2826
2827
2828 // locals
2829
2830 var dayTable;
2831 var dayHead;
2832 var dayHeadCells;
2833 var dayBody;
2834 var dayBodyCells;
2835 var dayBodyCellInners;
2836 var dayBodyCellContentInners;
2837 var dayBodyFirstCell;
2838 var dayBodyFirstCellStretcher;
2839 var slotLayer;
2840 var daySegmentContainer;
2841 var allDayTable;
2842 var allDayRow;
2843 var slotScroller;
2844 var slotContainer;
2845 var slotSegmentContainer;
2846 var slotTable;
2847 var selectionHelper;
2848
2849 var viewWidth;
2850 var viewHeight;
2851 var axisWidth;
2852 var colWidth;
2853 var gutterWidth;
2854 var slotHeight; // TODO: what if slotHeight changes? (see issue 650)
2855
2856 var snapMinutes;
2857 var snapRatio; // ratio of number of "selection" slots to normal slots. (ex: 1, 2, 4)
2858 var snapHeight; // holds the pixel hight of a "selection" slot
2859
2860 var colCnt;
2861 var slotCnt;
2862 var coordinateGrid;
2863 var hoverListener;
2864 var colPositions;
2865 var colContentPositions;
2866 var slotTopCache = {};
2867
2868 var tm;
2869 var rtl;
2870 var minMinute, maxMinute;
2871 var colFormat;
2872 var showWeekNumbers;
2873 var weekNumberTitle;
2874 var weekNumberFormat;
2875
2876
2877
2878 /* Rendering
2879 -----------------------------------------------------------------------------*/
2880
2881
2882 disableTextSelection(element.addClass('fc-agenda'));
2883
2884
2885 function renderAgenda(c) {
2886 colCnt = c;
2887 updateOptions();
2888
2889 if (!dayTable) { // first time rendering?
2890 buildSkeleton(); // builds day table, slot area, events containers
2891 }
2892 else {
2893 buildDayTable(); // rebuilds day table
2894 }
2895 }
2896
2897
2898 function updateOptions() {
2899
2900 tm = opt('theme') ? 'ui' : 'fc';
2901 rtl = opt('isRTL')
2902 minMinute = parseTime(opt('minTime'));
2903 maxMinute = parseTime(opt('maxTime'));
2904 colFormat = opt('columnFormat');
2905
2906 // week # options. (TODO: bad, logic also in other views)
2907 showWeekNumbers = opt('weekNumbers');
2908 weekNumberTitle = opt('weekNumberTitle');
2909 if (opt('weekNumberCalculation') != 'iso') {
2910 weekNumberFormat = "w";
2911 }
2912 else {
2913 weekNumberFormat = "W";
2914 }
2915
2916 snapMinutes = opt('snapMinutes') || opt('slotMinutes');
2917 }
2918
2919
2920
2921 /* Build DOM
2922 -----------------------------------------------------------------------*/
2923
2924
2925 function buildSkeleton() {
2926 var headerClass = tm + "-widget-header";
2927 var contentClass = tm + "-widget-content";
2928 var s;
2929 var d;
2930 var i;
2931 var maxd;
2932 var minutes;
2933 var slotNormal = opt('slotMinutes') % 15 == 0;
2934
2935 buildDayTable();
2936
2937 slotLayer =
2938 $("<div style='position:absolute;z-index:2;left:0;width:100%'/>")
2939 .appendTo(element);
2940
2941 if (opt('allDaySlot')) {
2942
2943 daySegmentContainer =
2944 $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
2945 .appendTo(slotLayer);
2946
2947 s =
2948 "<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" +
2949 "<tr>" +
2950 "<th class='" + headerClass + " fc-agenda-axis'>" + opt('allDayText') + "</th>" +
2951 "<td>" +
2952 "<div class='fc-day-content'><div style='position:relative'/></div>" +
2953 "</td>" +
2954 "<th class='" + headerClass + " fc-agenda-gutter'>&nbsp;</th>" +
2955 "</tr>" +
2956 "</table>";
2957 allDayTable = $(s).appendTo(slotLayer);
2958 allDayRow = allDayTable.find('tr');
2959
2960 dayBind(allDayRow.find('td'));
2961
2962 slotLayer.append(
2963 "<div class='fc-agenda-divider " + headerClass + "'>" +
2964 "<div class='fc-agenda-divider-inner'/>" +
2965 "</div>"
2966 );
2967
2968 }else{
2969
2970 daySegmentContainer = $([]); // in jQuery 1.4, we can just do $()
2971
2972 }
2973
2974 slotScroller =
2975 $("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>")
2976 .appendTo(slotLayer);
2977
2978 slotContainer =
2979 $("<div style='position:relative;width:100%;overflow:hidden'/>")
2980 .appendTo(slotScroller);
2981
2982 slotSegmentContainer =
2983 $("<div class='fc-event-container' style='position:absolute;z-index:8;top:0;left:0'/>")
2984 .appendTo(slotContainer);
2985
2986 s =
2987 "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" +
2988 "<tbody>";
2989 d = zeroDate();
2990 maxd = addMinutes(cloneDate(d), maxMinute);
2991 addMinutes(d, minMinute);
2992 slotCnt = 0;
2993 for (i=0; d < maxd; i++) {
2994 minutes = d.getMinutes();
2995 s +=
2996 "<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" +
2997 "<th class='fc-agenda-axis " + headerClass + "'>" +
2998 ((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : '&nbsp;') +
2999 "</th>" +
3000 "<td class='" + contentClass + "'>" +
3001 "<div style='position:relative'>&nbsp;</div>" +
3002 "</td>" +
3003 "</tr>";
3004 addMinutes(d, opt('slotMinutes'));
3005 slotCnt++;
3006 }
3007 s +=
3008 "</tbody>" +
3009 "</table>";
3010 slotTable = $(s).appendTo(slotContainer);
3011
3012 slotBind(slotTable.find('td'));
3013 }
3014
3015
3016
3017 /* Build Day Table
3018 -----------------------------------------------------------------------*/
3019
3020
3021 function buildDayTable() {
3022 var html = buildDayTableHTML();
3023
3024 if (dayTable) {
3025 dayTable.remove();
3026 }
3027 dayTable = $(html).appendTo(element);
3028
3029 dayHead = dayTable.find('thead');
3030 dayHeadCells = dayHead.find('th').slice(1, -1); // exclude gutter
3031 dayBody = dayTable.find('tbody');
3032 dayBodyCells = dayBody.find('td').slice(0, -1); // exclude gutter
3033 dayBodyCellInners = dayBodyCells.find('> div');
3034 dayBodyCellContentInners = dayBodyCells.find('.fc-day-content > div');
3035
3036 dayBodyFirstCell = dayBodyCells.eq(0);
3037 dayBodyFirstCellStretcher = dayBodyCellInners.eq(0);
3038
3039 markFirstLast(dayHead.add(dayHead.find('tr')));
3040 markFirstLast(dayBody.add(dayBody.find('tr')));
3041
3042 // TODO: now that we rebuild the cells every time, we should call dayRender
3043 }
3044
3045
3046 function buildDayTableHTML() {
3047 var html =
3048 "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" +
3049 buildDayTableHeadHTML() +
3050 buildDayTableBodyHTML() +
3051 "</table>";
3052
3053 return html;
3054 }
3055
3056
3057 function buildDayTableHeadHTML() {
3058 var headerClass = tm + "-widget-header";
3059 var date;
3060 var html = '';
3061 var weekText;
3062 var col;
3063
3064 html +=
3065 "<thead>" +
3066 "<tr>";
3067
3068 if (showWeekNumbers) {
3069 date = cellToDate(0, 0);
3070 weekText = formatDate(date, weekNumberFormat);
3071 if (rtl) {
3072 weekText += weekNumberTitle;
3073 }
3074 else {
3075 weekText = weekNumberTitle + weekText;
3076 }
3077 html +=
3078 "<th class='fc-agenda-axis fc-week-number " + headerClass + "'>" +
3079 htmlEscape(weekText) +
3080 "</th>";
3081 }
3082 else {
3083 html += "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>";
3084 }
3085
3086 for (col=0; col<colCnt; col++) {
3087 date = cellToDate(0, col);
3088 html +=
3089 "<th class='fc-" + dayIDs[date.getDay()] + " fc-col" + col + ' ' + headerClass + "'>" +
3090 htmlEscape(formatDate(date, colFormat)) +
3091 "</th>";
3092 }
3093
3094 html +=
3095 "<th class='fc-agenda-gutter " + headerClass + "'>&nbsp;</th>" +
3096 "</tr>" +
3097 "</thead>";
3098
3099 return html;
3100 }
3101
3102
3103 function buildDayTableBodyHTML() {
3104 var headerClass = tm + "-widget-header"; // TODO: make these when updateOptions() called
3105 var contentClass = tm + "-widget-content";
3106 var date;
3107 var today = clearTime(new Date());
3108 var col;
3109 var cellsHTML;
3110 var cellHTML;
3111 var classNames;
3112 var html = '';
3113
3114 html +=
3115 "<tbody>" +
3116 "<tr>" +
3117 "<th class='fc-agenda-axis " + headerClass + "'>&nbsp;</th>";
3118
3119 cellsHTML = '';
3120
3121 for (col=0; col<colCnt; col++) {
3122
3123 date = cellToDate(0, col);
3124
3125 classNames = [
3126 'fc-col' + col,
3127 'fc-' + dayIDs[date.getDay()],
3128 contentClass
3129 ];
3130 if (+date == +today) {
3131 classNames.push(
3132 tm + '-state-highlight',
3133 'fc-today'
3134 );
3135 }
3136 else if (date < today) {
3137 classNames.push('fc-past');
3138 }
3139 else {
3140 classNames.push('fc-future');
3141 }
3142
3143 cellHTML =
3144 "<td class='" + classNames.join(' ') + "'>" +
3145 "<div>" +
3146 "<div class='fc-day-content'>" +
3147 "<div style='position:relative'>&nbsp;</div>" +
3148 "</div>" +
3149 "</div>" +
3150 "</td>";
3151
3152 cellsHTML += cellHTML;
3153 }
3154
3155 html += cellsHTML;
3156 html +=
3157 "<td class='fc-agenda-gutter " + contentClass + "'>&nbsp;</td>" +
3158 "</tr>" +
3159 "</tbody>";
3160
3161 return html;
3162 }
3163
3164
3165 // TODO: data-date on the cells
3166
3167
3168
3169 /* Dimensions
3170 -----------------------------------------------------------------------*/
3171
3172
3173 function setHeight(height) {
3174 if (height === undefined) {
3175 height = viewHeight;
3176 }
3177 viewHeight = height;
3178 slotTopCache = {};
3179
3180 var headHeight = dayBody.position().top;
3181 var allDayHeight = slotScroller.position().top; // including divider
3182 var bodyHeight = Math.min( // total body height, including borders
3183 height - headHeight, // when scrollbars
3184 slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border
3185 );
3186
3187 dayBodyFirstCellStretcher
3188 .height(bodyHeight - vsides(dayBodyFirstCell));
3189
3190 slotLayer.css('top', headHeight);
3191
3192 slotScroller.height(bodyHeight - allDayHeight - 1);
3193
3194 // the stylesheet guarantees that the first row has no border.
3195 // this allows .height() to work well cross-browser.
3196 slotHeight = slotTable.find('tr:first').height() + 1; // +1 for bottom border
3197
3198 snapRatio = opt('slotMinutes') / snapMinutes;
3199 snapHeight = slotHeight / snapRatio;
3200 }
3201
3202
3203 function setWidth(width) {
3204 viewWidth = width;
3205 colPositions.clear();
3206 colContentPositions.clear();
3207
3208 var axisFirstCells = dayHead.find('th:first');
3209 if (allDayTable) {
3210 axisFirstCells = axisFirstCells.add(allDayTable.find('th:first'));
3211 }
3212 axisFirstCells = axisFirstCells.add(slotTable.find('th:first'));
3213
3214 axisWidth = 0;
3215 setOuterWidth(
3216 axisFirstCells
3217 .width('')
3218 .each(function(i, _cell) {
3219 axisWidth = Math.max(axisWidth, $(_cell).outerWidth());
3220 }),
3221 axisWidth
3222 );
3223
3224 var gutterCells = dayTable.find('.fc-agenda-gutter');
3225 if (allDayTable) {
3226 gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter'));
3227 }
3228
3229 var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7)
3230
3231 gutterWidth = slotScroller.width() - slotTableWidth;
3232 if (gutterWidth) {
3233 setOuterWidth(gutterCells, gutterWidth);
3234 gutterCells
3235 .show()
3236 .prev()
3237 .removeClass('fc-last');
3238 }else{
3239 gutterCells
3240 .hide()
3241 .prev()
3242 .addClass('fc-last');
3243 }
3244
3245 colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt);
3246 setOuterWidth(dayHeadCells.slice(0, -1), colWidth);
3247 }
3248
3249
3250
3251 /* Scrolling
3252 -----------------------------------------------------------------------*/
3253
3254
3255 function resetScroll() {
3256 var d0 = zeroDate();
3257 var scrollDate = cloneDate(d0);
3258 scrollDate.setHours(opt('firstHour'));
3259 var top = timePosition(d0, scrollDate) + 1; // +1 for the border
3260 function scroll() {
3261 slotScroller.scrollTop(top);
3262 }
3263 scroll();
3264 setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
3265 }
3266
3267
3268 function afterRender() { // after the view has been freshly rendered and sized
3269 resetScroll();
3270 }
3271
3272
3273
3274 /* Slot/Day clicking and binding
3275 -----------------------------------------------------------------------*/
3276
3277
3278 function dayBind(cells) {
3279 cells.click(slotClick)
3280 .mousedown(daySelectionMousedown);
3281 }
3282
3283
3284 function slotBind(cells) {
3285 cells.click(slotClick)
3286 .mousedown(slotSelectionMousedown);
3287 }
3288
3289
3290 function slotClick(ev) {
3291 if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
3292 var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth));
3293 var date = cellToDate(0, col);
3294 var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data
3295 if (rowMatch) {
3296 var mins = parseInt(rowMatch[1]) * opt('slotMinutes');
3297 var hours = Math.floor(mins/60);
3298 date.setHours(hours);
3299 date.setMinutes(mins%60 + minMinute);
3300 trigger('dayClick', dayBodyCells[col], date, false, ev);
3301 }else{
3302 trigger('dayClick', dayBodyCells[col], date, true, ev);
3303 }
3304 }
3305 }
3306
3307
3308
3309 /* Semi-transparent Overlay Helpers
3310 -----------------------------------------------------*/
3311 // TODO: should be consolidated with BasicView's methods
3312
3313
3314 function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
3315
3316 if (refreshCoordinateGrid) {
3317 coordinateGrid.build();
3318 }
3319
3320 var segments = rangeToSegments(overlayStart, overlayEnd);
3321
3322 for (var i=0; i<segments.length; i++) {
3323 var segment = segments[i];
3324 dayBind(
3325 renderCellOverlay(
3326 segment.row,
3327 segment.leftCol,
3328 segment.row,
3329 segment.rightCol
3330 )
3331 );
3332 }
3333 }
3334
3335
3336 function renderCellOverlay(row0, col0, row1, col1) { // only for all-day?
3337 var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer);
3338 return renderOverlay(rect, slotLayer);
3339 }
3340
3341
3342 function renderSlotOverlay(overlayStart, overlayEnd) {
3343 for (var i=0; i<colCnt; i++) {
3344 var dayStart = cellToDate(0, i);
3345 var dayEnd = addDays(cloneDate(dayStart), 1);
3346 var stretchStart = new Date(Math.max(dayStart, overlayStart));
3347 var stretchEnd = new Date(Math.min(dayEnd, overlayEnd));
3348 if (stretchStart < stretchEnd) {
3349 var rect = coordinateGrid.rect(0, i, 0, i, slotContainer); // only use it for horizontal coords
3350 var top = timePosition(dayStart, stretchStart);
3351 var bottom = timePosition(dayStart, stretchEnd);
3352 rect.top = top;
3353 rect.height = bottom - top;
3354 slotBind(
3355 renderOverlay(rect, slotContainer)
3356 );
3357 }
3358 }
3359 }
3360
3361
3362
3363 /* Coordinate Utilities
3364 -----------------------------------------------------------------------------*/
3365
3366
3367 coordinateGrid = new CoordinateGrid(function(rows, cols) {
3368 var e, n, p;
3369 dayHeadCells.each(function(i, _e) {
3370 e = $(_e);
3371 n = e.offset().left;
3372 if (i) {
3373 p[1] = n;
3374 }
3375 p = [n];
3376 cols[i] = p;
3377 });
3378 p[1] = n + e.outerWidth();
3379 if (opt('allDaySlot')) {
3380 e = allDayRow;
3381 n = e.offset().top;
3382 rows[0] = [n, n+e.outerHeight()];
3383 }
3384 var slotTableTop = slotContainer.offset().top;
3385 var slotScrollerTop = slotScroller.offset().top;
3386 var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight();
3387 function constrain(n) {
3388 return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n));
3389 }
3390 for (var i=0; i<slotCnt*snapRatio; i++) { // adapt slot count to increased/decreased selection slot count
3391 rows.push([
3392 constrain(slotTableTop + snapHeight*i),
3393 constrain(slotTableTop + snapHeight*(i+1))
3394 ]);
3395 }
3396 });
3397
3398
3399 hoverListener = new HoverListener(coordinateGrid);
3400
3401 colPositions = new HorizontalPositionCache(function(col) {
3402 return dayBodyCellInners.eq(col);
3403 });
3404
3405 colContentPositions = new HorizontalPositionCache(function(col) {
3406 return dayBodyCellContentInners.eq(col);
3407 });
3408
3409
3410 function colLeft(col) {
3411 return colPositions.left(col);
3412 }
3413
3414
3415 function colContentLeft(col) {
3416 return colContentPositions.left(col);
3417 }
3418
3419
3420 function colRight(col) {
3421 return colPositions.right(col);
3422 }
3423
3424
3425 function colContentRight(col) {
3426 return colContentPositions.right(col);
3427 }
3428
3429
3430 function getIsCellAllDay(cell) {
3431 return opt('allDaySlot') && !cell.row;
3432 }
3433
3434
3435 function realCellToDate(cell) { // ugh "real" ... but blame it on our abuse of the "cell" system
3436 var d = cellToDate(0, cell.col);
3437 var slotIndex = cell.row;
3438 if (opt('allDaySlot')) {
3439 slotIndex--;
3440 }
3441 if (slotIndex >= 0) {
3442 addMinutes(d, minMinute + slotIndex * snapMinutes);
3443 }
3444 return d;
3445 }
3446
3447
3448 // get the Y coordinate of the given time on the given day (both Date objects)
3449 function timePosition(day, time) { // both date objects. day holds 00:00 of current day
3450 day = cloneDate(day, true);
3451 if (time < addMinutes(cloneDate(day), minMinute)) {
3452 return 0;
3453 }
3454 if (time >= addMinutes(cloneDate(day), maxMinute)) {
3455 return slotTable.height();
3456 }
3457 var slotMinutes = opt('slotMinutes'),
3458 minutes = time.getHours()*60 + time.getMinutes() - minMinute,
3459 slotI = Math.floor(minutes / slotMinutes),
3460 slotTop = slotTopCache[slotI];
3461 if (slotTop === undefined) {
3462 slotTop = slotTopCache[slotI] =
3463 slotTable.find('tr').eq(slotI).find('td div')[0].offsetTop;
3464 // .eq() is faster than ":eq()" selector
3465 // [0].offsetTop is faster than .position().top (do we really need this optimization?)
3466 // a better optimization would be to cache all these divs
3467 }
3468 return Math.max(0, Math.round(
3469 slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes)
3470 ));
3471 }
3472
3473
3474 function getAllDayRow(index) {
3475 return allDayRow;
3476 }
3477
3478
3479 function defaultEventEnd(event) {
3480 var start = cloneDate(event.start);
3481 if (event.allDay) {
3482 return start;
3483 }
3484 return addMinutes(start, opt('defaultEventMinutes'));
3485 }
3486
3487
3488
3489 /* Selection
3490 ---------------------------------------------------------------------------------*/
3491
3492
3493 function defaultSelectionEnd(startDate, allDay) {
3494 if (allDay) {
3495 return cloneDate(startDate);
3496 }
3497 return addMinutes(cloneDate(startDate), opt('slotMinutes'));
3498 }
3499
3500
3501 function renderSelection(startDate, endDate, allDay) { // only for all-day
3502 if (allDay) {
3503 if (opt('allDaySlot')) {
3504 renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true);
3505 }
3506 }else{
3507 renderSlotSelection(startDate, endDate);
3508 }
3509 }
3510
3511
3512 function renderSlotSelection(startDate, endDate) {
3513 var helperOption = opt('selectHelper');
3514 coordinateGrid.build();
3515 if (helperOption) {
3516 var col = dateToCell(startDate).col;
3517 if (col >= 0 && col < colCnt) { // only works when times are on same day
3518 var rect = coordinateGrid.rect(0, col, 0, col, slotContainer); // only for horizontal coords
3519 var top = timePosition(startDate, startDate);
3520 var bottom = timePosition(startDate, endDate);
3521 if (bottom > top) { // protect against selections that are entirely before or after visible range
3522 rect.top = top;
3523 rect.height = bottom - top;
3524 rect.left += 2;
3525 rect.width -= 5;
3526 if ($.isFunction(helperOption)) {
3527 var helperRes = helperOption(startDate, endDate);
3528 if (helperRes) {
3529 rect.position = 'absolute';
3530 selectionHelper = $(helperRes)
3531 .css(rect)
3532 .appendTo(slotContainer);
3533 }
3534 }else{
3535 rect.isStart = true; // conside rect a "seg" now
3536 rect.isEnd = true; //
3537 selectionHelper = $(slotSegHtml(
3538 {
3539 title: '',
3540 start: startDate,
3541 end: endDate,
3542 className: ['fc-select-helper'],
3543 editable: false
3544 },
3545 rect
3546 ));
3547 selectionHelper.css('opacity', opt('dragOpacity'));
3548 }
3549 if (selectionHelper) {
3550 slotBind(selectionHelper);
3551 slotContainer.append(selectionHelper);
3552 setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended
3553 setOuterHeight(selectionHelper, rect.height, true);
3554 }
3555 }
3556 }
3557 }else{
3558 renderSlotOverlay(startDate, endDate);
3559 }
3560 }
3561
3562
3563 function clearSelection() {
3564 clearOverlays();
3565 if (selectionHelper) {
3566 selectionHelper.remove();
3567 selectionHelper = null;
3568 }
3569 }
3570
3571
3572 function slotSelectionMousedown(ev) {
3573 if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button
3574 unselect(ev);
3575 var dates;
3576 hoverListener.start(function(cell, origCell) {
3577 clearSelection();
3578 if (cell && cell.col == origCell.col && !getIsCellAllDay(cell)) {
3579 var d1 = realCellToDate(origCell);
3580 var d2 = realCellToDate(cell);
3581 dates = [
3582 d1,
3583 addMinutes(cloneDate(d1), snapMinutes), // calculate minutes depending on selection slot minutes
3584 d2,
3585 addMinutes(cloneDate(d2), snapMinutes)
3586 ].sort(dateCompare);
3587 renderSlotSelection(dates[0], dates[3]);
3588 }else{
3589 dates = null;
3590 }
3591 }, ev);
3592 $(document).one('mouseup', function(ev) {
3593 hoverListener.stop();
3594 if (dates) {
3595 if (+dates[0] == +dates[1]) {
3596 reportDayClick(dates[0], false, ev);
3597 }
3598 reportSelection(dates[0], dates[3], false, ev);
3599 }
3600 });
3601 }
3602 }
3603
3604
3605 function reportDayClick(date, allDay, ev) {
3606 trigger('dayClick', dayBodyCells[dateToCell(date).col], date, allDay, ev);
3607 }
3608
3609
3610
3611 /* External Dragging
3612 --------------------------------------------------------------------------------*/
3613
3614
3615 function dragStart(_dragElement, ev, ui) {
3616 hoverListener.start(function(cell) {
3617 clearOverlays();
3618 if (cell) {
3619 if (getIsCellAllDay(cell)) {
3620 renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
3621 }else{
3622 var d1 = realCellToDate(cell);
3623 var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes'));
3624 renderSlotOverlay(d1, d2);
3625 }
3626 }
3627 }, ev);
3628 }
3629
3630
3631 function dragStop(_dragElement, ev, ui) {
3632 var cell = hoverListener.stop();
3633 clearOverlays();
3634 if (cell) {
3635 trigger('drop', _dragElement, realCellToDate(cell), getIsCellAllDay(cell), ev, ui);
3636 }
3637 }
3638
3639
3640}
3641
3642;;
3643
3644function AgendaEventRenderer() {
3645 var t = this;
3646
3647
3648 // exports
3649 t.renderEvents = renderEvents;
3650 t.clearEvents = clearEvents;
3651 t.slotSegHtml = slotSegHtml;
3652
3653
3654 // imports
3655 DayEventRenderer.call(t);
3656 var opt = t.opt;
3657 var trigger = t.trigger;
3658 var isEventDraggable = t.isEventDraggable;
3659 var isEventResizable = t.isEventResizable;
3660 var eventEnd = t.eventEnd;
3661 var eventElementHandlers = t.eventElementHandlers;
3662 var setHeight = t.setHeight;
3663 var getDaySegmentContainer = t.getDaySegmentContainer;
3664 var getSlotSegmentContainer = t.getSlotSegmentContainer;
3665 var getHoverListener = t.getHoverListener;
3666 var getMaxMinute = t.getMaxMinute;
3667 var getMinMinute = t.getMinMinute;
3668 var timePosition = t.timePosition;
3669 var getIsCellAllDay = t.getIsCellAllDay;
3670 var colContentLeft = t.colContentLeft;
3671 var colContentRight = t.colContentRight;
3672 var cellToDate = t.cellToDate;
3673 var getColCnt = t.getColCnt;
3674 var getColWidth = t.getColWidth;
3675 var getSnapHeight = t.getSnapHeight;
3676 var getSnapMinutes = t.getSnapMinutes;
3677 var getSlotContainer = t.getSlotContainer;
3678 var reportEventElement = t.reportEventElement;
3679 var showEvents = t.showEvents;
3680 var hideEvents = t.hideEvents;
3681 var eventDrop = t.eventDrop;
3682 var eventResize = t.eventResize;
3683 var renderDayOverlay = t.renderDayOverlay;
3684 var clearOverlays = t.clearOverlays;
3685 var renderDayEvents = t.renderDayEvents;
3686 var calendar = t.calendar;
3687 var formatDate = calendar.formatDate;
3688 var formatDates = calendar.formatDates;
3689
3690
3691 // overrides
3692 t.draggableDayEvent = draggableDayEvent;
3693
3694
3695
3696 /* Rendering
3697 ----------------------------------------------------------------------------*/
3698
3699
3700 function renderEvents(events, modifiedEventId) {
3701 var i, len=events.length,
3702 dayEvents=[],
3703 slotEvents=[];
3704 for (i=0; i<len; i++) {
3705 if (events[i].allDay) {
3706 dayEvents.push(events[i]);
3707 }else{
3708 slotEvents.push(events[i]);
3709 }
3710 }
3711
3712 if (opt('allDaySlot')) {
3713 renderDayEvents(dayEvents, modifiedEventId);
3714 setHeight(); // no params means set to viewHeight
3715 }
3716
3717 renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId);
3718 }
3719
3720
3721 function clearEvents() {
3722 getDaySegmentContainer().empty();
3723 getSlotSegmentContainer().empty();
3724 }
3725
3726
3727 function compileSlotSegs(events) {
3728 var colCnt = getColCnt(),
3729 minMinute = getMinMinute(),
3730 maxMinute = getMaxMinute(),
3731 d,
3732 visEventEnds = $.map(events, slotEventEnd),
3733 i,
3734 j, seg,
3735 colSegs,
3736 segs = [];
3737
3738 for (i=0; i<colCnt; i++) {
3739
3740 d = cellToDate(0, i);
3741 addMinutes(d, minMinute);
3742
3743 colSegs = sliceSegs(
3744 events,
3745 visEventEnds,
3746 d,
3747 addMinutes(cloneDate(d), maxMinute-minMinute)
3748 );
3749
3750 colSegs = placeSlotSegs(colSegs); // returns a new order
3751
3752 for (j=0; j<colSegs.length; j++) {
3753 seg = colSegs[j];
3754 seg.col = i;
3755 segs.push(seg);
3756 }
3757 }
3758
3759 return segs;
3760 }
3761
3762
3763 function sliceSegs(events, visEventEnds, start, end) {
3764 var segs = [],
3765 i, len=events.length, event,
3766 eventStart, eventEnd,
3767 segStart, segEnd,
3768 isStart, isEnd;
3769 for (i=0; i<len; i++) {
3770 event = events[i];
3771 eventStart = event.start;
3772 eventEnd = visEventEnds[i];
3773 if (eventEnd > start && eventStart < end) {
3774 if (eventStart < start) {
3775 segStart = cloneDate(start);
3776 isStart = false;
3777 }else{
3778 segStart = eventStart;
3779 isStart = true;
3780 }
3781 if (eventEnd > end) {
3782 segEnd = cloneDate(end);
3783 isEnd = false;
3784 }else{
3785 segEnd = eventEnd;
3786 isEnd = true;
3787 }
3788 segs.push({
3789 event: event,
3790 start: segStart,
3791 end: segEnd,
3792 isStart: isStart,
3793 isEnd: isEnd
3794 });
3795 }
3796 }
3797 return segs.sort(compareSlotSegs);
3798 }
3799
3800
3801 function slotEventEnd(event) {
3802 if (event.end) {
3803 return cloneDate(event.end);
3804 }else{
3805 return addMinutes(cloneDate(event.start), opt('defaultEventMinutes'));
3806 }
3807 }
3808
3809
3810 // renders events in the 'time slots' at the bottom
3811 // TODO: when we refactor this, when user returns `false` eventRender, don't have empty space
3812 // TODO: refactor will include using pixels to detect collisions instead of dates (handy for seg cmp)
3813
3814 function renderSlotSegs(segs, modifiedEventId) {
3815
3816 var i, segCnt=segs.length, seg,
3817 event,
3818 top,
3819 bottom,
3820 columnLeft,
3821 columnRight,
3822 columnWidth,
3823 width,
3824 left,
3825 right,
3826 html = '',
3827 eventElements,
3828 eventElement,
3829 triggerRes,
3830 titleElement,
3831 height,
3832 slotSegmentContainer = getSlotSegmentContainer(),
3833 isRTL = opt('isRTL');
3834
3835 // calculate position/dimensions, create html
3836 for (i=0; i<segCnt; i++) {
3837 seg = segs[i];
3838 event = seg.event;
3839 top = timePosition(seg.start, seg.start);
3840 bottom = timePosition(seg.start, seg.end);
3841 columnLeft = colContentLeft(seg.col);
3842 columnRight = colContentRight(seg.col);
3843 columnWidth = columnRight - columnLeft;
3844
3845 // shave off space on right near scrollbars (2.5%)
3846 // TODO: move this to CSS somehow
3847 columnRight -= columnWidth * .025;
3848 columnWidth = columnRight - columnLeft;
3849
3850 width = columnWidth * (seg.forwardCoord - seg.backwardCoord);
3851
3852 if (opt('slotEventOverlap')) {
3853 // double the width while making sure resize handle is visible
3854 // (assumed to be 20px wide)
3855 width = Math.max(
3856 (width - (20/2)) * 2,
3857 width // narrow columns will want to make the segment smaller than
3858 // the natural width. don't allow it
3859 );
3860 }
3861
3862 if (isRTL) {
3863 right = columnRight - seg.backwardCoord * columnWidth;
3864 left = right - width;
3865 }
3866 else {
3867 left = columnLeft + seg.backwardCoord * columnWidth;
3868 right = left + width;
3869 }
3870
3871 // make sure horizontal coordinates are in bounds
3872 left = Math.max(left, columnLeft);
3873 right = Math.min(right, columnRight);
3874 width = right - left;
3875
3876 seg.top = top;
3877 seg.left = left;
3878 seg.outerWidth = width;
3879 seg.outerHeight = bottom - top;
3880 html += slotSegHtml(event, seg);
3881 }
3882
3883 slotSegmentContainer[0].innerHTML = html; // faster than html()
3884 eventElements = slotSegmentContainer.children();
3885
3886 // retrieve elements, run through eventRender callback, bind event handlers
3887 for (i=0; i<segCnt; i++) {
3888 seg = segs[i];
3889 event = seg.event;
3890 eventElement = $(eventElements[i]); // faster than eq()
3891 triggerRes = trigger('eventRender', event, event, eventElement);
3892 if (triggerRes === false) {
3893 eventElement.remove();
3894 }else{
3895 if (triggerRes && triggerRes !== true) {
3896 eventElement.remove();
3897 eventElement = $(triggerRes)
3898 .css({
3899 position: 'absolute',
3900 top: seg.top,
3901 left: seg.left
3902 })
3903 .appendTo(slotSegmentContainer);
3904 }
3905 seg.element = eventElement;
3906 if (event._id === modifiedEventId) {
3907 bindSlotSeg(event, eventElement, seg);
3908 }else{
3909 eventElement[0]._fci = i; // for lazySegBind
3910 }
3911 reportEventElement(event, eventElement);
3912 }
3913 }
3914
3915 lazySegBind(slotSegmentContainer, segs, bindSlotSeg);
3916
3917 // record event sides and title positions
3918 for (i=0; i<segCnt; i++) {
3919 seg = segs[i];
3920 if (eventElement = seg.element) {
3921 seg.vsides = vsides(eventElement, true);
3922 seg.hsides = hsides(eventElement, true);
3923 titleElement = eventElement.find('.fc-event-title');
3924 if (titleElement.length) {
3925 seg.contentTop = titleElement[0].offsetTop;
3926 }
3927 }
3928 }
3929
3930 // set all positions/dimensions at once
3931 for (i=0; i<segCnt; i++) {
3932 seg = segs[i];
3933 if (eventElement = seg.element) {
3934 eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
3935 height = Math.max(0, seg.outerHeight - seg.vsides);
3936 eventElement[0].style.height = height + 'px';
3937 event = seg.event;
3938 if (seg.contentTop !== undefined && height - seg.contentTop < 10) {
3939 // not enough room for title, put it in the time (TODO: maybe make both display:inline instead)
3940 eventElement.find('div.fc-event-time')
3941 .text(formatDate(event.start, opt('timeFormat')) + ' - ' + event.title);
3942 eventElement.find('div.fc-event-title')
3943 .remove();
3944 }
3945 trigger('eventAfterRender', event, event, eventElement);
3946 }
3947 }
3948
3949 }
3950
3951
3952 function slotSegHtml(event, seg) {
3953 var html = "<";
3954 var url = event.url;
3955 var skinCss = getSkinCss(event, opt);
3956 var classes = ['fc-event', 'fc-event-vert'];
3957 if (isEventDraggable(event)) {
3958 classes.push('fc-event-draggable');
3959 }
3960 if (seg.isStart) {
3961 classes.push('fc-event-start');
3962 }
3963 if (seg.isEnd) {
3964 classes.push('fc-event-end');
3965 }
3966 classes = classes.concat(event.className);
3967 if (event.source) {
3968 classes = classes.concat(event.source.className || []);
3969 }
3970 if (url) {
3971 html += "a href='" + htmlEscape(event.url) + "'";
3972 }else{
3973 html += "div";
3974 }
3975 html +=
3976 " class='" + classes.join(' ') + "'" +
3977 " style=" +
3978 "'" +
3979 "position:absolute;" +
3980 "top:" + seg.top + "px;" +
3981 "left:" + seg.left + "px;" +
3982 skinCss +
3983 "'" +
3984 ">" +
3985 "<div class='fc-event-inner'>" +
3986 "<div class='fc-event-time'>" +
3987 htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
3988 "</div>" +
3989 "<div class='fc-event-title'>" +
3990 htmlEscape(event.title || '') +
3991 "</div>" +
3992 "</div>" +
3993 "<div class='fc-event-bg'></div>";
3994 if (seg.isEnd && isEventResizable(event)) {
3995 html +=
3996 "<div class='ui-resizable-handle ui-resizable-s'>=</div>";
3997 }
3998 html +=
3999 "</" + (url ? "a" : "div") + ">";
4000 return html;
4001 }
4002
4003
4004 function bindSlotSeg(event, eventElement, seg) {
4005 var timeElement = eventElement.find('div.fc-event-time');
4006 if (isEventDraggable(event)) {
4007 draggableSlotEvent(event, eventElement, timeElement);
4008 }
4009 if (seg.isEnd && isEventResizable(event)) {
4010 resizableSlotEvent(event, eventElement, timeElement);
4011 }
4012 eventElementHandlers(event, eventElement);
4013 }
4014
4015
4016
4017 /* Dragging
4018 -----------------------------------------------------------------------------------*/
4019
4020
4021 // when event starts out FULL-DAY
4022 // overrides DayEventRenderer's version because it needs to account for dragging elements
4023 // to and from the slot area.
4024
4025 function draggableDayEvent(event, eventElement, seg) {
4026 var isStart = seg.isStart;
4027 var origWidth;
4028 var revert;
4029 var allDay = true;
4030 var dayDelta;
4031 var hoverListener = getHoverListener();
4032 var colWidth = getColWidth();
4033 var snapHeight = getSnapHeight();
4034 var snapMinutes = getSnapMinutes();
4035 var minMinute = getMinMinute();
4036 eventElement.draggable({
4037 opacity: opt('dragOpacity', 'month'), // use whatever the month view was using
4038 revertDuration: opt('dragRevertDuration'),
4039 start: function(ev, ui) {
4040 trigger('eventDragStart', eventElement, event, ev, ui);
4041 hideEvents(event, eventElement);
4042 origWidth = eventElement.width();
4043 hoverListener.start(function(cell, origCell) {
4044 clearOverlays();
4045 if (cell) {
4046 revert = false;
4047 var origDate = cellToDate(0, origCell.col);
4048 var date = cellToDate(0, cell.col);
4049 dayDelta = dayDiff(date, origDate);
4050 if (!cell.row) {
4051 // on full-days
4052 renderDayOverlay(
4053 addDays(cloneDate(event.start), dayDelta),
4054 addDays(exclEndDay(event), dayDelta)
4055 );
4056 resetElement();
4057 }else{
4058 // mouse is over bottom slots
4059 if (isStart) {
4060 if (allDay) {
4061 // convert event to temporary slot-event
4062 eventElement.width(colWidth - 10); // don't use entire width
4063 setOuterHeight(
4064 eventElement,
4065 snapHeight * Math.round(
4066 (event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes')) /
4067 snapMinutes
4068 )
4069 );
4070 eventElement.draggable('option', 'grid', [colWidth, 1]);
4071 allDay = false;
4072 }
4073 }else{
4074 revert = true;
4075 }
4076 }
4077 revert = revert || (allDay && !dayDelta);
4078 }else{
4079 resetElement();
4080 revert = true;
4081 }
4082 eventElement.draggable('option', 'revert', revert);
4083 }, ev, 'drag');
4084 },
4085 stop: function(ev, ui) {
4086 hoverListener.stop();
4087 clearOverlays();
4088 trigger('eventDragStop', eventElement, event, ev, ui);
4089 if (revert) {
4090 // hasn't moved or is out of bounds (draggable has already reverted)
4091 resetElement();
4092 eventElement.css('filter', ''); // clear IE opacity side-effects
4093 showEvents(event, eventElement);
4094 }else{
4095 // changed!
4096 var minuteDelta = 0;
4097 if (!allDay) {
4098 minuteDelta = Math.round((eventElement.offset().top - getSlotContainer().offset().top) / snapHeight)
4099 * snapMinutes
4100 + minMinute
4101 - (event.start.getHours() * 60 + event.start.getMinutes());
4102 }
4103 eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);
4104 }
4105 }
4106 });
4107 function resetElement() {
4108 if (!allDay) {
4109 eventElement
4110 .width(origWidth)
4111 .height('')
4112 .draggable('option', 'grid', null);
4113 allDay = true;
4114 }
4115 }
4116 }
4117
4118
4119 // when event starts out IN TIMESLOTS
4120
4121 function draggableSlotEvent(event, eventElement, timeElement) {
4122 var coordinateGrid = t.getCoordinateGrid();
4123 var colCnt = getColCnt();
4124 var colWidth = getColWidth();
4125 var snapHeight = getSnapHeight();
4126 var snapMinutes = getSnapMinutes();
4127
4128 // states
4129 var origPosition; // original position of the element, not the mouse
4130 var origCell;
4131 var isInBounds, prevIsInBounds;
4132 var isAllDay, prevIsAllDay;
4133 var colDelta, prevColDelta;
4134 var dayDelta; // derived from colDelta
4135 var minuteDelta, prevMinuteDelta;
4136
4137 eventElement.draggable({
4138 scroll: false,
4139 grid: [ colWidth, snapHeight ],
4140 axis: colCnt==1 ? 'y' : false,
4141 opacity: opt('dragOpacity'),
4142 revertDuration: opt('dragRevertDuration'),
4143 start: function(ev, ui) {
4144
4145 trigger('eventDragStart', eventElement, event, ev, ui);
4146 hideEvents(event, eventElement);
4147
4148 coordinateGrid.build();
4149
4150 // initialize states
4151 origPosition = eventElement.position();
4152 origCell = coordinateGrid.cell(ev.pageX, ev.pageY);
4153 isInBounds = prevIsInBounds = true;
4154 isAllDay = prevIsAllDay = getIsCellAllDay(origCell);
4155 colDelta = prevColDelta = 0;
4156 dayDelta = 0;
4157 minuteDelta = prevMinuteDelta = 0;
4158
4159 },
4160 drag: function(ev, ui) {
4161
4162 // NOTE: this `cell` value is only useful for determining in-bounds and all-day.
4163 // Bad for anything else due to the discrepancy between the mouse position and the
4164 // element position while snapping. (problem revealed in PR #55)
4165 //
4166 // PS- the problem exists for draggableDayEvent() when dragging an all-day event to a slot event.
4167 // We should overhaul the dragging system and stop relying on jQuery UI.
4168 var cell = coordinateGrid.cell(ev.pageX, ev.pageY);
4169
4170 // update states
4171 isInBounds = !!cell;
4172 if (isInBounds) {
4173 isAllDay = getIsCellAllDay(cell);
4174
4175 // calculate column delta
4176 colDelta = Math.round((ui.position.left - origPosition.left) / colWidth);
4177 if (colDelta != prevColDelta) {
4178 // calculate the day delta based off of the original clicked column and the column delta
4179 var origDate = cellToDate(0, origCell.col);
4180 var col = origCell.col + colDelta;
4181 col = Math.max(0, col);
4182 col = Math.min(colCnt-1, col);
4183 var date = cellToDate(0, col);
4184 dayDelta = dayDiff(date, origDate);
4185 }
4186
4187 // calculate minute delta (only if over slots)
4188 if (!isAllDay) {
4189 minuteDelta = Math.round((ui.position.top - origPosition.top) / snapHeight) * snapMinutes;
4190 }
4191 }
4192
4193 // any state changes?
4194 if (
4195 isInBounds != prevIsInBounds ||
4196 isAllDay != prevIsAllDay ||
4197 colDelta != prevColDelta ||
4198 minuteDelta != prevMinuteDelta
4199 ) {
4200
4201 updateUI();
4202
4203 // update previous states for next time
4204 prevIsInBounds = isInBounds;
4205 prevIsAllDay = isAllDay;
4206 prevColDelta = colDelta;
4207 prevMinuteDelta = minuteDelta;
4208 }
4209
4210 // if out-of-bounds, revert when done, and vice versa.
4211 eventElement.draggable('option', 'revert', !isInBounds);
4212
4213 },
4214 stop: function(ev, ui) {
4215
4216 clearOverlays();
4217 trigger('eventDragStop', eventElement, event, ev, ui);
4218
4219 if (isInBounds && (isAllDay || dayDelta || minuteDelta)) { // changed!
4220 eventDrop(this, event, dayDelta, isAllDay ? 0 : minuteDelta, isAllDay, ev, ui);
4221 }
4222 else { // either no change or out-of-bounds (draggable has already reverted)
4223
4224 // reset states for next time, and for updateUI()
4225 isInBounds = true;
4226 isAllDay = false;
4227 colDelta = 0;
4228 dayDelta = 0;
4229 minuteDelta = 0;
4230
4231 updateUI();
4232 eventElement.css('filter', ''); // clear IE opacity side-effects
4233
4234 // sometimes fast drags make event revert to wrong position, so reset.
4235 // also, if we dragged the element out of the area because of snapping,
4236 // but the *mouse* is still in bounds, we need to reset the position.
4237 eventElement.css(origPosition);
4238
4239 showEvents(event, eventElement);
4240 }
4241 }
4242 });
4243
4244 function updateUI() {
4245 clearOverlays();
4246 if (isInBounds) {
4247 if (isAllDay) {
4248 timeElement.hide();
4249 eventElement.draggable('option', 'grid', null); // disable grid snapping
4250 renderDayOverlay(
4251 addDays(cloneDate(event.start), dayDelta),
4252 addDays(exclEndDay(event), dayDelta)
4253 );
4254 }
4255 else {
4256 updateTimeText(minuteDelta);
4257 timeElement.css('display', ''); // show() was causing display=inline
4258 eventElement.draggable('option', 'grid', [colWidth, snapHeight]); // re-enable grid snapping
4259 }
4260 }
4261 }
4262
4263 function updateTimeText(minuteDelta) {
4264 var newStart = addMinutes(cloneDate(event.start), minuteDelta);
4265 var newEnd;
4266 if (event.end) {
4267 newEnd = addMinutes(cloneDate(event.end), minuteDelta);
4268 }
4269 timeElement.text(formatDates(newStart, newEnd, opt('timeFormat')));
4270 }
4271
4272 }
4273
4274
4275
4276 /* Resizing
4277 --------------------------------------------------------------------------------------*/
4278
4279
4280 function resizableSlotEvent(event, eventElement, timeElement) {
4281 var snapDelta, prevSnapDelta;
4282 var snapHeight = getSnapHeight();
4283 var snapMinutes = getSnapMinutes();
4284 eventElement.resizable({
4285 handles: {
4286 s: '.ui-resizable-handle'
4287 },
4288 grid: snapHeight,
4289 start: function(ev, ui) {
4290 snapDelta = prevSnapDelta = 0;
4291 hideEvents(event, eventElement);
4292 trigger('eventResizeStart', this, event, ev, ui);
4293 },
4294 resize: function(ev, ui) {
4295 // don't rely on ui.size.height, doesn't take grid into account
4296 snapDelta = Math.round((Math.max(snapHeight, eventElement.height()) - ui.originalSize.height) / snapHeight);
4297 if (snapDelta != prevSnapDelta) {
4298 timeElement.text(
4299 formatDates(
4300 event.start,
4301 (!snapDelta && !event.end) ? null : // no change, so don't display time range
4302 addMinutes(eventEnd(event), snapMinutes*snapDelta),
4303 opt('timeFormat')
4304 )
4305 );
4306 prevSnapDelta = snapDelta;
4307 }
4308 },
4309 stop: function(ev, ui) {
4310 trigger('eventResizeStop', this, event, ev, ui);
4311 if (snapDelta) {
4312 eventResize(this, event, 0, snapMinutes*snapDelta, ev, ui);
4313 }else{
4314 showEvents(event, eventElement);
4315 // BUG: if event was really short, need to put title back in span
4316 }
4317 }
4318 });
4319 }
4320
4321
4322}
4323
4324
4325
4326/* Agenda Event Segment Utilities
4327-----------------------------------------------------------------------------*/
4328
4329
4330// Sets the seg.backwardCoord and seg.forwardCoord on each segment and returns a new
4331// list in the order they should be placed into the DOM (an implicit z-index).
4332function placeSlotSegs(segs) {
4333 var levels = buildSlotSegLevels(segs);
4334 var level0 = levels[0];
4335 var i;
4336
4337 computeForwardSlotSegs(levels);
4338
4339 if (level0) {
4340
4341 for (i=0; i<level0.length; i++) {
4342 computeSlotSegPressures(level0[i]);
4343 }
4344
4345 for (i=0; i<level0.length; i++) {
4346 computeSlotSegCoords(level0[i], 0, 0);
4347 }
4348 }
4349
4350 return flattenSlotSegLevels(levels);
4351}
4352
4353
4354// Builds an array of segments "levels". The first level will be the leftmost tier of segments
4355// if the calendar is left-to-right, or the rightmost if the calendar is right-to-left.
4356function buildSlotSegLevels(segs) {
4357 var levels = [];
4358 var i, seg;
4359 var j;
4360
4361 for (i=0; i<segs.length; i++) {
4362 seg = segs[i];
4363
4364 // go through all the levels and stop on the first level where there are no collisions
4365 for (j=0; j<levels.length; j++) {
4366 if (!computeSlotSegCollisions(seg, levels[j]).length) {
4367 break;
4368 }
4369 }
4370
4371 (levels[j] || (levels[j] = [])).push(seg);
4372 }
4373
4374 return levels;
4375}
4376
4377
4378// For every segment, figure out the other segments that are in subsequent
4379// levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
4380function computeForwardSlotSegs(levels) {
4381 var i, level;
4382 var j, seg;
4383 var k;
4384
4385 for (i=0; i<levels.length; i++) {
4386 level = levels[i];
4387
4388 for (j=0; j<level.length; j++) {
4389 seg = level[j];
4390
4391 seg.forwardSegs = [];
4392 for (k=i+1; k<levels.length; k++) {
4393 computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
4394 }
4395 }
4396 }
4397}
4398
4399
4400// Figure out which path forward (via seg.forwardSegs) results in the longest path until
4401// the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
4402function computeSlotSegPressures(seg) {
4403 var forwardSegs = seg.forwardSegs;
4404 var forwardPressure = 0;
4405 var i, forwardSeg;
4406
4407 if (seg.forwardPressure === undefined) { // not already computed
4408
4409 for (i=0; i<forwardSegs.length; i++) {
4410 forwardSeg = forwardSegs[i];
4411
4412 // figure out the child's maximum forward path
4413 computeSlotSegPressures(forwardSeg);
4414
4415 // either use the existing maximum, or use the child's forward pressure
4416 // plus one (for the forwardSeg itself)
4417 forwardPressure = Math.max(
4418 forwardPressure,
4419 1 + forwardSeg.forwardPressure
4420 );
4421 }
4422
4423 seg.forwardPressure = forwardPressure;
4424 }
4425}
4426
4427
4428// Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
4429// from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
4430// seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
4431//
4432// The segment might be part of a "series", which means consecutive segments with the same pressure
4433// who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
4434// segments behind this one in the current series, and `seriesBackwardCoord` is the starting
4435// coordinate of the first segment in the series.
4436function computeSlotSegCoords(seg, seriesBackwardPressure, seriesBackwardCoord) {
4437 var forwardSegs = seg.forwardSegs;
4438 var i;
4439
4440 if (seg.forwardCoord === undefined) { // not already computed
4441
4442 if (!forwardSegs.length) {
4443
4444 // if there are no forward segments, this segment should butt up against the edge
4445 seg.forwardCoord = 1;
4446 }
4447 else {
4448
4449 // sort highest pressure first
4450 forwardSegs.sort(compareForwardSlotSegs);
4451
4452 // this segment's forwardCoord will be calculated from the backwardCoord of the
4453 // highest-pressure forward segment.
4454 computeSlotSegCoords(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
4455 seg.forwardCoord = forwardSegs[0].backwardCoord;
4456 }
4457
4458 // calculate the backwardCoord from the forwardCoord. consider the series
4459 seg.backwardCoord = seg.forwardCoord -
4460 (seg.forwardCoord - seriesBackwardCoord) / // available width for series
4461 (seriesBackwardPressure + 1); // # of segments in the series
4462
4463 // use this segment's coordinates to computed the coordinates of the less-pressurized
4464 // forward segments
4465 for (i=0; i<forwardSegs.length; i++) {
4466 computeSlotSegCoords(forwardSegs[i], 0, seg.forwardCoord);
4467 }
4468 }
4469}
4470
4471
4472// Outputs a flat array of segments, from lowest to highest level
4473function flattenSlotSegLevels(levels) {
4474 var segs = [];
4475 var i, level;
4476 var j;
4477
4478 for (i=0; i<levels.length; i++) {
4479 level = levels[i];
4480
4481 for (j=0; j<level.length; j++) {
4482 segs.push(level[j]);
4483 }
4484 }
4485
4486 return segs;
4487}
4488
4489
4490// Find all the segments in `otherSegs` that vertically collide with `seg`.
4491// Append into an optionally-supplied `results` array and return.
4492function computeSlotSegCollisions(seg, otherSegs, results) {
4493 results = results || [];
4494
4495 for (var i=0; i<otherSegs.length; i++) {
4496 if (isSlotSegCollision(seg, otherSegs[i])) {
4497 results.push(otherSegs[i]);
4498 }
4499 }
4500
4501 return results;
4502}
4503
4504
4505// Do these segments occupy the same vertical space?
4506function isSlotSegCollision(seg1, seg2) {
4507 return seg1.end > seg2.start && seg1.start < seg2.end;
4508}
4509
4510
4511// A cmp function for determining which forward segment to rely on more when computing coordinates.
4512function compareForwardSlotSegs(seg1, seg2) {
4513 // put higher-pressure first
4514 return seg2.forwardPressure - seg1.forwardPressure ||
4515 // put segments that are closer to initial edge first (and favor ones with no coords yet)
4516 (seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
4517 // do normal sorting...
4518 compareSlotSegs(seg1, seg2);
4519}
4520
4521
4522// A cmp function for determining which segment should be closer to the initial edge
4523// (the left edge on a left-to-right calendar).
4524function compareSlotSegs(seg1, seg2) {
4525 return seg1.start - seg2.start || // earlier start time goes first
4526 (seg2.end - seg2.start) - (seg1.end - seg1.start) || // tie? longer-duration goes first
4527 (seg1.event.title || '').localeCompare(seg2.event.title); // tie? alphabetically by title
4528}
4529
4530
4531;;
4532
4533
4534function View(element, calendar, viewName) {
4535 var t = this;
4536
4537
4538 // exports
4539 t.element = element;
4540 t.calendar = calendar;
4541 t.name = viewName;
4542 t.opt = opt;
4543 t.trigger = trigger;
4544 t.isEventDraggable = isEventDraggable;
4545 t.isEventResizable = isEventResizable;
4546 t.setEventData = setEventData;
4547 t.clearEventData = clearEventData;
4548 t.eventEnd = eventEnd;
4549 t.reportEventElement = reportEventElement;
4550 t.triggerEventDestroy = triggerEventDestroy;
4551 t.eventElementHandlers = eventElementHandlers;
4552 t.showEvents = showEvents;
4553 t.hideEvents = hideEvents;
4554 t.eventDrop = eventDrop;
4555 t.eventResize = eventResize;
4556 // t.title
4557 // t.start, t.end
4558 // t.visStart, t.visEnd
4559
4560
4561 // imports
4562 var defaultEventEnd = t.defaultEventEnd;
4563 var normalizeEvent = calendar.normalizeEvent; // in EventManager
4564 var reportEventChange = calendar.reportEventChange;
4565
4566
4567 // locals
4568 var eventsByID = {}; // eventID mapped to array of events (there can be multiple b/c of repeating events)
4569 var eventElementsByID = {}; // eventID mapped to array of jQuery elements
4570 var eventElementCouples = []; // array of objects, { event, element } // TODO: unify with segment system
4571 var options = calendar.options;
4572
4573
4574
4575 function opt(name, viewNameOverride) {
4576 var v = options[name];
4577 if ($.isPlainObject(v)) {
4578 return smartProperty(v, viewNameOverride || viewName);
4579 }
4580 return v;
4581 }
4582
4583
4584 function trigger(name, thisObj) {
4585 return calendar.trigger.apply(
4586 calendar,
4587 [name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t])
4588 );
4589 }
4590
4591
4592
4593 /* Event Editable Boolean Calculations
4594 ------------------------------------------------------------------------------*/
4595
4596
4597 function isEventDraggable(event) {
4598 var source = event.source || {};
4599 return firstDefined(
4600 event.startEditable,
4601 source.startEditable,
4602 opt('eventStartEditable'),
4603 event.editable,
4604 source.editable,
4605 opt('editable')
4606 )
4607 && !opt('disableDragging'); // deprecated
4608 }
4609
4610
4611 function isEventResizable(event) { // but also need to make sure the seg.isEnd == true
4612 var source = event.source || {};
4613 return firstDefined(
4614 event.durationEditable,
4615 source.durationEditable,
4616 opt('eventDurationEditable'),
4617 event.editable,
4618 source.editable,
4619 opt('editable')
4620 )
4621 && !opt('disableResizing'); // deprecated
4622 }
4623
4624
4625
4626 /* Event Data
4627 ------------------------------------------------------------------------------*/
4628
4629
4630 function setEventData(events) { // events are already normalized at this point
4631 eventsByID = {};
4632 var i, len=events.length, event;
4633 for (i=0; i<len; i++) {
4634 event = events[i];
4635 if (eventsByID[event._id]) {
4636 eventsByID[event._id].push(event);
4637 }else{
4638 eventsByID[event._id] = [event];
4639 }
4640 }
4641 }
4642
4643
4644 function clearEventData() {
4645 eventsByID = {};
4646 eventElementsByID = {};
4647 eventElementCouples = [];
4648 }
4649
4650
4651 // returns a Date object for an event's end
4652 function eventEnd(event) {
4653 return event.end ? cloneDate(event.end) : defaultEventEnd(event);
4654 }
4655
4656
4657
4658 /* Event Elements
4659 ------------------------------------------------------------------------------*/
4660
4661
4662 // report when view creates an element for an event
4663 function reportEventElement(event, element) {
4664 eventElementCouples.push({ event: event, element: element });
4665 if (eventElementsByID[event._id]) {
4666 eventElementsByID[event._id].push(element);
4667 }else{
4668 eventElementsByID[event._id] = [element];
4669 }
4670 }
4671
4672
4673 function triggerEventDestroy() {
4674 $.each(eventElementCouples, function(i, couple) {
4675 t.trigger('eventDestroy', couple.event, couple.event, couple.element);
4676 });
4677 }
4678
4679
4680 // attaches eventClick, eventMouseover, eventMouseout
4681 function eventElementHandlers(event, eventElement) {
4682 eventElement
4683 .click(function(ev) {
4684 if (!eventElement.hasClass('ui-draggable-dragging') &&
4685 !eventElement.hasClass('ui-resizable-resizing')) {
4686 return trigger('eventClick', this, event, ev);
4687 }
4688 })
4689 .hover(
4690 function(ev) {
4691 trigger('eventMouseover', this, event, ev);
4692 },
4693 function(ev) {
4694 trigger('eventMouseout', this, event, ev);
4695 }
4696 );
4697 // TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
4698 // TODO: same for resizing
4699 }
4700
4701
4702 function showEvents(event, exceptElement) {
4703 eachEventElement(event, exceptElement, 'show');
4704 }
4705
4706
4707 function hideEvents(event, exceptElement) {
4708 eachEventElement(event, exceptElement, 'hide');
4709 }
4710
4711
4712 function eachEventElement(event, exceptElement, funcName) {
4713 // NOTE: there may be multiple events per ID (repeating events)
4714 // and multiple segments per event
4715 var elements = eventElementsByID[event._id],
4716 i, len = elements.length;
4717 for (i=0; i<len; i++) {
4718 if (!exceptElement || elements[i][0] != exceptElement[0]) {
4719 elements[i][funcName]();
4720 }
4721 }
4722 }
4723
4724
4725
4726 /* Event Modification Reporting
4727 ---------------------------------------------------------------------------------*/
4728
4729
4730 function eventDrop(e, event, dayDelta, minuteDelta, allDay, ev, ui) {
4731 var oldAllDay = event.allDay;
4732 var eventId = event._id;
4733 moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay);
4734 trigger(
4735 'eventDrop',
4736 e,
4737 event,
4738 dayDelta,
4739 minuteDelta,
4740 allDay,
4741 function() {
4742 // TODO: investigate cases where this inverse technique might not work
4743 moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay);
4744 reportEventChange(eventId);
4745 },
4746 ev,
4747 ui
4748 );
4749 reportEventChange(eventId);
4750 }
4751
4752
4753 function eventResize(e, event, dayDelta, minuteDelta, ev, ui) {
4754 var eventId = event._id;
4755 elongateEvents(eventsByID[eventId], dayDelta, minuteDelta);
4756 trigger(
4757 'eventResize',
4758 e,
4759 event,
4760 dayDelta,
4761 minuteDelta,
4762 function() {
4763 // TODO: investigate cases where this inverse technique might not work
4764 elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta);
4765 reportEventChange(eventId);
4766 },
4767 ev,
4768 ui
4769 );
4770 reportEventChange(eventId);
4771 }
4772
4773
4774
4775 /* Event Modification Math
4776 ---------------------------------------------------------------------------------*/
4777
4778
4779 function moveEvents(events, dayDelta, minuteDelta, allDay) {
4780 minuteDelta = minuteDelta || 0;
4781 for (var e, len=events.length, i=0; i<len; i++) {
4782 e = events[i];
4783 if (allDay !== undefined) {
4784 e.allDay = allDay;
4785 }
4786 addMinutes(addDays(e.start, dayDelta, true), minuteDelta);
4787 if (e.end) {
4788 e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta);
4789 }
4790 normalizeEvent(e, options);
4791 }
4792 }
4793
4794
4795 function elongateEvents(events, dayDelta, minuteDelta) {
4796 minuteDelta = minuteDelta || 0;
4797 for (var e, len=events.length, i=0; i<len; i++) {
4798 e = events[i];
4799 e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta);
4800 normalizeEvent(e, options);
4801 }
4802 }
4803
4804
4805
4806 // ====================================================================================================
4807 // Utilities for day "cells"
4808 // ====================================================================================================
4809 // The "basic" views are completely made up of day cells.
4810 // The "agenda" views have day cells at the top "all day" slot.
4811 // This was the obvious common place to put these utilities, but they should be abstracted out into
4812 // a more meaningful class (like DayEventRenderer).
4813 // ====================================================================================================
4814
4815
4816 // For determining how a given "cell" translates into a "date":
4817 //
4818 // 1. Convert the "cell" (row and column) into a "cell offset" (the # of the cell, cronologically from the first).
4819 // Keep in mind that column indices are inverted with isRTL. This is taken into account.
4820 //
4821 // 2. Convert the "cell offset" to a "day offset" (the # of days since the first visible day in the view).
4822 //
4823 // 3. Convert the "day offset" into a "date" (a JavaScript Date object).
4824 //
4825 // The reverse transformation happens when transforming a date into a cell.
4826
4827
4828 // exports
4829 t.isHiddenDay = isHiddenDay;
4830 t.skipHiddenDays = skipHiddenDays;
4831 t.getCellsPerWeek = getCellsPerWeek;
4832 t.dateToCell = dateToCell;
4833 t.dateToDayOffset = dateToDayOffset;
4834 t.dayOffsetToCellOffset = dayOffsetToCellOffset;
4835 t.cellOffsetToCell = cellOffsetToCell;
4836 t.cellToDate = cellToDate;
4837 t.cellToCellOffset = cellToCellOffset;
4838 t.cellOffsetToDayOffset = cellOffsetToDayOffset;
4839 t.dayOffsetToDate = dayOffsetToDate;
4840 t.rangeToSegments = rangeToSegments;
4841
4842
4843 // internals
4844 var hiddenDays = opt('hiddenDays') || []; // array of day-of-week indices that are hidden
4845 var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
4846 var cellsPerWeek;
4847 var dayToCellMap = []; // hash from dayIndex -> cellIndex, for one week
4848 var cellToDayMap = []; // hash from cellIndex -> dayIndex, for one week
4849 var isRTL = opt('isRTL');
4850
4851
4852 // initialize important internal variables
4853 (function() {
4854
4855 if (opt('weekends') === false) {
4856 hiddenDays.push(0, 6); // 0=sunday, 6=saturday
4857 }
4858
4859 // Loop through a hypothetical week and determine which
4860 // days-of-week are hidden. Record in both hashes (one is the reverse of the other).
4861 for (var dayIndex=0, cellIndex=0; dayIndex<7; dayIndex++) {
4862 dayToCellMap[dayIndex] = cellIndex;
4863 isHiddenDayHash[dayIndex] = $.inArray(dayIndex, hiddenDays) != -1;
4864 if (!isHiddenDayHash[dayIndex]) {
4865 cellToDayMap[cellIndex] = dayIndex;
4866 cellIndex++;
4867 }
4868 }
4869
4870 cellsPerWeek = cellIndex;
4871 if (!cellsPerWeek) {
4872 throw 'invalid hiddenDays'; // all days were hidden? bad.
4873 }
4874
4875 })();
4876
4877
4878 // Is the current day hidden?
4879 // `day` is a day-of-week index (0-6), or a Date object
4880 function isHiddenDay(day) {
4881 if (typeof day == 'object') {
4882 day = day.getDay();
4883 }
4884 return isHiddenDayHash[day];
4885 }
4886
4887
4888 function getCellsPerWeek() {
4889 return cellsPerWeek;
4890 }
4891
4892
4893 // Keep incrementing the current day until it is no longer a hidden day.
4894 // If the initial value of `date` is not a hidden day, don't do anything.
4895 // Pass `isExclusive` as `true` if you are dealing with an end date.
4896 // `inc` defaults to `1` (increment one day forward each time)
4897 function skipHiddenDays(date, inc, isExclusive) {
4898 inc = inc || 1;
4899 while (
4900 isHiddenDayHash[ ( date.getDay() + (isExclusive ? inc : 0) + 7 ) % 7 ]
4901 ) {
4902 addDays(date, inc);
4903 }
4904 }
4905
4906
4907 //
4908 // TRANSFORMATIONS: cell -> cell offset -> day offset -> date
4909 //
4910
4911 // cell -> date (combines all transformations)
4912 // Possible arguments:
4913 // - row, col
4914 // - { row:#, col: # }
4915 function cellToDate() {
4916 var cellOffset = cellToCellOffset.apply(null, arguments);
4917 var dayOffset = cellOffsetToDayOffset(cellOffset);
4918 var date = dayOffsetToDate(dayOffset);
4919 return date;
4920 }
4921
4922 // cell -> cell offset
4923 // Possible arguments:
4924 // - row, col
4925 // - { row:#, col:# }
4926 function cellToCellOffset(row, col) {
4927 var colCnt = t.getColCnt();
4928
4929 // rtl variables. wish we could pre-populate these. but where?
4930 var dis = isRTL ? -1 : 1;
4931 var dit = isRTL ? colCnt - 1 : 0;
4932
4933 if (typeof row == 'object') {
4934 col = row.col;
4935 row = row.row;
4936 }
4937 var cellOffset = row * colCnt + (col * dis + dit); // column, adjusted for RTL (dis & dit)
4938
4939 return cellOffset;
4940 }
4941
4942 // cell offset -> day offset
4943 function cellOffsetToDayOffset(cellOffset) {
4944 var day0 = t.visStart.getDay(); // first date's day of week
4945 cellOffset += dayToCellMap[day0]; // normlize cellOffset to beginning-of-week
4946 return Math.floor(cellOffset / cellsPerWeek) * 7 // # of days from full weeks
4947 + cellToDayMap[ // # of days from partial last week
4948 (cellOffset % cellsPerWeek + cellsPerWeek) % cellsPerWeek // crazy math to handle negative cellOffsets
4949 ]
4950 - day0; // adjustment for beginning-of-week normalization
4951 }
4952
4953 // day offset -> date (JavaScript Date object)
4954 function dayOffsetToDate(dayOffset) {
4955 var date = cloneDate(t.visStart);
4956 addDays(date, dayOffset);
4957 return date;
4958 }
4959
4960
4961 //
4962 // TRANSFORMATIONS: date -> day offset -> cell offset -> cell
4963 //
4964
4965 // date -> cell (combines all transformations)
4966 function dateToCell(date) {
4967 var dayOffset = dateToDayOffset(date);
4968 var cellOffset = dayOffsetToCellOffset(dayOffset);
4969 var cell = cellOffsetToCell(cellOffset);
4970 return cell;
4971 }
4972
4973 // date -> day offset
4974 function dateToDayOffset(date) {
4975 return dayDiff(date, t.visStart);
4976 }
4977
4978 // day offset -> cell offset
4979 function dayOffsetToCellOffset(dayOffset) {
4980 var day0 = t.visStart.getDay(); // first date's day of week
4981 dayOffset += day0; // normalize dayOffset to beginning-of-week
4982 return Math.floor(dayOffset / 7) * cellsPerWeek // # of cells from full weeks
4983 + dayToCellMap[ // # of cells from partial last week
4984 (dayOffset % 7 + 7) % 7 // crazy math to handle negative dayOffsets
4985 ]
4986 - dayToCellMap[day0]; // adjustment for beginning-of-week normalization
4987 }
4988
4989 // cell offset -> cell (object with row & col keys)
4990 function cellOffsetToCell(cellOffset) {
4991 var colCnt = t.getColCnt();
4992
4993 // rtl variables. wish we could pre-populate these. but where?
4994 var dis = isRTL ? -1 : 1;
4995 var dit = isRTL ? colCnt - 1 : 0;
4996
4997 var row = Math.floor(cellOffset / colCnt);
4998 var col = ((cellOffset % colCnt + colCnt) % colCnt) * dis + dit; // column, adjusted for RTL (dis & dit)
4999 return {
5000 row: row,
5001 col: col
5002 };
5003 }
5004
5005
5006 //
5007 // Converts a date range into an array of segment objects.
5008 // "Segments" are horizontal stretches of time, sliced up by row.
5009 // A segment object has the following properties:
5010 // - row
5011 // - cols
5012 // - isStart
5013 // - isEnd
5014 //
5015 function rangeToSegments(startDate, endDate) {
5016 var rowCnt = t.getRowCnt();
5017 var colCnt = t.getColCnt();
5018 var segments = []; // array of segments to return
5019
5020 // day offset for given date range
5021 var rangeDayOffsetStart = dateToDayOffset(startDate);
5022 var rangeDayOffsetEnd = dateToDayOffset(endDate); // exclusive
5023
5024 // first and last cell offset for the given date range
5025 // "last" implies inclusivity
5026 var rangeCellOffsetFirst = dayOffsetToCellOffset(rangeDayOffsetStart);
5027 var rangeCellOffsetLast = dayOffsetToCellOffset(rangeDayOffsetEnd) - 1;
5028
5029 // loop through all the rows in the view
5030 for (var row=0; row<rowCnt; row++) {
5031
5032 // first and last cell offset for the row
5033 var rowCellOffsetFirst = row * colCnt;
5034 var rowCellOffsetLast = rowCellOffsetFirst + colCnt - 1;
5035
5036 // get the segment's cell offsets by constraining the range's cell offsets to the bounds of the row
5037 var segmentCellOffsetFirst = Math.max(rangeCellOffsetFirst, rowCellOffsetFirst);
5038 var segmentCellOffsetLast = Math.min(rangeCellOffsetLast, rowCellOffsetLast);
5039
5040 // make sure segment's offsets are valid and in view
5041 if (segmentCellOffsetFirst <= segmentCellOffsetLast) {
5042
5043 // translate to cells
5044 var segmentCellFirst = cellOffsetToCell(segmentCellOffsetFirst);
5045 var segmentCellLast = cellOffsetToCell(segmentCellOffsetLast);
5046
5047 // view might be RTL, so order by leftmost column
5048 var cols = [ segmentCellFirst.col, segmentCellLast.col ].sort();
5049
5050 // Determine if segment's first/last cell is the beginning/end of the date range.
5051 // We need to compare "day offset" because "cell offsets" are often ambiguous and
5052 // can translate to multiple days, and an edge case reveals itself when we the
5053 // range's first cell is hidden (we don't want isStart to be true).
5054 var isStart = cellOffsetToDayOffset(segmentCellOffsetFirst) == rangeDayOffsetStart;
5055 var isEnd = cellOffsetToDayOffset(segmentCellOffsetLast) + 1 == rangeDayOffsetEnd; // +1 for comparing exclusively
5056
5057 segments.push({
5058 row: row,
5059 leftCol: cols[0],
5060 rightCol: cols[1],
5061 isStart: isStart,
5062 isEnd: isEnd
5063 });
5064 }
5065 }
5066
5067 return segments;
5068 }
5069
5070
5071}
5072
5073;;
5074
5075function DayEventRenderer() {
5076 var t = this;
5077
5078
5079 // exports
5080 t.renderDayEvents = renderDayEvents;
5081 t.draggableDayEvent = draggableDayEvent; // made public so that subclasses can override
5082 t.resizableDayEvent = resizableDayEvent; // "
5083
5084
5085 // imports
5086 var opt = t.opt;
5087 var trigger = t.trigger;
5088 var isEventDraggable = t.isEventDraggable;
5089 var isEventResizable = t.isEventResizable;
5090 var eventEnd = t.eventEnd;
5091 var reportEventElement = t.reportEventElement;
5092 var eventElementHandlers = t.eventElementHandlers;
5093 var showEvents = t.showEvents;
5094 var hideEvents = t.hideEvents;
5095 var eventDrop = t.eventDrop;
5096 var eventResize = t.eventResize;
5097 var getRowCnt = t.getRowCnt;
5098 var getColCnt = t.getColCnt;
5099 var getColWidth = t.getColWidth;
5100 var allDayRow = t.allDayRow; // TODO: rename
5101 var colLeft = t.colLeft;
5102 var colRight = t.colRight;
5103 var colContentLeft = t.colContentLeft;
5104 var colContentRight = t.colContentRight;
5105 var dateToCell = t.dateToCell;
5106 var getDaySegmentContainer = t.getDaySegmentContainer;
5107 var formatDates = t.calendar.formatDates;
5108 var renderDayOverlay = t.renderDayOverlay;
5109 var clearOverlays = t.clearOverlays;
5110 var clearSelection = t.clearSelection;
5111 var getHoverListener = t.getHoverListener;
5112 var rangeToSegments = t.rangeToSegments;
5113 var cellToDate = t.cellToDate;
5114 var cellToCellOffset = t.cellToCellOffset;
5115 var cellOffsetToDayOffset = t.cellOffsetToDayOffset;
5116 var dateToDayOffset = t.dateToDayOffset;
5117 var dayOffsetToCellOffset = t.dayOffsetToCellOffset;
5118
5119
5120 // Render `events` onto the calendar, attach mouse event handlers, and call the `eventAfterRender` callback for each.
5121 // Mouse event will be lazily applied, except if the event has an ID of `modifiedEventId`.
5122 // Can only be called when the event container is empty (because it wipes out all innerHTML).
5123 function renderDayEvents(events, modifiedEventId) {
5124
5125 // do the actual rendering. Receive the intermediate "segment" data structures.
5126 var segments = _renderDayEvents(
5127 events,
5128 false, // don't append event elements
5129 true // set the heights of the rows
5130 );
5131
5132 // report the elements to the View, for general drag/resize utilities
5133 segmentElementEach(segments, function(segment, element) {
5134 reportEventElement(segment.event, element);
5135 });
5136
5137 // attach mouse handlers
5138 attachHandlers(segments, modifiedEventId);
5139
5140 // call `eventAfterRender` callback for each event
5141 segmentElementEach(segments, function(segment, element) {
5142 trigger('eventAfterRender', segment.event, segment.event, element);
5143 });
5144 }
5145
5146
5147 // Render an event on the calendar, but don't report them anywhere, and don't attach mouse handlers.
5148 // Append this event element to the event container, which might already be populated with events.
5149 // If an event's segment will have row equal to `adjustRow`, then explicitly set its top coordinate to `adjustTop`.
5150 // This hack is used to maintain continuity when user is manually resizing an event.
5151 // Returns an array of DOM elements for the event.
5152 function renderTempDayEvent(event, adjustRow, adjustTop) {
5153
5154 // actually render the event. `true` for appending element to container.
5155 // Recieve the intermediate "segment" data structures.
5156 var segments = _renderDayEvents(
5157 [ event ],
5158 true, // append event elements
5159 false // don't set the heights of the rows
5160 );
5161
5162 var elements = [];
5163
5164 // Adjust certain elements' top coordinates
5165 segmentElementEach(segments, function(segment, element) {
5166 if (segment.row === adjustRow) {
5167 element.css('top', adjustTop);
5168 }
5169 elements.push(element[0]); // accumulate DOM nodes
5170 });
5171
5172 return elements;
5173 }
5174
5175
5176 // Render events onto the calendar. Only responsible for the VISUAL aspect.
5177 // Not responsible for attaching handlers or calling callbacks.
5178 // Set `doAppend` to `true` for rendering elements without clearing the existing container.
5179 // Set `doRowHeights` to allow setting the height of each row, to compensate for vertical event overflow.
5180 function _renderDayEvents(events, doAppend, doRowHeights) {
5181
5182 // where the DOM nodes will eventually end up
5183 var finalContainer = getDaySegmentContainer();
5184
5185 // the container where the initial HTML will be rendered.
5186 // If `doAppend`==true, uses a temporary container.
5187 var renderContainer = doAppend ? $("<div/>") : finalContainer;
5188
5189 var segments = buildSegments(events);
5190 var html;
5191 var elements;
5192
5193 // calculate the desired `left` and `width` properties on each segment object
5194 calculateHorizontals(segments);
5195
5196 // build the HTML string. relies on `left` property
5197 html = buildHTML(segments);
5198
5199 // render the HTML. innerHTML is considerably faster than jQuery's .html()
5200 renderContainer[0].innerHTML = html;
5201
5202 // retrieve the individual elements
5203 elements = renderContainer.children();
5204
5205 // if we were appending, and thus using a temporary container,
5206 // re-attach elements to the real container.
5207 if (doAppend) {
5208 finalContainer.append(elements);
5209 }
5210
5211 // assigns each element to `segment.event`, after filtering them through user callbacks
5212 resolveElements(segments, elements);
5213
5214 // Calculate the left and right padding+margin for each element.
5215 // We need this for setting each element's desired outer width, because of the W3C box model.
5216 // It's important we do this in a separate pass from acually setting the width on the DOM elements
5217 // because alternating reading/writing dimensions causes reflow for every iteration.
5218 segmentElementEach(segments, function(segment, element) {
5219 segment.hsides = hsides(element, true); // include margins = `true`
5220 });
5221
5222 // Set the width of each element
5223 segmentElementEach(segments, function(segment, element) {
5224 element.width(
5225 Math.max(0, segment.outerWidth - segment.hsides)
5226 );
5227 });
5228
5229 // Grab each element's outerHeight (setVerticals uses this).
5230 // To get an accurate reading, it's important to have each element's width explicitly set already.
5231 segmentElementEach(segments, function(segment, element) {
5232 segment.outerHeight = element.outerHeight(true); // include margins = `true`
5233 });
5234
5235 // Set the top coordinate on each element (requires segment.outerHeight)
5236 setVerticals(segments, doRowHeights);
5237
5238 return segments;
5239 }
5240
5241
5242 // Generate an array of "segments" for all events.
5243 function buildSegments(events) {
5244 var segments = [];
5245 for (var i=0; i<events.length; i++) {
5246 var eventSegments = buildSegmentsForEvent(events[i]);
5247 segments.push.apply(segments, eventSegments); // append an array to an array
5248 }
5249 return segments;
5250 }
5251
5252
5253 // Generate an array of segments for a single event.
5254 // A "segment" is the same data structure that View.rangeToSegments produces,
5255 // with the addition of the `event` property being set to reference the original event.
5256 function buildSegmentsForEvent(event) {
5257 var startDate = event.start;
5258 var endDate = exclEndDay(event);
5259 var segments = rangeToSegments(startDate, endDate);
5260 for (var i=0; i<segments.length; i++) {
5261 segments[i].event = event;
5262 }
5263 return segments;
5264 }
5265
5266
5267 // Sets the `left` and `outerWidth` property of each segment.
5268 // These values are the desired dimensions for the eventual DOM elements.
5269 function calculateHorizontals(segments) {
5270 var isRTL = opt('isRTL');
5271 for (var i=0; i<segments.length; i++) {
5272 var segment = segments[i];
5273
5274 // Determine functions used for calulating the elements left/right coordinates,
5275 // depending on whether the view is RTL or not.
5276 // NOTE:
5277 // colLeft/colRight returns the coordinate butting up the edge of the cell.
5278 // colContentLeft/colContentRight is indented a little bit from the edge.
5279 var leftFunc = (isRTL ? segment.isEnd : segment.isStart) ? colContentLeft : colLeft;
5280 var rightFunc = (isRTL ? segment.isStart : segment.isEnd) ? colContentRight : colRight;
5281
5282 var left = leftFunc(segment.leftCol);
5283 var right = rightFunc(segment.rightCol);
5284 segment.left = left;
5285 segment.outerWidth = right - left;
5286 }
5287 }
5288
5289
5290 // Build a concatenated HTML string for an array of segments
5291 function buildHTML(segments) {
5292 var html = '';
5293 for (var i=0; i<segments.length; i++) {
5294 html += buildHTMLForSegment(segments[i]);
5295 }
5296 return html;
5297 }
5298
5299
5300 // Build an HTML string for a single segment.
5301 // Relies on the following properties:
5302 // - `segment.event` (from `buildSegmentsForEvent`)
5303 // - `segment.left` (from `calculateHorizontals`)
5304 function buildHTMLForSegment(segment) {
5305 var html = '';
5306 var isRTL = opt('isRTL');
5307 var event = segment.event;
5308 var url = event.url;
5309
5310 // generate the list of CSS classNames
5311 var classNames = [ 'fc-event', 'fc-event-hori' ];
5312 if (isEventDraggable(event)) {
5313 classNames.push('fc-event-draggable');
5314 }
5315 if (segment.isStart) {
5316 classNames.push('fc-event-start');
5317 }
5318 if (segment.isEnd) {
5319 classNames.push('fc-event-end');
5320 }
5321 // use the event's configured classNames
5322 // guaranteed to be an array via `normalizeEvent`
5323 classNames = classNames.concat(event.className);
5324 if (event.source) {
5325 // use the event's source's classNames, if specified
5326 classNames = classNames.concat(event.source.className || []);
5327 }
5328
5329 // generate a semicolon delimited CSS string for any of the "skin" properties
5330 // of the event object (`backgroundColor`, `borderColor` and such)
5331 var skinCss = getSkinCss(event, opt);
5332
5333 if (url) {
5334 html += "<a href='" + htmlEscape(url) + "'";
5335 }else{
5336 html += "<div";
5337 }
5338 html +=
5339 " class='" + classNames.join(' ') + "'" +
5340 " style=" +
5341 "'" +
5342 "position:absolute;" +
5343 "left:" + segment.left + "px;" +
5344 skinCss +
5345 "'" +
5346 ">" +
5347 "<div class='fc-event-inner'>";
5348 if (!event.allDay && segment.isStart) {
5349 html +=
5350 "<span class='fc-event-time'>" +
5351 htmlEscape(
5352 formatDates(event.start, event.end, opt('timeFormat'))
5353 ) +
5354 "</span>";
5355 }
5356 html +=
5357 "<span class='fc-event-title'>" +
5358 htmlEscape(event.title || '') +
5359 "</span>" +
5360 "</div>";
5361 if (segment.isEnd && isEventResizable(event)) {
5362 html +=
5363 "<div class='ui-resizable-handle ui-resizable-" + (isRTL ? 'w' : 'e') + "'>" +
5364 "&nbsp;&nbsp;&nbsp;" + // makes hit area a lot better for IE6/7
5365 "</div>";
5366 }
5367 html += "</" + (url ? "a" : "div") + ">";
5368
5369 // TODO:
5370 // When these elements are initially rendered, they will be briefly visibile on the screen,
5371 // even though their widths/heights are not set.
5372 // SOLUTION: initially set them as visibility:hidden ?
5373
5374 return html;
5375 }
5376
5377
5378 // Associate each segment (an object) with an element (a jQuery object),
5379 // by setting each `segment.element`.
5380 // Run each element through the `eventRender` filter, which allows developers to
5381 // modify an existing element, supply a new one, or cancel rendering.
5382 function resolveElements(segments, elements) {
5383 for (var i=0; i<segments.length; i++) {
5384 var segment = segments[i];
5385 var event = segment.event;
5386 var element = elements.eq(i);
5387
5388 // call the trigger with the original element
5389 var triggerRes = trigger('eventRender', event, event, element);
5390
5391 if (triggerRes === false) {
5392 // if `false`, remove the event from the DOM and don't assign it to `segment.event`
5393 element.remove();
5394 }
5395 else {
5396 if (triggerRes && triggerRes !== true) {
5397 // the trigger returned a new element, but not `true` (which means keep the existing element)
5398
5399 // re-assign the important CSS dimension properties that were already assigned in `buildHTMLForSegment`
5400 triggerRes = $(triggerRes)
5401 .css({
5402 position: 'absolute',
5403 left: segment.left
5404 });
5405
5406 element.replaceWith(triggerRes);
5407 element = triggerRes;
5408 }
5409
5410 segment.element = element;
5411 }
5412 }
5413 }
5414
5415
5416
5417 /* Top-coordinate Methods
5418 -------------------------------------------------------------------------------------------------*/
5419
5420
5421 // Sets the "top" CSS property for each element.
5422 // If `doRowHeights` is `true`, also sets each row's first cell to an explicit height,
5423 // so that if elements vertically overflow, the cell expands vertically to compensate.
5424 function setVerticals(segments, doRowHeights) {
5425 var rowContentHeights = calculateVerticals(segments); // also sets segment.top
5426 var rowContentElements = getRowContentElements(); // returns 1 inner div per row
5427 var rowContentTops = [];
5428
5429 // Set each row's height by setting height of first inner div
5430 if (doRowHeights) {
5431 for (var i=0; i<rowContentElements.length; i++) {
5432 rowContentElements[i].height(rowContentHeights[i]);
5433 }
5434 }
5435
5436 // Get each row's top, relative to the views's origin.
5437 // Important to do this after setting each row's height.
5438 for (var i=0; i<rowContentElements.length; i++) {
5439 rowContentTops.push(
5440 rowContentElements[i].position().top
5441 );
5442 }
5443
5444 // Set each segment element's CSS "top" property.
5445 // Each segment object has a "top" property, which is relative to the row's top, but...
5446 segmentElementEach(segments, function(segment, element) {
5447 element.css(
5448 'top',
5449 rowContentTops[segment.row] + segment.top // ...now, relative to views's origin
5450 );
5451 });
5452 }
5453
5454
5455 // Calculate the "top" coordinate for each segment, relative to the "top" of the row.
5456 // Also, return an array that contains the "content" height for each row
5457 // (the height displaced by the vertically stacked events in the row).
5458 // Requires segments to have their `outerHeight` property already set.
5459 function calculateVerticals(segments) {
5460 var rowCnt = getRowCnt();
5461 var colCnt = getColCnt();
5462 var rowContentHeights = []; // content height for each row
5463 var segmentRows = buildSegmentRows(segments); // an array of segment arrays, one for each row
5464
5465 for (var rowI=0; rowI<rowCnt; rowI++) {
5466 var segmentRow = segmentRows[rowI];
5467
5468 // an array of running total heights for each column.
5469 // initialize with all zeros.
5470 var colHeights = [];
5471 for (var colI=0; colI<colCnt; colI++) {
5472 colHeights.push(0);
5473 }
5474
5475 // loop through every segment
5476 for (var segmentI=0; segmentI<segmentRow.length; segmentI++) {
5477 var segment = segmentRow[segmentI];
5478
5479 // find the segment's top coordinate by looking at the max height
5480 // of all the columns the segment will be in.
5481 segment.top = arrayMax(
5482 colHeights.slice(
5483 segment.leftCol,
5484 segment.rightCol + 1 // make exclusive for slice
5485 )
5486 );
5487
5488 // adjust the columns to account for the segment's height
5489 for (var colI=segment.leftCol; colI<=segment.rightCol; colI++) {
5490 colHeights[colI] = segment.top + segment.outerHeight;
5491 }
5492 }
5493
5494 // the tallest column in the row should be the "content height"
5495 rowContentHeights.push(arrayMax(colHeights));
5496 }
5497
5498 return rowContentHeights;
5499 }
5500
5501
5502 // Build an array of segment arrays, each representing the segments that will
5503 // be in a row of the grid, sorted by which event should be closest to the top.
5504 function buildSegmentRows(segments) {
5505 var rowCnt = getRowCnt();
5506 var segmentRows = [];
5507 var segmentI;
5508 var segment;
5509 var rowI;
5510
5511 // group segments by row
5512 for (segmentI=0; segmentI<segments.length; segmentI++) {
5513 segment = segments[segmentI];
5514 rowI = segment.row;
5515 if (segment.element) { // was rendered?
5516 if (segmentRows[rowI]) {
5517 // already other segments. append to array
5518 segmentRows[rowI].push(segment);
5519 }
5520 else {
5521 // first segment in row. create new array
5522 segmentRows[rowI] = [ segment ];
5523 }
5524 }
5525 }
5526
5527 // sort each row
5528 for (rowI=0; rowI<rowCnt; rowI++) {
5529 segmentRows[rowI] = sortSegmentRow(
5530 segmentRows[rowI] || [] // guarantee an array, even if no segments
5531 );
5532 }
5533
5534 return segmentRows;
5535 }
5536
5537
5538 // Sort an array of segments according to which segment should appear closest to the top
5539 function sortSegmentRow(segments) {
5540 var sortedSegments = [];
5541
5542 // build the subrow array
5543 var subrows = buildSegmentSubrows(segments);
5544
5545 // flatten it
5546 for (var i=0; i<subrows.length; i++) {
5547 sortedSegments.push.apply(sortedSegments, subrows[i]); // append an array to an array
5548 }
5549
5550 return sortedSegments;
5551 }
5552
5553
5554 // Take an array of segments, which are all assumed to be in the same row,
5555 // and sort into subrows.
5556 function buildSegmentSubrows(segments) {
5557
5558 // Give preference to elements with certain criteria, so they have
5559 // a chance to be closer to the top.
5560 segments.sort(compareDaySegments);
5561
5562 var subrows = [];
5563 for (var i=0; i<segments.length; i++) {
5564 var segment = segments[i];
5565
5566 // loop through subrows, starting with the topmost, until the segment
5567 // doesn't collide with other segments.
5568 for (var j=0; j<subrows.length; j++) {
5569 if (!isDaySegmentCollision(segment, subrows[j])) {
5570 break;
5571 }
5572 }
5573 // `j` now holds the desired subrow index
5574 if (subrows[j]) {
5575 subrows[j].push(segment);
5576 }
5577 else {
5578 subrows[j] = [ segment ];
5579 }
5580 }
5581
5582 return subrows;
5583 }
5584
5585
5586 // Return an array of jQuery objects for the placeholder content containers of each row.
5587 // The content containers don't actually contain anything, but their dimensions should match
5588 // the events that are overlaid on top.
5589 function getRowContentElements() {
5590 var i;
5591 var rowCnt = getRowCnt();
5592 var rowDivs = [];
5593 for (i=0; i<rowCnt; i++) {
5594 rowDivs[i] = allDayRow(i)
5595 .find('div.fc-day-content > div');
5596 }
5597 return rowDivs;
5598 }
5599
5600
5601
5602 /* Mouse Handlers
5603 ---------------------------------------------------------------------------------------------------*/
5604 // TODO: better documentation!
5605
5606
5607 function attachHandlers(segments, modifiedEventId) {
5608 var segmentContainer = getDaySegmentContainer();
5609
5610 segmentElementEach(segments, function(segment, element, i) {
5611 var event = segment.event;
5612 if (event._id === modifiedEventId) {
5613 bindDaySeg(event, element, segment);
5614 }else{
5615 element[0]._fci = i; // for lazySegBind
5616 }
5617 });
5618
5619 lazySegBind(segmentContainer, segments, bindDaySeg);
5620 }
5621
5622
5623 function bindDaySeg(event, eventElement, segment) {
5624
5625 if (isEventDraggable(event)) {
5626 t.draggableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
5627 }
5628
5629 if (
5630 segment.isEnd && // only allow resizing on the final segment for an event
5631 isEventResizable(event)
5632 ) {
5633 t.resizableDayEvent(event, eventElement, segment); // use `t` so subclasses can override
5634 }
5635
5636 // attach all other handlers.
5637 // needs to be after, because resizableDayEvent might stopImmediatePropagation on click
5638 eventElementHandlers(event, eventElement);
5639 }
5640
5641
5642 function draggableDayEvent(event, eventElement) {
5643 var hoverListener = getHoverListener();
5644 var dayDelta;
5645 eventElement.draggable({
5646 delay: 50,
5647 opacity: opt('dragOpacity'),
5648 revertDuration: opt('dragRevertDuration'),
5649 start: function(ev, ui) {
5650 trigger('eventDragStart', eventElement, event, ev, ui);
5651 hideEvents(event, eventElement);
5652 hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
5653 eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta);
5654 clearOverlays();
5655 if (cell) {
5656 var origDate = cellToDate(origCell);
5657 var date = cellToDate(cell);
5658 dayDelta = dayDiff(date, origDate);
5659 renderDayOverlay(
5660 addDays(cloneDate(event.start), dayDelta),
5661 addDays(exclEndDay(event), dayDelta)
5662 );
5663 }else{
5664 dayDelta = 0;
5665 }
5666 }, ev, 'drag');
5667 },
5668 stop: function(ev, ui) {
5669 hoverListener.stop();
5670 clearOverlays();
5671 trigger('eventDragStop', eventElement, event, ev, ui);
5672 if (dayDelta) {
5673 eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui);
5674 }else{
5675 eventElement.css('filter', ''); // clear IE opacity side-effects
5676 showEvents(event, eventElement);
5677 }
5678 }
5679 });
5680 }
5681
5682
5683 function resizableDayEvent(event, element, segment) {
5684 var isRTL = opt('isRTL');
5685 var direction = isRTL ? 'w' : 'e';
5686 var handle = element.find('.ui-resizable-' + direction); // TODO: stop using this class because we aren't using jqui for this
5687 var isResizing = false;
5688
5689 // TODO: look into using jquery-ui mouse widget for this stuff
5690 disableTextSelection(element); // prevent native <a> selection for IE
5691 element
5692 .mousedown(function(ev) { // prevent native <a> selection for others
5693 ev.preventDefault();
5694 })
5695 .click(function(ev) {
5696 if (isResizing) {
5697 ev.preventDefault(); // prevent link from being visited (only method that worked in IE6)
5698 ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called
5699 // (eventElementHandlers needs to be bound after resizableDayEvent)
5700 }
5701 });
5702
5703 handle.mousedown(function(ev) {
5704 if (ev.which != 1) {
5705 return; // needs to be left mouse button
5706 }
5707 isResizing = true;
5708 var hoverListener = getHoverListener();
5709 var rowCnt = getRowCnt();
5710 var colCnt = getColCnt();
5711 var elementTop = element.css('top');
5712 var dayDelta;
5713 var helpers;
5714 var eventCopy = $.extend({}, event);
5715 var minCellOffset = dayOffsetToCellOffset( dateToDayOffset(event.start) );
5716 clearSelection();
5717 $('body')
5718 .css('cursor', direction + '-resize')
5719 .one('mouseup', mouseup);
5720 trigger('eventResizeStart', this, event, ev);
5721 hoverListener.start(function(cell, origCell) {
5722 if (cell) {
5723
5724 var origCellOffset = cellToCellOffset(origCell);
5725 var cellOffset = cellToCellOffset(cell);
5726
5727 // don't let resizing move earlier than start date cell
5728 cellOffset = Math.max(cellOffset, minCellOffset);
5729
5730 dayDelta =
5731 cellOffsetToDayOffset(cellOffset) -
5732 cellOffsetToDayOffset(origCellOffset);
5733
5734 if (dayDelta) {
5735 eventCopy.end = addDays(eventEnd(event), dayDelta, true);
5736 var oldHelpers = helpers;
5737
5738 helpers = renderTempDayEvent(eventCopy, segment.row, elementTop);
5739 helpers = $(helpers); // turn array into a jQuery object
5740
5741 helpers.find('*').css('cursor', direction + '-resize');
5742 if (oldHelpers) {
5743 oldHelpers.remove();
5744 }
5745
5746 hideEvents(event);
5747 }
5748 else {
5749 if (helpers) {
5750 showEvents(event);
5751 helpers.remove();
5752 helpers = null;
5753 }
5754 }
5755 clearOverlays();
5756 renderDayOverlay( // coordinate grid already rebuilt with hoverListener.start()
5757 event.start,
5758 addDays( exclEndDay(event), dayDelta )
5759 // TODO: instead of calling renderDayOverlay() with dates,
5760 // call _renderDayOverlay (or whatever) with cell offsets.
5761 );
5762 }
5763 }, ev);
5764
5765 function mouseup(ev) {
5766 trigger('eventResizeStop', this, event, ev);
5767 $('body').css('cursor', '');
5768 hoverListener.stop();
5769 clearOverlays();
5770 if (dayDelta) {
5771 eventResize(this, event, dayDelta, 0, ev);
5772 // event redraw will clear helpers
5773 }
5774 // otherwise, the drag handler already restored the old events
5775
5776 setTimeout(function() { // make this happen after the element's click event
5777 isResizing = false;
5778 },0);
5779 }
5780 });
5781 }
5782
5783
5784}
5785
5786
5787
5788/* Generalized Segment Utilities
5789-------------------------------------------------------------------------------------------------*/
5790
5791
5792function isDaySegmentCollision(segment, otherSegments) {
5793 for (var i=0; i<otherSegments.length; i++) {
5794 var otherSegment = otherSegments[i];
5795 if (
5796 otherSegment.leftCol <= segment.rightCol &&
5797 otherSegment.rightCol >= segment.leftCol
5798 ) {
5799 return true;
5800 }
5801 }
5802 return false;
5803}
5804
5805
5806function segmentElementEach(segments, callback) { // TODO: use in AgendaView?
5807 for (var i=0; i<segments.length; i++) {
5808 var segment = segments[i];
5809 var element = segment.element;
5810 if (element) {
5811 callback(segment, element, i);
5812 }
5813 }
5814}
5815
5816
5817// A cmp function for determining which segments should appear higher up
5818function compareDaySegments(a, b) {
5819 return (b.rightCol - b.leftCol) - (a.rightCol - a.leftCol) || // put wider events first
5820 b.event.allDay - a.event.allDay || // if tie, put all-day events first (booleans cast to 0/1)
5821 a.event.start - b.event.start || // if a tie, sort by event start date
5822 (a.event.title || '').localeCompare(b.event.title) // if a tie, sort by event title
5823}
5824
5825
5826;;
5827
5828//BUG: unselect needs to be triggered when events are dragged+dropped
5829
5830function SelectionManager() {
5831 var t = this;
5832
5833
5834 // exports
5835 t.select = select;
5836 t.unselect = unselect;
5837 t.reportSelection = reportSelection;
5838 t.daySelectionMousedown = daySelectionMousedown;
5839
5840
5841 // imports
5842 var opt = t.opt;
5843 var trigger = t.trigger;
5844 var defaultSelectionEnd = t.defaultSelectionEnd;
5845 var renderSelection = t.renderSelection;
5846 var clearSelection = t.clearSelection;
5847
5848
5849 // locals
5850 var selected = false;
5851
5852
5853
5854 // unselectAuto
5855 if (opt('selectable') && opt('unselectAuto')) {
5856 $(document).mousedown(function(ev) {
5857 var ignore = opt('unselectCancel');
5858 if (ignore) {
5859 if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
5860 return;
5861 }
5862 }
5863 unselect(ev);
5864 });
5865 }
5866
5867
5868 function select(startDate, endDate, allDay) {
5869 unselect();
5870 if (!endDate) {
5871 endDate = defaultSelectionEnd(startDate, allDay);
5872 }
5873 renderSelection(startDate, endDate, allDay);
5874 reportSelection(startDate, endDate, allDay);
5875 }
5876
5877
5878 function unselect(ev) {
5879 if (selected) {
5880 selected = false;
5881 clearSelection();
5882 trigger('unselect', null, ev);
5883 }
5884 }
5885
5886
5887 function reportSelection(startDate, endDate, allDay, ev) {
5888 selected = true;
5889 trigger('select', null, startDate, endDate, allDay, ev);
5890 }
5891
5892
5893 function daySelectionMousedown(ev) { // not really a generic manager method, oh well
5894 var cellToDate = t.cellToDate;
5895 var getIsCellAllDay = t.getIsCellAllDay;
5896 var hoverListener = t.getHoverListener();
5897 var reportDayClick = t.reportDayClick; // this is hacky and sort of weird
5898 if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button
5899 unselect(ev);
5900 var _mousedownElement = this;
5901 var dates;
5902 hoverListener.start(function(cell, origCell) { // TODO: maybe put cellToDate/getIsCellAllDay info in cell
5903 clearSelection();
5904 if (cell && getIsCellAllDay(cell)) {
5905 dates = [ cellToDate(origCell), cellToDate(cell) ].sort(dateCompare);
5906 renderSelection(dates[0], dates[1], true);
5907 }else{
5908 dates = null;
5909 }
5910 }, ev);
5911 $(document).one('mouseup', function(ev) {
5912 hoverListener.stop();
5913 if (dates) {
5914 if (+dates[0] == +dates[1]) {
5915 reportDayClick(dates[0], true, ev);
5916 }
5917 reportSelection(dates[0], dates[1], true, ev);
5918 }
5919 });
5920 }
5921 }
5922
5923
5924}
5925
5926;;
5927
5928function OverlayManager() {
5929 var t = this;
5930
5931
5932 // exports
5933 t.renderOverlay = renderOverlay;
5934 t.clearOverlays = clearOverlays;
5935
5936
5937 // locals
5938 var usedOverlays = [];
5939 var unusedOverlays = [];
5940
5941
5942 function renderOverlay(rect, parent) {
5943 var e = unusedOverlays.shift();
5944 if (!e) {
5945 e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>");
5946 }
5947 if (e[0].parentNode != parent[0]) {
5948 e.appendTo(parent);
5949 }
5950 usedOverlays.push(e.css(rect).show());
5951 return e;
5952 }
5953
5954
5955 function clearOverlays() {
5956 var e;
5957 while (e = usedOverlays.shift()) {
5958 unusedOverlays.push(e.hide().unbind());
5959 }
5960 }
5961
5962
5963}
5964
5965;;
5966
5967function CoordinateGrid(buildFunc) {
5968
5969 var t = this;
5970 var rows;
5971 var cols;
5972
5973
5974 t.build = function() {
5975 rows = [];
5976 cols = [];
5977 buildFunc(rows, cols);
5978 };
5979
5980
5981 t.cell = function(x, y) {
5982 var rowCnt = rows.length;
5983 var colCnt = cols.length;
5984 var i, r=-1, c=-1;
5985 for (i=0; i<rowCnt; i++) {
5986 if (y >= rows[i][0] && y < rows[i][1]) {
5987 r = i;
5988 break;
5989 }
5990 }
5991 for (i=0; i<colCnt; i++) {
5992 if (x >= cols[i][0] && x < cols[i][1]) {
5993 c = i;
5994 break;
5995 }
5996 }
5997 return (r>=0 && c>=0) ? { row:r, col:c } : null;
5998 };
5999
6000
6001 t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive
6002 var origin = originElement.offset();
6003 return {
6004 top: rows[row0][0] - origin.top,
6005 left: cols[col0][0] - origin.left,
6006 width: cols[col1][1] - cols[col0][0],
6007 height: rows[row1][1] - rows[row0][0]
6008 };
6009 };
6010
6011}
6012
6013;;
6014
6015function HoverListener(coordinateGrid) {
6016
6017
6018 var t = this;
6019 var bindType;
6020 var change;
6021 var firstCell;
6022 var cell;
6023
6024
6025 t.start = function(_change, ev, _bindType) {
6026 change = _change;
6027 firstCell = cell = null;
6028 coordinateGrid.build();
6029 mouse(ev);
6030 bindType = _bindType || 'mousemove';
6031 $(document).bind(bindType, mouse);
6032 };
6033
6034
6035 function mouse(ev) {
6036 _fixUIEvent(ev); // see below
6037 var newCell = coordinateGrid.cell(ev.pageX, ev.pageY);
6038 if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) {
6039 if (newCell) {
6040 if (!firstCell) {
6041 firstCell = newCell;
6042 }
6043 change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col);
6044 }else{
6045 change(newCell, firstCell);
6046 }
6047 cell = newCell;
6048 }
6049 }
6050
6051
6052 t.stop = function() {
6053 $(document).unbind(bindType, mouse);
6054 return cell;
6055 };
6056
6057
6058}
6059
6060
6061
6062// this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1)
6063// upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem
6064// but keep this in here for 1.8.16 users
6065// and maybe remove it down the line
6066
6067function _fixUIEvent(event) { // for issue 1168
6068 if (event.pageX === undefined) {
6069 event.pageX = event.originalEvent.pageX;
6070 event.pageY = event.originalEvent.pageY;
6071 }
6072}
6073;;
6074
6075function HorizontalPositionCache(getElement) {
6076
6077 var t = this,
6078 elements = {},
6079 lefts = {},
6080 rights = {};
6081
6082 function e(i) {
6083 return elements[i] = elements[i] || getElement(i);
6084 }
6085
6086 t.left = function(i) {
6087 return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i];
6088 };
6089
6090 t.right = function(i) {
6091 return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i];
6092 };
6093
6094 t.clear = function() {
6095 elements = {};
6096 lefts = {};
6097 rights = {};
6098 };
6099
6100}
6101
6102;;
6103
6104})(jQuery);
Note: See TracBrowser for help on using the repository browser.