4 * http://arshaw.com/fullcalendar/
6 * Use fullcalendar.css for basic styling.
7 * For event drag & drop, requires jQuery UI draggable.
8 * For event resizing, requires jQuery UI resizable.
10 * Copyright (c) 2011 Adam Shaw
11 * Dual licensed under the MIT and GPL licenses, located in
12 * MIT-LICENSE.txt and GPL-LICENSE.txt respectively.
14 * Date: Mon Feb 6 22:40:40 2012 -0800
18 (function($, undefined) {
29 right: 'today prev,next'
35 //disableDragging: false,
36 //disableResizing: false,
49 week: "MMM d[ yyyy]{ '—'[ MMM] d yyyy}",
50 day: 'dddd, MMM d, yyyy'
57 timeFormat: { // for event elements
58 '': 'h(:mm)t' // default
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'],
69 prev: ' ◄ ',
70 next: ' ► ',
71 prevYear: ' << ',
72 nextYear: ' >> ',
82 prev: 'circle-triangle-w',
83 next: 'circle-triangle-e'
93 // right-to-left defaults
96 left: 'next,prev today',
101 prev: ' ► ',
102 next: ' ◄ ',
103 prevYear: ' >> ',
104 nextYear: ' << '
107 prev: 'circle-triangle-e',
108 next: 'circle-triangle-w'
114 var fc = $.fullCalendar = { version: "1.5.3" };
115 var fcViews = fc.views = {};
118 $.fn.fullCalendar = function(options) {
122 if (typeof options == 'string') {
123 var args = Array.prototype.slice.call(arguments, 1);
125 this.each(function() {
126 var calendar = $.data(this, 'fullCalendar');
127 if (calendar && $.isFunction(calendar[options])) {
128 var r = calendar[options].apply(calendar, args);
129 if (res === undefined) {
132 if (options == 'destroy') {
133 $.removeData(this, 'fullCalendar');
137 if (res !== undefined) {
144 // would like to have this logic in EventManager, but needs to happen before options are recursively extended
145 var eventSources = options.eventSources || [];
146 delete options.eventSources;
147 if (options.events) {
148 eventSources.push(options.events);
149 delete options.events;
153 options = $.extend(true, {},
155 (options.isRTL || options.isRTL===undefined && defaults.isRTL) ? rtlDefaults : {},
160 this.each(function(i, _element) {
161 var element = $(_element);
162 var calendar = new Calendar(element, options, eventSources);
163 element.data('fullCalendar', calendar); // TODO: look into memory leak implications
173 // function for adding/overriding defaults
174 function setDefaults(d) {
175 $.extend(true, defaults, d);
181 function Calendar(element, options, eventSources) {
189 t.refetchEvents = refetchEvents;
190 t.reportEvents = reportEvents;
191 t.reportEventChange = reportEventChange;
192 t.rerenderEvents = rerenderEvents;
193 t.changeView = changeView;
195 t.unselect = unselect;
198 t.prevYear = prevYear;
199 t.nextYear = nextYear;
201 t.gotoDate = gotoDate;
202 t.incrementDate = incrementDate;
203 t.formatDate = function(format, date) { return formatDate(format, date, options) };
204 t.formatDates = function(format, date1, date2) { return formatDates(format, date1, date2, options) };
212 EventManager.call(t, options, eventSources);
213 var isFetchNeeded = t.isFetchNeeded;
214 var fetchEvents = t.fetchEvents;
218 var _element = element[0];
222 var tm; // for making theme classes
224 var viewInstances = {};
225 var elementOuterWidth;
226 var suggestedViewHeight;
227 var absoluteViewElement;
229 var ignoreWindowResize = 0;
230 var date = new Date();
237 -----------------------------------------------------------------------------*/
240 setYMD(date, options.year, options.month, options.date);
243 function render(inc) {
255 function initialRender() {
256 tm = options.theme ? 'ui' : 'fc';
257 element.addClass('fc');
259 element.addClass('fc-rtl');
262 element.addClass('ui-widget');
264 content = $("<div class='fc-content' style='position:relative'/>")
266 header = new Header(t, options);
267 headerElement = header.render();
269 element.prepend(headerElement);
271 changeView(options.defaultView);
272 $(window).resize(windowResize);
273 // needed for IE in a 0x0 iframe, b/c when it is resized, never triggers a windowResize
274 if (!bodyVisible()) {
280 // called when we know the calendar couldn't be rendered when it was initialized,
281 // but we think it's ready now
282 function lateRender() {
283 setTimeout(function() { // IE7 needs this so dimensions are calculated correctly
284 if (!currentView.start && bodyVisible()) { // !currentView.start makes sure this never happens more than once
292 $(window).unbind('resize', windowResize);
295 element.removeClass('fc fc-rtl ui-widget');
300 function elementVisible() {
301 return _element.offsetWidth !== 0;
305 function bodyVisible() {
306 return $('body')[0].offsetWidth !== 0;
312 -----------------------------------------------------------------------------*/
314 // TODO: improve view switching (still weird transition in IE, and FF has whiteout problem)
316 function changeView(newViewName) {
317 if (!currentView || newViewName != currentView.name) {
318 ignoreWindowResize++; // because setMinHeight might change the height before render (and subsequently setSize) is reached
322 var oldView = currentView;
326 (oldView.beforeHide || noop)(); // called before changing min-height. if called after, scroll state is reset (in Opera)
327 setMinHeight(content, content.height());
328 oldView.element.hide();
330 setMinHeight(content, 1); // needs to be 1 (not 0) for IE7, or else view dimensions miscalculated
332 content.css('overflow', 'hidden');
334 currentView = viewInstances[newViewName];
336 currentView.element.show();
338 currentView = viewInstances[newViewName] = new fcViews[newViewName](
339 newViewElement = absoluteViewElement =
340 $("<div class='fc-view fc-view-" + newViewName + "' style='position:absolute'/>")
342 t // the calendar object
347 header.deactivateButton(oldView.name);
349 header.activateButton(newViewName);
351 renderView(); // after height has been set, will make absoluteViewElement's position=relative, then set to null
353 content.css('overflow', '');
355 setMinHeight(content, 1);
358 if (!newViewElement) {
359 (currentView.afterShow || noop)(); // called after setting min-height/overflow, so in final scroll state (for Opera)
362 ignoreWindowResize--;
368 function renderView(inc) {
369 if (elementVisible()) {
370 ignoreWindowResize++; // because renderEvents might temporarily change the height before setSize is reached
374 if (suggestedViewHeight === undefined) {
378 var forceEventRender = false;
379 if (!currentView.start || inc || date < currentView.start || date >= currentView.end) {
380 // view must render an entire new date range (and refetch/render events)
381 currentView.render(date, inc || 0); // responsible for clearing events
383 forceEventRender = true;
385 else if (currentView.sizeDirty) {
386 // view must resize (and rerender events)
387 currentView.clearEvents();
389 forceEventRender = true;
391 else if (currentView.eventsDirty) {
392 currentView.clearEvents();
393 forceEventRender = true;
395 currentView.sizeDirty = false;
396 currentView.eventsDirty = false;
397 updateEvents(forceEventRender);
399 elementOuterWidth = element.outerWidth();
401 header.updateTitle(currentView.title);
402 var today = new Date();
403 if (today >= currentView.start && today < currentView.end) {
404 header.disableButton('today');
406 header.enableButton('today');
409 ignoreWindowResize--;
410 currentView.trigger('viewDisplay', _element);
417 -----------------------------------------------------------------------------*/
420 function updateSize() {
422 if (elementVisible()) {
426 currentView.clearEvents();
427 currentView.renderEvents(events);
428 currentView.sizeDirty = false;
433 function markSizesDirty() {
434 $.each(viewInstances, function(i, inst) {
435 inst.sizeDirty = true;
440 function calcSize() {
441 if (options.contentHeight) {
442 suggestedViewHeight = options.contentHeight;
444 else if (options.height) {
445 suggestedViewHeight = options.height - (headerElement ? headerElement.height() : 0) - vsides(content);
448 suggestedViewHeight = Math.round(content.width() / Math.max(options.aspectRatio, .5));
453 function setSize(dateChanged) { // todo: dateChanged?
454 ignoreWindowResize++;
455 currentView.setHeight(suggestedViewHeight, dateChanged);
456 if (absoluteViewElement) {
457 absoluteViewElement.css('position', 'relative');
458 absoluteViewElement = null;
460 currentView.setWidth(content.width(), dateChanged);
461 ignoreWindowResize--;
465 function windowResize() {
466 if (!ignoreWindowResize) {
467 if (currentView.start) { // view has already been rendered
468 var uid = ++resizeUID;
469 setTimeout(function() { // add a delay
470 if (uid == resizeUID && !ignoreWindowResize && elementVisible()) {
471 if (elementOuterWidth != (elementOuterWidth = element.outerWidth())) {
472 ignoreWindowResize++; // in case the windowResize callback changes the height
474 currentView.trigger('windowResize', _element);
475 ignoreWindowResize--;
480 // calendar must have been initialized in a 0x0 iframe that has just been resized
488 /* Event Fetching/Rendering
489 -----------------------------------------------------------------------------*/
492 // fetches events if necessary, rerenders events if necessary (or if forced)
493 function updateEvents(forceRender) {
494 if (!options.lazyFetching || isFetchNeeded(currentView.visStart, currentView.visEnd)) {
497 else if (forceRender) {
503 function refetchEvents() {
504 fetchEvents(currentView.visStart, currentView.visEnd); // will call reportEvents
508 // called when event data arrives
509 function reportEvents(_events) {
515 // called when a single event's data has been changed
516 function reportEventChange(eventID) {
517 rerenderEvents(eventID);
521 // attempts to rerenderEvents
522 function rerenderEvents(modifiedEventID) {
524 if (elementVisible()) {
525 currentView.clearEvents();
526 currentView.renderEvents(events, modifiedEventID);
527 currentView.eventsDirty = false;
532 function markEventsDirty() {
533 $.each(viewInstances, function(i, inst) {
534 inst.eventsDirty = true;
541 -----------------------------------------------------------------------------*/
544 function select(start, end, allDay) {
545 currentView.select(start, end, allDay===undefined ? true : allDay);
549 function unselect() { // safe to be called before renderView
551 currentView.unselect();
558 -----------------------------------------------------------------------------*/
571 function prevYear() {
577 function nextYear() {
589 function gotoDate(year, month, dateOfMonth) {
590 if (year instanceof Date) {
591 date = cloneDate(year); // provided 1 argument, a Date
593 setYMD(date, year, month, dateOfMonth);
599 function incrementDate(years, months, days) {
600 if (years !== undefined) {
601 addYears(date, years);
603 if (months !== undefined) {
604 addMonths(date, months);
606 if (days !== undefined) {
614 return cloneDate(date);
620 -----------------------------------------------------------------------------*/
628 function option(name, value) {
629 if (value === undefined) {
630 return options[name];
632 if (name == 'height' || name == 'contentHeight' || name == 'aspectRatio') {
633 options[name] = value;
639 function trigger(name, thisObj) {
641 return options[name].apply(
643 Array.prototype.slice.call(arguments, 2)
651 ------------------------------------------------------------------------*/
653 if (options.droppable) {
655 .bind('dragstart', function(ev, ui) {
658 if (!e.parents('.fc').length) { // not already inside a calendar
659 var accept = options.dropAccept;
660 if ($.isFunction(accept) ? accept.call(_e, e) : e.is(accept)) {
662 currentView.dragStart(_dragElement, ev, ui);
666 .bind('dragstop', function(ev, ui) {
668 currentView.dragStop(_dragElement, ev, ui);
677 function Header(calendar, options) {
684 t.updateTitle = updateTitle;
685 t.activateButton = activateButton;
686 t.deactivateButton = deactivateButton;
687 t.disableButton = disableButton;
688 t.enableButton = enableButton;
698 tm = options.theme ? 'ui' : 'fc';
699 var sections = options.header;
701 element = $("<table class='fc-header' style='width:100%'/>")
704 .append(renderSection('left'))
705 .append(renderSection('center'))
706 .append(renderSection('right'))
718 function renderSection(position) {
719 var e = $("<td class='fc-header-" + position + "'/>");
720 var buttonStr = options.header[position];
722 $.each(buttonStr.split(' '), function(i) {
724 e.append("<span class='fc-header-space'/>");
727 $.each(this.split(','), function(j, buttonName) {
728 if (buttonName == 'title') {
729 e.append("<span class='fc-header-title'><h2> </h2></span>");
731 prevButton.addClass(tm + '-corner-right');
736 if (calendar[buttonName]) {
737 buttonClick = calendar[buttonName]; // calendar method
739 else if (fcViews[buttonName]) {
740 buttonClick = function() {
741 button.removeClass(tm + '-state-hover'); // forget why
742 calendar.changeView(buttonName);
746 var icon = options.theme ? smartProperty(options.buttonIcons, buttonName) : null; // why are we using smartProperty here?
747 var text = smartProperty(options.buttonText, buttonName); // why are we using smartProperty here?
749 "<span class='fc-button fc-button-" + buttonName + " " + tm + "-state-default'>" +
750 "<span class='fc-button-inner'>" +
751 "<span class='fc-button-content'>" +
753 "<span class='fc-icon-wrap'>" +
754 "<span class='ui-icon ui-icon-" + icon + "'/>" +
759 "<span class='fc-button-effect'><span></span></span>" +
766 if (!button.hasClass(tm + '-state-disabled')) {
770 .mousedown(function() {
772 .not('.' + tm + '-state-active')
773 .not('.' + tm + '-state-disabled')
774 .addClass(tm + '-state-down');
776 .mouseup(function() {
777 button.removeClass(tm + '-state-down');
782 .not('.' + tm + '-state-active')
783 .not('.' + tm + '-state-disabled')
784 .addClass(tm + '-state-hover');
788 .removeClass(tm + '-state-hover')
789 .removeClass(tm + '-state-down');
794 button.addClass(tm + '-corner-left');
802 prevButton.addClass(tm + '-corner-right');
810 function updateTitle(html) {
816 function activateButton(buttonName) {
817 element.find('span.fc-button-' + buttonName)
818 .addClass(tm + '-state-active');
822 function deactivateButton(buttonName) {
823 element.find('span.fc-button-' + buttonName)
824 .removeClass(tm + '-state-active');
828 function disableButton(buttonName) {
829 element.find('span.fc-button-' + buttonName)
830 .addClass(tm + '-state-disabled');
834 function enableButton(buttonName) {
835 element.find('span.fc-button-' + buttonName)
836 .removeClass(tm + '-state-disabled');
842 fc.sourceNormalizers = [];
843 fc.sourceFetchers = [];
853 function EventManager(options, _sources) {
858 t.isFetchNeeded = isFetchNeeded;
859 t.fetchEvents = fetchEvents;
860 t.addEventSource = addEventSource;
861 t.removeEventSource = removeEventSource;
862 t.updateEvent = updateEvent;
863 t.renderEvent = renderEvent;
864 t.removeEvents = removeEvents;
865 t.clientEvents = clientEvents;
866 t.normalizeEvent = normalizeEvent;
870 var trigger = t.trigger;
871 var getView = t.getView;
872 var reportEvents = t.reportEvents;
876 var stickySource = { events: [] };
877 var sources = [ stickySource ];
878 var rangeStart, rangeEnd;
879 var currentFetchID = 0;
880 var pendingSourceCnt = 0;
881 var loadingLevel = 0;
885 for (var i=0; i<_sources.length; i++) {
886 _addEventSource(_sources[i]);
892 -----------------------------------------------------------------------------*/
895 function isFetchNeeded(start, end) {
896 return !rangeStart || start < rangeStart || end > rangeEnd;
900 function fetchEvents(start, end) {
904 var fetchID = ++currentFetchID;
905 var len = sources.length;
906 pendingSourceCnt = len;
907 for (var i=0; i<len; i++) {
908 fetchEventSource(sources[i], fetchID);
913 function fetchEventSource(source, fetchID) {
914 _fetchEventSource(source, function(events) {
915 if (fetchID == currentFetchID) {
917 for (var i=0; i<events.length; i++) {
918 events[i].source = source;
919 normalizeEvent(events[i]);
921 cache = cache.concat(events);
924 if (!pendingSourceCnt) {
932 function _fetchEventSource(source, callback) {
934 var fetchers = fc.sourceFetchers;
936 for (i=0; i<fetchers.length; i++) {
937 res = fetchers[i](source, rangeStart, rangeEnd, callback);
939 // the fetcher is in charge. made its own async request
942 else if (typeof res == 'object') {
943 // the fetcher returned a new source. process it
944 _fetchEventSource(res, callback);
948 var events = source.events;
950 if ($.isFunction(events)) {
952 events(cloneDate(rangeStart), cloneDate(rangeEnd), function(events) {
957 else if ($.isArray(events)) {
964 var url = source.url;
966 var success = source.success;
967 var error = source.error;
968 var complete = source.complete;
969 var data = $.extend({}, source.data || {});
970 var startParam = firstDefined(source.startParam, options.startParam);
971 var endParam = firstDefined(source.endParam, options.endParam);
973 data[startParam] = Math.round(+rangeStart / 1000);
976 data[endParam] = Math.round(+rangeEnd / 1000);
979 $.ajax($.extend({}, ajaxDefaults, source, {
981 success: function(events) {
982 events = events || [];
983 var res = applyAll(success, this, arguments);
984 if ($.isArray(res)) {
990 applyAll(error, this, arguments);
993 complete: function() {
994 applyAll(complete, this, arguments);
1007 -----------------------------------------------------------------------------*/
1010 function addEventSource(source) {
1011 source = _addEventSource(source);
1014 fetchEventSource(source, currentFetchID); // will eventually call reportEvents
1019 function _addEventSource(source) {
1020 if ($.isFunction(source) || $.isArray(source)) {
1021 source = { events: source };
1023 else if (typeof source == 'string') {
1024 source = { url: source };
1026 if (typeof source == 'object') {
1027 normalizeSource(source);
1028 sources.push(source);
1034 function removeEventSource(source) {
1035 sources = $.grep(sources, function(src) {
1036 return !isSourcesEqual(src, source);
1038 // remove all client events from that source
1039 cache = $.grep(cache, function(e) {
1040 return !isSourcesEqual(e.source, source);
1042 reportEvents(cache);
1048 -----------------------------------------------------------------------------*/
1051 function updateEvent(event) { // update an existing event
1052 var i, len = cache.length, e,
1053 defaultEventEnd = getView().defaultEventEnd, // getView???
1054 startDelta = event.start - event._start,
1055 endDelta = event.end ?
1056 (event.end - (event._end || defaultEventEnd(event))) // event._end would be null if event.end
1057 : 0; // was null and event was just resized
1058 for (i=0; i<len; i++) {
1060 if (e._id == event._id && e != event) {
1061 e.start = new Date(+e.start + startDelta);
1064 e.end = new Date(+e.end + endDelta);
1066 e.end = new Date(+defaultEventEnd(e) + endDelta);
1071 e.title = event.title;
1073 e.allDay = event.allDay;
1074 e.className = event.className;
1075 e.editable = event.editable;
1076 e.color = event.color;
1077 e.backgroudColor = event.backgroudColor;
1078 e.borderColor = event.borderColor;
1079 e.textColor = event.textColor;
1083 normalizeEvent(event);
1084 reportEvents(cache);
1088 function renderEvent(event, stick) {
1089 normalizeEvent(event);
1090 if (!event.source) {
1092 stickySource.events.push(event);
1093 event.source = stickySource;
1097 reportEvents(cache);
1101 function removeEvents(filter) {
1102 if (!filter) { // remove all
1104 // clear all array sources
1105 for (var i=0; i<sources.length; i++) {
1106 if ($.isArray(sources[i].events)) {
1107 sources[i].events = [];
1111 if (!$.isFunction(filter)) { // an event ID
1112 var id = filter + '';
1113 filter = function(e) {
1117 cache = $.grep(cache, filter, true);
1118 // remove events from array sources
1119 for (var i=0; i<sources.length; i++) {
1120 if ($.isArray(sources[i].events)) {
1121 sources[i].events = $.grep(sources[i].events, filter, true);
1125 reportEvents(cache);
1129 function clientEvents(filter) {
1130 if ($.isFunction(filter)) {
1131 return $.grep(cache, filter);
1133 else if (filter) { // an event ID
1135 return $.grep(cache, function(e) {
1136 return e._id == filter;
1139 return cache; // else, return all
1145 -----------------------------------------------------------------------------*/
1148 function pushLoading() {
1149 if (!loadingLevel++) {
1150 trigger('loading', null, true);
1155 function popLoading() {
1156 if (!--loadingLevel) {
1157 trigger('loading', null, false);
1163 /* Event Normalization
1164 -----------------------------------------------------------------------------*/
1167 function normalizeEvent(event) {
1168 var source = event.source || {};
1169 var ignoreTimezone = firstDefined(source.ignoreTimezone, options.ignoreTimezone);
1170 event._id = event._id || (event.id === undefined ? '_fc' + eventGUID++ : event.id + '');
1173 event.start = event.date;
1177 event._start = cloneDate(event.start = parseDate(event.start, ignoreTimezone));
1178 event.end = parseDate(event.end, ignoreTimezone);
1179 if (event.end && event.end <= event.start) {
1182 event._end = event.end ? cloneDate(event.end) : null;
1183 if (event.allDay === undefined) {
1184 event.allDay = firstDefined(source.allDayDefault, options.allDayDefault);
1186 if (event.className) {
1187 if (typeof event.className == 'string') {
1188 event.className = event.className.split(/\s+/);
1191 event.className = [];
1193 // TODO: if there is no start date, return false to indicate an invalid event
1199 ------------------------------------------------------------------------------*/
1202 function normalizeSource(source) {
1203 if (source.className) {
1204 // TODO: repeat code, same code for event classNames
1205 if (typeof source.className == 'string') {
1206 source.className = source.className.split(/\s+/);
1209 source.className = [];
1211 var normalizers = fc.sourceNormalizers;
1212 for (var i=0; i<normalizers.length; i++) {
1213 normalizers[i](source);
1218 function isSourcesEqual(source1, source2) {
1219 return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
1223 function getSourcePrimitive(source) {
1224 return ((typeof source == 'object') ? (source.events || source.url) : '') || source;
1231 fc.addDays = addDays;
1232 fc.cloneDate = cloneDate;
1233 fc.parseDate = parseDate;
1234 fc.parseISO8601 = parseISO8601;
1235 fc.parseTime = parseTime;
1236 fc.formatDate = formatDate;
1237 fc.formatDates = formatDates;
1242 -----------------------------------------------------------------------------*/
1244 var dayIDs = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'],
1250 function addYears(d, n, keepTime) {
1251 d.setFullYear(d.getFullYear() + n);
1259 function addMonths(d, n, keepTime) { // prevents day overflow/underflow
1260 if (+d) { // prevent infinite looping on invalid dates
1261 var m = d.getMonth() + n,
1262 check = cloneDate(d);
1269 while (d.getMonth() != check.getMonth()) {
1270 d.setDate(d.getDate() + (d < check ? 1 : -1));
1277 function addDays(d, n, keepTime) { // deals with daylight savings
1279 var dd = d.getDate() + n,
1280 check = cloneDate(d);
1281 check.setHours(9); // set to middle of day
1293 function fixDate(d, check) { // force d to be on check's YMD, for daylight savings purposes
1294 if (+d) { // prevent infinite looping on invalid dates
1295 while (d.getDate() != check.getDate()) {
1296 d.setTime(+d + (d < check ? 1 : -1) * HOUR_MS);
1302 function addMinutes(d, n) {
1303 d.setMinutes(d.getMinutes() + n);
1308 function clearTime(d) {
1312 d.setMilliseconds(0);
1317 function cloneDate(d, dontKeepTime) {
1319 return clearTime(new Date(+d));
1321 return new Date(+d);
1325 function zeroDate() { // returns a Date with time 00:00:00 and dateOfMonth=1
1328 d = new Date(1970, i++, 1);
1329 } while (d.getHours()); // != 0
1334 function skipWeekend(date, inc, excl) {
1336 while (!date.getDay() || (excl && date.getDay()==1 || !excl && date.getDay()==6)) {
1343 function dayDiff(d1, d2) { // d1 - d2
1344 return Math.round((cloneDate(d1, true) - cloneDate(d2, true)) / DAY_MS);
1348 function setYMD(date, y, m, d) {
1349 if (y !== undefined && y != date.getFullYear()) {
1352 date.setFullYear(y);
1354 if (m !== undefined && m != date.getMonth()) {
1358 if (d !== undefined) {
1366 -----------------------------------------------------------------------------*/
1369 function parseDate(s, ignoreTimezone) { // ignoreTimezone defaults to true
1370 if (typeof s == 'object') { // already a Date object
1373 if (typeof s == 'number') { // a UNIX timestamp
1374 return new Date(s * 1000);
1376 if (typeof s == 'string') {
1377 if (s.match(/^\d+(\.\d+)?$/)) { // a UNIX timestamp
1378 return new Date(parseFloat(s) * 1000);
1380 if (ignoreTimezone === undefined) {
1381 ignoreTimezone = true;
1383 return parseISO8601(s, ignoreTimezone) || (s ? new Date(s) : null);
1385 // TODO: never return invalid dates (like from new Date(<string>)), return null instead
1390 function parseISO8601(s, ignoreTimezone) { // ignoreTimezone defaults to false
1391 // derived from http://delete.me.uk/2005/03/iso8601.html
1392 // TODO: for a know glitch/feature, read tests/issue_206_parseDate_dst.html
1393 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}))?))?)?)?)?$/);
1397 var date = new Date(m[1], 0, 1);
1398 if (ignoreTimezone || !m[13]) {
1399 var check = new Date(m[1], 0, 1, 9, 0);
1401 date.setMonth(m[3] - 1);
1402 check.setMonth(m[3] - 1);
1406 check.setDate(m[5]);
1408 fixDate(date, check);
1410 date.setHours(m[7]);
1413 date.setMinutes(m[8]);
1416 date.setSeconds(m[10]);
1419 date.setMilliseconds(Number("0." + m[12]) * 1000);
1421 fixDate(date, check);
1423 date.setUTCFullYear(
1425 m[3] ? m[3] - 1 : 0,
1432 m[12] ? Number("0." + m[12]) * 1000 : 0
1435 var offset = Number(m[16]) * 60 + (m[18] ? Number(m[18]) : 0);
1436 offset *= m[15] == '-' ? 1 : -1;
1437 date = new Date(+date + (offset * 60 * 1000));
1444 function parseTime(s) { // returns minutes since start of day
1445 if (typeof s == 'number') { // an hour
1448 if (typeof s == 'object') { // a Date object
1449 return s.getHours() * 60 + s.getMinutes();
1451 var m = s.match(/(\d+)(?::(\d+))?\s*(\w+)?/);
1453 var h = parseInt(m[1], 10);
1456 if (m[3].toLowerCase().charAt(0) == 'p') {
1460 return h * 60 + (m[2] ? parseInt(m[2], 10) : 0);
1467 -----------------------------------------------------------------------------*/
1468 // TODO: use same function formatDate(date, [date2], format, [options])
1471 function formatDate(date, format, options) {
1472 return formatDates(date, null, format, options);
1476 function formatDates(date1, date2, format, options) {
1477 options = options || defaults;
1480 i, len = format.length, c,
1483 for (i=0; i<len; i++) {
1484 c = format.charAt(i);
1486 for (i2=i+1; i2<len; i2++) {
1487 if (format.charAt(i2) == "'") {
1492 res += format.substring(i+1, i2);
1500 else if (c == '(') {
1501 for (i2=i+1; i2<len; i2++) {
1502 if (format.charAt(i2) == ')') {
1503 var subres = formatDate(date, format.substring(i+1, i2), options);
1504 if (parseInt(subres.replace(/\D/, ''), 10)) {
1512 else if (c == '[') {
1513 for (i2=i+1; i2<len; i2++) {
1514 if (format.charAt(i2) == ']') {
1515 var subformat = format.substring(i+1, i2);
1516 var subres = formatDate(date, subformat, options);
1517 if (subres != formatDate(otherDate, subformat, options)) {
1525 else if (c == '{') {
1529 else if (c == '}') {
1534 for (i2=len; i2>i; i2--) {
1535 if (formatter = dateFormatters[format.substring(i, i2)]) {
1537 res += formatter(date, options);
1554 var dateFormatters = {
1555 s : function(d) { return d.getSeconds() },
1556 ss : function(d) { return zeroPad(d.getSeconds()) },
1557 m : function(d) { return d.getMinutes() },
1558 mm : function(d) { return zeroPad(d.getMinutes()) },
1559 h : function(d) { return d.getHours() % 12 || 12 },
1560 hh : function(d) { return zeroPad(d.getHours() % 12 || 12) },
1561 H : function(d) { return d.getHours() },
1562 HH : function(d) { return zeroPad(d.getHours()) },
1563 d : function(d) { return d.getDate() },
1564 dd : function(d) { return zeroPad(d.getDate()) },
1565 ddd : function(d,o) { return o.dayNamesShort[d.getDay()] },
1566 dddd: function(d,o) { return o.dayNames[d.getDay()] },
1567 M : function(d) { return d.getMonth() + 1 },
1568 MM : function(d) { return zeroPad(d.getMonth() + 1) },
1569 MMM : function(d,o) { return o.monthNamesShort[d.getMonth()] },
1570 MMMM: function(d,o) { return o.monthNames[d.getMonth()] },
1571 yy : function(d) { return (d.getFullYear()+'').substring(2) },
1572 yyyy: function(d) { return d.getFullYear() },
1573 t : function(d) { return d.getHours() < 12 ? 'a' : 'p' },
1574 tt : function(d) { return d.getHours() < 12 ? 'am' : 'pm' },
1575 T : function(d) { return d.getHours() < 12 ? 'A' : 'P' },
1576 TT : function(d) { return d.getHours() < 12 ? 'AM' : 'PM' },
1577 u : function(d) { return formatDate(d, "yyyy-MM-dd'T'HH:mm:ss'Z'") },
1579 var date = d.getDate();
1580 if (date > 10 && date < 20) {
1583 return ['st', 'nd', 'rd'][date%10-1] || 'th';
1589 fc.applyAll = applyAll;
1593 -----------------------------------------------------------------------------*/
1596 function exclEndDay(event) {
1598 return _exclEndDay(event.end, event.allDay);
1600 return addDays(cloneDate(event.start), 1);
1605 function _exclEndDay(end, allDay) {
1606 end = cloneDate(end);
1607 return allDay || end.getHours() || end.getMinutes() ? addDays(end, 1) : clearTime(end);
1611 function segCmp(a, b) {
1612 return (b.msLength - a.msLength) * 100 + (a.event.start - b.event.start);
1616 function segsCollide(seg1, seg2) {
1617 return seg1.end > seg2.start && seg1.start < seg2.end;
1623 -----------------------------------------------------------------------------*/
1626 // event rendering utilities
1627 function sliceSegs(events, visEventEnds, start, end) {
1629 i, len=events.length, event,
1630 eventStart, eventEnd,
1633 for (i=0; i<len; i++) {
1635 eventStart = event.start;
1636 eventEnd = visEventEnds[i];
1637 if (eventEnd > start && eventStart < end) {
1638 if (eventStart < start) {
1639 segStart = cloneDate(start);
1642 segStart = eventStart;
1645 if (eventEnd > end) {
1646 segEnd = cloneDate(end);
1658 msLength: segEnd - segStart
1662 return segs.sort(segCmp);
1666 // event rendering calculation utilities
1667 function stackSegs(segs) {
1669 i, len = segs.length, seg,
1671 for (i=0; i<len; i++) {
1673 j = 0; // the level index where seg should belong
1677 for (k=0; k<levels[j].length; k++) {
1678 if (segsCollide(levels[j][k], seg)) {
1691 levels[j].push(seg);
1701 /* Event Element Binding
1702 -----------------------------------------------------------------------------*/
1705 function lazySegBind(container, segs, bindHandlers) {
1706 container.unbind('mouseover').mouseover(function(ev) {
1707 var parent=ev.target, e,
1709 while (parent != this) {
1711 parent = parent.parentNode;
1713 if ((i = e._fci) !== undefined) {
1716 bindHandlers(seg.event, seg.element, seg);
1717 $(ev.target).trigger(ev);
1719 ev.stopPropagation();
1725 /* Element Dimensions
1726 -----------------------------------------------------------------------------*/
1729 function setOuterWidth(element, width, includeMargins) {
1730 for (var i=0, e; i<element.length; i++) {
1732 e.width(Math.max(0, width - hsides(e, includeMargins)));
1737 function setOuterHeight(element, height, includeMargins) {
1738 for (var i=0, e; i<element.length; i++) {
1740 e.height(Math.max(0, height - vsides(e, includeMargins)));
1745 // TODO: curCSS has been deprecated (jQuery 1.4.3 - 10/16/2010)
1748 function hsides(element, includeMargins) {
1749 return hpadding(element) + hborders(element) + (includeMargins ? hmargins(element) : 0);
1753 function hpadding(element) {
1754 return (parseFloat($.curCSS(element[0], 'paddingLeft', true)) || 0) +
1755 (parseFloat($.curCSS(element[0], 'paddingRight', true)) || 0);
1759 function hmargins(element) {
1760 return (parseFloat($.curCSS(element[0], 'marginLeft', true)) || 0) +
1761 (parseFloat($.curCSS(element[0], 'marginRight', true)) || 0);
1765 function hborders(element) {
1766 return (parseFloat($.curCSS(element[0], 'borderLeftWidth', true)) || 0) +
1767 (parseFloat($.curCSS(element[0], 'borderRightWidth', true)) || 0);
1771 function vsides(element, includeMargins) {
1772 return vpadding(element) + vborders(element) + (includeMargins ? vmargins(element) : 0);
1776 function vpadding(element) {
1777 return (parseFloat($.curCSS(element[0], 'paddingTop', true)) || 0) +
1778 (parseFloat($.curCSS(element[0], 'paddingBottom', true)) || 0);
1782 function vmargins(element) {
1783 return (parseFloat($.curCSS(element[0], 'marginTop', true)) || 0) +
1784 (parseFloat($.curCSS(element[0], 'marginBottom', true)) || 0);
1788 function vborders(element) {
1789 return (parseFloat($.curCSS(element[0], 'borderTopWidth', true)) || 0) +
1790 (parseFloat($.curCSS(element[0], 'borderBottomWidth', true)) || 0);
1794 function setMinHeight(element, height) {
1795 height = (typeof height == 'number' ? height + 'px' : height);
1796 element.each(function(i, _element) {
1797 _element.style.cssText += ';min-height:' + height + ';_height:' + height;
1798 // why can't we just use .css() ? i forget
1805 -----------------------------------------------------------------------------*/
1809 //TODO: isFunction, grep ?
1815 function cmp(a, b) {
1820 function arrayMax(a) {
1821 return Math.max.apply(Math, a);
1825 function zeroPad(n) {
1826 return (n < 10 ? '0' : '') + n;
1830 function smartProperty(obj, name) { // get a camel-cased/namespaced property of an object
1831 if (obj[name] !== undefined) {
1834 var parts = name.split(/(?=[A-Z])/),
1835 i=parts.length-1, res;
1837 res = obj[parts[i].toLowerCase()];
1838 if (res !== undefined) {
1846 function htmlEscape(s) {
1847 return s.replace(/&/g, '&')
1848 .replace(/</g, '<')
1849 .replace(/>/g, '>')
1850 .replace(/'/g, ''')
1851 .replace(/"/g, '"')
1852 .replace(/\n/g, '<br />');
1856 function cssKey(_element) {
1857 return _element.id + '/' + _element.className + '/' + _element.style.cssText.replace(/(^|;)\s*(top|left|width|height)\s*:[^;]*/ig, '');
1861 function disableTextSelection(element) {
1863 .attr('unselectable', 'on')
1864 .css('MozUserSelect', 'none')
1865 .bind('selectstart.ui', function() { return false; });
1870 function enableTextSelection(element) {
1872 .attr('unselectable', 'off')
1873 .css('MozUserSelect', '')
1874 .unbind('selectstart.ui');
1879 function markFirstLast(e) {
1881 .removeClass('fc-first fc-last')
1882 .filter(':first-child')
1883 .addClass('fc-first')
1885 .filter(':last-child')
1886 .addClass('fc-last');
1890 function setDayID(cell, date) {
1891 cell.each(function(i, _cell) {
1892 _cell.className = _cell.className.replace(/^fc-\w*/, 'fc-' + dayIDs[date.getDay()]);
1893 // TODO: make a way that doesn't rely on order of classes
1898 function getSkinCss(event, opt) {
1899 var source = event.source || {};
1900 var eventColor = event.color;
1901 var sourceColor = source.color;
1902 var optionColor = opt('eventColor');
1903 var backgroundColor =
1904 event.backgroundColor ||
1906 source.backgroundColor ||
1908 opt('eventBackgroundColor') ||
1911 event.borderColor ||
1913 source.borderColor ||
1915 opt('eventBorderColor') ||
1920 opt('eventTextColor');
1921 var statements = [];
1922 if (backgroundColor) {
1923 statements.push('background-color:' + backgroundColor);
1926 statements.push('border-color:' + borderColor);
1929 statements.push('color:' + textColor);
1931 return statements.join(';');
1935 function applyAll(functions, thisObj, args) {
1936 if ($.isFunction(functions)) {
1937 functions = [ functions ];
1942 for (i=0; i<functions.length; i++) {
1943 ret = functions[i].apply(thisObj, args) || ret;
1950 function firstDefined() {
1951 for (var i=0; i<arguments.length; i++) {
1952 if (arguments[i] !== undefined) {
1953 return arguments[i];
1960 fcViews.month = MonthView;
1962 function MonthView(element, calendar) {
1971 BasicView.call(t, element, calendar, 'month');
1973 var renderBasic = t.renderBasic;
1974 var formatDate = calendar.formatDate;
1978 function render(date, delta) {
1980 addMonths(date, delta);
1983 var start = cloneDate(date, true);
1985 var end = addMonths(cloneDate(start), 1);
1986 var visStart = cloneDate(start);
1987 var visEnd = cloneDate(end);
1988 var firstDay = opt('firstDay');
1989 var nwe = opt('weekends') ? 0 : 1;
1991 skipWeekend(visStart);
1992 skipWeekend(visEnd, -1, true);
1994 addDays(visStart, -((visStart.getDay() - Math.max(firstDay, nwe) + 7) % 7));
1995 addDays(visEnd, (7 - visEnd.getDay() + Math.max(firstDay, nwe)) % 7);
1996 var rowCnt = Math.round((visEnd - visStart) / (DAY_MS * 7));
1997 if (opt('weekMode') == 'fixed') {
1998 addDays(visEnd, (6 - rowCnt) * 7);
2001 t.title = formatDate(start, opt('titleFormat'));
2004 t.visStart = visStart;
2006 renderBasic(6, rowCnt, nwe ? 5 : 7, true);
2012 fcViews.basicWeek = BasicWeekView;
2014 function BasicWeekView(element, calendar) {
2023 BasicView.call(t, element, calendar, 'basicWeek');
2025 var renderBasic = t.renderBasic;
2026 var formatDates = calendar.formatDates;
2030 function render(date, delta) {
2032 addDays(date, delta * 7);
2034 var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
2035 var end = addDays(cloneDate(start), 7);
2036 var visStart = cloneDate(start);
2037 var visEnd = cloneDate(end);
2038 var weekends = opt('weekends');
2040 skipWeekend(visStart);
2041 skipWeekend(visEnd, -1, true);
2043 t.title = formatDates(
2045 addDays(cloneDate(visEnd), -1),
2050 t.visStart = visStart;
2052 renderBasic(1, 1, weekends ? 7 : 5, false);
2058 fcViews.basicDay = BasicDayView;
2060 //TODO: when calendar's date starts out on a weekend, shouldn't happen
2063 function BasicDayView(element, calendar) {
2072 BasicView.call(t, element, calendar, 'basicDay');
2074 var renderBasic = t.renderBasic;
2075 var formatDate = calendar.formatDate;
2079 function render(date, delta) {
2081 addDays(date, delta);
2082 if (!opt('weekends')) {
2083 skipWeekend(date, delta < 0 ? -1 : 1);
2086 t.title = formatDate(date, opt('titleFormat'));
2087 t.start = t.visStart = cloneDate(date, true);
2088 t.end = t.visEnd = addDays(cloneDate(t.start), 1);
2089 renderBasic(1, 1, 1, false);
2100 function BasicView(element, calendar, viewName) {
2105 t.renderBasic = renderBasic;
2106 t.setHeight = setHeight;
2107 t.setWidth = setWidth;
2108 t.renderDayOverlay = renderDayOverlay;
2109 t.defaultSelectionEnd = defaultSelectionEnd;
2110 t.renderSelection = renderSelection;
2111 t.clearSelection = clearSelection;
2112 t.reportDayClick = reportDayClick; // for selection (kinda hacky)
2113 t.dragStart = dragStart;
2114 t.dragStop = dragStop;
2115 t.defaultEventEnd = defaultEventEnd;
2116 t.getHoverListener = function() { return hoverListener };
2117 t.colContentLeft = colContentLeft;
2118 t.colContentRight = colContentRight;
2119 t.dayOfWeekCol = dayOfWeekCol;
2120 t.dateCell = dateCell;
2121 t.cellDate = cellDate;
2122 t.cellIsAllDay = function() { return true };
2123 t.allDayRow = allDayRow;
2124 t.allDayBounds = allDayBounds;
2125 t.getRowCnt = function() { return rowCnt };
2126 t.getColCnt = function() { return colCnt };
2127 t.getColWidth = function() { return colWidth };
2128 t.getDaySegmentContainer = function() { return daySegmentContainer };
2132 View.call(t, element, calendar, viewName);
2133 OverlayManager.call(t);
2134 SelectionManager.call(t);
2135 BasicEventRenderer.call(t);
2137 var trigger = t.trigger;
2138 var clearEvents = t.clearEvents;
2139 var renderOverlay = t.renderOverlay;
2140 var clearOverlays = t.clearOverlays;
2141 var daySelectionMousedown = t.daySelectionMousedown;
2142 var formatDate = calendar.formatDate;
2153 var bodyCellTopInners;
2154 var daySegmentContainer;
2163 var colContentPositions;
2174 ------------------------------------------------------------*/
2177 disableTextSelection(element.addClass('fc-grid'));
2180 function renderBasic(maxr, r, c, showNumbers) {
2184 var firstTime = !body;
2186 buildSkeleton(maxr, showNumbers);
2190 updateCells(firstTime);
2195 function updateOptions() {
2204 firstDay = opt('firstDay');
2205 nwe = opt('weekends') ? 0 : 1;
2206 tm = opt('theme') ? 'ui' : 'fc';
2207 colFormat = opt('columnFormat');
2212 function buildSkeleton(maxRowCnt, showNumbers) {
2214 var headerClass = tm + "-widget-header";
2215 var contentClass = tm + "-widget-content";
2220 "<table class='fc-border-separate' style='width:100%' cellspacing='0'>" +
2223 for (i=0; i<colCnt; i++) {
2225 "<th class='fc- " + headerClass + "'/>"; // need fc- for setDayID
2231 for (i=0; i<maxRowCnt; i++) {
2233 "<tr class='fc-week" + i + "'>";
2234 for (j=0; j<colCnt; j++) {
2236 "<td class='fc- " + contentClass + " fc-day" + (i*colCnt+j) + "'>" + // need fc- for setDayID
2239 "<div class='fc-day-number'/>" :
2242 "<div class='fc-day-content'>" +
2243 "<div style='position:relative'> </div>" +
2254 table = $(s).appendTo(element);
2256 head = table.find('thead');
2257 headCells = head.find('th');
2258 body = table.find('tbody');
2259 bodyRows = body.find('tr');
2260 bodyCells = body.find('td');
2261 bodyFirstCells = bodyCells.filter(':first-child');
2262 bodyCellTopInners = bodyRows.eq(0).find('div.fc-day-content div');
2264 markFirstLast(head.add(head.find('tr'))); // marks first+last tr/th's
2265 markFirstLast(bodyRows); // marks first+last td's
2266 bodyRows.eq(0).addClass('fc-first'); // fc-last is done in updateCells
2270 daySegmentContainer =
2271 $("<div style='position:absolute;z-index:8;top:0;left:0'/>")
2277 function updateCells(firstTime) {
2278 var dowDirty = firstTime || rowCnt == 1; // could the cells' day-of-weeks need updating?
2279 var month = t.start.getMonth();
2280 var today = clearTime(new Date());
2286 headCells.each(function(i, _cell) {
2288 date = indexDate(i);
2289 cell.html(formatDate(date, colFormat));
2290 setDayID(cell, date);
2294 bodyCells.each(function(i, _cell) {
2296 date = indexDate(i);
2297 if (date.getMonth() == month) {
2298 cell.removeClass('fc-other-month');
2300 cell.addClass('fc-other-month');
2302 if (+date == +today) {
2303 cell.addClass(tm + '-state-highlight fc-today');
2305 cell.removeClass(tm + '-state-highlight fc-today');
2307 cell.find('div.fc-day-number').text(date.getDate());
2309 setDayID(cell, date);
2313 bodyRows.each(function(i, _row) {
2317 if (i == rowCnt-1) {
2318 row.addClass('fc-last');
2320 row.removeClass('fc-last');
2330 function setHeight(height) {
2331 viewHeight = height;
2333 var bodyHeight = viewHeight - head.height();
2338 if (opt('weekMode') == 'variable') {
2339 rowHeight = rowHeightLast = Math.floor(bodyHeight / (rowCnt==1 ? 2 : 6));
2341 rowHeight = Math.floor(bodyHeight / rowCnt);
2342 rowHeightLast = bodyHeight - rowHeight * (rowCnt-1);
2345 bodyFirstCells.each(function(i, _cell) {
2350 (i==rowCnt-1 ? rowHeightLast : rowHeight) - vsides(cell)
2358 function setWidth(width) {
2360 colContentPositions.clear();
2361 colWidth = Math.floor(viewWidth / colCnt);
2362 setOuterWidth(headCells.slice(0, -1), colWidth);
2367 /* Day clicking and binding
2368 -----------------------------------------------------------*/
2371 function dayBind(days) {
2372 days.click(dayClick)
2373 .mousedown(daySelectionMousedown);
2377 function dayClick(ev) {
2378 if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
2379 var index = parseInt(this.className.match(/fc\-day(\d+)/)[1]); // TODO: maybe use .data
2380 var date = indexDate(index);
2381 trigger('dayClick', this, date, true, ev);
2387 /* Semi-transparent Overlay Helpers
2388 ------------------------------------------------------*/
2391 function renderDayOverlay(overlayStart, overlayEnd, refreshCoordinateGrid) { // overlayEnd is exclusive
2392 if (refreshCoordinateGrid) {
2393 coordinateGrid.build();
2395 var rowStart = cloneDate(t.visStart);
2396 var rowEnd = addDays(cloneDate(rowStart), colCnt);
2397 for (var i=0; i<rowCnt; i++) {
2398 var stretchStart = new Date(Math.max(rowStart, overlayStart));
2399 var stretchEnd = new Date(Math.min(rowEnd, overlayEnd));
2400 if (stretchStart < stretchEnd) {
2401 var colStart, colEnd;
2403 colStart = dayDiff(stretchEnd, rowStart)*dis+dit+1;
2404 colEnd = dayDiff(stretchStart, rowStart)*dis+dit+1;
2406 colStart = dayDiff(stretchStart, rowStart);
2407 colEnd = dayDiff(stretchEnd, rowStart);
2410 renderCellOverlay(i, colStart, i, colEnd-1)
2413 addDays(rowStart, 7);
2419 function renderCellOverlay(row0, col0, row1, col1) { // row1,col1 is inclusive
2420 var rect = coordinateGrid.rect(row0, col0, row1, col1, element);
2421 return renderOverlay(rect, element);
2427 -----------------------------------------------------------------------*/
2430 function defaultSelectionEnd(startDate, allDay) {
2431 return cloneDate(startDate);
2435 function renderSelection(startDate, endDate, allDay) {
2436 renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true); // rebuild every time???
2440 function clearSelection() {
2445 function reportDayClick(date, allDay, ev) {
2446 var cell = dateCell(date);
2447 var _element = bodyCells[cell.row*colCnt + cell.col];
2448 trigger('dayClick', _element, date, allDay, ev);
2453 /* External Dragging
2454 -----------------------------------------------------------------------*/
2457 function dragStart(_dragElement, ev, ui) {
2458 hoverListener.start(function(cell) {
2461 renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
2467 function dragStop(_dragElement, ev, ui) {
2468 var cell = hoverListener.stop();
2471 var d = cellDate(cell);
2472 trigger('drop', _dragElement, d, true, ev, ui);
2479 --------------------------------------------------------*/
2482 function defaultEventEnd(event) {
2483 return cloneDate(event.start);
2487 coordinateGrid = new CoordinateGrid(function(rows, cols) {
2489 headCells.each(function(i, _e) {
2491 n = e.offset().left;
2498 p[1] = n + e.outerWidth();
2499 bodyRows.each(function(i, _e) {
2510 p[1] = n + e.outerHeight();
2514 hoverListener = new HoverListener(coordinateGrid);
2517 colContentPositions = new HorizontalPositionCache(function(col) {
2518 return bodyCellTopInners.eq(col);
2522 function colContentLeft(col) {
2523 return colContentPositions.left(col);
2527 function colContentRight(col) {
2528 return colContentPositions.right(col);
2534 function dateCell(date) {
2536 row: Math.floor(dayDiff(date, t.visStart) / 7),
2537 col: dayOfWeekCol(date.getDay())
2542 function cellDate(cell) {
2543 return _cellDate(cell.row, cell.col);
2547 function _cellDate(row, col) {
2548 return addDays(cloneDate(t.visStart), row*7 + col*dis+dit);
2549 // what about weekends in middle of week?
2553 function indexDate(index) {
2554 return _cellDate(Math.floor(index/colCnt), index%colCnt);
2558 function dayOfWeekCol(dayOfWeek) {
2559 return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt) * dis + dit;
2565 function allDayRow(i) {
2566 return bodyRows.eq(i);
2570 function allDayBounds(i) {
2580 function BasicEventRenderer() {
2585 t.renderEvents = renderEvents;
2586 t.compileDaySegs = compileSegs; // for DayEventRenderer
2587 t.clearEvents = clearEvents;
2588 t.bindDaySeg = bindDaySeg;
2592 DayEventRenderer.call(t);
2594 var trigger = t.trigger;
2595 //var setOverflowHidden = t.setOverflowHidden;
2596 var isEventDraggable = t.isEventDraggable;
2597 var isEventResizable = t.isEventResizable;
2598 var reportEvents = t.reportEvents;
2599 var reportEventClear = t.reportEventClear;
2600 var eventElementHandlers = t.eventElementHandlers;
2601 var showEvents = t.showEvents;
2602 var hideEvents = t.hideEvents;
2603 var eventDrop = t.eventDrop;
2604 var getDaySegmentContainer = t.getDaySegmentContainer;
2605 var getHoverListener = t.getHoverListener;
2606 var renderDayOverlay = t.renderDayOverlay;
2607 var clearOverlays = t.clearOverlays;
2608 var getRowCnt = t.getRowCnt;
2609 var getColCnt = t.getColCnt;
2610 var renderDaySegs = t.renderDaySegs;
2611 var resizableDayEvent = t.resizableDayEvent;
2616 --------------------------------------------------------------------*/
2619 function renderEvents(events, modifiedEventId) {
2620 reportEvents(events);
2621 renderDaySegs(compileSegs(events), modifiedEventId);
2625 function clearEvents() {
2627 getDaySegmentContainer().empty();
2631 function compileSegs(events) {
2632 var rowCnt = getRowCnt(),
2633 colCnt = getColCnt(),
2634 d1 = cloneDate(t.visStart),
2635 d2 = addDays(cloneDate(d1), colCnt),
2636 visEventsEnds = $.map(events, exclEndDay),
2641 for (i=0; i<rowCnt; i++) {
2642 row = stackSegs(sliceSegs(events, visEventsEnds, d1, d2));
2643 for (j=0; j<row.length; j++) {
2645 for (k=0; k<level.length; k++) {
2648 seg.level = j; // not needed anymore
2659 function bindDaySeg(event, eventElement, seg) {
2660 if (isEventDraggable(event)) {
2661 draggableDayEvent(event, eventElement);
2663 if (seg.isEnd && isEventResizable(event)) {
2664 resizableDayEvent(event, eventElement, seg);
2666 eventElementHandlers(event, eventElement);
2667 // needs to be after, because resizableDayEvent might stopImmediatePropagation on click
2673 ----------------------------------------------------------------------------*/
2676 function draggableDayEvent(event, eventElement) {
2677 var hoverListener = getHoverListener();
2679 eventElement.draggable({
2682 opacity: opt('dragOpacity'),
2683 revertDuration: opt('dragRevertDuration'),
2684 start: function(ev, ui) {
2685 trigger('eventDragStart', eventElement, event, ev, ui);
2686 hideEvents(event, eventElement);
2687 hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
2688 eventElement.draggable('option', 'revert', !cell || !rowDelta && !colDelta);
2691 //setOverflowHidden(true);
2692 dayDelta = rowDelta*7 + colDelta * (opt('isRTL') ? -1 : 1);
2694 addDays(cloneDate(event.start), dayDelta),
2695 addDays(exclEndDay(event), dayDelta)
2698 //setOverflowHidden(false);
2703 stop: function(ev, ui) {
2704 hoverListener.stop();
2706 trigger('eventDragStop', eventElement, event, ev, ui);
2708 eventDrop(this, event, dayDelta, 0, event.allDay, ev, ui);
2710 eventElement.css('filter', ''); // clear IE opacity side-effects
2711 showEvents(event, eventElement);
2713 //setOverflowHidden(false);
2721 fcViews.agendaWeek = AgendaWeekView;
2723 function AgendaWeekView(element, calendar) {
2732 AgendaView.call(t, element, calendar, 'agendaWeek');
2734 var renderAgenda = t.renderAgenda;
2735 var formatDates = calendar.formatDates;
2739 function render(date, delta) {
2741 addDays(date, delta * 7);
2743 var start = addDays(cloneDate(date), -((date.getDay() - opt('firstDay') + 7) % 7));
2744 var end = addDays(cloneDate(start), 7);
2745 var visStart = cloneDate(start);
2746 var visEnd = cloneDate(end);
2747 var weekends = opt('weekends');
2749 skipWeekend(visStart);
2750 skipWeekend(visEnd, -1, true);
2752 t.title = formatDates(
2754 addDays(cloneDate(visEnd), -1),
2759 t.visStart = visStart;
2761 renderAgenda(weekends ? 7 : 5);
2767 fcViews.agendaDay = AgendaDayView;
2769 function AgendaDayView(element, calendar) {
2778 AgendaView.call(t, element, calendar, 'agendaDay');
2780 var renderAgenda = t.renderAgenda;
2781 var formatDate = calendar.formatDate;
2785 function render(date, delta) {
2787 addDays(date, delta);
2788 if (!opt('weekends')) {
2789 skipWeekend(date, delta < 0 ? -1 : 1);
2792 var start = cloneDate(date, true);
2793 var end = addDays(cloneDate(start), 1);
2794 t.title = formatDate(date, opt('titleFormat'));
2795 t.start = t.visStart = start;
2796 t.end = t.visEnd = end;
2805 allDayText: 'all-day',
2808 defaultEventMinutes: 120,
2809 axisFormat: 'h(:mm)tt',
2811 agenda: 'h:mm{ - h:mm}'
2821 // TODO: make it work in quirks mode (event corners, all-day height)
2822 // TODO: test liquid width, especially in IE6
2825 function AgendaView(element, calendar, viewName) {
2830 t.renderAgenda = renderAgenda;
2831 t.setWidth = setWidth;
2832 t.setHeight = setHeight;
2833 t.beforeHide = beforeHide;
2834 t.afterShow = afterShow;
2835 t.defaultEventEnd = defaultEventEnd;
2836 t.timePosition = timePosition;
2837 t.dayOfWeekCol = dayOfWeekCol;
2838 t.dateCell = dateCell;
2839 t.cellDate = cellDate;
2840 t.cellIsAllDay = cellIsAllDay;
2841 t.allDayRow = getAllDayRow;
2842 t.allDayBounds = allDayBounds;
2843 t.getHoverListener = function() { return hoverListener };
2844 t.colContentLeft = colContentLeft;
2845 t.colContentRight = colContentRight;
2846 t.getDaySegmentContainer = function() { return daySegmentContainer };
2847 t.getSlotSegmentContainer = function() { return slotSegmentContainer };
2848 t.getMinMinute = function() { return minMinute };
2849 t.getMaxMinute = function() { return maxMinute };
2850 t.getBodyContent = function() { return slotContent }; // !!??
2851 t.getRowCnt = function() { return 1 };
2852 t.getColCnt = function() { return colCnt };
2853 t.getColWidth = function() { return colWidth };
2854 t.getSlotHeight = function() { return slotHeight };
2855 t.defaultSelectionEnd = defaultSelectionEnd;
2856 t.renderDayOverlay = renderDayOverlay;
2857 t.renderSelection = renderSelection;
2858 t.clearSelection = clearSelection;
2859 t.reportDayClick = reportDayClick; // selection mousedown hack
2860 t.dragStart = dragStart;
2861 t.dragStop = dragStop;
2865 View.call(t, element, calendar, viewName);
2866 OverlayManager.call(t);
2867 SelectionManager.call(t);
2868 AgendaEventRenderer.call(t);
2870 var trigger = t.trigger;
2871 var clearEvents = t.clearEvents;
2872 var renderOverlay = t.renderOverlay;
2873 var clearOverlays = t.clearOverlays;
2874 var reportSelection = t.reportSelection;
2875 var unselect = t.unselect;
2876 var daySelectionMousedown = t.daySelectionMousedown;
2877 var slotSegHtml = t.slotSegHtml;
2878 var formatDate = calendar.formatDate;
2888 var dayBodyCellInners;
2889 var dayBodyFirstCell;
2890 var dayBodyFirstCellStretcher;
2892 var daySegmentContainer;
2897 var slotSegmentContainer;
2899 var slotTableFirstInner;
2902 var selectionHelper;
2909 var slotHeight; // TODO: what if slotHeight changes? (see issue 650)
2916 var colContentPositions;
2917 var slotTopCache = {};
2921 var nwe; // no weekends (int)
2922 var rtl, dis, dit; // day index sign / translate
2923 var minMinute, maxMinute;
2929 -----------------------------------------------------------------------------*/
2932 disableTextSelection(element.addClass('fc-agenda'));
2935 function renderAgenda(c) {
2948 function updateOptions() {
2949 tm = opt('theme') ? 'ui' : 'fc';
2950 nwe = opt('weekends') ? 0 : 1;
2951 firstDay = opt('firstDay');
2952 if (rtl = opt('isRTL')) {
2959 minMinute = parseTime(opt('minTime'));
2960 maxMinute = parseTime(opt('maxTime'));
2961 colFormat = opt('columnFormat');
2966 function buildSkeleton() {
2967 var headerClass = tm + "-widget-header";
2968 var contentClass = tm + "-widget-content";
2974 var slotNormal = opt('slotMinutes') % 15 == 0;
2977 "<table style='width:100%' class='fc-agenda-days fc-border-separate' cellspacing='0'>" +
2980 "<th class='fc-agenda-axis " + headerClass + "'> </th>";
2981 for (i=0; i<colCnt; i++) {
2983 "<th class='fc- fc-col" + i + ' ' + headerClass + "'/>"; // fc- needed for setDayID
2986 "<th class='fc-agenda-gutter " + headerClass + "'> </th>" +
2991 "<th class='fc-agenda-axis " + headerClass + "'> </th>";
2992 for (i=0; i<colCnt; i++) {
2994 "<td class='fc- fc-col" + i + ' ' + contentClass + "'>" + // fc- needed for setDayID
2996 "<div class='fc-day-content'>" +
2997 "<div style='position:relative'> </div>" +
3003 "<td class='fc-agenda-gutter " + contentClass + "'> </td>" +
3007 dayTable = $(s).appendTo(element);
3008 dayHead = dayTable.find('thead');
3009 dayHeadCells = dayHead.find('th').slice(1, -1);
3010 dayBody = dayTable.find('tbody');
3011 dayBodyCells = dayBody.find('td').slice(0, -1);
3012 dayBodyCellInners = dayBodyCells.find('div.fc-day-content div');
3013 dayBodyFirstCell = dayBodyCells.eq(0);
3014 dayBodyFirstCellStretcher = dayBodyFirstCell.find('> div');
3016 markFirstLast(dayHead.add(dayHead.find('tr')));
3017 markFirstLast(dayBody.add(dayBody.find('tr')));
3019 axisFirstCells = dayHead.find('th:first');
3020 gutterCells = dayTable.find('.fc-agenda-gutter');
3023 $("<div style='position:absolute;z-index:2;left:0;width:100%'/>")
3026 if (opt('allDaySlot')) {
3028 daySegmentContainer =
3029 $("<div style='position:absolute;z-index:8;top:0;left:0'/>")
3030 .appendTo(slotLayer);
3033 "<table style='width:100%' class='fc-agenda-allday' cellspacing='0'>" +
3035 "<th class='" + headerClass + " fc-agenda-axis'>" + opt('allDayText') + "</th>" +
3037 "<div class='fc-day-content'><div style='position:relative'/></div>" +
3039 "<th class='" + headerClass + " fc-agenda-gutter'> </th>" +
3042 allDayTable = $(s).appendTo(slotLayer);
3043 allDayRow = allDayTable.find('tr');
3045 dayBind(allDayRow.find('td'));
3047 axisFirstCells = axisFirstCells.add(allDayTable.find('th:first'));
3048 gutterCells = gutterCells.add(allDayTable.find('th.fc-agenda-gutter'));
3051 "<div class='fc-agenda-divider " + headerClass + "'>" +
3052 "<div class='fc-agenda-divider-inner'/>" +
3058 daySegmentContainer = $([]); // in jQuery 1.4, we can just do $()
3063 $("<div style='position:absolute;width:100%;overflow-x:hidden;overflow-y:auto'/>")
3064 .appendTo(slotLayer);
3067 $("<div style='position:relative;width:100%;overflow:hidden'/>")
3068 .appendTo(slotScroller);
3070 slotSegmentContainer =
3071 $("<div style='position:absolute;z-index:8;top:0;left:0'/>")
3072 .appendTo(slotContent);
3075 "<table class='fc-agenda-slots' style='width:100%' cellspacing='0'>" +
3078 maxd = addMinutes(cloneDate(d), maxMinute);
3079 addMinutes(d, minMinute);
3081 for (i=0; d < maxd; i++) {
3082 minutes = d.getMinutes();
3084 "<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" +
3085 "<th class='fc-agenda-axis " + headerClass + "'>" +
3086 ((!slotNormal || !minutes) ? formatDate(d, opt('axisFormat')) : ' ') +
3088 "<td class='" + contentClass + "'>" +
3089 "<div style='position:relative'> </div>" +
3092 addMinutes(d, opt('slotMinutes'));
3098 slotTable = $(s).appendTo(slotContent);
3099 slotTableFirstInner = slotTable.find('div:first');
3101 slotBind(slotTable.find('td'));
3103 axisFirstCells = axisFirstCells.add(slotTable.find('th:first'));
3108 function updateCells() {
3113 var today = clearTime(new Date());
3114 for (i=0; i<colCnt; i++) {
3116 headCell = dayHeadCells.eq(i);
3117 headCell.html(formatDate(date, colFormat));
3118 bodyCell = dayBodyCells.eq(i);
3119 if (+date == +today) {
3120 bodyCell.addClass(tm + '-state-highlight fc-today');
3122 bodyCell.removeClass(tm + '-state-highlight fc-today');
3124 setDayID(headCell.add(bodyCell), date);
3130 function setHeight(height, dateChanged) {
3131 if (height === undefined) {
3132 height = viewHeight;
3134 viewHeight = height;
3137 var headHeight = dayBody.position().top;
3138 var allDayHeight = slotScroller.position().top; // including divider
3139 var bodyHeight = Math.min( // total body height, including borders
3140 height - headHeight, // when scrollbars
3141 slotTable.height() + allDayHeight + 1 // when no scrollbars. +1 for bottom border
3144 dayBodyFirstCellStretcher
3145 .height(bodyHeight - vsides(dayBodyFirstCell));
3147 slotLayer.css('top', headHeight);
3149 slotScroller.height(bodyHeight - allDayHeight - 1);
3151 slotHeight = slotTableFirstInner.height() + 1; // +1 for border
3160 function setWidth(width) {
3162 colContentPositions.clear();
3168 .each(function(i, _cell) {
3169 axisWidth = Math.max(axisWidth, $(_cell).outerWidth());
3174 var slotTableWidth = slotScroller[0].clientWidth; // needs to be done after axisWidth (for IE7)
3175 //slotTable.width(slotTableWidth);
3177 gutterWidth = slotScroller.width() - slotTableWidth;
3179 setOuterWidth(gutterCells, gutterWidth);
3183 .removeClass('fc-last');
3188 .addClass('fc-last');
3191 colWidth = Math.floor((slotTableWidth - axisWidth) / colCnt);
3192 setOuterWidth(dayHeadCells.slice(0, -1), colWidth);
3197 function resetScroll() {
3198 var d0 = zeroDate();
3199 var scrollDate = cloneDate(d0);
3200 scrollDate.setHours(opt('firstHour'));
3201 var top = timePosition(d0, scrollDate) + 1; // +1 for the border
3203 slotScroller.scrollTop(top);
3206 setTimeout(scroll, 0); // overrides any previous scroll state made by the browser
3210 function beforeHide() {
3211 savedScrollTop = slotScroller.scrollTop();
3215 function afterShow() {
3216 slotScroller.scrollTop(savedScrollTop);
3221 /* Slot/Day clicking and binding
3222 -----------------------------------------------------------------------*/
3225 function dayBind(cells) {
3226 cells.click(slotClick)
3227 .mousedown(daySelectionMousedown);
3231 function slotBind(cells) {
3232 cells.click(slotClick)
3233 .mousedown(slotSelectionMousedown);
3237 function slotClick(ev) {
3238 if (!opt('selectable')) { // if selectable, SelectionManager will worry about dayClick
3239 var col = Math.min(colCnt-1, Math.floor((ev.pageX - dayTable.offset().left - axisWidth) / colWidth));
3240 var date = colDate(col);
3241 var rowMatch = this.parentNode.className.match(/fc-slot(\d+)/); // TODO: maybe use data
3243 var mins = parseInt(rowMatch[1]) * opt('slotMinutes');
3244 var hours = Math.floor(mins/60);
3245 date.setHours(hours);
3246 date.setMinutes(mins%60 + minMinute);
3247 trigger('dayClick', dayBodyCells[col], date, false, ev);
3249 trigger('dayClick', dayBodyCells[col], date, true, ev);
3256 /* Semi-transparent Overlay Helpers
3257 -----------------------------------------------------*/
3260 function renderDayOverlay(startDate, endDate, refreshCoordinateGrid) { // endDate is exclusive
3261 if (refreshCoordinateGrid) {
3262 coordinateGrid.build();
3264 var visStart = cloneDate(t.visStart);
3265 var startCol, endCol;
3267 startCol = dayDiff(endDate, visStart)*dis+dit+1;
3268 endCol = dayDiff(startDate, visStart)*dis+dit+1;
3270 startCol = dayDiff(startDate, visStart);
3271 endCol = dayDiff(endDate, visStart);
3273 startCol = Math.max(0, startCol);
3274 endCol = Math.min(colCnt, endCol);
3275 if (startCol < endCol) {
3277 renderCellOverlay(0, startCol, 0, endCol-1)
3283 function renderCellOverlay(row0, col0, row1, col1) { // only for all-day?
3284 var rect = coordinateGrid.rect(row0, col0, row1, col1, slotLayer);
3285 return renderOverlay(rect, slotLayer);
3289 function renderSlotOverlay(overlayStart, overlayEnd) {
3290 var dayStart = cloneDate(t.visStart);
3291 var dayEnd = addDays(cloneDate(dayStart), 1);
3292 for (var i=0; i<colCnt; i++) {
3293 var stretchStart = new Date(Math.max(dayStart, overlayStart));
3294 var stretchEnd = new Date(Math.min(dayEnd, overlayEnd));
3295 if (stretchStart < stretchEnd) {
3296 var col = i*dis+dit;
3297 var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only use it for horizontal coords
3298 var top = timePosition(dayStart, stretchStart);
3299 var bottom = timePosition(dayStart, stretchEnd);
3301 rect.height = bottom - top;
3303 renderOverlay(rect, slotContent)
3306 addDays(dayStart, 1);
3313 /* Coordinate Utilities
3314 -----------------------------------------------------------------------------*/
3317 coordinateGrid = new CoordinateGrid(function(rows, cols) {
3319 dayHeadCells.each(function(i, _e) {
3321 n = e.offset().left;
3328 p[1] = n + e.outerWidth();
3329 if (opt('allDaySlot')) {
3332 rows[0] = [n, n+e.outerHeight()];
3334 var slotTableTop = slotContent.offset().top;
3335 var slotScrollerTop = slotScroller.offset().top;
3336 var slotScrollerBottom = slotScrollerTop + slotScroller.outerHeight();
3337 function constrain(n) {
3338 return Math.max(slotScrollerTop, Math.min(slotScrollerBottom, n));
3340 for (var i=0; i<slotCnt; i++) {
3342 constrain(slotTableTop + slotHeight*i),
3343 constrain(slotTableTop + slotHeight*(i+1))
3349 hoverListener = new HoverListener(coordinateGrid);
3352 colContentPositions = new HorizontalPositionCache(function(col) {
3353 return dayBodyCellInners.eq(col);
3357 function colContentLeft(col) {
3358 return colContentPositions.left(col);
3362 function colContentRight(col) {
3363 return colContentPositions.right(col);
3369 function dateCell(date) { // "cell" terminology is now confusing
3371 row: Math.floor(dayDiff(date, t.visStart) / 7),
3372 col: dayOfWeekCol(date.getDay())
3377 function cellDate(cell) {
3378 var d = colDate(cell.col);
3379 var slotIndex = cell.row;
3380 if (opt('allDaySlot')) {
3383 if (slotIndex >= 0) {
3384 addMinutes(d, minMinute + slotIndex * opt('slotMinutes'));
3390 function colDate(col) { // returns dates with 00:00:00
3391 return addDays(cloneDate(t.visStart), col*dis+dit);
3395 function cellIsAllDay(cell) {
3396 return opt('allDaySlot') && !cell.row;
3400 function dayOfWeekCol(dayOfWeek) {
3401 return ((dayOfWeek - Math.max(firstDay, nwe) + colCnt) % colCnt)*dis+dit;
3407 // get the Y coordinate of the given time on the given day (both Date objects)
3408 function timePosition(day, time) { // both date objects. day holds 00:00 of current day
3409 day = cloneDate(day, true);
3410 if (time < addMinutes(cloneDate(day), minMinute)) {
3413 if (time >= addMinutes(cloneDate(day), maxMinute)) {
3414 return slotTable.height();
3416 var slotMinutes = opt('slotMinutes'),
3417 minutes = time.getHours()*60 + time.getMinutes() - minMinute,
3418 slotI = Math.floor(minutes / slotMinutes),
3419 slotTop = slotTopCache[slotI];
3420 if (slotTop === undefined) {
3421 slotTop = slotTopCache[slotI] = slotTable.find('tr:eq(' + slotI + ') td div')[0].offsetTop; //.position().top; // need this optimization???
3423 return Math.max(0, Math.round(
3424 slotTop - 1 + slotHeight * ((minutes % slotMinutes) / slotMinutes)
3429 function allDayBounds() {
3432 right: viewWidth - gutterWidth
3437 function getAllDayRow(index) {
3442 function defaultEventEnd(event) {
3443 var start = cloneDate(event.start);
3447 return addMinutes(start, opt('defaultEventMinutes'));
3453 ---------------------------------------------------------------------------------*/
3456 function defaultSelectionEnd(startDate, allDay) {
3458 return cloneDate(startDate);
3460 return addMinutes(cloneDate(startDate), opt('slotMinutes'));
3464 function renderSelection(startDate, endDate, allDay) { // only for all-day
3466 if (opt('allDaySlot')) {
3467 renderDayOverlay(startDate, addDays(cloneDate(endDate), 1), true);
3470 renderSlotSelection(startDate, endDate);
3475 function renderSlotSelection(startDate, endDate) {
3476 var helperOption = opt('selectHelper');
3477 coordinateGrid.build();
3479 var col = dayDiff(startDate, t.visStart) * dis + dit;
3480 if (col >= 0 && col < colCnt) { // only works when times are on same day
3481 var rect = coordinateGrid.rect(0, col, 0, col, slotContent); // only for horizontal coords
3482 var top = timePosition(startDate, startDate);
3483 var bottom = timePosition(startDate, endDate);
3484 if (bottom > top) { // protect against selections that are entirely before or after visible range
3486 rect.height = bottom - top;
3489 if ($.isFunction(helperOption)) {
3490 var helperRes = helperOption(startDate, endDate);
3492 rect.position = 'absolute';
3494 selectionHelper = $(helperRes)
3496 .appendTo(slotContent);
3499 rect.isStart = true; // conside rect a "seg" now
3500 rect.isEnd = true; //
3501 selectionHelper = $(slotSegHtml(
3506 className: ['fc-select-helper'],
3511 selectionHelper.css('opacity', opt('dragOpacity'));
3513 if (selectionHelper) {
3514 slotBind(selectionHelper);
3515 slotContent.append(selectionHelper);
3516 setOuterWidth(selectionHelper, rect.width, true); // needs to be after appended
3517 setOuterHeight(selectionHelper, rect.height, true);
3522 renderSlotOverlay(startDate, endDate);
3527 function clearSelection() {
3529 if (selectionHelper) {
3530 selectionHelper.remove();
3531 selectionHelper = null;
3536 function slotSelectionMousedown(ev) {
3537 if (ev.which == 1 && opt('selectable')) { // ev.which==1 means left mouse button
3540 hoverListener.start(function(cell, origCell) {
3542 if (cell && cell.col == origCell.col && !cellIsAllDay(cell)) {
3543 var d1 = cellDate(origCell);
3544 var d2 = cellDate(cell);
3547 addMinutes(cloneDate(d1), opt('slotMinutes')),
3549 addMinutes(cloneDate(d2), opt('slotMinutes'))
3551 renderSlotSelection(dates[0], dates[3]);
3556 $(document).one('mouseup', function(ev) {
3557 hoverListener.stop();
3559 if (+dates[0] == +dates[1]) {
3560 reportDayClick(dates[0], false, ev);
3562 reportSelection(dates[0], dates[3], false, ev);
3569 function reportDayClick(date, allDay, ev) {
3570 trigger('dayClick', dayBodyCells[dayOfWeekCol(date.getDay())], date, allDay, ev);
3575 /* External Dragging
3576 --------------------------------------------------------------------------------*/
3579 function dragStart(_dragElement, ev, ui) {
3580 hoverListener.start(function(cell) {
3583 if (cellIsAllDay(cell)) {
3584 renderCellOverlay(cell.row, cell.col, cell.row, cell.col);
3586 var d1 = cellDate(cell);
3587 var d2 = addMinutes(cloneDate(d1), opt('defaultEventMinutes'));
3588 renderSlotOverlay(d1, d2);
3595 function dragStop(_dragElement, ev, ui) {
3596 var cell = hoverListener.stop();
3599 trigger('drop', _dragElement, cellDate(cell), cellIsAllDay(cell), ev, ui);
3606 function AgendaEventRenderer() {
3611 t.renderEvents = renderEvents;
3612 t.compileDaySegs = compileDaySegs; // for DayEventRenderer
3613 t.clearEvents = clearEvents;
3614 t.slotSegHtml = slotSegHtml;
3615 t.bindDaySeg = bindDaySeg;
3619 DayEventRenderer.call(t);
3621 var trigger = t.trigger;
3622 //var setOverflowHidden = t.setOverflowHidden;
3623 var isEventDraggable = t.isEventDraggable;
3624 var isEventResizable = t.isEventResizable;
3625 var eventEnd = t.eventEnd;
3626 var reportEvents = t.reportEvents;
3627 var reportEventClear = t.reportEventClear;
3628 var eventElementHandlers = t.eventElementHandlers;
3629 var setHeight = t.setHeight;
3630 var getDaySegmentContainer = t.getDaySegmentContainer;
3631 var getSlotSegmentContainer = t.getSlotSegmentContainer;
3632 var getHoverListener = t.getHoverListener;
3633 var getMaxMinute = t.getMaxMinute;
3634 var getMinMinute = t.getMinMinute;
3635 var timePosition = t.timePosition;
3636 var colContentLeft = t.colContentLeft;
3637 var colContentRight = t.colContentRight;
3638 var renderDaySegs = t.renderDaySegs;
3639 var resizableDayEvent = t.resizableDayEvent; // TODO: streamline binding architecture
3640 var getColCnt = t.getColCnt;
3641 var getColWidth = t.getColWidth;
3642 var getSlotHeight = t.getSlotHeight;
3643 var getBodyContent = t.getBodyContent;
3644 var reportEventElement = t.reportEventElement;
3645 var showEvents = t.showEvents;
3646 var hideEvents = t.hideEvents;
3647 var eventDrop = t.eventDrop;
3648 var eventResize = t.eventResize;
3649 var renderDayOverlay = t.renderDayOverlay;
3650 var clearOverlays = t.clearOverlays;
3651 var calendar = t.calendar;
3652 var formatDate = calendar.formatDate;
3653 var formatDates = calendar.formatDates;
3658 ----------------------------------------------------------------------------*/
3661 function renderEvents(events, modifiedEventId) {
3662 reportEvents(events);
3663 var i, len=events.length,
3666 for (i=0; i<len; i++) {
3667 if (events[i].allDay) {
3668 dayEvents.push(events[i]);
3670 slotEvents.push(events[i]);
3673 if (opt('allDaySlot')) {
3674 renderDaySegs(compileDaySegs(dayEvents), modifiedEventId);
3675 setHeight(); // no params means set to viewHeight
3677 renderSlotSegs(compileSlotSegs(slotEvents), modifiedEventId);
3681 function clearEvents() {
3683 getDaySegmentContainer().empty();
3684 getSlotSegmentContainer().empty();
3688 function compileDaySegs(events) {
3689 var levels = stackSegs(sliceSegs(events, $.map(events, exclEndDay), t.visStart, t.visEnd)),
3690 i, levelCnt=levels.length, level,
3693 for (i=0; i<levelCnt; i++) {
3695 for (j=0; j<level.length; j++) {
3698 seg.level = i; // not needed anymore
3706 function compileSlotSegs(events) {
3707 var colCnt = getColCnt(),
3708 minMinute = getMinMinute(),
3709 maxMinute = getMaxMinute(),
3710 d = addMinutes(cloneDate(t.visStart), minMinute),
3711 visEventEnds = $.map(events, slotEventEnd),
3716 for (i=0; i<colCnt; i++) {
3717 col = stackSegs(sliceSegs(events, visEventEnds, d, addMinutes(cloneDate(d), maxMinute-minMinute)));
3718 countForwardSegs(col);
3719 for (j=0; j<col.length; j++) {
3721 for (k=0; k<level.length; k++) {
3728 addDays(d, 1, true);
3734 function slotEventEnd(event) {
3736 return cloneDate(event.end);
3738 return addMinutes(cloneDate(event.start), opt('defaultEventMinutes'));
3743 // renders events in the 'time slots' at the bottom
3745 function renderSlotSegs(segs, modifiedEventId) {
3747 var i, segCnt=segs.length, seg,
3751 colI, levelI, forward,
3765 slotSegmentContainer = getSlotSegmentContainer(),
3767 colCnt = getColCnt();
3769 if (rtl = opt('isRTL')) {
3777 // calculate position/dimensions, create html
3778 for (i=0; i<segCnt; i++) {
3781 top = timePosition(seg.start, seg.start);
3782 bottom = timePosition(seg.start, seg.end);
3785 forward = seg.forward || 0;
3786 leftmost = colContentLeft(colI*dis + dit);
3787 availWidth = colContentRight(colI*dis + dit) - leftmost;
3788 availWidth = Math.min(availWidth-6, availWidth*.95); // TODO: move this to CSS
3790 // indented and thin
3791 outerWidth = availWidth / (levelI + forward + 1);
3794 // moderately wide, aligned left still
3795 outerWidth = ((availWidth / (forward + 1)) - (12/2)) * 2; // 12 is the predicted width of resizer =
3797 // can be entire width, aligned left
3798 outerWidth = availWidth;
3801 left = leftmost + // leftmost possible
3802 (availWidth / (levelI + forward + 1) * levelI) // indentation
3803 * dis + (rtl ? availWidth - outerWidth : 0); // rtl
3806 seg.outerWidth = outerWidth;
3807 seg.outerHeight = bottom - top;
3808 html += slotSegHtml(event, seg);
3810 slotSegmentContainer[0].innerHTML = html; // faster than html()
3811 eventElements = slotSegmentContainer.children();
3813 // retrieve elements, run through eventRender callback, bind event handlers
3814 for (i=0; i<segCnt; i++) {
3817 eventElement = $(eventElements[i]); // faster than eq()
3818 triggerRes = trigger('eventRender', event, event, eventElement);
3819 if (triggerRes === false) {
3820 eventElement.remove();
3822 if (triggerRes && triggerRes !== true) {
3823 eventElement.remove();
3824 eventElement = $(triggerRes)
3826 position: 'absolute',
3830 .appendTo(slotSegmentContainer);
3832 seg.element = eventElement;
3833 if (event._id === modifiedEventId) {
3834 bindSlotSeg(event, eventElement, seg);
3836 eventElement[0]._fci = i; // for lazySegBind
3838 reportEventElement(event, eventElement);
3842 lazySegBind(slotSegmentContainer, segs, bindSlotSeg);
3844 // record event sides and title positions
3845 for (i=0; i<segCnt; i++) {
3847 if (eventElement = seg.element) {
3848 val = vsideCache[key = seg.key = cssKey(eventElement[0])];
3849 seg.vsides = val === undefined ? (vsideCache[key] = vsides(eventElement, true)) : val;
3850 val = hsideCache[key];
3851 seg.hsides = val === undefined ? (hsideCache[key] = hsides(eventElement, true)) : val;
3852 contentElement = eventElement.find('div.fc-event-content');
3853 if (contentElement.length) {
3854 seg.contentTop = contentElement[0].offsetTop;
3859 // set all positions/dimensions at once
3860 for (i=0; i<segCnt; i++) {
3862 if (eventElement = seg.element) {
3863 eventElement[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
3864 height = Math.max(0, seg.outerHeight - seg.vsides);
3865 eventElement[0].style.height = height + 'px';
3867 if (seg.contentTop !== undefined && height - seg.contentTop < 10) {
3868 // not enough room for title, put it in the time header
3869 eventElement.find('div.fc-event-time')
3870 .text(formatDate(event.start, opt('timeFormat')) + ' - ' + event.title);
3871 eventElement.find('div.fc-event-title')
3874 trigger('eventAfterRender', event, event, eventElement);
3881 function slotSegHtml(event, seg) {
3883 var url = event.url;
3884 var skinCss = getSkinCss(event, opt);
3885 var skinCssAttr = (skinCss ? " style='" + skinCss + "'" : '');
3886 var classes = ['fc-event', 'fc-event-skin', 'fc-event-vert'];
3887 if (isEventDraggable(event)) {
3888 classes.push('fc-event-draggable');
3891 classes.push('fc-corner-top');
3894 classes.push('fc-corner-bottom');
3896 classes = classes.concat(event.className);
3898 classes = classes.concat(event.source.className || []);
3901 html += "a href='" + htmlEscape(event.url) + "'";
3906 " class='" + classes.join(' ') + "'" +
3907 " style='position:absolute;z-index:8;top:" + seg.top + "px;left:" + seg.left + "px;" + skinCss + "'" +
3909 "<div class='fc-event-inner fc-event-skin'" + skinCssAttr + ">" +
3910 "<div class='fc-event-head fc-event-skin'" + skinCssAttr + ">" +
3911 "<div class='fc-event-time'>" +
3912 htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
3915 "<div class='fc-event-content'>" +
3916 "<div class='fc-event-title'>" +
3917 htmlEscape(event.title) +
3920 "<div class='fc-event-bg'></div>" +
3921 "</div>"; // close inner
3922 if (seg.isEnd && isEventResizable(event)) {
3924 "<div class='ui-resizable-handle ui-resizable-s'>=</div>";
3927 "</" + (url ? "a" : "div") + ">";
3932 function bindDaySeg(event, eventElement, seg) {
3933 if (isEventDraggable(event)) {
3934 draggableDayEvent(event, eventElement, seg.isStart);
3936 if (seg.isEnd && isEventResizable(event)) {
3937 resizableDayEvent(event, eventElement, seg);
3939 eventElementHandlers(event, eventElement);
3940 // needs to be after, because resizableDayEvent might stopImmediatePropagation on click
3944 function bindSlotSeg(event, eventElement, seg) {
3945 var timeElement = eventElement.find('div.fc-event-time');
3946 if (isEventDraggable(event)) {
3947 draggableSlotEvent(event, eventElement, timeElement);
3949 if (seg.isEnd && isEventResizable(event)) {
3950 resizableSlotEvent(event, eventElement, timeElement);
3952 eventElementHandlers(event, eventElement);
3958 -----------------------------------------------------------------------------------*/
3961 // when event starts out FULL-DAY
3963 function draggableDayEvent(event, eventElement, isStart) {
3968 var dis = opt('isRTL') ? -1 : 1;
3969 var hoverListener = getHoverListener();
3970 var colWidth = getColWidth();
3971 var slotHeight = getSlotHeight();
3972 var minMinute = getMinMinute();
3973 eventElement.draggable({
3975 opacity: opt('dragOpacity', 'month'), // use whatever the month view was using
3976 revertDuration: opt('dragRevertDuration'),
3977 start: function(ev, ui) {
3978 trigger('eventDragStart', eventElement, event, ev, ui);
3979 hideEvents(event, eventElement);
3980 origWidth = eventElement.width();
3981 hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
3984 //setOverflowHidden(true);
3986 dayDelta = colDelta * dis;
3990 addDays(cloneDate(event.start), dayDelta),
3991 addDays(exclEndDay(event), dayDelta)
3995 // mouse is over bottom slots
3998 // convert event to temporary slot-event
3999 eventElement.width(colWidth - 10); // don't use entire width
4002 slotHeight * Math.round(
4003 (event.end ? ((event.end - event.start) / MINUTE_MS) : opt('defaultEventMinutes'))
4004 / opt('slotMinutes')
4007 eventElement.draggable('option', 'grid', [colWidth, 1]);
4014 revert = revert || (allDay && !dayDelta);
4017 //setOverflowHidden(false);
4020 eventElement.draggable('option', 'revert', revert);
4023 stop: function(ev, ui) {
4024 hoverListener.stop();
4026 trigger('eventDragStop', eventElement, event, ev, ui);
4028 // hasn't moved or is out of bounds (draggable has already reverted)
4030 eventElement.css('filter', ''); // clear IE opacity side-effects
4031 showEvents(event, eventElement);
4034 var minuteDelta = 0;
4036 minuteDelta = Math.round((eventElement.offset().top - getBodyContent().offset().top) / slotHeight)
4037 * opt('slotMinutes')
4039 - (event.start.getHours() * 60 + event.start.getMinutes());
4041 eventDrop(this, event, dayDelta, minuteDelta, allDay, ev, ui);
4043 //setOverflowHidden(false);
4046 function resetElement() {
4051 .draggable('option', 'grid', null);
4058 // when event starts out IN TIMESLOTS
4060 function draggableSlotEvent(event, eventElement, timeElement) {
4065 var prevMinuteDelta;
4066 var dis = opt('isRTL') ? -1 : 1;
4067 var hoverListener = getHoverListener();
4068 var colCnt = getColCnt();
4069 var colWidth = getColWidth();
4070 var slotHeight = getSlotHeight();
4071 eventElement.draggable({
4074 grid: [colWidth, slotHeight],
4075 axis: colCnt==1 ? 'y' : false,
4076 opacity: opt('dragOpacity'),
4077 revertDuration: opt('dragRevertDuration'),
4078 start: function(ev, ui) {
4079 trigger('eventDragStart', eventElement, event, ev, ui);
4080 hideEvents(event, eventElement);
4081 origPosition = eventElement.position();
4082 minuteDelta = prevMinuteDelta = 0;
4083 hoverListener.start(function(cell, origCell, rowDelta, colDelta) {
4084 eventElement.draggable('option', 'revert', !cell);
4087 dayDelta = colDelta * dis;
4088 if (opt('allDaySlot') && !cell.row) {
4091 // convert to temporary all-day event
4094 eventElement.draggable('option', 'grid', null);
4097 addDays(cloneDate(event.start), dayDelta),
4098 addDays(exclEndDay(event), dayDelta)
4107 drag: function(ev, ui) {
4108 minuteDelta = Math.round((ui.position.top - origPosition.top) / slotHeight) * opt('slotMinutes');
4109 if (minuteDelta != prevMinuteDelta) {
4111 updateTimeText(minuteDelta);
4113 prevMinuteDelta = minuteDelta;
4116 stop: function(ev, ui) {
4117 var cell = hoverListener.stop();
4119 trigger('eventDragStop', eventElement, event, ev, ui);
4120 if (cell && (dayDelta || minuteDelta || allDay)) {
4122 eventDrop(this, event, dayDelta, allDay ? 0 : minuteDelta, allDay, ev, ui);
4124 // either no change or out-of-bounds (draggable has already reverted)
4126 eventElement.css('filter', ''); // clear IE opacity side-effects
4127 eventElement.css(origPosition); // sometimes fast drags make event revert to wrong position
4129 showEvents(event, eventElement);
4133 function updateTimeText(minuteDelta) {
4134 var newStart = addMinutes(cloneDate(event.start), minuteDelta);
4137 newEnd = addMinutes(cloneDate(event.end), minuteDelta);
4139 timeElement.text(formatDates(newStart, newEnd, opt('timeFormat')));
4141 function resetElement() {
4142 // convert back to original slot-event
4144 timeElement.css('display', ''); // show() was causing display=inline
4145 eventElement.draggable('option', 'grid', [colWidth, slotHeight]);
4154 --------------------------------------------------------------------------------------*/
4157 function resizableSlotEvent(event, eventElement, timeElement) {
4158 var slotDelta, prevSlotDelta;
4159 var slotHeight = getSlotHeight();
4160 eventElement.resizable({
4162 s: 'div.ui-resizable-s'
4165 start: function(ev, ui) {
4166 slotDelta = prevSlotDelta = 0;
4167 hideEvents(event, eventElement);
4168 eventElement.css('z-index', 9);
4169 trigger('eventResizeStart', this, event, ev, ui);
4171 resize: function(ev, ui) {
4172 // don't rely on ui.size.height, doesn't take grid into account
4173 slotDelta = Math.round((Math.max(slotHeight, eventElement.height()) - ui.originalSize.height) / slotHeight);
4174 if (slotDelta != prevSlotDelta) {
4178 (!slotDelta && !event.end) ? null : // no change, so don't display time range
4179 addMinutes(eventEnd(event), opt('slotMinutes')*slotDelta),
4183 prevSlotDelta = slotDelta;
4186 stop: function(ev, ui) {
4187 trigger('eventResizeStop', this, event, ev, ui);
4189 eventResize(this, event, 0, opt('slotMinutes')*slotDelta, ev, ui);
4191 eventElement.css('z-index', 8);
4192 showEvents(event, eventElement);
4193 // BUG: if event was really short, need to put title back in span
4203 function countForwardSegs(levels) {
4204 var i, j, k, level, segForward, segBack;
4205 for (i=levels.length-1; i>0; i--) {
4207 for (j=0; j<level.length; j++) {
4208 segForward = level[j];
4209 for (k=0; k<levels[i-1].length; k++) {
4210 segBack = levels[i-1][k];
4211 if (segsCollide(segForward, segBack)) {
4212 segBack.forward = Math.max(segBack.forward||0, (segForward.forward||0)+1);
4222 function View(element, calendar, viewName) {
4227 t.element = element;
4228 t.calendar = calendar;
4231 t.trigger = trigger;
4232 //t.setOverflowHidden = setOverflowHidden;
4233 t.isEventDraggable = isEventDraggable;
4234 t.isEventResizable = isEventResizable;
4235 t.reportEvents = reportEvents;
4236 t.eventEnd = eventEnd;
4237 t.reportEventElement = reportEventElement;
4238 t.reportEventClear = reportEventClear;
4239 t.eventElementHandlers = eventElementHandlers;
4240 t.showEvents = showEvents;
4241 t.hideEvents = hideEvents;
4242 t.eventDrop = eventDrop;
4243 t.eventResize = eventResize;
4246 // t.visStart, t.visEnd
4250 var defaultEventEnd = t.defaultEventEnd;
4251 var normalizeEvent = calendar.normalizeEvent; // in EventManager
4252 var reportEventChange = calendar.reportEventChange;
4256 var eventsByID = {};
4257 var eventElements = [];
4258 var eventElementsByID = {};
4259 var options = calendar.options;
4263 function opt(name, viewNameOverride) {
4264 var v = options[name];
4265 if (typeof v == 'object') {
4266 return smartProperty(v, viewNameOverride || viewName);
4272 function trigger(name, thisObj) {
4273 return calendar.trigger.apply(
4275 [name, thisObj || t].concat(Array.prototype.slice.call(arguments, 2), [t])
4281 function setOverflowHidden(bool) {
4282 element.css('overflow', bool ? 'hidden' : '');
4287 function isEventDraggable(event) {
4288 return isEventEditable(event) && !opt('disableDragging');
4292 function isEventResizable(event) { // but also need to make sure the seg.isEnd == true
4293 return isEventEditable(event) && !opt('disableResizing');
4297 function isEventEditable(event) {
4298 return firstDefined(event.editable, (event.source || {}).editable, opt('editable'));
4304 ------------------------------------------------------------------------------*/
4307 // report when view receives new events
4308 function reportEvents(events) { // events are already normalized at this point
4310 var i, len=events.length, event;
4311 for (i=0; i<len; i++) {
4313 if (eventsByID[event._id]) {
4314 eventsByID[event._id].push(event);
4316 eventsByID[event._id] = [event];
4322 // returns a Date object for an event's end
4323 function eventEnd(event) {
4324 return event.end ? cloneDate(event.end) : defaultEventEnd(event);
4330 ------------------------------------------------------------------------------*/
4333 // report when view creates an element for an event
4334 function reportEventElement(event, element) {
4335 eventElements.push(element);
4336 if (eventElementsByID[event._id]) {
4337 eventElementsByID[event._id].push(element);
4339 eventElementsByID[event._id] = [element];
4344 function reportEventClear() {
4346 eventElementsByID = {};
4350 // attaches eventClick, eventMouseover, eventMouseout
4351 function eventElementHandlers(event, eventElement) {
4353 .click(function(ev) {
4354 if (!eventElement.hasClass('ui-draggable-dragging') &&
4355 !eventElement.hasClass('ui-resizable-resizing')) {
4356 return trigger('eventClick', this, event, ev);
4361 trigger('eventMouseover', this, event, ev);
4364 trigger('eventMouseout', this, event, ev);
4367 // TODO: don't fire eventMouseover/eventMouseout *while* dragging is occuring (on subject element)
4368 // TODO: same for resizing
4372 function showEvents(event, exceptElement) {
4373 eachEventElement(event, exceptElement, 'show');
4377 function hideEvents(event, exceptElement) {
4378 eachEventElement(event, exceptElement, 'hide');
4382 function eachEventElement(event, exceptElement, funcName) {
4383 var elements = eventElementsByID[event._id],
4384 i, len = elements.length;
4385 for (i=0; i<len; i++) {
4386 if (!exceptElement || elements[i][0] != exceptElement[0]) {
4387 elements[i][funcName]();
4394 /* Event Modification Reporting
4395 ---------------------------------------------------------------------------------*/
4398 function eventDrop(e, event, dayDelta, minuteDelta, allDay, ev, ui) {
4399 var oldAllDay = event.allDay;
4400 var eventId = event._id;
4401 moveEvents(eventsByID[eventId], dayDelta, minuteDelta, allDay);
4410 // TODO: investigate cases where this inverse technique might not work
4411 moveEvents(eventsByID[eventId], -dayDelta, -minuteDelta, oldAllDay);
4412 reportEventChange(eventId);
4417 reportEventChange(eventId);
4421 function eventResize(e, event, dayDelta, minuteDelta, ev, ui) {
4422 var eventId = event._id;
4423 elongateEvents(eventsByID[eventId], dayDelta, minuteDelta);
4431 // TODO: investigate cases where this inverse technique might not work
4432 elongateEvents(eventsByID[eventId], -dayDelta, -minuteDelta);
4433 reportEventChange(eventId);
4438 reportEventChange(eventId);
4443 /* Event Modification Math
4444 ---------------------------------------------------------------------------------*/
4447 function moveEvents(events, dayDelta, minuteDelta, allDay) {
4448 minuteDelta = minuteDelta || 0;
4449 for (var e, len=events.length, i=0; i<len; i++) {
4451 if (allDay !== undefined) {
4454 addMinutes(addDays(e.start, dayDelta, true), minuteDelta);
4456 e.end = addMinutes(addDays(e.end, dayDelta, true), minuteDelta);
4458 normalizeEvent(e, options);
4463 function elongateEvents(events, dayDelta, minuteDelta) {
4464 minuteDelta = minuteDelta || 0;
4465 for (var e, len=events.length, i=0; i<len; i++) {
4467 e.end = addMinutes(addDays(eventEnd(e), dayDelta, true), minuteDelta);
4468 normalizeEvent(e, options);
4475 function DayEventRenderer() {
4480 t.renderDaySegs = renderDaySegs;
4481 t.resizableDayEvent = resizableDayEvent;
4486 var trigger = t.trigger;
4487 var isEventDraggable = t.isEventDraggable;
4488 var isEventResizable = t.isEventResizable;
4489 var eventEnd = t.eventEnd;
4490 var reportEventElement = t.reportEventElement;
4491 var showEvents = t.showEvents;
4492 var hideEvents = t.hideEvents;
4493 var eventResize = t.eventResize;
4494 var getRowCnt = t.getRowCnt;
4495 var getColCnt = t.getColCnt;
4496 var getColWidth = t.getColWidth;
4497 var allDayRow = t.allDayRow;
4498 var allDayBounds = t.allDayBounds;
4499 var colContentLeft = t.colContentLeft;
4500 var colContentRight = t.colContentRight;
4501 var dayOfWeekCol = t.dayOfWeekCol;
4502 var dateCell = t.dateCell;
4503 var compileDaySegs = t.compileDaySegs;
4504 var getDaySegmentContainer = t.getDaySegmentContainer;
4505 var bindDaySeg = t.bindDaySeg; //TODO: streamline this
4506 var formatDates = t.calendar.formatDates;
4507 var renderDayOverlay = t.renderDayOverlay;
4508 var clearOverlays = t.clearOverlays;
4509 var clearSelection = t.clearSelection;
4514 -----------------------------------------------------------------------------*/
4517 function renderDaySegs(segs, modifiedEventId) {
4518 var segmentContainer = getDaySegmentContainer();
4520 var rowCnt = getRowCnt();
4521 var colCnt = getColCnt();
4527 var segCnt = segs.length;
4531 segmentContainer[0].innerHTML = daySegHTML(segs); // faster than .html()
4532 daySegElementResolve(segs, segmentContainer.children());
4533 daySegElementReport(segs);
4534 daySegHandlers(segs, segmentContainer, modifiedEventId);
4535 daySegCalcHSides(segs);
4536 daySegSetWidths(segs);
4537 daySegCalcHeights(segs);
4538 rowDivs = getRowDivs();
4539 // set row heights, calculate event tops (in relation to row top)
4540 for (rowI=0; rowI<rowCnt; rowI++) {
4543 for (j=0; j<colCnt; j++) {
4546 while (i<segCnt && (seg = segs[i]).row == rowI) {
4547 // loop through segs in a row
4548 top = arrayMax(colHeights.slice(seg.startCol, seg.endCol));
4550 top += seg.outerHeight;
4551 for (k=seg.startCol; k<seg.endCol; k++) {
4552 colHeights[k] = top;
4556 rowDivs[rowI].height(arrayMax(colHeights));
4558 daySegSetTops(segs, getRowTops(rowDivs));
4562 function renderTempDaySegs(segs, adjustRow, adjustTop) {
4563 var tempContainer = $("<div/>");
4565 var segmentContainer = getDaySegmentContainer();
4567 var segCnt = segs.length;
4569 tempContainer[0].innerHTML = daySegHTML(segs); // faster than .html()
4570 elements = tempContainer.children();
4571 segmentContainer.append(elements);
4572 daySegElementResolve(segs, elements);
4573 daySegCalcHSides(segs);
4574 daySegSetWidths(segs);
4575 daySegCalcHeights(segs);
4576 daySegSetTops(segs, getRowTops(getRowDivs()));
4578 for (i=0; i<segCnt; i++) {
4579 element = segs[i].element;
4581 if (segs[i].row === adjustRow) {
4582 element.css('top', adjustTop);
4584 elements.push(element[0]);
4591 function daySegHTML(segs) { // also sets seg.left and seg.outerWidth
4592 var rtl = opt('isRTL');
4594 var segCnt=segs.length;
4599 var bounds = allDayBounds();
4600 var minLeft = bounds.left;
4601 var maxLeft = bounds.right;
4608 // calculate desired position/dimensions, create html
4609 for (i=0; i<segCnt; i++) {
4612 classes = ['fc-event', 'fc-event-skin', 'fc-event-hori'];
4613 if (isEventDraggable(event)) {
4614 classes.push('fc-event-draggable');
4618 classes.push('fc-corner-right');
4621 classes.push('fc-corner-left');
4623 leftCol = dayOfWeekCol(seg.end.getDay()-1);
4624 rightCol = dayOfWeekCol(seg.start.getDay());
4625 left = seg.isEnd ? colContentLeft(leftCol) : minLeft;
4626 right = seg.isStart ? colContentRight(rightCol) : maxLeft;
4629 classes.push('fc-corner-left');
4632 classes.push('fc-corner-right');
4634 leftCol = dayOfWeekCol(seg.start.getDay());
4635 rightCol = dayOfWeekCol(seg.end.getDay()-1);
4636 left = seg.isStart ? colContentLeft(leftCol) : minLeft;
4637 right = seg.isEnd ? colContentRight(rightCol) : maxLeft;
4639 classes = classes.concat(event.className);
4641 classes = classes.concat(event.source.className || []);
4644 skinCss = getSkinCss(event, opt);
4646 html += "<a href='" + htmlEscape(url) + "'";
4651 " class='" + classes.join(' ') + "'" +
4652 " style='position:absolute;z-index:8;left:"+left+"px;" + skinCss + "'" +
4655 " class='fc-event-inner fc-event-skin'" +
4656 (skinCss ? " style='" + skinCss + "'" : '') +
4658 if (!event.allDay && seg.isStart) {
4660 "<span class='fc-event-time'>" +
4661 htmlEscape(formatDates(event.start, event.end, opt('timeFormat'))) +
4665 "<span class='fc-event-title'>" + htmlEscape(event.title) + "</span>" +
4667 if (seg.isEnd && isEventResizable(event)) {
4669 "<div class='ui-resizable-handle ui-resizable-" + (rtl ? 'w' : 'e') + "'>" +
4670 " " + // makes hit area a lot better for IE6/7
4674 "</" + (url ? "a" : "div" ) + ">";
4676 seg.outerWidth = right - left;
4677 seg.startCol = leftCol;
4678 seg.endCol = rightCol + 1; // needs to be exclusive
4684 function daySegElementResolve(segs, elements) { // sets seg.element
4686 var segCnt = segs.length;
4691 for (i=0; i<segCnt; i++) {
4694 element = $(elements[i]); // faster than .eq()
4695 triggerRes = trigger('eventRender', event, event, element);
4696 if (triggerRes === false) {
4699 if (triggerRes && triggerRes !== true) {
4700 triggerRes = $(triggerRes)
4702 position: 'absolute',
4705 element.replaceWith(triggerRes);
4706 element = triggerRes;
4708 seg.element = element;
4714 function daySegElementReport(segs) {
4716 var segCnt = segs.length;
4719 for (i=0; i<segCnt; i++) {
4721 element = seg.element;
4723 reportEventElement(seg.event, element);
4729 function daySegHandlers(segs, segmentContainer, modifiedEventId) {
4731 var segCnt = segs.length;
4735 // retrieve elements, run through eventRender callback, bind handlers
4736 for (i=0; i<segCnt; i++) {
4738 element = seg.element;
4741 if (event._id === modifiedEventId) {
4742 bindDaySeg(event, element, seg);
4744 element[0]._fci = i; // for lazySegBind
4748 lazySegBind(segmentContainer, segs, bindDaySeg);
4752 function daySegCalcHSides(segs) { // also sets seg.key
4754 var segCnt = segs.length;
4758 var hsideCache = {};
4759 // record event horizontal sides
4760 for (i=0; i<segCnt; i++) {
4762 element = seg.element;
4764 key = seg.key = cssKey(element[0]);
4765 val = hsideCache[key];
4766 if (val === undefined) {
4767 val = hsideCache[key] = hsides(element, true);
4775 function daySegSetWidths(segs) {
4777 var segCnt = segs.length;
4780 for (i=0; i<segCnt; i++) {
4782 element = seg.element;
4784 element[0].style.width = Math.max(0, seg.outerWidth - seg.hsides) + 'px';
4790 function daySegCalcHeights(segs) {
4792 var segCnt = segs.length;
4796 var vmarginCache = {};
4797 // record event heights
4798 for (i=0; i<segCnt; i++) {
4800 element = seg.element;
4802 key = seg.key; // created in daySegCalcHSides
4803 val = vmarginCache[key];
4804 if (val === undefined) {
4805 val = vmarginCache[key] = vmargins(element);
4807 seg.outerHeight = element[0].offsetHeight + val;
4813 function getRowDivs() {
4815 var rowCnt = getRowCnt();
4817 for (i=0; i<rowCnt; i++) {
4818 rowDivs[i] = allDayRow(i)
4819 .find('td:first div.fc-day-content > div'); // optimal selector?
4825 function getRowTops(rowDivs) {
4827 var rowCnt = rowDivs.length;
4829 for (i=0; i<rowCnt; i++) {
4830 tops[i] = rowDivs[i][0].offsetTop; // !!?? but this means the element needs position:relative if in a table cell!!!!
4836 function daySegSetTops(segs, rowTops) { // also triggers eventAfterRender
4838 var segCnt = segs.length;
4842 for (i=0; i<segCnt; i++) {
4844 element = seg.element;
4846 element[0].style.top = rowTops[seg.row] + (seg.top||0) + 'px';
4848 trigger('eventAfterRender', event, event, element);
4856 -----------------------------------------------------------------------------------*/
4859 function resizableDayEvent(event, element, seg) {
4860 var rtl = opt('isRTL');
4861 var direction = rtl ? 'w' : 'e';
4862 var handle = element.find('div.ui-resizable-' + direction);
4863 var isResizing = false;
4865 // TODO: look into using jquery-ui mouse widget for this stuff
4866 disableTextSelection(element); // prevent native <a> selection for IE
4868 .mousedown(function(ev) { // prevent native <a> selection for others
4869 ev.preventDefault();
4871 .click(function(ev) {
4873 ev.preventDefault(); // prevent link from being visited (only method that worked in IE6)
4874 ev.stopImmediatePropagation(); // prevent fullcalendar eventClick handler from being called
4875 // (eventElementHandlers needs to be bound after resizableDayEvent)
4879 handle.mousedown(function(ev) {
4880 if (ev.which != 1) {
4881 return; // needs to be left mouse button
4884 var hoverListener = t.getHoverListener();
4885 var rowCnt = getRowCnt();
4886 var colCnt = getColCnt();
4887 var dis = rtl ? -1 : 1;
4888 var dit = rtl ? colCnt-1 : 0;
4889 var elementTop = element.css('top');
4892 var eventCopy = $.extend({}, event);
4893 var minCell = dateCell(event.start);
4896 .css('cursor', direction + '-resize')
4897 .one('mouseup', mouseup);
4898 trigger('eventResizeStart', this, event, ev);
4899 hoverListener.start(function(cell, origCell) {
4901 var r = Math.max(minCell.row, cell.row);
4904 r = 0; // hack for all-day area in agenda views
4906 if (r == minCell.row) {
4908 c = Math.min(minCell.col, c);
4910 c = Math.max(minCell.col, c);
4913 dayDelta = (r*7 + c*dis+dit) - (origCell.row*7 + origCell.col*dis+dit);
4914 var newEnd = addDays(eventEnd(event), dayDelta, true);
4916 eventCopy.end = newEnd;
4917 var oldHelpers = helpers;
4918 helpers = renderTempDaySegs(compileDaySegs([eventCopy]), seg.row, elementTop);
4919 helpers.find('*').css('cursor', direction + '-resize');
4921 oldHelpers.remove();
4932 renderDayOverlay(event.start, addDays(cloneDate(newEnd), 1)); // coordinate grid already rebuild at hoverListener.start
4936 function mouseup(ev) {
4937 trigger('eventResizeStop', this, event, ev);
4938 $('body').css('cursor', '');
4939 hoverListener.stop();
4942 eventResize(this, event, dayDelta, 0, ev);
4943 // event redraw will clear helpers
4945 // otherwise, the drag handler already restored the old events
4947 setTimeout(function() { // make this happen after the element's click event
4958 //BUG: unselect needs to be triggered when events are dragged+dropped
4960 function SelectionManager() {
4966 t.unselect = unselect;
4967 t.reportSelection = reportSelection;
4968 t.daySelectionMousedown = daySelectionMousedown;
4973 var trigger = t.trigger;
4974 var defaultSelectionEnd = t.defaultSelectionEnd;
4975 var renderSelection = t.renderSelection;
4976 var clearSelection = t.clearSelection;
4980 var selected = false;
4985 if (opt('selectable') && opt('unselectAuto')) {
4986 $(document).mousedown(function(ev) {
4987 var ignore = opt('unselectCancel');
4989 if ($(ev.target).parents(ignore).length) { // could be optimized to stop after first match
4998 function select(startDate, endDate, allDay) {
5001 endDate = defaultSelectionEnd(startDate, allDay);
5003 renderSelection(startDate, endDate, allDay);
5004 reportSelection(startDate, endDate, allDay);
5008 function unselect(ev) {
5012 trigger('unselect', null, ev);
5017 function reportSelection(startDate, endDate, allDay, ev) {
5019 trigger('select', null, startDate, endDate, allDay, ev);
5023 function daySelectionMousedown(ev) { // not really a generic manager method, oh well
5024 var cellDate = t.cellDate;
5025 var cellIsAllDay = t.cellIsAllDay;
5026 var hoverListener = t.getHoverListener();
5027 var reportDayClick = t.reportDayClick; // this is hacky and sort of weird
5028 if (ev.which == 1 && opt('selectable')) { // which==1 means left mouse button
5030 var _mousedownElement = this;
5032 hoverListener.start(function(cell, origCell) { // TODO: maybe put cellDate/cellIsAllDay info in cell
5034 if (cell && cellIsAllDay(cell)) {
5035 dates = [ cellDate(origCell), cellDate(cell) ].sort(cmp);
5036 renderSelection(dates[0], dates[1], true);
5041 $(document).one('mouseup', function(ev) {
5042 hoverListener.stop();
5044 if (+dates[0] == +dates[1]) {
5045 reportDayClick(dates[0], true, ev);
5047 reportSelection(dates[0], dates[1], true, ev);
5056 function OverlayManager() {
5061 t.renderOverlay = renderOverlay;
5062 t.clearOverlays = clearOverlays;
5066 var usedOverlays = [];
5067 var unusedOverlays = [];
5070 function renderOverlay(rect, parent) {
5071 var e = unusedOverlays.shift();
5073 e = $("<div class='fc-cell-overlay' style='position:absolute;z-index:3'/>");
5075 if (e[0].parentNode != parent[0]) {
5078 usedOverlays.push(e.css(rect).show());
5083 function clearOverlays() {
5085 while (e = usedOverlays.shift()) {
5086 unusedOverlays.push(e.hide().unbind());
5093 function CoordinateGrid(buildFunc) {
5100 t.build = function() {
5103 buildFunc(rows, cols);
5107 t.cell = function(x, y) {
5108 var rowCnt = rows.length;
5109 var colCnt = cols.length;
5111 for (i=0; i<rowCnt; i++) {
5112 if (y >= rows[i][0] && y < rows[i][1]) {
5117 for (i=0; i<colCnt; i++) {
5118 if (x >= cols[i][0] && x < cols[i][1]) {
5123 return (r>=0 && c>=0) ? { row:r, col:c } : null;
5127 t.rect = function(row0, col0, row1, col1, originElement) { // row1,col1 is inclusive
5128 var origin = originElement.offset();
5130 top: rows[row0][0] - origin.top,
5131 left: cols[col0][0] - origin.left,
5132 width: cols[col1][1] - cols[col0][0],
5133 height: rows[row1][1] - rows[row0][0]
5139 function HoverListener(coordinateGrid) {
5149 t.start = function(_change, ev, _bindType) {
5151 firstCell = cell = null;
5152 coordinateGrid.build();
5154 bindType = _bindType || 'mousemove';
5155 $(document).bind(bindType, mouse);
5159 function mouse(ev) {
5160 _fixUIEvent(ev); // see below
5161 var newCell = coordinateGrid.cell(ev.pageX, ev.pageY);
5162 if (!newCell != !cell || newCell && (newCell.row != cell.row || newCell.col != cell.col)) {
5165 firstCell = newCell;
5167 change(newCell, firstCell, newCell.row-firstCell.row, newCell.col-firstCell.col);
5169 change(newCell, firstCell);
5176 t.stop = function() {
5177 $(document).unbind(bindType, mouse);
5186 // this fix was only necessary for jQuery UI 1.8.16 (and jQuery 1.7 or 1.7.1)
5187 // upgrading to jQuery UI 1.8.17 (and using either jQuery 1.7 or 1.7.1) fixed the problem
5188 // but keep this in here for 1.8.16 users
5189 // and maybe remove it down the line
5191 function _fixUIEvent(event) { // for issue 1168
5192 if (event.pageX === undefined) {
5193 event.pageX = event.originalEvent.pageX;
5194 event.pageY = event.originalEvent.pageY;
5197 function HorizontalPositionCache(getElement) {
5205 return elements[i] = elements[i] || getElement(i);
5208 t.left = function(i) {
5209 return lefts[i] = lefts[i] === undefined ? e(i).position().left : lefts[i];
5212 t.right = function(i) {
5213 return rights[i] = rights[i] === undefined ? t.left(i) + e(i).width() : rights[i];
5216 t.clear = function() {