PageSourceSearch

https://imprensanacional.pt/wp-content/themes/imprensa_nacional/js/calander/fullcalendar.js?ver=1790856328

js imprensanacional.pt collected 2026-10-02 07:53:54 UTC 393,222 bytes, 13,524 lines download raw bytes

1/*!
2 * FullCalendar v3.0.1
3 * Docs & License: http://fullcalendar.io/
4 * (c) 2016 Adam Shaw
5 */
6
7(function(factory) {
8	if (typeof define === 'function' && define.amd) {
9		define([ 'jquery', 'moment' ], factory);
10	}
11	else if (typeof exports === 'object') { // Node/CommonJS
12		module.exports = factory(require('jquery'), require('moment'));
13	}
14	else {
15		factory(jQuery, moment);
16	}
17})(function($, moment) {
18
19;;
20
21var FC = $.fullCalendar = {
22	version: "3.0.1",
23	internalApiVersion: 6
24};
25var fcViews = FC.views = {};
26
27
28$.fn.fullCalendar = function(options) {
29	var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
30	var res = this; // what this function will return (this jQuery object by default)
31
32	this.each(function(i, _element) { // loop each DOM element involved
33		var element = $(_element);
34		var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
35		var singleRes; // the returned value of this single method call
36
37		// a method call
38		if (typeof options === 'string') {
39			if (calendar && $.isFunction(calendar[options])) {
40				singleRes = calendar[options].apply(calendar, args);
41				if (!i) {
42					res = singleRes; // record the first method call result
43				}
44				if (options === 'destroy') { // for the destroy method, must remove Calendar object data
45					element.removeData('fullCalendar');
46				}
47			}
48		}
49		// a new calendar initialization
50		else if (!calendar) { // don't initialize twice
51			calendar = new Calendar(element, options);
52			element.data('fullCalendar', calendar);
53			calendar.render();
54		}
55	});
56	
57	return res;
58};
59
60
61var complexOptions = [ // names of options that are objects whose properties should be combined
62	'header',
63	'buttonText',
64	'buttonIcons',
65	'themeButtonIcons'
66];
67
68
69// Merges an array of option objects into a single object
70function mergeOptions(optionObjs) {
71	return mergeProps(optionObjs, complexOptions);
72}
73
74;;
75
76// exports
77FC.intersectRanges = intersectRanges;
78FC.applyAll = applyAll;
79FC.debounce = debounce;
80FC.isInt = isInt;
81FC.htmlEscape = htmlEscape;
82FC.cssToStr = cssToStr;
83FC.proxy = proxy;
84FC.capitaliseFirstLetter = capitaliseFirstLetter;
85
86
87/* FullCalendar-specific DOM Utilities
88----------------------------------------------------------------------------------------------------------------------*/
89
90
91// Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left
92// and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that.
93function compensateScroll(rowEls, scrollbarWidths) {
94	if (scrollbarWidths.left) {
95		rowEls.css({
96			'border-left-width': 1,
97			'margin-left': scrollbarWidths.left - 1
98		});
99	}
100	if (scrollbarWidths.right) {
101		rowEls.css({
102			'border-right-width': 1,
103			'margin-right': scrollbarWidths.right - 1
104		});
105	}
106}
107
108
109// Undoes compensateScroll and restores all borders/margins
110function uncompensateScroll(rowEls) {
111	rowEls.css({
112		'margin-left': '',
113		'margin-right': '',
114		'border-left-width': '',
115		'border-right-width': ''
116	});
117}
118
119
120// Make the mouse cursor express that an event is not allowed in the current area
121function disableCursor() {
122	$('body').addClass('fc-not-allowed');
123}
124
125
126// Returns the mouse cursor to its original look
127function enableCursor() {
128	$('body').removeClass('fc-not-allowed');
129}
130
131
132// Given a total available height to fill, have `els` (essentially child rows) expand to accomodate.
133// By default, all elements that are shorter than the recommended height are expanded uniformly, not considering
134// any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and 
135// reduces the available height.
136function distributeHeight(els, availableHeight, shouldRedistribute) {
137
138	// *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions,
139	// and it is better to be shorter than taller, to avoid creating unnecessary scrollbars.
140
141	var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element
142	var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE*
143	var flexEls = []; // elements that are allowed to expand. array of DOM nodes
144	var flexOffsets = []; // amount of vertical space it takes up
145	var flexHeights = []; // actual css height
146	var usedHeight = 0;
147
148	undistributeHeight(els); // give all elements their natural height
149
150	// find elements that are below the recommended height (expandable).
151	// important to query for heights in a single first pass (to avoid reflow oscillation).
152	els.each(function(i, el) {
153		var minOffset = i === els.length - 1 ? minOffset2 : minOffset1;
154		var naturalOffset = $(el).outerHeight(true);
155
156		if (naturalOffset < minOffset) {
157			flexEls.push(el);
158			flexOffsets.push(naturalOffset);
159			flexHeights.push($(el).height());
160		}
161		else {
162			// this element stretches past recommended height (non-expandable). mark the space as occupied.
163			usedHeight += naturalOffset;
164		}
165	});
166
167	// readjust the recommended height to only consider the height available to non-maxed-out rows.
168	if (shouldRedistribute) {
169		availableHeight -= usedHeight;
170		minOffset1 = Math.floor(availableHeight / flexEls.length);
171		minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE*
172	}
173
174	// assign heights to all expandable elements
175	$(flexEls).each(function(i, el) {
176		var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1;
177		var naturalOffset = flexOffsets[i];
178		var naturalHeight = flexHeights[i];
179		var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding
180
181		if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things
182			$(el).height(newHeight);
183		}
184	});
185}
186
187
188// Undoes distrubuteHeight, restoring all els to their natural height
189function undistributeHeight(els) {
190	els.height('');
191}
192
193
194// Given `els`, a jQuery set of <td> cells, find the cell with the largest natural width and set the widths of all the
195// cells to be that width.
196// PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline
197function matchCellWidths(els) {
198	var maxInnerWidth = 0;
199
200	els.find('> *').each(function(i, innerEl) {
201		var innerWidth = $(innerEl).outerWidth();
202		if (innerWidth > maxInnerWidth) {
203			maxInnerWidth = innerWidth;
204		}
205	});
206
207	maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance
208
209	els.width(maxInnerWidth);
210
211	return maxInnerWidth;
212}
213
214
215// Given one element that resides inside another,
216// Subtracts the height of the inner element from the outer element.
217function subtractInnerElHeight(outerEl, innerEl) {
218	var both = outerEl.add(innerEl);
219	var diff;
220
221	// effin' IE8/9/10/11 sometimes returns 0 for dimensions. this weird hack was the only thing that worked
222	both.css({
223		position: 'relative', // cause a reflow, which will force fresh dimension recalculation
224		left: -1 // ensure reflow in case the el was already relative. negative is less likely to cause new scroll
225	});
226	diff = outerEl.outerHeight() - innerEl.outerHeight(); // grab the dimensions
227	both.css({ position: '', left: '' }); // undo hack
228
229	return diff;
230}
231
232
233/* Element Geom Utilities
234----------------------------------------------------------------------------------------------------------------------*/
235
236FC.getOuterRect = getOuterRect;
237FC.getClientRect = getClientRect;
238FC.getContentRect = getContentRect;
239FC.getScrollbarWidths = getScrollbarWidths;
240
241
242// borrowed from https://github.com/jquery/jquery-ui/blob/1.11.0/ui/core.js#L51
243function getScrollParent(el) {
244	var position = el.css('position'),
245		scrollParent = el.parents().filter(function() {
246			var parent = $(this);
247			return (/(auto|scroll)/).test(
248				parent.css('overflow') + parent.css('overflow-y') + parent.css('overflow-x')
249			);
250		}).eq(0);
251
252	return position === 'fixed' || !scrollParent.length ? $(el[0].ownerDocument || document) : scrollParent;
253}
254
255
256// Queries the outer bounding area of a jQuery element.
257// Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
258// Origin is optional.
259function getOuterRect(el, origin) {
260	var offset = el.offset();
261	var left = offset.left - (origin ? origin.left : 0);
262	var top = offset.top - (origin ? origin.top : 0);
263
264	return {
265		left: left,
266		right: left + el.outerWidth(),
267		top: top,
268		bottom: top + el.outerHeight()
269	};
270}
271
272
273// Queries the area within the margin/border/scrollbars of a jQuery element. Does not go within the padding.
274// Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
275// Origin is optional.
276// NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
277function getClientRect(el, origin) {
278	var offset = el.offset();
279	var scrollbarWidths = getScrollbarWidths(el);
280	var left = offset.left + getCssFloat(el, 'border-left-width') + scrollbarWidths.left - (origin ? origin.left : 0);
281	var top = offset.top + getCssFloat(el, 'border-top-width') + scrollbarWidths.top - (origin ? origin.top : 0);
282
283	return {
284		left: left,
285		right: left + el[0].clientWidth, // clientWidth includes padding but NOT scrollbars
286		top: top,
287		bottom: top + el[0].clientHeight // clientHeight includes padding but NOT scrollbars
288	};
289}
290
291
292// Queries the area within the margin/border/padding of a jQuery element. Assumed not to have scrollbars.
293// Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
294// Origin is optional.
295function getContentRect(el, origin) {
296	var offset = el.offset(); // just outside of border, margin not included
297	var left = offset.left + getCssFloat(el, 'border-left-width') + getCssFloat(el, 'padding-left') -
298		(origin ? origin.left : 0);
299	var top = offset.top + getCssFloat(el, 'border-top-width') + getCssFloat(el, 'padding-top') -
300		(origin ? origin.top : 0);
301
302	return {
303		left: left,
304		right: left + el.width(),
305		top: top,
306		bottom: top + el.height()
307	};
308}
309
310
311// Returns the computed left/right/top/bottom scrollbar widths for the given jQuery element.
312// NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
313function getScrollbarWidths(el) {
314	var leftRightWidth = el.innerWidth() - el[0].clientWidth; // the paddings cancel out, leaving the scrollbars
315	var widths = {
316		left: 0,
317		right: 0,
318		top: 0,
319		bottom: el.innerHeight() - el[0].clientHeight // the paddings cancel out, leaving the bottom scrollbar
320	};
321
322	if (getIsLeftRtlScrollbars() && el.css('direction') == 'rtl') { // is the scrollbar on the left side?
323		widths.left = leftRightWidth;
324	}
325	else {
326		widths.right = leftRightWidth;
327	}
328
329	return widths;
330}
331
332
333// Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side
334
335var _isLeftRtlScrollbars = null;
336
337function getIsLeftRtlScrollbars() { // responsible for caching the computation
338	if (_isLeftRtlScrollbars === null) {
339		_isLeftRtlScrollbars = computeIsLeftRtlScrollbars();
340	}
341	return _isLeftRtlScrollbars;
342}
343
344function computeIsLeftRtlScrollbars() { // creates an offscreen test element, then removes it
345	var el = $('<div><div/></div>')
346		.css({
347			position: 'absolute',
348			top: -1000,
349			left: 0,
350			border: 0,
351			padding: 0,
352			overflow: 'scroll',
353			direction: 'rtl'
354		})
355		.appendTo('body');
356	var innerEl = el.children();
357	var res = innerEl.offset().left > el.offset().left; // is the inner div shifted to accommodate a left scrollbar?
358	el.remove();
359	return res;
360}
361
362
363// Retrieves a jQuery element's computed CSS value as a floating-point number.
364// If the queried value is non-numeric (ex: IE can return "medium" for border width), will just return zero.
365function getCssFloat(el, prop) {
366	return parseFloat(el.css(prop)) || 0;
367}
368
369
370/* Mouse / Touch Utilities
371----------------------------------------------------------------------------------------------------------------------*/
372
373FC.preventDefault = preventDefault;
374
375
376// Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
377function isPrimaryMouseButton(ev) {
378	return ev.which == 1 && !ev.ctrlKey;
379}
380
381
382function getEvX(ev) {
383	if (ev.pageX !== undefined) {
384		return ev.pageX;
385	}
386	var touches = ev.originalEvent.touches;
387	if (touches) {
388		return touches[0].pageX;
389	}
390}
391
392
393function getEvY(ev) {
394	if (ev.pageY !== undefined) {
395		return ev.pageY;
396	}
397	var touches = ev.originalEvent.touches;
398	if (touches) {
399		return touches[0].pageY;
400	}
401}
402
403
404function getEvIsTouch(ev) {
405	return /^touch/.test(ev.type);
406}
407
408
409function preventSelection(el) {
410	el.addClass('fc-unselectable')
411		.on('selectstart', preventDefault);
412}
413
414
415// Stops a mouse/touch event from doing it's native browser action
416function preventDefault(ev) {
417	ev.preventDefault();
418}
419
420
421// attach a handler to get called when ANY scroll action happens on the page.
422// this was impossible to do with normal on/off because 'scroll' doesn't bubble.
423// http://stackoverflow.com/a/32954565/96342
424// returns `true` on success.
425function bindAnyScroll(handler) {
426	if (window.addEventListener) {
427		window.addEventListener('scroll', handler, true); // useCapture=true
428		return true;
429	}
430	return false;
431}
432
433
434// undoes bindAnyScroll. must pass in the original function.
435// returns `true` on success.
436function unbindAnyScroll(handler) {
437	if (window.removeEventListener) {
438		window.removeEventListener('scroll', handler, true); // useCapture=true
439		return true;
440	}
441	return false;
442}
443
444
445/* General Geometry Utils
446----------------------------------------------------------------------------------------------------------------------*/
447
448FC.intersectRects = intersectRects;
449
450// Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false
451function intersectRects(rect1, rect2) {
452	var res = {
453		left: Math.max(rect1.left, rect2.left),
454		right: Math.min(rect1.right, rect2.right),
455		top: Math.max(rect1.top, rect2.top),
456		bottom: Math.min(rect1.bottom, rect2.bottom)
457	};
458
459	if (res.left < res.right && res.top < res.bottom) {
460		return res;
461	}
462	return false;
463}
464
465
466// Returns a new point that will have been moved to reside within the given rectangle
467function constrainPoint(point, rect) {
468	return {
469		left: Math.min(Math.max(point.left, rect.left), rect.right),
470		top: Math.min(Math.max(point.top, rect.top), rect.bottom)
471	};
472}
473
474
475// Returns a point that is the center of the given rectangle
476function getRectCenter(rect) {
477	return {
478		left: (rect.left + rect.right) / 2,
479		top: (rect.top + rect.bottom) / 2
480	};
481}
482
483
484// Subtracts point2's coordinates from point1's coordinates, returning a delta
485function diffPoints(point1, point2) {
486	return {
487		left: point1.left - point2.left,
488		top: point1.top - point2.top
489	};
490}
491
492
493/* Object Ordering by Field
494----------------------------------------------------------------------------------------------------------------------*/
495
496FC.parseFieldSpecs = parseFieldSpecs;
497FC.compareByFieldSpecs = compareByFieldSpecs;
498FC.compareByFieldSpec = compareByFieldSpec;
499FC.flexibleCompare = flexibleCompare;
500
501
502function parseFieldSpecs(input) {
503	var specs = [];
504	var tokens = [];
505	var i, token;
506
507	if (typeof input === 'string') {
508		tokens = input.split(/\s*,\s*/);
509	}
510	else if (typeof input === 'function') {
511		tokens = [ input ];
512	}
513	else if ($.isArray(input)) {
514		tokens = input;
515	}
516
517	for (i = 0; i < tokens.length; i++) {
518		token = tokens[i];
519
520		if (typeof token === 'string') {
521			specs.push(
522				token.charAt(0) == '-' ?
523					{ field: token.substring(1), order: -1 } :
524					{ field: token, order: 1 }
525			);
526		}
527		else if (typeof token === 'function') {
528			specs.push({ func: token });
529		}
530	}
531
532	return specs;
533}
534
535
536function compareByFieldSpecs(obj1, obj2, fieldSpecs) {
537	var i;
538	var cmp;
539
540	for (i = 0; i < fieldSpecs.length; i++) {
541		cmp = compareByFieldSpec(obj1, obj2, fieldSpecs[i]);
542		if (cmp) {
543			return cmp;
544		}
545	}
546
547	return 0;
548}
549
550
551function compareByFieldSpec(obj1, obj2, fieldSpec) {
552	if (fieldSpec.func) {
553		return fieldSpec.func(obj1, obj2);
554	}
555	return flexibleCompare(obj1[fieldSpec.field], obj2[fieldSpec.field]) *
556		(fieldSpec.order || 1);
557}
558
559
560function flexibleCompare(a, b) {
561	if (!a && !b) {
562		return 0;
563	}
564	if (b == null) {
565		return -1;
566	}
567	if (a == null) {
568		return 1;
569	}
570	if ($.type(a) === 'string' || $.type(b) === 'string') {
571		return String(a).localeCompare(String(b));
572	}
573	return a - b;
574}
575
576
577/* FullCalendar-specific Misc Utilities
578----------------------------------------------------------------------------------------------------------------------*/
579
580
581// Computes the intersection of the two ranges. Will return fresh date clones in a range.
582// Returns undefined if no intersection.
583// Expects all dates to be normalized to the same timezone beforehand.
584// TODO: move to date section?
585function intersectRanges(subjectRange, constraintRange) {
586	var subjectStart = subjectRange.start;
587	var subjectEnd = subjectRange.end;
588	var constraintStart = constraintRange.start;
589	var constraintEnd = constraintRange.end;
590	var segStart, segEnd;
591	var isStart, isEnd;
592
593	if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all?
594
595		if (subjectStart >= constraintStart) {
596			segStart = subjectStart.clone();
597			isStart = true;
598		}
599		else {
600			segStart = constraintStart.clone();
601			isStart =  false;
602		}
603
604		if (subjectEnd <= constraintEnd) {
605			segEnd = subjectEnd.clone();
606			isEnd = true;
607		}
608		else {
609			segEnd = constraintEnd.clone();
610			isEnd = false;
611		}
612
613		return {
614			start: segStart,
615			end: segEnd,
616			isStart: isStart,
617			isEnd: isEnd
618		};
619	}
620}
621
622
623/* Date Utilities
624----------------------------------------------------------------------------------------------------------------------*/
625
626FC.computeIntervalUnit = computeIntervalUnit;
627FC.divideRangeByDuration = divideRangeByDuration;
628FC.divideDurationByDuration = divideDurationByDuration;
629FC.multiplyDuration = multiplyDuration;
630FC.durationHasTime = durationHasTime;
631
632var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
633var intervalUnits = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ];
634
635
636// Diffs the two moments into a Duration where full-days are recorded first, then the remaining time.
637// Moments will have their timezones normalized.
638function diffDayTime(a, b) {
639	return moment.duration({
640		days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'),
641		ms: a.time() - b.time() // time-of-day from day start. disregards timezone
642	});
643}
644
645
646// Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations.
647function diffDay(a, b) {
648	return moment.duration({
649		days: a.clone().stripTime().diff(b.clone().stripTime(), 'days')
650	});
651}
652
653
654// Diffs two moments, producing a duration, made of a whole-unit-increment of the given unit. Uses rounding.
655function diffByUnit(a, b, unit) {
656	return moment.duration(
657		Math.round(a.diff(b, unit, true)), // returnFloat=true
658		unit
659	);
660}
661
662
663// Computes the unit name of the largest whole-unit period of time.
664// For example, 48 hours will be "days" whereas 49 hours will be "hours".
665// Accepts start/end, a range object, or an original duration object.
666function computeIntervalUnit(start, end) {
667	var i, unit;
668	var val;
669
670	for (i = 0; i < intervalUnits.length; i++) {
671		unit = intervalUnits[i];
672		val = computeRangeAs(unit, start, end);
673
674		if (val >= 1 && isInt(val)) {
675			break;
676		}
677	}
678
679	return unit; // will be "milliseconds" if nothing else matches
680}
681
682
683// Computes the number of units (like "hours") in the given range.
684// Range can be a {start,end} object, separate start/end args, or a Duration.
685// Results are based on Moment's .as() and .diff() methods, so results can depend on internal handling
686// of month-diffing logic (which tends to vary from version to version).
687function computeRangeAs(unit, start, end) {
688
689	if (end != null) { // given start, end
690		return end.diff(start, unit, true);
691	}
692	else if (moment.isDuration(start)) { // given duration
693		return start.as(unit);
694	}
695	else { // given { start, end } range object
696		return start.end.diff(start.start, unit, true);
697	}
698}
699
700
701// Intelligently divides a range (specified by a start/end params) by a duration
702function divideRangeByDuration(start, end, dur) {
703	var months;
704
705	if (durationHasTime(dur)) {
706		return (end - start) / dur;
707	}
708	months = dur.asMonths();
709	if (Math.abs(months) >= 1 && isInt(months)) {
710		return end.diff(start, 'months', true) / months;
711	}
712	return end.diff(start, 'days', true) / dur.asDays();
713}
714
715
716// Intelligently divides one duration by another
717function divideDurationByDuration(dur1, dur2) {
718	var months1, months2;
719
720	if (durationHasTime(dur1) || durationHasTime(dur2)) {
721		return dur1 / dur2;
722	}
723	months1 = dur1.asMonths();
724	months2 = dur2.asMonths();
725	if (
726		Math.abs(months1) >= 1 && isInt(months1) &&
727		Math.abs(months2) >= 1 && isInt(months2)
728	) {
729		return months1 / months2;
730	}
731	return dur1.asDays() / dur2.asDays();
732}
733
734
735// Intelligently multiplies a duration by a number
736function multiplyDuration(dur, n) {
737	var months;
738
739	if (durationHasTime(dur)) {
740		return moment.duration(dur * n);
741	}
742	months = dur.asMonths();
743	if (Math.abs(months) >= 1 && isInt(months)) {
744		return moment.duration({ months: months * n });
745	}
746	return moment.duration({ days: dur.asDays() * n });
747}
748
749
750// Returns a boolean about whether the given duration has any time parts (hours/minutes/seconds/ms)
751function durationHasTime(dur) {
752	return Boolean(dur.hours() || dur.minutes() || dur.seconds() || dur.milliseconds());
753}
754
755
756function isNativeDate(input) {
757	return  Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
758}
759
760
761// Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00"
762function isTimeString(str) {
763	return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str);
764}
765
766
767/* Logging and Debug
768----------------------------------------------------------------------------------------------------------------------*/
769
770FC.log = function() {
771	var console = window.console;
772
773	if (console && console.log) {
774		return console.log.apply(console, arguments);
775	}
776};
777
778FC.warn = function() {
779	var console = window.console;
780
781	if (console && console.warn) {
782		return console.warn.apply(console, arguments);
783	}
784	else {
785		return FC.log.apply(FC, arguments);
786	}
787};
788
789
790/* General Utilities
791----------------------------------------------------------------------------------------------------------------------*/
792
793var hasOwnPropMethod = {}.hasOwnProperty;
794
795
796// Merges an array of objects into a single object.
797// The second argument allows for an array of property names who's object values will be merged together.
798function mergeProps(propObjs, complexProps) {
799	var dest = {};
800	var i, name;
801	var complexObjs;
802	var j, val;
803	var props;
804
805	if (complexProps) {
806		for (i = 0; i < complexProps.length; i++) {
807			name = complexProps[i];
808			complexObjs = [];
809
810			// collect the trailing object values, stopping when a non-object is discovered
811			for (j = propObjs.length - 1; j >= 0; j--) {
812				val = propObjs[j][name];
813
814				if (typeof val === 'object') {
815					complexObjs.unshift(val);
816				}
817				else if (val !== undefined) {
818					dest[name] = val; // if there were no objects, this value will be used
819					break;
820				}
821			}
822
823			// if the trailing values were objects, use the merged value
824			if (complexObjs.length) {
825				dest[name] = mergeProps(complexObjs);
826			}
827		}
828	}
829
830	// copy values into the destination, going from last to first
831	for (i = propObjs.length - 1; i >= 0; i--) {
832		props = propObjs[i];
833
834		for (name in props) {
835			if (!(name in dest)) { // if already assigned by previous props or complex props, don't reassign
836				dest[name] = props[name];
837			}
838		}
839	}
840
841	return dest;
842}
843
844
845// Create an object that has the given prototype. Just like Object.create
846function createObject(proto) {
847	var f = function() {};
848	f.prototype = proto;
849	return new f();
850}
851
852
853function copyOwnProps(src, dest) {
854	for (var name in src) {
855		if (hasOwnProp(src, name)) {
856			dest[name] = src[name];
857		}
858	}
859}
860
861
862function hasOwnProp(obj, name) {
863	return hasOwnPropMethod.call(obj, name);
864}
865
866
867// Is the given value a non-object non-function value?
868function isAtomic(val) {
869	return /undefined|null|boolean|number|string/.test($.type(val));
870}
871
872
873function applyAll(functions, thisObj, args) {
874	if ($.isFunction(functions)) {
875		functions = [ functions ];
876	}
877	if (functions) {
878		var i;
879		var ret;
880		for (i=0; i<functions.length; i++) {
881			ret = functions[i].apply(thisObj, args) || ret;
882		}
883		return ret;
884	}
885}
886
887
888function firstDefined() {
889	for (var i=0; i<arguments.length; i++) {
890		if (arguments[i] !== undefined) {
891			return arguments[i];
892		}
893	}
894}
895
896
897function htmlEscape(s) {
898	return (s + '').replace(/&/g, '&amp;')
899		.replace(/</g, '&lt;')
900		.replace(/>/g, '&gt;')
901		.replace(/'/g, '&#039;')
902		.replace(/"/g, '&quot;')
903		.replace(/\n/g, '<br />');
904}
905
906
907function stripHtmlEntities(text) {
908	return text.replace(/&.*?;/g, '');
909}
910
911
912// Given a hash of CSS properties, returns a string of CSS.
913// Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values.
914function cssToStr(cssProps) {
915	var statements = [];
916
917	$.each(cssProps, function(name, val) {
918		if (val != null) {
919			statements.push(name + ':' + val);
920		}
921	});
922
923	return statements.join(';');
924}
925
926
927// Given an object hash of HTML attribute names to values,
928// generates a string that can be injected between < > in HTML
929function attrsToStr(attrs) {
930	var parts = [];
931
932	$.each(attrs, function(name, val) {
933		if (val != null) {
934			parts.push(name + '="' + htmlEscape(val) + '"');
935		}
936	});
937
938	return parts.join(' ');
939}
940
941
942function capitaliseFirstLetter(str) {
943	return str.charAt(0).toUpperCase() + str.slice(1);
944}
945
946
947function compareNumbers(a, b) { // for .sort()
948	return a - b;
949}
950
951
952function isInt(n) {
953	return n % 1 === 0;
954}
955
956
957// Returns a method bound to the given object context.
958// Just like one of the jQuery.proxy signatures, but without the undesired behavior of treating the same method with
959// different contexts as identical when binding/unbinding events.
960function proxy(obj, methodName) {
961	var method = obj[methodName];
962
963	return function() {
964		return method.apply(obj, arguments);
965	};
966}
967
968
969// Returns a function, that, as long as it continues to be invoked, will not
970// be triggered. The function will be called after it stops being called for
971// N milliseconds. If `immediate` is passed, trigger the function on the
972// leading edge, instead of the trailing.
973// https://github.com/jashkenas/underscore/blob/1.6.0/underscore.js#L714
974function debounce(func, wait, immediate) {
975	var timeout, args, context, timestamp, result;
976
977	var later = function() {
978		var last = +new Date() - timestamp;
979		if (last < wait) {
980			timeout = setTimeout(later, wait - last);
981		}
982		else {
983			timeout = null;
984			if (!immediate) {
985				result = func.apply(context, args);
986				context = args = null;
987			}
988		}
989	};
990
991	return function() {
992		context = this;
993		args = arguments;
994		timestamp = +new Date();
995		var callNow = immediate && !timeout;
996		if (!timeout) {
997			timeout = setTimeout(later, wait);
998		}
999		if (callNow) {
1000			result = func.apply(context, args);
1001			context = args = null;
1002		}
1003		return result;
1004	};
1005}
1006
1007
1008// HACK around jQuery's now A+ promises: execute callback synchronously if already resolved.
1009// thenFunc shouldn't accept args.
1010// similar to whenResources in Scheduler plugin.
1011function syncThen(promise, thenFunc) {
1012	// not a promise, or an already-resolved promise?
1013	if (!promise || !promise.then || promise.state() === 'resolved') {
1014		return $.when(thenFunc()); // resolve immediately
1015	}
1016	else if (thenFunc) {
1017		return promise.then(thenFunc);
1018	}
1019}
1020
1021;;
1022
1023/*
1024GENERAL NOTE on moments throughout the *entire rest* of the codebase:
1025All moments are assumed to be ambiguously-zoned unless otherwise noted,
1026with the NOTABLE EXCEOPTION of start/end dates that live on *Event Objects*.
1027Ambiguously-TIMED moments are assumed to be ambiguously-zoned by nature.
1028*/
1029
1030var ambigDateOfMonthRegex = /^\s*\d{4}-\d\d$/;
1031var ambigTimeOrZoneRegex =
1032	/^\s*\d{4}-(?:(\d\d-\d\d)|(W\d\d$)|(W\d\d-\d)|(\d\d\d))((T| )(\d\d(:\d\d(:\d\d(\.\d+)?)?)?)?)?$/;
1033var newMomentProto = moment.fn; // where we will attach our new methods
1034var oldMomentProto = $.extend({}, newMomentProto); // copy of original moment methods
1035
1036// tell momentjs to transfer these properties upon clone
1037var momentProperties = moment.momentProperties;
1038momentProperties.push('_fullCalendar');
1039momentProperties.push('_ambigTime');
1040momentProperties.push('_ambigZone');
1041
1042
1043// Creating
1044// -------------------------------------------------------------------------------------------------
1045
1046// Creates a new moment, similar to the vanilla moment(...) constructor, but with
1047// extra features (ambiguous time, enhanced formatting). When given an existing moment,
1048// it will function as a clone (and retain the zone of the moment). Anything else will
1049// result in a moment in the local zone.
1050FC.moment = function() {
1051	return makeMoment(arguments);
1052};
1053
1054// Sames as FC.moment, but forces the resulting moment to be in the UTC timezone.
1055FC.moment.utc = function() {
1056	var mom = makeMoment(arguments, true);
1057
1058	// Force it into UTC because makeMoment doesn't guarantee it
1059	// (if given a pre-existing moment for example)
1060	if (mom.hasTime()) { // don't give ambiguously-timed moments a UTC zone
1061		mom.utc();
1062	}
1063
1064	return mom;
1065};
1066
1067// Same as FC.moment, but when given an ISO8601 string, the timezone offset is preserved.
1068// ISO8601 strings with no timezone offset will become ambiguously zoned.
1069FC.moment.parseZone = function() {
1070	return makeMoment(arguments, true, true);
1071};
1072
1073// Builds an enhanced moment from args. When given an existing moment, it clones. When given a
1074// native Date, or called with no arguments (the current time), the resulting moment will be local.
1075// Anything else needs to be "parsed" (a string or an array), and will be affected by:
1076//    parseAsUTC - if there is no zone information, should we parse the input in UTC?
1077//    parseZone - if there is zone information, should we force the zone of the moment?
1078function makeMoment(args, parseAsUTC, parseZone) {
1079	var input = args[0];
1080	var isSingleString = args.length == 1 && typeof input === 'string';
1081	var isAmbigTime;
1082	var isAmbigZone;
1083	var ambigMatch;
1084	var mom;
1085
1086	if (moment.isMoment(input) || isNativeDate(input) || input === undefined) {
1087		mom = moment.apply(null, args);
1088	}
1089	else { // "parsing" is required
1090		isAmbigTime = false;
1091		isAmbigZone = false;
1092
1093		if (isSingleString) {
1094			if (ambigDateOfMonthRegex.test(input)) {
1095				// accept strings like '2014-05', but convert to the first of the month
1096				input += '-01';
1097				args = [ input ]; // for when we pass it on to moment's constructor
1098				isAmbigTime = true;
1099				isAmbigZone = true;
1100			}
1101			else if ((ambigMatch = ambigTimeOrZoneRegex.exec(input))) {
1102				isAmbigTime = !ambigMatch[5]; // no time part?
1103				isAmbigZone = true;
1104			}
1105		}
1106		else if ($.isArray(input)) {
1107			// arrays have no timezone information, so assume ambiguous zone
1108			isAmbigZone = true;
1109		}
1110		// otherwise, probably a string with a format
1111
1112		if (parseAsUTC || isAmbigTime) {
1113			mom = moment.utc.apply(moment, args);
1114		}
1115		else {
1116			mom = moment.apply(null, args);
1117		}
1118
1119		if (isAmbigTime) {
1120			mom._ambigTime = true;
1121			mom._ambigZone = true; // ambiguous time always means ambiguous zone
1122		}
1123		else if (parseZone) { // let's record the inputted zone somehow
1124			if (isAmbigZone) {
1125				mom._ambigZone = true;
1126			}
1127			else if (isSingleString) {
1128				mom.utcOffset(input); // if not a valid zone, will assign UTC
1129			}
1130		}
1131	}
1132
1133	mom._fullCalendar = true; // flag for extended functionality
1134
1135	return mom;
1136}
1137
1138
1139// Week Number
1140// -------------------------------------------------------------------------------------------------
1141
1142
1143// Returns the week number, considering the locale's custom week number calcuation
1144// `weeks` is an alias for `week`
1145newMomentProto.week = newMomentProto.weeks = function(input) {
1146	var weekCalc = this._locale._fullCalendar_weekCalc;
1147
1148	if (input == null && typeof weekCalc === 'function') { // custom function only works for getter
1149		return weekCalc(this);
1150	}
1151	else if (weekCalc === 'ISO') {
1152		return oldMomentProto.isoWeek.apply(this, arguments); // ISO getter/setter
1153	}
1154
1155	return oldMomentProto.week.apply(this, arguments); // local getter/setter
1156};
1157
1158
1159// Time-of-day
1160// -------------------------------------------------------------------------------------------------
1161
1162// GETTER
1163// Returns a Duration with the hours/minutes/seconds/ms values of the moment.
1164// If the moment has an ambiguous time, a duration of 00:00 will be returned.
1165//
1166// SETTER
1167// You can supply a Duration, a Moment, or a Duration-like argument.
1168// When setting the time, and the moment has an ambiguous time, it then becomes unambiguous.
1169newMomentProto.time = function(time) {
1170
1171	// Fallback to the original method (if there is one) if this moment wasn't created via FullCalendar.
1172	// `time` is a generic enough method name where this precaution is necessary to avoid collisions w/ other plugins.
1173	if (!this._fullCalendar) {
1174		return oldMomentProto.time.apply(this, arguments);
1175	}
1176
1177	if (time == null) { // getter
1178		return moment.duration({
1179			hours: this.hours(),
1180			minutes: this.minutes(),
1181			seconds: this.seconds(),
1182			milliseconds: this.milliseconds()
1183		});
1184	}
1185	else { // setter
1186
1187		this._ambigTime = false; // mark that the moment now has a time
1188
1189		if (!moment.isDuration(time) && !moment.isMoment(time)) {
1190			time = moment.duration(time);
1191		}
1192
1193		// The day value should cause overflow (so 24 hours becomes 00:00:00 of next day).
1194		// Only for Duration times, not Moment times.
1195		var dayHours = 0;
1196		if (moment.isDuration(time)) {
1197			dayHours = Math.floor(time.asDays()) * 24;
1198		}
1199
1200		// We need to set the individual fields.
1201		// Can't use startOf('day') then add duration. In case of DST at start of day.
1202		return this.hours(dayHours + time.hours())
1203			.minutes(time.minutes())
1204			.seconds(time.seconds())
1205			.milliseconds(time.milliseconds());
1206	}
1207};
1208
1209// Converts the moment to UTC, stripping out its time-of-day and timezone offset,
1210// but preserving its YMD. A moment with a stripped time will display no time
1211// nor timezone offset when .format() is called.
1212newMomentProto.stripTime = function() {
1213
1214	if (!this._ambigTime) {
1215
1216		this.utc(true); // keepLocalTime=true (for keeping *date* value)
1217
1218		// set time to zero
1219		this.set({
1220			hours: 0,
1221			minutes: 0,
1222			seconds: 0,
1223			ms: 0
1224		});
1225
1226		// Mark the time as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
1227		// which clears all ambig flags.
1228		this._ambigTime = true;
1229		this._ambigZone = true; // if ambiguous time, also ambiguous timezone offset
1230	}
1231
1232	return this; // for chaining
1233};
1234
1235// Returns if the moment has a non-ambiguous time (boolean)
1236newMomentProto.hasTime = function() {
1237	return !this._ambigTime;
1238};
1239
1240
1241// Timezone
1242// -------------------------------------------------------------------------------------------------
1243
1244// Converts the moment to UTC, stripping out its timezone offset, but preserving its
1245// YMD and time-of-day. A moment with a stripped timezone offset will display no
1246// timezone offset when .format() is called.
1247newMomentProto.stripZone = function() {
1248	var wasAmbigTime;
1249
1250	if (!this._ambigZone) {
1251
1252		wasAmbigTime = this._ambigTime;
1253
1254		this.utc(true); // keepLocalTime=true (for keeping date and time values)
1255
1256		// the above call to .utc()/.utcOffset() unfortunately might clear the ambig flags, so restore
1257		this._ambigTime = wasAmbigTime || false;
1258
1259		// Mark the zone as ambiguous. This needs to happen after the .utc() call, which might call .utcOffset(),
1260		// which clears the ambig flags.
1261		this._ambigZone = true;
1262	}
1263
1264	return this; // for chaining
1265};
1266
1267// Returns of the moment has a non-ambiguous timezone offset (boolean)
1268newMomentProto.hasZone = function() {
1269	return !this._ambigZone;
1270};
1271
1272
1273// implicitly marks a zone
1274newMomentProto.local = function(keepLocalTime) {
1275
1276	// for when converting from ambiguously-zoned to local,
1277	// keep the time values when converting from UTC -> local
1278	oldMomentProto.local.call(this, this._ambigZone || keepLocalTime);
1279
1280	// ensure non-ambiguous
1281	// this probably already happened via local() -> utcOffset(), but don't rely on Moment's internals
1282	this._ambigTime = false;
1283	this._ambigZone = false;
1284
1285	return this; // for chaining
1286};
1287
1288
1289// implicitly marks a zone
1290newMomentProto.utc = function(keepLocalTime) {
1291
1292	oldMomentProto.utc.call(this, keepLocalTime);
1293
1294	// ensure non-ambiguous
1295	// this probably already happened via utc() -> utcOffset(), but don't rely on Moment's internals
1296	this._ambigTime = false;
1297	this._ambigZone = false;
1298
1299	return this;
1300};
1301
1302
1303// implicitly marks a zone (will probably get called upon .utc() and .local())
1304newMomentProto.utcOffset = function(tzo) {
1305
1306	if (tzo != null) { // setter
1307		// these assignments needs to happen before the original zone method is called.
1308		// I forget why, something to do with a browser crash.
1309		this._ambigTime = false;
1310		this._ambigZone = false;
1311	}
1312
1313	return oldMomentProto.utcOffset.apply(this, arguments);
1314};
1315
1316
1317// Formatting
1318// -------------------------------------------------------------------------------------------------
1319
1320newMomentProto.format = function() {
1321	if (this._fullCalendar && arguments[0]) { // an enhanced moment? and a format string provided?
1322		return formatDate(this, arguments[0]); // our extended formatting
1323	}
1324	if (this._ambigTime) {
1325		return oldMomentFormat(this, 'YYYY-MM-DD');
1326	}
1327	if (this._ambigZone) {
1328		return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
1329	}
1330	return oldMomentProto.format.apply(this, arguments);
1331};
1332
1333newMomentProto.toISOString = function() {
1334	if (this._ambigTime) {
1335		return oldMomentFormat(this, 'YYYY-MM-DD');
1336	}
1337	if (this._ambigZone) {
1338		return oldMomentFormat(this, 'YYYY-MM-DD[T]HH:mm:ss');
1339	}
1340	return oldMomentProto.toISOString.apply(this, arguments);
1341};
1342
1343;;
1344
1345// Single Date Formatting
1346// -------------------------------------------------------------------------------------------------
1347
1348
1349// call this if you want Moment's original format method to be used
1350function oldMomentFormat(mom, formatStr) {
1351	return oldMomentProto.format.call(mom, formatStr); // oldMomentProto defined in moment-ext.js
1352}
1353
1354
1355// Formats `date` with a Moment formatting string, but allow our non-zero areas and
1356// additional token.
1357function formatDate(date, formatStr) {
1358	return formatDateWithChunks(date, getFormatStringChunks(formatStr));
1359}
1360
1361
1362function formatDateWithChunks(date, chunks) {
1363	var s = '';
1364	var i;
1365
1366	for (i=0; i<chunks.length; i++) {
1367		s += formatDateWithChunk(date, chunks[i]);
1368	}
1369
1370	return s;
1371}
1372
1373
1374// addition formatting tokens we want recognized
1375var tokenOverrides = {
1376	t: function(date) { // "a" or "p"
1377		return oldMomentFormat(date, 'a').charAt(0);
1378	},
1379	T: function(date) { // "A" or "P"
1380		return oldMomentFormat(date, 'A').charAt(0);
1381	}
1382};
1383
1384
1385function formatDateWithChunk(date, chunk) {
1386	var token;
1387	var maybeStr;
1388
1389	if (typeof chunk === 'string') { // a literal string
1390		return chunk;
1391	}
1392	else if ((token = chunk.token)) { // a token, like "YYYY"
1393		if (tokenOverrides[token]) {
1394			return tokenOverrides[token](date); // use our custom token
1395		}
1396		return oldMomentFormat(date, token);
1397	}
1398	else if (chunk.maybe) { // a grouping of other chunks that must be non-zero
1399		maybeStr = formatDateWithChunks(date, chunk.maybe);
1400		if (maybeStr.match(/[1-9]/)) {
1401			return maybeStr;
1402		}
1403	}
1404
1405	return '';
1406}
1407
1408
1409// Date Range Formatting
1410// -------------------------------------------------------------------------------------------------
1411// TODO: make it work with timezone offset
1412
1413// Using a formatting string meant for a single date, generate a range string, like
1414// "Sep 2 - 9 2013", that intelligently inserts a separator where the dates differ.
1415// If the dates are the same as far as the format string is concerned, just return a single
1416// rendering of one date, without any separator.
1417function formatRange(date1, date2, formatStr, separator, isRTL) {
1418	var localeData;
1419
1420	date1 = FC.moment.parseZone(date1);
1421	date2 = FC.moment.parseZone(date2);
1422
1423	localeData = date1.localeData();
1424
1425	// Expand localized format strings, like "LL" -> "MMMM D YYYY"
1426	formatStr = localeData.longDateFormat(formatStr) || formatStr;
1427	// BTW, this is not important for `formatDate` because it is impossible to put custom tokens
1428	// or non-zero areas in Moment's localized format strings.
1429
1430	separator = separator || ' - ';
1431
1432	return formatRangeWithChunks(
1433		date1,
1434		date2,
1435		getFormatStringChunks(formatStr),
1436		separator,
1437		isRTL
1438	);
1439}
1440FC.formatRange = formatRange; // expose
1441
1442
1443function formatRangeWithChunks(date1, date2, chunks, separator, isRTL) {
1444	var unzonedDate1 = date1.clone().stripZone(); // for formatSimilarChunk
1445	var unzonedDate2 = date2.clone().stripZone(); // "
1446	var chunkStr; // the rendering of the chunk
1447	var leftI;
1448	var leftStr = '';
1449	var rightI;
1450	var rightStr = '';
1451	var middleI;
1452	var middleStr1 = '';
1453	var middleStr2 = '';
1454	var middleStr = '';
1455
1456	// Start at the leftmost side of the formatting string and continue until you hit a token
1457	// that is not the same between dates.
1458	for (leftI=0; leftI<chunks.length; leftI++) {
1459		chunkStr = formatSimilarChunk(date1, date2, unzonedDate1, unzonedDate2, chunks[leftI]);
1460		if (chunkStr === false) {
1461			break;
1462		}
1463		leftStr += chunkStr;
1464	}
1465
1466	// Similarly, start at the rightmost side of the formatting string and move left
1467	for (rightI=chunks.length-1; rightI>leftI; rightI--) {
1468		chunkStr = formatSimilarChunk(date1, date2, unzonedDate1, unzonedDate2,  chunks[rightI]);
1469		if (chunkStr === false) {
1470			break;
1471		}
1472		rightStr = chunkStr + rightStr;
1473	}
1474
1475	// The area in the middle is different for both of the dates.
1476	// Collect them distinctly so we can jam them together later.
1477	for (middleI=leftI; middleI<=rightI; middleI++) {
1478		middleStr1 += formatDateWithChunk(date1, chunks[middleI]);
1479		middleStr2 += formatDateWithChunk(date2, chunks[middleI]);
1480	}
1481
1482	if (middleStr1 || middleStr2) {
1483		if (isRTL) {
1484			middleStr = middleStr2 + separator + middleStr1;
1485		}
1486		else {
1487			middleStr = middleStr1 + separator + middleStr2;
1488		}
1489	}
1490
1491	return leftStr + middleStr + rightStr;
1492}
1493
1494
1495var similarUnitMap = {
1496	Y: 'year',
1497	M: 'month',
1498	D: 'day', // day of month
1499	d: 'day', // day of week
1500	// prevents a separator between anything time-related...
1501	A: 'second', // AM/PM
1502	a: 'second', // am/pm
1503	T: 'second', // A/P
1504	t: 'second', // a/p
1505	H: 'second', // hour (24)
1506	h: 'second', // hour (12)
1507	m: 'second', // minute
1508	s: 'second' // second
1509};
1510// TODO: week maybe?
1511
1512
1513// Given a formatting chunk, and given that both dates are similar in the regard the
1514// formatting chunk is concerned, format date1 against `chunk`. Otherwise, return `false`.
1515function formatSimilarChunk(date1, date2, unzonedDate1, unzonedDate2, chunk) {
1516	var token;
1517	var unit;
1518
1519	if (typeof chunk === 'string') { // a literal string
1520		return chunk;
1521	}
1522	else if ((token = chunk.token)) {
1523		unit = similarUnitMap[token.charAt(0)];
1524
1525		// are the dates the same for this unit of measurement?
1526		// use the unzoned dates for this calculation because unreliable when near DST (bug #2396)
1527		if (unit && unzonedDate1.isSame(unzonedDate2, unit)) {
1528			return oldMomentFormat(date1, token); // would be the same if we used `date2`
1529			// BTW, don't support custom tokens
1530		}
1531	}
1532
1533	return false; // the chunk is NOT the same for the two dates
1534	// BTW, don't support splitting on non-zero areas
1535}
1536
1537
1538// Chunking Utils
1539// -------------------------------------------------------------------------------------------------
1540
1541
1542var formatStringChunkCache = {};
1543
1544
1545function getFormatStringChunks(formatStr) {
1546	if (formatStr in formatStringChunkCache) {
1547		return formatStringChunkCache[formatStr];
1548	}
1549	return (formatStringChunkCache[formatStr] = chunkFormatString(formatStr));
1550}
1551
1552
1553// Break the formatting string into an array of chunks
1554function chunkFormatString(formatStr) {
1555	var chunks = [];
1556	var chunker = /\[([^\]]*)\]|\(([^\)]*)\)|(LTS|LT|(\w)\4*o?)|([^\w\[\(]+)/g; // TODO: more descrimination
1557	var match;
1558
1559	while ((match = chunker.exec(formatStr))) {
1560		if (match[1]) { // a literal string inside [ ... ]
1561			chunks.push(match[1]);
1562		}
1563		else if (match[2]) { // non-zero formatting inside ( ... )
1564			chunks.push({ maybe: chunkFormatString(match[2]) });
1565		}
1566		else if (match[3]) { // a formatting token
1567			chunks.push({ token: match[3] });
1568		}
1569		else if (match[5]) { // an unenclosed literal string
1570			chunks.push(match[5]);
1571		}
1572	}
1573
1574	return chunks;
1575}
1576
1577
1578// Misc Utils
1579// -------------------------------------------------------------------------------------------------
1580
1581
1582// granularity only goes up until day
1583// TODO: unify with similarUnitMap
1584var tokenGranularities = {
1585	Y: { value: 1, unit: 'year' },
1586	M: { value: 2, unit: 'month' },
1587	W: { value: 3, unit: 'week' },
1588	w: { value: 3, unit: 'week' },
1589	D: { value: 4, unit: 'day' }, // day of month
1590	d: { value: 4, unit: 'day' } // day of week
1591};
1592
1593// returns a unit string, either 'year', 'month', 'day', or null
1594// for the most granular formatting token in the string.
1595FC.queryMostGranularFormatUnit = function(formatStr) {
1596	var chunks = getFormatStringChunks(formatStr);
1597	var i, chunk;
1598	var candidate;
1599	var best;
1600
1601	for (i = 0; i < chunks.length; i++) {
1602		chunk = chunks[i];
1603		if (chunk.token) {
1604			candidate = tokenGranularities[chunk.token.charAt(0)];
1605			if (candidate) {
1606				if (!best || candidate.value > best.value) {
1607					best = candidate;
1608				}
1609			}
1610		}
1611	}
1612
1613	if (best) {
1614		return best.unit;
1615	}
1616
1617	return null;
1618};
1619
1620;;
1621
1622FC.Class = Class; // export
1623
1624// Class that all other classes will inherit from
1625function Class() { }
1626
1627
1628// Called on a class to create a subclass.
1629// Last argument contains instance methods. Any argument before the last are considered mixins.
1630Class.extend = function() {
1631	var len = arguments.length;
1632	var i;
1633	var members;
1634
1635	for (i = 0; i < len; i++) {
1636		members = arguments[i];
1637		if (i < len - 1) { // not the last argument?
1638			mixIntoClass(this, members);
1639		}
1640	}
1641
1642	return extendClass(this, members || {}); // members will be undefined if no arguments
1643};
1644
1645
1646// Adds new member variables/methods to the class's prototype.
1647// Can be called with another class, or a plain object hash containing new members.
1648Class.mixin = function(members) {
1649	mixIntoClass(this, members);
1650};
1651
1652
1653function extendClass(superClass, members) {
1654	var subClass;
1655
1656	// ensure a constructor for the subclass, forwarding all arguments to the super-constructor if it doesn't exist
1657	if (hasOwnProp(members, 'constructor')) {
1658		subClass = members.constructor;
1659	}
1660	if (typeof subClass !== 'function') {
1661		subClass = members.constructor = function() {
1662			superClass.apply(this, arguments);
1663		};
1664	}
1665
1666	// build the base prototype for the subclass, which is an new object chained to the superclass's prototype
1667	subClass.prototype = createObject(superClass.prototype);
1668
1669	// copy each member variable/method onto the the subclass's prototype
1670	copyOwnProps(members, subClass.prototype);
1671
1672	// copy over all class variables/methods to the subclass, such as `extend` and `mixin`
1673	copyOwnProps(superClass, subClass);
1674
1675	return subClass;
1676}
1677
1678
1679function mixIntoClass(theClass, members) {
1680	copyOwnProps(members, theClass.prototype);
1681}
1682;;
1683
1684var EmitterMixin = FC.EmitterMixin = {
1685
1686	// jQuery-ification via $(this) allows a non-DOM object to have
1687	// the same event handling capabilities (including namespaces).
1688
1689
1690	on: function(types, handler) {
1691
1692		// handlers are always called with an "event" object as their first param.
1693		// sneak the `this` context and arguments into the extra parameter object
1694		// and forward them on to the original handler.
1695		var intercept = function(ev, extra) {
1696			return handler.apply(
1697				extra.context || this,
1698				extra.args || []
1699			);
1700		};
1701
1702		// mimick jQuery's internal "proxy" system (risky, I know)
1703		// causing all functions with the same .guid to appear to be the same.
1704		// https://github.com/jquery/jquery/blob/2.2.4/src/core.js#L448
1705		// this is needed for calling .off with the original non-intercept handler.
1706		if (!handler.guid) {
1707			handler.guid = $.guid++;
1708		}
1709		intercept.guid = handler.guid;
1710
1711		$(this).on(types, intercept);
1712
1713		return this; // for chaining
1714	},
1715
1716
1717	off: function(types, handler) {
1718		$(this).off(types, handler);
1719
1720		return this; // for chaining
1721	},
1722
1723
1724	trigger: function(types) {
1725		var args = Array.prototype.slice.call(arguments, 1); // arguments after the first
1726
1727		// pass in "extra" info to the intercept
1728		$(this).triggerHandler(types, { args: args });
1729
1730		return this; // for chaining
1731	},
1732
1733
1734	triggerWith: function(types, context, args) {
1735
1736		// `triggerHandler` is less reliant on the DOM compared to `trigger`.
1737		// pass in "extra" info to the intercept.
1738		$(this).triggerHandler(types, { context: context, args: args });
1739
1740		return this; // for chaining
1741	}
1742
1743};
1744
1745;;
1746
1747/*
1748Utility methods for easily listening to events on another object,
1749and more importantly, easily unlistening from them.
1750*/
1751var ListenerMixin = FC.ListenerMixin = (function() {
1752	var guid = 0;
1753	var ListenerMixin = {
1754
1755		listenerId: null,
1756
1757		/*
1758		Given an `other` object that has on/off methods, bind the given `callback` to an event by the given name.
1759		The `callback` will be called with the `this` context of the object that .listenTo is being called on.
1760		Can be called:
1761			.listenTo(other, eventName, callback)
1762		OR
1763			.listenTo(other, {
1764				eventName1: callback1,
1765				eventName2: callback2
1766			})
1767		*/
1768		listenTo: function(other, arg, callback) {
1769			if (typeof arg === 'object') { // given dictionary of callbacks
1770				for (var eventName in arg) {
1771					if (arg.hasOwnProperty(eventName)) {
1772						this.listenTo(other, eventName, arg[eventName]);
1773					}
1774				}
1775			}
1776			else if (typeof arg === 'string') {
1777				other.on(
1778					arg + '.' + this.getListenerNamespace(), // use event namespacing to identify this object
1779					$.proxy(callback, this) // always use `this` context
1780						// the usually-undesired jQuery guid behavior doesn't matter,
1781						// because we always unbind via namespace
1782				);
1783			}
1784		},
1785
1786		/*
1787		Causes the current object to stop listening to events on the `other` object.
1788		`eventName` is optional. If omitted, will stop listening to ALL events on `other`.
1789		*/
1790		stopListeningTo: function(other, eventName) {
1791			other.off((eventName || '') + '.' + this.getListenerNamespace());
1792		},
1793
1794		/*
1795		Returns a string, unique to this object, to be used for event namespacing
1796		*/
1797		getListenerNamespace: function() {
1798			if (this.listenerId == null) {
1799				this.listenerId = guid++;
1800			}
1801			return '_listener' + this.listenerId;
1802		}
1803
1804	};
1805	return ListenerMixin;
1806})();
1807;;
1808
1809// simple class for toggle a `isIgnoringMouse` flag on delay
1810// initMouseIgnoring must first be called, with a millisecond delay setting.
1811var MouseIgnorerMixin = {
1812
1813	isIgnoringMouse: false, // bool
1814	delayUnignoreMouse: null, // method
1815
1816
1817	initMouseIgnoring: function(delay) {
1818		this.delayUnignoreMouse = debounce(proxy(this, 'unignoreMouse'), delay || 1000);
1819	},
1820
1821
1822	// temporarily ignore mouse actions on segments
1823	tempIgnoreMouse: function() {
1824		this.isIgnoringMouse = true;
1825		this.delayUnignoreMouse();
1826	},
1827
1828
1829	// delayUnignoreMouse eventually calls this
1830	unignoreMouse: function() {
1831		this.isIgnoringMouse = false;
1832	}
1833
1834};
1835
1836;;
1837
1838/* A rectangular panel that is absolutely positioned over other content
1839------------------------------------------------------------------------------------------------------------------------
1840Options:
1841	- className (string)
1842	- content (HTML string or jQuery element set)
1843	- parentEl
1844	- top
1845	- left
1846	- right (the x coord of where the right edge should be. not a "CSS" right)
1847	- autoHide (boolean)
1848	- show (callback)
1849	- hide (callback)
1850*/
1851
1852var Popover = Class.extend(ListenerMixin, {
1853
1854	isHidden: true,
1855	options: null,
1856	el: null, // the container element for the popover. generated by this object
1857	margin: 10, // the space required between the popover and the edges of the scroll container
1858
1859
1860	constructor: function(options) {
1861		this.options = options || {};
1862	},
1863
1864
1865	// Shows the popover on the specified position. Renders it if not already
1866	show: function() {
1867		if (this.isHidden) {
1868			if (!this.el) {
1869				this.render();
1870			}
1871			this.el.show();
1872			this.position();
1873			this.isHidden = false;
1874			this.trigger('show');
1875		}
1876	},
1877
1878
1879	// Hides the popover, through CSS, but does not remove it from the DOM
1880	hide: function() {
1881		if (!this.isHidden) {
1882			this.el.hide();
1883			this.isHidden = true;
1884			this.trigger('hide');
1885		}
1886	},
1887
1888
1889	// Creates `this.el` and renders content inside of it
1890	render: function() {
1891		var _this = this;
1892		var options = this.options;
1893
1894		this.el = $('<div class="fc-popover"/>')
1895			.addClass(options.className || '')
1896			.css({
1897				// position initially to the top left to avoid creating scrollbars
1898				top: 0,
1899				left: 0
1900			})
1901			.append(options.content)
1902			.appendTo(options.parentEl);
1903
1904		// when a click happens on anything inside with a 'fc-close' className, hide the popover
1905		this.el.on('click', '.fc-close', function() {
1906			_this.hide();
1907		});
1908
1909		if (options.autoHide) {
1910			this.listenTo($(document), 'mousedown', this.documentMousedown);
1911		}
1912	},
1913
1914
1915	// Triggered when the user clicks *anywhere* in the document, for the autoHide feature
1916	documentMousedown: function(ev) {
1917		// only hide the popover if the click happened outside the popover
1918		if (this.el && !$(ev.target).closest(this.el).length) {
1919			this.hide();
1920		}
1921	},
1922
1923
1924	// Hides and unregisters any handlers
1925	removeElement: function() {
1926		this.hide();
1927
1928		if (this.el) {
1929			this.el.remove();
1930			this.el = null;
1931		}
1932
1933		this.stopListeningTo($(document), 'mousedown');
1934	},
1935
1936
1937	// Positions the popover optimally, using the top/left/right options
1938	position: function() {
1939		var options = this.options;
1940		var origin = this.el.offsetParent().offset();
1941		var width = this.el.outerWidth();
1942		var height = this.el.outerHeight();
1943		var windowEl = $(window);
1944		var viewportEl = getScrollParent(this.el);
1945		var viewportTop;
1946		var viewportLeft;
1947		var viewportOffset;
1948		var top; // the "position" (not "offset") values for the popover
1949		var left; //
1950
1951		// compute top and left
1952		top = options.top || 0;
1953		if (options.left !== undefined) {
1954			left = options.left;
1955		}
1956		else if (options.right !== undefined) {
1957			left = options.right - width; // derive the left value from the right value
1958		}
1959		else {
1960			left = 0;
1961		}
1962
1963		if (viewportEl.is(window) || viewportEl.is(document)) { // normalize getScrollParent's result
1964			viewportEl = windowEl;
1965			viewportTop = 0; // the window is always at the top left
1966			viewportLeft = 0; // (and .offset() won't work if called here)
1967		}
1968		else {
1969			viewportOffset = viewportEl.offset();
1970			viewportTop = viewportOffset.top;
1971			viewportLeft = viewportOffset.left;
1972		}
1973
1974		// if the window is scrolled, it causes the visible area to be further down
1975		viewportTop += windowEl.scrollTop();
1976		viewportLeft += windowEl.scrollLeft();
1977
1978		// constrain to the view port. if constrained by two edges, give precedence to top/left
1979		if (options.viewportConstrain !== false) {
1980			top = Math.min(top, viewportTop + viewportEl.outerHeight() - height - this.margin);
1981			top = Math.max(top, viewportTop + this.margin);
1982			left = Math.min(left, viewportLeft + viewportEl.outerWidth() - width - this.margin);
1983			left = Math.max(left, viewportLeft + this.margin);
1984		}
1985
1986		this.el.css({
1987			top: top - origin.top,
1988			left: left - origin.left
1989		});
1990	},
1991
1992
1993	// Triggers a callback. Calls a function in the option hash of the same name.
1994	// Arguments beyond the first `name` are forwarded on.
1995	// TODO: better code reuse for this. Repeat code
1996	trigger: function(name) {
1997		if (this.options[name]) {
1998			this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
1999		}
2000	}
2001
2002});
2003
2004;;
2005
2006/*
2007A cache for the left/right/top/bottom/width/height values for one or more elements.
2008Works with both offset (from topleft document) and position (from offsetParent).
2009
2010options:
2011- els
2012- isHorizontal
2013- isVertical
2014*/
2015var CoordCache = FC.CoordCache = Class.extend({
2016
2017	els: null, // jQuery set (assumed to be siblings)
2018	forcedOffsetParentEl: null, // options can override the natural offsetParent
2019	origin: null, // {left,top} position of offsetParent of els
2020	boundingRect: null, // constrain cordinates to this rectangle. {left,right,top,bottom} or null
2021	isHorizontal: false, // whether to query for left/right/width
2022	isVertical: false, // whether to query for top/bottom/height
2023
2024	// arrays of coordinates (offsets from topleft of document)
2025	lefts: null,
2026	rights: null,
2027	tops: null,
2028	bottoms: null,
2029
2030
2031	constructor: function(options) {
2032		this.els = $(options.els);
2033		this.isHorizontal = options.isHorizontal;
2034		this.isVertical = options.isVertical;
2035		this.forcedOffsetParentEl = options.offsetParent ? $(options.offsetParent) : null;
2036	},
2037
2038
2039	// Queries the els for coordinates and stores them.
2040	// Call this method before using and of the get* methods below.
2041	build: function() {
2042		var offsetParentEl = this.forcedOffsetParentEl || this.els.eq(0).offsetParent();
2043
2044		this.origin = offsetParentEl.offset();
2045		this.boundingRect = this.queryBoundingRect();
2046
2047		if (this.isHorizontal) {
2048			this.buildElHorizontals();
2049		}
2050		if (this.isVertical) {
2051			this.buildElVerticals();
2052		}
2053	},
2054
2055
2056	// Destroys all internal data about coordinates, freeing memory
2057	clear: function() {
2058		this.origin = null;
2059		this.boundingRect = null;
2060		this.lefts = null;
2061		this.rights = null;
2062		this.tops = null;
2063		this.bottoms = null;
2064	},
2065
2066
2067	// When called, if coord caches aren't built, builds them
2068	ensureBuilt: function() {
2069		if (!this.origin) {
2070			this.build();
2071		}
2072	},
2073
2074
2075	// Populates the left/right internal coordinate arrays
2076	buildElHorizontals: function() {
2077		var lefts = [];
2078		var rights = [];
2079
2080		this.els.each(function(i, node) {
2081			var el = $(node);
2082			var left = el.offset().left;
2083			var width = el.outerWidth();
2084
2085			lefts.push(left);
2086			rights.push(left + width);
2087		});
2088
2089		this.lefts = lefts;
2090		this.rights = rights;
2091	},
2092
2093
2094	// Populates the top/bottom internal coordinate arrays
2095	buildElVerticals: function() {
2096		var tops = [];
2097		var bottoms = [];
2098
2099		this.els.each(function(i, node) {
2100			var el = $(node);
2101			var top = el.offset().top;
2102			var height = el.outerHeight();
2103
2104			tops.push(top);
2105			bottoms.push(top + height);
2106		});
2107
2108		this.tops = tops;
2109		this.bottoms = bottoms;
2110	},
2111
2112
2113	// Given a left offset (from document left), returns the index of the el that it horizontally intersects.
2114	// If no intersection is made, returns undefined.
2115	getHorizontalIndex: function(leftOffset) {
2116		this.ensureBuilt();
2117
2118		var lefts = this.lefts;
2119		var rights = this.rights;
2120		var len = lefts.length;
2121		var i;
2122
2123		for (i = 0; i < len; i++) {
2124			if (leftOffset >= lefts[i] && leftOffset < rights[i]) {
2125				return i;
2126			}
2127		}
2128	},
2129
2130
2131	// Given a top offset (from document top), returns the index of the el that it vertically intersects.
2132	// If no intersection is made, returns undefined.
2133	getVerticalIndex: function(topOffset) {
2134		this.ensureBuilt();
2135
2136		var tops = this.tops;
2137		var bottoms = this.bottoms;
2138		var len = tops.length;
2139		var i;
2140
2141		for (i = 0; i < len; i++) {
2142			if (topOffset >= tops[i] && topOffset < bottoms[i]) {
2143				return i;
2144			}
2145		}
2146	},
2147
2148
2149	// Gets the left offset (from document left) of the element at the given index
2150	getLeftOffset: function(leftIndex) {
2151		this.ensureBuilt();
2152		return this.lefts[leftIndex];
2153	},
2154
2155
2156	// Gets the left position (from offsetParent left) of the element at the given index
2157	getLeftPosition: function(leftIndex) {
2158		this.ensureBuilt();
2159		return this.lefts[leftIndex] - this.origin.left;
2160	},
2161
2162
2163	// Gets the right offset (from document left) of the element at the given index.
2164	// This value is NOT relative to the document's right edge, like the CSS concept of "right" would be.
2165	getRightOffset: function(leftIndex) {
2166		this.ensureBuilt();
2167		return this.rights[leftIndex];
2168	},
2169
2170
2171	// Gets the right position (from offsetParent left) of the element at the given index.
2172	// This value is NOT relative to the offsetParent's right edge, like the CSS concept of "right" would be.
2173	getRightPosition: function(leftIndex) {
2174		this.ensureBuilt();
2175		return this.rights[leftIndex] - this.origin.left;
2176	},
2177
2178
2179	// Gets the width of the element at the given index
2180	getWidth: function(leftIndex) {
2181		this.ensureBuilt();
2182		return this.rights[leftIndex] - this.lefts[leftIndex];
2183	},
2184
2185
2186	// Gets the top offset (from document top) of the element at the given index
2187	getTopOffset: function(topIndex) {
2188		this.ensureBuilt();
2189		return this.tops[topIndex];
2190	},
2191
2192
2193	// Gets the top position (from offsetParent top) of the element at the given position
2194	getTopPosition: function(topIndex) {
2195		this.ensureBuilt();
2196		return this.tops[topIndex] - this.origin.top;
2197	},
2198
2199	// Gets the bottom offset (from the document top) of the element at the given index.
2200	// This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
2201	getBottomOffset: function(topIndex) {
2202		this.ensureBuilt();
2203		return this.bottoms[topIndex];
2204	},
2205
2206
2207	// Gets the bottom position (from the offsetParent top) of the element at the given index.
2208	// This value is NOT relative to the offsetParent's bottom edge, like the CSS concept of "bottom" would be.
2209	getBottomPosition: function(topIndex) {
2210		this.ensureBuilt();
2211		return this.bottoms[topIndex] - this.origin.top;
2212	},
2213
2214
2215	// Gets the height of the element at the given index
2216	getHeight: function(topIndex) {
2217		this.ensureBuilt();
2218		return this.bottoms[topIndex] - this.tops[topIndex];
2219	},
2220
2221
2222	// Bounding Rect
2223	// TODO: decouple this from CoordCache
2224
2225	// Compute and return what the elements' bounding rectangle is, from the user's perspective.
2226	// Right now, only returns a rectangle if constrained by an overflow:scroll element.
2227	queryBoundingRect: function() {
2228		var scrollParentEl = getScrollParent(this.els.eq(0));
2229
2230		if (!scrollParentEl.is(document)) {
2231			return getClientRect(scrollParentEl);
2232		}
2233	},
2234
2235	isPointInBounds: function(leftOffset, topOffset) {
2236		return this.isLeftInBounds(leftOffset) && this.isTopInBounds(topOffset);
2237	},
2238
2239	isLeftInBounds: function(leftOffset) {
2240		return !this.boundingRect || (leftOffset >= this.boundingRect.left && leftOffset < this.boundingRect.right);
2241	},
2242
2243	isTopInBounds: function(topOffset) {
2244		return !this.boundingRect || (topOffset >= this.boundingRect.top && topOffset < this.boundingRect.bottom);
2245	}
2246
2247});
2248
2249;;
2250
2251/* Tracks a drag's mouse movement, firing various handlers
2252----------------------------------------------------------------------------------------------------------------------*/
2253// TODO: use Emitter
2254
2255var DragListener = FC.DragListener = Class.extend(ListenerMixin, MouseIgnorerMixin, {
2256
2257	options: null,
2258	subjectEl: null,
2259
2260	// coordinates of the initial mousedown
2261	originX: null,
2262	originY: null,
2263
2264	// the wrapping element that scrolls, or MIGHT scroll if there's overflow.
2265	// TODO: do this for wrappers that have overflow:hidden as well.
2266	scrollEl: null,
2267
2268	isInteracting: false,
2269	isDistanceSurpassed: false,
2270	isDelayEnded: false,
2271	isDragging: false,
2272	isTouch: false,
2273
2274	delay: null,
2275	delayTimeoutId: null,
2276	minDistance: null,
2277
2278	handleTouchScrollProxy: null, // calls handleTouchScroll, always bound to `this`
2279
2280
2281	constructor: function(options) {
2282		this.options = options || {};
2283		this.handleTouchScrollProxy = proxy(this, 'handleTouchScroll');
2284		this.initMouseIgnoring(500);
2285	},
2286
2287
2288	// Interaction (high-level)
2289	// -----------------------------------------------------------------------------------------------------------------
2290
2291
2292	startInteraction: function(ev, extraOptions) {
2293		var isTouch = getEvIsTouch(ev);
2294
2295		if (ev.type === 'mousedown') {
2296			if (this.isIgnoringMouse) {
2297				return;
2298			}
2299			else if (!isPrimaryMouseButton(ev)) {
2300				return;
2301			}
2302			else {
2303				ev.preventDefault(); // prevents native selection in most browsers
2304			}
2305		}
2306
2307		if (!this.isInteracting) {
2308
2309			// process options
2310			extraOptions = extraOptions || {};
2311			this.delay = firstDefined(extraOptions.delay, this.options.delay, 0);
2312			this.minDistance = firstDefined(extraOptions.distance, this.options.distance, 0);
2313			this.subjectEl = this.options.subjectEl;
2314
2315			this.isInteracting = true;
2316			this.isTouch = isTouch;
2317			this.isDelayEnded = false;
2318			this.isDistanceSurpassed = false;
2319
2320			this.originX = getEvX(ev);
2321			this.originY = getEvY(ev);
2322			this.scrollEl = getScrollParent($(ev.target));
2323
2324			this.bindHandlers();
2325			this.initAutoScroll();
2326			this.handleInteractionStart(ev);
2327			this.startDelay(ev);
2328
2329			if (!this.minDistance) {
2330				this.handleDistanceSurpassed(ev);
2331			}
2332		}
2333	},
2334
2335
2336	handleInteractionStart: function(ev) {
2337		this.trigger('interactionStart', ev);
2338	},
2339
2340
2341	endInteraction: function(ev, isCancelled) {
2342		if (this.isInteracting) {
2343			this.endDrag(ev);
2344
2345			if (this.delayTimeoutId) {
2346				clearTimeout(this.delayTimeoutId);
2347				this.delayTimeoutId = null;
2348			}
2349
2350			this.destroyAutoScroll();
2351			this.unbindHandlers();
2352
2353			this.isInteracting = false;
2354			this.handleInteractionEnd(ev, isCancelled);
2355
2356			// a touchstart+touchend on the same element will result in the following addition simulated events:
2357			// mouseover + mouseout + click
2358			// let's ignore these bogus events
2359			if (this.isTouch) {
2360				this.tempIgnoreMouse();
2361			}
2362		}
2363	},
2364
2365
2366	handleInteractionEnd: function(ev, isCancelled) {
2367		this.trigger('interactionEnd', ev, isCancelled || false);
2368	},
2369
2370
2371	// Binding To DOM
2372	// -----------------------------------------------------------------------------------------------------------------
2373
2374
2375	bindHandlers: function() {
2376		var _this = this;
2377		var touchStartIgnores = 1;
2378
2379		if (this.isTouch) {
2380			this.listenTo($(document), {
2381				touchmove: this.handleTouchMove,
2382				touchend: this.endInteraction,
2383				touchcancel: this.endInteraction,
2384
2385				// Sometimes touchend doesn't fire
2386				// (can't figure out why. touchcancel doesn't fire either. has to do with scrolling?)
2387				// If another touchstart happens, we know it's bogus, so cancel the drag.
2388				// touchend will continue to be broken until user does a shorttap/scroll, but this is best we can do.
2389				touchstart: function(ev) {
2390					if (touchStartIgnores) { // bindHandlers is called from within a touchstart,
2391						touchStartIgnores--; // and we don't want this to fire immediately, so ignore.
2392					}
2393					else {
2394						_this.endInteraction(ev, true); // isCancelled=true
2395					}
2396				}
2397			});
2398
2399			// listen to ALL scroll actions on the page
2400			if (
2401				!bindAnyScroll(this.handleTouchScrollProxy) && // hopefully this works and short-circuits the rest
2402				this.scrollEl // otherwise, attach a single handler to this
2403			) {
2404				this.listenTo(this.scrollEl, 'scroll', this.handleTouchScroll);
2405			}
2406		}
2407		else {
2408			this.listenTo($(document), {
2409				mousemove: this.handleMouseMove,
2410				mouseup: this.endInteraction
2411			});
2412		}
2413
2414		this.listenTo($(document), {
2415			selectstart: preventDefault, // don't allow selection while dragging
2416			contextmenu: preventDefault // long taps would open menu on Chrome dev tools
2417		});
2418	},
2419
2420
2421	unbindHandlers: function() {
2422		this.stopListeningTo($(document));
2423
2424		// unbind scroll listening
2425		unbindAnyScroll(this.handleTouchScrollProxy);
2426		if (this.scrollEl) {
2427			this.stopListeningTo(this.scrollEl, 'scroll');
2428		}
2429	},
2430
2431
2432	// Drag (high-level)
2433	// -----------------------------------------------------------------------------------------------------------------
2434
2435
2436	// extraOptions ignored if drag already started
2437	startDrag: function(ev, extraOptions) {
2438		this.startInteraction(ev, extraOptions); // ensure interaction began
2439
2440		if (!this.isDragging) {
2441			this.isDragging = true;
2442			this.handleDragStart(ev);
2443		}
2444	},
2445
2446
2447	handleDragStart: function(ev) {
2448		this.trigger('dragStart', ev);
2449	},
2450
2451
2452	handleMove: function(ev) {
2453		var dx = getEvX(ev) - this.originX;
2454		var dy = getEvY(ev) - this.originY;
2455		var minDistance = this.minDistance;
2456		var distanceSq; // current distance from the origin, squared
2457
2458		if (!this.isDistanceSurpassed) {
2459			distanceSq = dx * dx + dy * dy;
2460			if (distanceSq >= minDistance * minDistance) { // use pythagorean theorem
2461				this.handleDistanceSurpassed(ev);
2462			}
2463		}
2464
2465		if (this.isDragging) {
2466			this.handleDrag(dx, dy, ev);
2467		}
2468	},
2469
2470
2471	// Called while the mouse is being moved and when we know a legitimate drag is taking place
2472	handleDrag: function(dx, dy, ev) {
2473		this.trigger('drag', dx, dy, ev);
2474		this.updateAutoScroll(ev); // will possibly cause scrolling
2475	},
2476
2477
2478	endDrag: function(ev) {
2479		if (this.isDragging) {
2480			this.isDragging = false;
2481			this.handleDragEnd(ev);
2482		}
2483	},
2484
2485
2486	handleDragEnd: function(ev) {
2487		this.trigger('dragEnd', ev);
2488	},
2489
2490
2491	// Delay
2492	// -----------------------------------------------------------------------------------------------------------------
2493
2494
2495	startDelay: function(initialEv) {
2496		var _this = this;
2497
2498		if (this.delay) {
2499			this.delayTimeoutId = setTimeout(function() {
2500				_this.handleDelayEnd(initialEv);
2501			}, this.delay);
2502		}
2503		else {
2504			this.handleDelayEnd(initialEv);
2505		}
2506	},
2507
2508
2509	handleDelayEnd: function(initialEv) {
2510		this.isDelayEnded = true;
2511
2512		if (this.isDistanceSurpassed) {
2513			this.startDrag(initialEv);
2514		}
2515	},
2516
2517
2518	// Distance
2519	// -----------------------------------------------------------------------------------------------------------------
2520
2521
2522	handleDistanceSurpassed: function(ev) {
2523		this.isDistanceSurpassed = true;
2524
2525		if (this.isDelayEnded) {
2526			this.startDrag(ev);
2527		}
2528	},
2529
2530
2531	// Mouse / Touch
2532	// -----------------------------------------------------------------------------------------------------------------
2533
2534
2535	handleTouchMove: function(ev) {
2536		// prevent inertia and touchmove-scrolling while dragging
2537		if (this.isDragging) {
2538			ev.preventDefault();
2539		}
2540
2541		this.handleMove(ev);
2542	},
2543
2544
2545	handleMouseMove: function(ev) {
2546		this.handleMove(ev);
2547	},
2548
2549
2550	// Scrolling (unrelated to auto-scroll)
2551	// -----------------------------------------------------------------------------------------------------------------
2552
2553
2554	handleTouchScroll: function(ev) {
2555		// if the drag is being initiated by touch, but a scroll happens before
2556		// the drag-initiating delay is over, cancel the drag
2557		if (!this.isDragging) {
2558			this.endInteraction(ev, true); // isCancelled=true
2559		}
2560	},
2561
2562
2563	// Utils
2564	// -----------------------------------------------------------------------------------------------------------------
2565
2566
2567	// Triggers a callback. Calls a function in the option hash of the same name.
2568	// Arguments beyond the first `name` are forwarded on.
2569	trigger: function(name) {
2570		if (this.options[name]) {
2571			this.options[name].apply(this, Array.prototype.slice.call(arguments, 1));
2572		}
2573		// makes _methods callable by event name. TODO: kill this
2574		if (this['_' + name]) {
2575			this['_' + name].apply(this, Array.prototype.slice.call(arguments, 1));
2576		}
2577	}
2578
2579
2580});
2581
2582;;
2583/*
2584this.scrollEl is set in DragListener
2585*/
2586DragListener.mixin({
2587
2588	isAutoScroll: false,
2589
2590	scrollBounds: null, // { top, bottom, left, right }
2591	scrollTopVel: null, // pixels per second
2592	scrollLeftVel: null, // pixels per second
2593	scrollIntervalId: null, // ID of setTimeout for scrolling animation loop
2594
2595	// defaults
2596	scrollSensitivity: 30, // pixels from edge for scrolling to start
2597	scrollSpeed: 200, // pixels per second, at maximum speed
2598	scrollIntervalMs: 50, // millisecond wait between scroll increment
2599
2600
2601	initAutoScroll: function() {
2602		var scrollEl = this.scrollEl;
2603
2604		this.isAutoScroll =
2605			this.options.scroll &&
2606			scrollEl &&
2607			!scrollEl.is(window) &&
2608			!scrollEl.is(document);
2609
2610		if (this.isAutoScroll) {
2611			// debounce makes sure rapid calls don't happen
2612			this.listenTo(scrollEl, 'scroll', debounce(this.handleDebouncedScroll, 100));
2613		}
2614	},
2615
2616
2617	destroyAutoScroll: function() {
2618		this.endAutoScroll(); // kill any animation loop
2619
2620		// remove the scroll handler if there is a scrollEl
2621		if (this.isAutoScroll) {
2622			this.stopListeningTo(this.scrollEl, 'scroll'); // will probably get removed by unbindHandlers too :(
2623		}
2624	},
2625
2626
2627	// Computes and stores the bounding rectangle of scrollEl
2628	computeScrollBounds: function() {
2629		if (this.isAutoScroll) {
2630			this.scrollBounds = getOuterRect(this.scrollEl);
2631			// TODO: use getClientRect in future. but prevents auto scrolling when on top of scrollbars
2632		}
2633	},
2634
2635
2636	// Called when the dragging is in progress and scrolling should be updated
2637	updateAutoScroll: function(ev) {
2638		var sensitivity = this.scrollSensitivity;
2639		var bounds = this.scrollBounds;
2640		var topCloseness, bottomCloseness;
2641		var leftCloseness, rightCloseness;
2642		var topVel = 0;
2643		var leftVel = 0;
2644
2645		if (bounds) { // only scroll if scrollEl exists
2646
2647			// compute closeness to edges. valid range is from 0.0 - 1.0
2648			topCloseness = (sensitivity - (getEvY(ev) - bounds.top)) / sensitivity;
2649			bottomCloseness = (sensitivity - (bounds.bottom - getEvY(ev))) / sensitivity;
2650			leftCloseness = (sensitivity - (getEvX(ev) - bounds.left)) / sensitivity;
2651			rightCloseness = (sensitivity - (bounds.right - getEvX(ev))) / sensitivity;
2652
2653			// translate vertical closeness into velocity.
2654			// mouse must be completely in bounds for velocity to happen.
2655			if (topCloseness >= 0 && topCloseness <= 1) {
2656				topVel = topCloseness * this.scrollSpeed * -1; // negative. for scrolling up
2657			}
2658			else if (bottomCloseness >= 0 && bottomCloseness <= 1) {
2659				topVel = bottomCloseness * this.scrollSpeed;
2660			}
2661
2662			// translate horizontal closeness into velocity
2663			if (leftCloseness >= 0 && leftCloseness <= 1) {
2664				leftVel = leftCloseness * this.scrollSpeed * -1; // negative. for scrolling left
2665			}
2666			else if (rightCloseness >= 0 && rightCloseness <= 1) {
2667				leftVel = rightCloseness * this.scrollSpeed;
2668			}
2669		}
2670
2671		this.setScrollVel(topVel, leftVel);
2672	},
2673
2674
2675	// Sets the speed-of-scrolling for the scrollEl
2676	setScrollVel: function(topVel, leftVel) {
2677
2678		this.scrollTopVel = topVel;
2679		this.scrollLeftVel = leftVel;
2680
2681		this.constrainScrollVel(); // massages into realistic values
2682
2683		// if there is non-zero velocity, and an animation loop hasn't already started, then START
2684		if ((this.scrollTopVel || this.scrollLeftVel) && !this.scrollIntervalId) {
2685			this.scrollIntervalId = setInterval(
2686				proxy(this, 'scrollIntervalFunc'), // scope to `this`
2687				this.scrollIntervalMs
2688			);
2689		}
2690	},
2691
2692
2693	// Forces scrollTopVel and scrollLeftVel to be zero if scrolling has already gone all the way
2694	constrainScrollVel: function() {
2695		var el = this.scrollEl;
2696
2697		if (this.scrollTopVel < 0) { // scrolling up?
2698			if (el.scrollTop() <= 0) { // already scrolled all the way up?
2699				this.scrollTopVel = 0;
2700			}
2701		}
2702		else if (this.scrollTopVel > 0) { // scrolling down?
2703			if (el.scrollTop() + el[0].clientHeight >= el[0].scrollHeight) { // already scrolled all the way down?
2704				this.scrollTopVel = 0;
2705			}
2706		}
2707
2708		if (this.scrollLeftVel < 0) { // scrolling left?
2709			if (el.scrollLeft() <= 0) { // already scrolled all the left?
2710				this.scrollLeftVel = 0;
2711			}
2712		}
2713		else if (this.scrollLeftVel > 0) { // scrolling right?
2714			if (el.scrollLeft() + el[0].clientWidth >= el[0].scrollWidth) { // already scrolled all the way right?
2715				this.scrollLeftVel = 0;
2716			}
2717		}
2718	},
2719
2720
2721	// This function gets called during every iteration of the scrolling animation loop
2722	scrollIntervalFunc: function() {
2723		var el = this.scrollEl;
2724		var frac = this.scrollIntervalMs / 1000; // considering animation frequency, what the vel should be mult'd by
2725
2726		// change the value of scrollEl's scroll
2727		if (this.scrollTopVel) {
2728			el.scrollTop(el.scrollTop() + this.scrollTopVel * frac);
2729		}
2730		if (this.scrollLeftVel) {
2731			el.scrollLeft(el.scrollLeft() + this.scrollLeftVel * frac);
2732		}
2733
2734		this.constrainScrollVel(); // since the scroll values changed, recompute the velocities
2735
2736		// if scrolled all the way, which causes the vels to be zero, stop the animation loop
2737		if (!this.scrollTopVel && !this.scrollLeftVel) {
2738			this.endAutoScroll();
2739		}
2740	},
2741
2742
2743	// Kills any existing scrolling animation loop
2744	endAutoScroll: function() {
2745		if (this.scrollIntervalId) {
2746			clearInterval(this.scrollIntervalId);
2747			this.scrollIntervalId = null;
2748
2749			this.handleScrollEnd();
2750		}
2751	},
2752
2753
2754	// Get called when the scrollEl is scrolled (NOTE: this is delayed via debounce)
2755	handleDebouncedScroll: function() {
2756		// recompute all coordinates, but *only* if this is *not* part of our scrolling animation
2757		if (!this.scrollIntervalId) {
2758			this.handleScrollEnd();
2759		}
2760	},
2761
2762
2763	// Called when scrolling has stopped, whether through auto scroll, or the user scrolling
2764	handleScrollEnd: function() {
2765	}
2766
2767});
2768;;
2769
2770/* Tracks mouse movements over a component and raises events about which hit the mouse is over.
2771------------------------------------------------------------------------------------------------------------------------
2772options:
2773- subjectEl
2774- subjectCenter
2775*/
2776
2777var HitDragListener = DragListener.extend({
2778
2779	component: null, // converts coordinates to hits
2780		// methods: prepareHits, releaseHits, queryHit
2781
2782	origHit: null, // the hit the mouse was over when listening started
2783	hit: null, // the hit the mouse is over
2784	coordAdjust: null, // delta that will be added to the mouse coordinates when computing collisions
2785
2786
2787	constructor: function(component, options) {
2788		DragListener.call(this, options); // call the super-constructor
2789
2790		this.component = component;
2791	},
2792
2793
2794	// Called when drag listening starts (but a real drag has not necessarily began).
2795	// ev might be undefined if dragging was started manually.
2796	handleInteractionStart: function(ev) {
2797		var subjectEl = this.subjectEl;
2798		var subjectRect;
2799		var origPoint;
2800		var point;
2801
2802		this.computeCoords();
2803
2804		if (ev) {
2805			origPoint = { left: getEvX(ev), top: getEvY(ev) };
2806			point = origPoint;
2807
2808			// constrain the point to bounds of the element being dragged
2809			if (subjectEl) {
2810				subjectRect = getOuterRect(subjectEl); // used for centering as well
2811				point = constrainPoint(point, subjectRect);
2812			}
2813
2814			this.origHit = this.queryHit(point.left, point.top);
2815
2816			// treat the center of the subject as the collision point?
2817			if (subjectEl && this.options.subjectCenter) {
2818
2819				// only consider the area the subject overlaps the hit. best for large subjects.
2820				// TODO: skip this if hit didn't supply left/right/top/bottom
2821				if (this.origHit) {
2822					subjectRect = intersectRects(this.origHit, subjectRect) ||
2823						subjectRect; // in case there is no intersection
2824				}
2825
2826				point = getRectCenter(subjectRect);
2827			}
2828
2829			this.coordAdjust = diffPoints(point, origPoint); // point - origPoint
2830		}
2831		else {
2832			this.origHit = null;
2833			this.coordAdjust = null;
2834		}
2835
2836		// call the super-method. do it after origHit has been computed
2837		DragListener.prototype.handleInteractionStart.apply(this, arguments);
2838	},
2839
2840
2841	// Recomputes the drag-critical positions of elements
2842	computeCoords: function() {
2843		this.component.prepareHits();
2844		this.computeScrollBounds(); // why is this here??????
2845	},
2846
2847
2848	// Called when the actual drag has started
2849	handleDragStart: function(ev) {
2850		var hit;
2851
2852		DragListener.prototype.handleDragStart.apply(this, arguments); // call the super-method
2853
2854		// might be different from this.origHit if the min-distance is large
2855		hit = this.queryHit(getEvX(ev), getEvY(ev));
2856
2857		// report the initial hit the mouse is over
2858		// especially important if no min-distance and drag starts immediately
2859		if (hit) {
2860			this.handleHitOver(hit);
2861		}
2862	},
2863
2864
2865	// Called when the drag moves
2866	handleDrag: function(dx, dy, ev) {
2867		var hit;
2868
2869		DragListener.prototype.handleDrag.apply(this, arguments); // call the super-method
2870
2871		hit = this.queryHit(getEvX(ev), getEvY(ev));
2872
2873		if (!isHitsEqual(hit, this.hit)) { // a different hit than before?
2874			if (this.hit) {
2875				this.handleHitOut();
2876			}
2877			if (hit) {
2878				this.handleHitOver(hit);
2879			}
2880		}
2881	},
2882
2883
2884	// Called when dragging has been stopped
2885	handleDragEnd: function() {
2886		this.handleHitDone();
2887		DragListener.prototype.handleDragEnd.apply(this, arguments); // call the super-method
2888	},
2889
2890
2891	// Called when a the mouse has just moved over a new hit
2892	handleHitOver: function(hit) {
2893		var isOrig = isHitsEqual(hit, this.origHit);
2894
2895		this.hit = hit;
2896
2897		this.trigger('hitOver', this.hit, isOrig, this.origHit);
2898	},
2899
2900
2901	// Called when the mouse has just moved out of a hit
2902	handleHitOut: function() {
2903		if (this.hit) {
2904			this.trigger('hitOut', this.hit);
2905			this.handleHitDone();
2906			this.hit = null;
2907		}
2908	},
2909
2910
2911	// Called after a hitOut. Also called before a dragStop
2912	handleHitDone: function() {
2913		if (this.hit) {
2914			this.trigger('hitDone', this.hit);
2915		}
2916	},
2917
2918
2919	// Called when the interaction ends, whether there was a real drag or not
2920	handleInteractionEnd: function() {
2921		DragListener.prototype.handleInteractionEnd.apply(this, arguments); // call the super-method
2922
2923		this.origHit = null;
2924		this.hit = null;
2925
2926		this.component.releaseHits();
2927	},
2928
2929
2930	// Called when scrolling has stopped, whether through auto scroll, or the user scrolling
2931	handleScrollEnd: function() {
2932		DragListener.prototype.handleScrollEnd.apply(this, arguments); // call the super-method
2933
2934		this.computeCoords(); // hits' absolute positions will be in new places. recompute
2935	},
2936
2937
2938	// Gets the hit underneath the coordinates for the given mouse event
2939	queryHit: function(left, top) {
2940
2941		if (this.coordAdjust) {
2942			left += this.coordAdjust.left;
2943			top += this.coordAdjust.top;
2944		}
2945
2946		return this.component.queryHit(left, top);
2947	}
2948
2949});
2950
2951
2952// Returns `true` if the hits are identically equal. `false` otherwise. Must be from the same component.
2953// Two null values will be considered equal, as two "out of the component" states are the same.
2954function isHitsEqual(hit0, hit1) {
2955
2956	if (!hit0 && !hit1) {
2957		return true;
2958	}
2959
2960	if (hit0 && hit1) {
2961		return hit0.component === hit1.component &&
2962			isHitPropsWithin(hit0, hit1) &&
2963			isHitPropsWithin(hit1, hit0); // ensures all props are identical
2964	}
2965
2966	return false;
2967}
2968
2969
2970// Returns true if all of subHit's non-standard properties are within superHit
2971function isHitPropsWithin(subHit, superHit) {
2972	for (var propName in subHit) {
2973		if (!/^(component|left|right|top|bottom)$/.test(propName)) {
2974			if (subHit[propName] !== superHit[propName]) {
2975				return false;
2976			}
2977		}
2978	}
2979	return true;
2980}
2981
2982;;
2983
2984/* Creates a clone of an element and lets it track the mouse as it moves
2985----------------------------------------------------------------------------------------------------------------------*/
2986
2987var MouseFollower = Class.extend(ListenerMixin, {
2988
2989	options: null,
2990
2991	sourceEl: null, // the element that will be cloned and made to look like it is dragging
2992	el: null, // the clone of `sourceEl` that will track the mouse
2993	parentEl: null, // the element that `el` (the clone) will be attached to
2994
2995	// the initial position of el, relative to the offset parent. made to match the initial offset of sourceEl
2996	top0: null,
2997	left0: null,
2998
2999	// the absolute coordinates of the initiating touch/mouse action
3000	y0: null,
3001	x0: null,
3002
3003	// the number of pixels the mouse has moved from its initial position
3004	topDelta: null,
3005	leftDelta: null,
3006
3007	isFollowing: false,
3008	isHidden: false,
3009	isAnimating: false, // doing the revert animation?
3010
3011	constructor: function(sourceEl, options) {
3012		this.options = options = options || {};
3013		this.sourceEl = sourceEl;
3014		this.parentEl = options.parentEl ? $(options.parentEl) : sourceEl.parent(); // default to sourceEl's parent
3015	},
3016
3017
3018	// Causes the element to start following the mouse
3019	start: function(ev) {
3020		if (!this.isFollowing) {
3021			this.isFollowing = true;
3022
3023			this.y0 = getEvY(ev);
3024			this.x0 = getEvX(ev);
3025			this.topDelta = 0;
3026			this.leftDelta = 0;
3027
3028			if (!this.isHidden) {
3029				this.updatePosition();
3030			}
3031
3032			if (getEvIsTouch(ev)) {
3033				this.listenTo($(document), 'touchmove', this.handleMove);
3034			}
3035			else {
3036				this.listenTo($(document), 'mousemove', this.handleMove);
3037			}
3038		}
3039	},
3040
3041
3042	// Causes the element to stop following the mouse. If shouldRevert is true, will animate back to original position.
3043	// `callback` gets invoked when the animation is complete. If no animation, it is invoked immediately.
3044	stop: function(shouldRevert, callback) {
3045		var _this = this;
3046		var revertDuration = this.options.revertDuration;
3047
3048		function complete() { // might be called by .animate(), which might change `this` context
3049			_this.isAnimating = false;
3050			_this.removeElement();
3051
3052			_this.top0 = _this.left0 = null; // reset state for future updatePosition calls
3053
3054			if (callback) {
3055				callback();
3056			}
3057		}
3058
3059		if (this.isFollowing && !this.isAnimating) { // disallow more than one stop animation at a time
3060			this.isFollowing = false;
3061
3062			this.stopListeningTo($(document));
3063
3064			if (shouldRevert && revertDuration && !this.isHidden) { // do a revert animation?
3065				this.isAnimating = true;
3066				this.el.animate({
3067					top: this.top0,
3068					left: this.left0
3069				}, {
3070					duration: revertDuration,
3071					complete: complete
3072				});
3073			}
3074			else {
3075				complete();
3076			}
3077		}
3078	},
3079
3080
3081	// Gets the tracking element. Create it if necessary
3082	getEl: function() {
3083		var el = this.el;
3084
3085		if (!el) {
3086			el = this.el = this.sourceEl.clone()
3087				.addClass(this.options.additionalClass || '')
3088				.css({
3089					position: 'absolute',
3090					visibility: '', // in case original element was hidden (commonly through hideEvents())
3091					display: this.isHidden ? 'none' : '', // for when initially hidden
3092					margin: 0,
3093					right: 'auto', // erase and set width instead
3094					bottom: 'auto', // erase and set height instead
3095					width: this.sourceEl.width(), // explicit height in case there was a 'right' value
3096					height: this.sourceEl.height(), // explicit width in case there was a 'bottom' value
3097					opacity: this.options.opacity || '',
3098					zIndex: this.options.zIndex
3099				});
3100
3101			// we don't want long taps or any mouse interaction causing selection/menus.
3102			// would use preventSelection(), but that prevents selectstart, causing problems.
3103			el.addClass('fc-unselectable');
3104
3105			el.appendTo(this.parentEl);
3106		}
3107
3108		return el;
3109	},
3110
3111
3112	// Removes the tracking element if it has already been created
3113	removeElement: function() {
3114		if (this.el) {
3115			this.el.remove();
3116			this.el = null;
3117		}
3118	},
3119
3120
3121	// Update the CSS position of the tracking element
3122	updatePosition: function() {
3123		var sourceOffset;
3124		var origin;
3125
3126		this.getEl(); // ensure this.el
3127
3128		// make sure origin info was computed
3129		if (this.top0 === null) {
3130			sourceOffset = this.sourceEl.offset();
3131			origin = this.el.offsetParent().offset();
3132			this.top0 = sourceOffset.top - origin.top;
3133			this.left0 = sourceOffset.left - origin.left;
3134		}
3135
3136		this.el.css({
3137			top: this.top0 + this.topDelta,
3138			left: this.left0 + this.leftDelta
3139		});
3140	},
3141
3142
3143	// Gets called when the user moves the mouse
3144	handleMove: function(ev) {
3145		this.topDelta = getEvY(ev) - this.y0;
3146		this.leftDelta = getEvX(ev) - this.x0;
3147
3148		if (!this.isHidden) {
3149			this.updatePosition();
3150		}
3151	},
3152
3153
3154	// Temporarily makes the tracking element invisible. Can be called before following starts
3155	hide: function() {
3156		if (!this.isHidden) {
3157			this.isHidden = true;
3158			if (this.el) {
3159				this.el.hide();
3160			}
3161		}
3162	},
3163
3164
3165	// Show the tracking element after it has been temporarily hidden
3166	show: function() {
3167		if (this.isHidden) {
3168			this.isHidden = false;
3169			this.updatePosition();
3170			this.getEl().show();
3171		}
3172	}
3173
3174});
3175
3176;;
3177
3178/* An abstract class comprised of a "grid" of areas that each represent a specific datetime
3179----------------------------------------------------------------------------------------------------------------------*/
3180
3181var Grid = FC.Grid = Class.extend(ListenerMixin, MouseIgnorerMixin, {
3182
3183	// self-config, overridable by subclasses
3184	hasDayInteractions: true, // can user click/select ranges of time?
3185
3186	view: null, // a View object
3187	isRTL: null, // shortcut to the view's isRTL option
3188
3189	start: null,
3190	end: null,
3191
3192	el: null, // the containing element
3193	elsByFill: null, // a hash of jQuery element sets used for rendering each fill. Keyed by fill name.
3194
3195	// derived from options
3196	eventTimeFormat: null,
3197	displayEventTime: null,
3198	displayEventEnd: null,
3199
3200	minResizeDuration: null, // TODO: hack. set by subclasses. minumum event resize duration
3201
3202	// if defined, holds the unit identified (ex: "year" or "month") that determines the level of granularity
3203	// of the date areas. if not defined, assumes to be day and time granularity.
3204	// TODO: port isTimeScale into same system?
3205	largeUnit: null,
3206
3207	dayDragListener: null,
3208	segDragListener: null,
3209	segResizeListener: null,
3210	externalDragListener: null,
3211
3212
3213	constructor: function(view) {
3214		this.view = view;
3215		this.isRTL = view.opt('isRTL');
3216		this.elsByFill = {};
3217
3218		this.dayDragListener = this.buildDayDragListener();
3219		this.initMouseIgnoring();
3220	},
3221
3222
3223	/* Options
3224	------------------------------------------------------------------------------------------------------------------*/
3225
3226
3227	// Generates the format string used for event time text, if not explicitly defined by 'timeFormat'
3228	computeEventTimeFormat: function() {
3229		return this.view.opt('smallTimeFormat');
3230	},
3231
3232
3233	// Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventTime'.
3234	// Only applies to non-all-day events.
3235	computeDisplayEventTime: function() {
3236		return true;
3237	},
3238
3239
3240	// Determines whether events should have their end times displayed, if not explicitly defined by 'displayEventEnd'
3241	computeDisplayEventEnd: function() {
3242		return true;
3243	},
3244
3245
3246	/* Dates
3247	------------------------------------------------------------------------------------------------------------------*/
3248
3249
3250	// Tells the grid about what period of time to display.
3251	// Any date-related internal data should be generated.
3252	setRange: function(range) {
3253		this.start = range.start.clone();
3254		this.end = range.end.clone();
3255
3256		this.rangeUpdated();
3257		this.processRangeOptions();
3258	},
3259
3260
3261	// Called when internal variables that rely on the range should be updated
3262	rangeUpdated: function() {
3263	},
3264
3265
3266	// Updates values that rely on options and also relate to range
3267	processRangeOptions: function() {
3268		var view = this.view;
3269		var displayEventTime;
3270		var displayEventEnd;
3271
3272		this.eventTimeFormat =
3273			view.opt('eventTimeFormat') ||
3274			view.opt('timeFormat') || // deprecated
3275			this.computeEventTimeFormat();
3276
3277		displayEventTime = view.opt('displayEventTime');
3278		if (displayEventTime == null) {
3279			displayEventTime = this.computeDisplayEventTime(); // might be based off of range
3280		}
3281
3282		displayEventEnd = view.opt('displayEventEnd');
3283		if (displayEventEnd == null) {
3284			displayEventEnd = this.computeDisplayEventEnd(); // might be based off of range
3285		}
3286
3287		this.displayEventTime = displayEventTime;
3288		this.displayEventEnd = displayEventEnd;
3289	},
3290
3291
3292	// Converts a span (has unzoned start/end and any other grid-specific location information)
3293	// into an array of segments (pieces of events whose format is decided by the grid).
3294	spanToSegs: function(span) {
3295		// subclasses must implement
3296	},
3297
3298
3299	// Diffs the two dates, returning a duration, based on granularity of the grid
3300	// TODO: port isTimeScale into this system?
3301	diffDates: function(a, b) {
3302		if (this.largeUnit) {
3303			return diffByUnit(a, b, this.largeUnit);
3304		}
3305		else {
3306			return diffDayTime(a, b);
3307		}
3308	},
3309
3310
3311	/* Hit Area
3312	------------------------------------------------------------------------------------------------------------------*/
3313
3314
3315	// Called before one or more queryHit calls might happen. Should prepare any cached coordinates for queryHit
3316	prepareHits: function() {
3317	},
3318
3319
3320	// Called when queryHit calls have subsided. Good place to clear any coordinate caches.
3321	releaseHits: function() {
3322	},
3323
3324
3325	// Given coordinates from the topleft of the document, return data about the date-related area underneath.
3326	// Can return an object with arbitrary properties (although top/right/left/bottom are encouraged).
3327	// Must have a `grid` property, a reference to this current grid. TODO: avoid this
3328	// The returned object will be processed by getHitSpan and getHitEl.
3329	queryHit: function(leftOffset, topOffset) {
3330	},
3331
3332
3333	// Given position-level information about a date-related area within the grid,
3334	// should return an object with at least a start/end date. Can provide other information as well.
3335	getHitSpan: function(hit) {
3336	},
3337
3338
3339	// Given position-level information about a date-related area within the grid,
3340	// should return a jQuery element that best represents it. passed to dayClick callback.
3341	getHitEl: function(hit) {
3342	},
3343
3344
3345	/* Rendering
3346	------------------------------------------------------------------------------------------------------------------*/
3347
3348
3349	// Sets the container element that the grid should render inside of.
3350	// Does other DOM-related initializations.
3351	setElement: function(el) {
3352		this.el = el;
3353
3354		if (this.hasDayInteractions) {
3355			preventSelection(el);
3356
3357			this.bindDayHandler('touchstart', this.dayTouchStart);
3358			this.bindDayHandler('mousedown', this.dayMousedown);
3359		}
3360
3361		// attach event-element-related handlers. in Grid.events
3362		// same garbage collection note as above.
3363		this.bindSegHandlers();
3364
3365		this.bindGlobalHandlers();
3366	},
3367
3368
3369	bindDayHandler: function(name, handler) {
3370		var _this = this;
3371
3372		// attach a handler to the grid's root element.
3373		// jQuery will take care of unregistering them when removeElement gets called.
3374		this.el.on(name, function(ev) {
3375			if (
3376				!$(ev.target).is(
3377					_this.segSelector + ',' + // directly on an event element
3378					_this.segSelector + ' *,' + // within an event element
3379					'.fc-more,' + // a "more.." link
3380					'a[data-goto]' // a clickable nav link
3381				)
3382			) {
3383				return handler.call(_this, ev);
3384			}
3385		});
3386	},
3387
3388
3389	// Removes the grid's container element from the DOM. Undoes any other DOM-related attachments.
3390	// DOES NOT remove any content beforehand (doesn't clear events or call unrenderDates), unlike View
3391	removeElement: function() {
3392		this.unbindGlobalHandlers();
3393		this.clearDragListeners();
3394
3395		this.el.remove();
3396
3397		// NOTE: we don't null-out this.el for the same reasons we don't do it within View::removeElement
3398	},
3399
3400
3401	// Renders the basic structure of grid view before any content is rendered
3402	renderSkeleton: function() {
3403		// subclasses should implement
3404	},
3405
3406
3407	// Renders the grid's date-related content (like areas that represent days/times).
3408	// Assumes setRange has already been called and the skeleton has already been rendered.
3409	renderDates: function() {
3410		// subclasses should implement
3411	},
3412
3413
3414	// Unrenders the grid's date-related content
3415	unrenderDates: function() {
3416		// subclasses should implement
3417	},
3418
3419
3420	/* Handlers
3421	------------------------------------------------------------------------------------------------------------------*/
3422
3423
3424	// Binds DOM handlers to elements that reside outside the grid, such as the document
3425	bindGlobalHandlers: function() {
3426		this.listenTo($(document), {
3427			dragstart: this.externalDragStart, // jqui
3428			sortstart: this.externalDragStart // jqui
3429		});
3430	},
3431
3432
3433	// Unbinds DOM handlers from elements that reside outside the grid
3434	unbindGlobalHandlers: function() {
3435		this.stopListeningTo($(document));
3436	},
3437
3438
3439	// Process a mousedown on an element that represents a day. For day clicking and selecting.
3440	dayMousedown: function(ev) {
3441		if (!this.isIgnoringMouse) {
3442			this.dayDragListener.startInteraction(ev, {
3443				//distance: 5, // needs more work if we want dayClick to fire correctly
3444			});
3445		}
3446	},
3447
3448
3449	dayTouchStart: function(ev) {
3450		var view = this.view;
3451
3452		// HACK to prevent a user's clickaway for unselecting a range or an event
3453		// from causing a dayClick.
3454		if (view.isSelected || view.selectedEvent) {
3455			this.tempIgnoreMouse();
3456		}
3457
3458		this.dayDragListener.startInteraction(ev, {
3459			delay: this.view.opt('longPressDelay')
3460		});
3461	},
3462
3463
3464	// Creates a listener that tracks the user's drag across day elements.
3465	// For day clicking and selecting.
3466	buildDayDragListener: function() {
3467		var _this = this;
3468		var view = this.view;
3469		var isSelectable = view.opt('selectable');
3470		var dayClickHit; // null if invalid dayClick
3471		var selectionSpan; // null if invalid selection
3472
3473		// this listener tracks a mousedown on a day element, and a subsequent drag.
3474		// if the drag ends on the same day, it is a 'dayClick'.
3475		// if 'selectable' is enabled, this listener also detects selections.
3476		var dragListener = new HitDragListener(this, {
3477			scroll: view.opt('dragScroll'),
3478			interactionStart: function() {
3479				dayClickHit = dragListener.origHit; // for dayClick, where no dragging happens
3480				selectionSpan = null;
3481			},
3482			dragStart: function() {
3483				view.unselect(); // since we could be rendering a new selection, we want to clear any old one
3484			},
3485			hitOver: function(hit, isOrig, origHit) {
3486				if (origHit) { // click needs to have started on a hit
3487
3488					// if user dragged to another cell at any point, it can no longer be a dayClick
3489					if (!isOrig) {
3490						dayClickHit = null;
3491					}
3492
3493					if (isSelectable) {
3494						selectionSpan = _this.computeSelection(
3495							_this.getHitSpan(origHit),
3496							_this.getHitSpan(hit)
3497						);
3498						if (selectionSpan) {
3499							_this.renderSelection(selectionSpan);
3500						}
3501						else if (selectionSpan === false) {
3502							disableCursor();
3503						}
3504					}
3505				}
3506			},
3507			hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
3508				dayClickHit = null;
3509				selectionSpan = null;
3510				_this.unrenderSelection();
3511			},
3512			hitDone: function() { // called after a hitOut OR before a dragEnd
3513				enableCursor();
3514			},
3515			interactionEnd: function(ev, isCancelled) {
3516				if (!isCancelled) {
3517					if (
3518						dayClickHit &&
3519						!_this.isIgnoringMouse // see hack in dayTouchStart
3520					) {
3521						view.triggerDayClick(
3522							_this.getHitSpan(dayClickHit),
3523							_this.getHitEl(dayClickHit),
3524							ev
3525						);
3526					}
3527					if (selectionSpan) {
3528						// the selection will already have been rendered. just report it
3529						view.reportSelection(selectionSpan, ev);
3530					}
3531				}
3532			}
3533		});
3534
3535		return dragListener;
3536	},
3537
3538
3539	// Kills all in-progress dragging.
3540	// Useful for when public API methods that result in re-rendering are invoked during a drag.
3541	// Also useful for when touch devices misbehave and don't fire their touchend.
3542	clearDragListeners: function() {
3543		this.dayDragListener.endInteraction();
3544
3545		if (this.segDragListener) {
3546			this.segDragListener.endInteraction(); // will clear this.segDragListener
3547		}
3548		if (this.segResizeListener) {
3549			this.segResizeListener.endInteraction(); // will clear this.segResizeListener
3550		}
3551		if (this.externalDragListener) {
3552			this.externalDragListener.endInteraction(); // will clear this.externalDragListener
3553		}
3554	},
3555
3556
3557	/* Event Helper
3558	------------------------------------------------------------------------------------------------------------------*/
3559	// TODO: should probably move this to Grid.events, like we did event dragging / resizing
3560
3561
3562	// Renders a mock event at the given event location, which contains zoned start/end properties.
3563	// Returns all mock event elements.
3564	renderEventLocationHelper: function(eventLocation, sourceSeg) {
3565		var fakeEvent = this.fabricateHelperEvent(eventLocation, sourceSeg);
3566
3567		return this.renderHelper(fakeEvent, sourceSeg); // do the actual rendering
3568	},
3569
3570
3571	// Builds a fake event given zoned event date properties and a segment is should be inspired from.
3572	// The range's end can be null, in which case the mock event that is rendered will have a null end time.
3573	// `sourceSeg` is the internal segment object involved in the drag. If null, something external is dragging.
3574	fabricateHelperEvent: function(eventLocation, sourceSeg) {
3575		var fakeEvent = sourceSeg ? createObject(sourceSeg.event) : {}; // mask the original event object if possible
3576
3577		fakeEvent.start = eventLocation.start.clone();
3578		fakeEvent.end = eventLocation.end ? eventLocation.end.clone() : null;
3579		fakeEvent.allDay = null; // force it to be freshly computed by normalizeEventDates
3580		this.view.calendar.normalizeEventDates(fakeEvent);
3581
3582		// this extra className will be useful for differentiating real events from mock events in CSS
3583		fakeEvent.className = (fakeEvent.className || []).concat('fc-helper');
3584
3585		// if something external is being dragged in, don't render a resizer
3586		if (!sourceSeg) {
3587			fakeEvent.editable = false;
3588		}
3589
3590		return fakeEvent;
3591	},
3592
3593
3594	// Renders a mock event. Given zoned event date properties.
3595	// Must return all mock event elements.
3596	renderHelper: function(eventLocation, sourceSeg) {
3597		// subclasses must implement
3598	},
3599
3600
3601	// Unrenders a mock event
3602	unrenderHelper: function() {
3603		// subclasses must implement
3604	},
3605
3606
3607	/* Selection
3608	------------------------------------------------------------------------------------------------------------------*/
3609
3610
3611	// Renders a visual indication of a selection. Will highlight by default but can be overridden by subclasses.
3612	// Given a span (unzoned start/end and other misc data)
3613	renderSelection: function(span) {
3614		this.renderHighlight(span);
3615	},
3616
3617
3618	// Unrenders any visual indications of a selection. Will unrender a highlight by default.
3619	unrenderSelection: function() {
3620		this.unrenderHighlight();
3621	},
3622
3623
3624	// Given the first and last date-spans of a selection, returns another date-span object.
3625	// Subclasses can override and provide additional data in the span object. Will be passed to render
3625Selection().
3626	// Will return false if the selection is invalid and this should be indicated to the user.
3627	// Will return null/undefined if a selection invalid but no error should be reported.
3628	computeSelection: function(span0, span1) {
3629		var span = this.computeSelectionSpan(span0, span1);
3630
3631		if (span && !this.view.calendar.isSelectionSpanAllowed(span)) {
3632			return false;
3633		}
3634
3635		return span;
3636	},
3637
3638
3639	// Given two spans, must return the combination of the two.
3640	// TODO: do this separation of concerns (combining VS validation) for event dnd/resize too.
3641	computeSelectionSpan: function(span0, span1) {
3642		var dates = [ span0.start, span0.end, span1.start, span1.end ];
3643
3644		dates.sort(compareNumbers); // sorts chronologically. works with Moments
3645
3646		return { start: dates[0].clone(), end: dates[3].clone() };
3647	},
3648
3649
3650	/* Highlight
3651	------------------------------------------------------------------------------------------------------------------*/
3652
3653
3654	// Renders an emphasis on the given date range. Given a span (unzoned start/end and other misc data)
3655	renderHighlight: function(span) {
3656		this.renderFill('highlight', this.spanToSegs(span));
3657	},
3658
3659
3660	// Unrenders the emphasis on a date range
3661	unrenderHighlight: function() {
3662		this.unrenderFill('highlight');
3663	},
3664
3665
3666	// Generates an array of classNames for rendering the highlight. Used by the fill system.
3667	highlightSegClasses: function() {
3668		return [ 'fc-highlight' ];
3669	},
3670
3671
3672	/* Business Hours
3673	------------------------------------------------------------------------------------------------------------------*/
3674
3675
3676	renderBusinessHours: function() {
3677	},
3678
3679
3680	unrenderBusinessHours: function() {
3681	},
3682
3683
3684	/* Now Indicator
3685	------------------------------------------------------------------------------------------------------------------*/
3686
3687
3688	getNowIndicatorUnit: function() {
3689	},
3690
3691
3692	renderNowIndicator: function(date) {
3693	},
3694
3695
3696	unrenderNowIndicator: function() {
3697	},
3698
3699
3700	/* Fill System (highlight, background events, business hours)
3701	--------------------------------------------------------------------------------------------------------------------
3702	TODO: remove this system. like we did in TimeGrid
3703	*/
3704
3705
3706	// Renders a set of rectangles over the given segments of time.
3707	// MUST RETURN a subset of segs, the segs that were actually rendered.
3708	// Responsible for populating this.elsByFill. TODO: better API for expressing this requirement
3709	renderFill: function(type, segs) {
3710		// subclasses must implement
3711	},
3712
3713
3714	// Unrenders a specific type of fill that is currently rendered on the grid
3715	unrenderFill: function(type) {
3716		var el = this.elsByFill[type];
3717
3718		if (el) {
3719			el.remove();
3720			delete this.elsByFill[type];
3721		}
3722	},
3723
3724
3725	// Renders and assigns an `el` property for each fill segment. Generic enough to work with different types.
3726	// Only returns segments that successfully rendered.
3727	// To be harnessed by renderFill (implemented by subclasses).
3728	// Analagous to renderFgSegEls.
3729	renderFillSegEls: function(type, segs) {
3730		var _this = this;
3731		var segElMethod = this[type + 'SegEl'];
3732		var html = '';
3733		var renderedSegs = [];
3734		var i;
3735
3736		if (segs.length) {
3737
3738			// build a large concatenation of segment HTML
3739			for (i = 0; i < segs.length; i++) {
3740				html += this.fillSegHtml(type, segs[i]);
3741			}
3742
3743			// Grab individual elements from the combined HTML string. Use each as the default rendering.
3744			// Then, compute the 'el' for each segment.
3745			$(html).each(function(i, node) {
3746				var seg = segs[i];
3747				var el = $(node);
3748
3749				// allow custom filter methods per-type
3750				if (segElMethod) {
3751					el = segElMethod.call(_this, seg, el);
3752				}
3753
3754				if (el) { // custom filters did not cancel the render
3755					el = $(el); // allow custom filter to return raw DOM node
3756
3757					// correct element type? (would be bad if a non-TD were inserted into a table for example)
3758					if (el.is(_this.fillSegTag)) {
3759						seg.el = el;
3760						renderedSegs.push(seg);
3761					}
3762				}
3763			});
3764		}
3765
3766		return renderedSegs;
3767	},
3768
3769
3770	fillSegTag: 'div', // subclasses can override
3771
3772
3773	// Builds the HTML needed for one fill segment. Generic enough to work with different types.
3774	fillSegHtml: function(type, seg) {
3775
3776		// custom hooks per-type
3777		var classesMethod = this[type + 'SegClasses'];
3778		var cssMethod = this[type + 'SegCss'];
3779
3780		var classes = classesMethod ? classesMethod.call(this, seg) : [];
3781		var css = cssToStr(cssMethod ? cssMethod.call(this, seg) : {});
3782
3783		return '<' + this.fillSegTag +
3784			(classes.length ? ' class="' + classes.join(' ') + '"' : '') +
3785			(css ? ' style="' + css + '"' : '') +
3786			' />';
3787	},
3788
3789
3790
3791	/* Generic rendering utilities for subclasses
3792	------------------------------------------------------------------------------------------------------------------*/
3793
3794
3795	// Computes HTML classNames for a single-day element
3796	getDayClasses: function(date) {
3797		var view = this.view;
3798		var today = view.calendar.getNow();
3799		var classes = [ 'fc-' + dayIDs[date.day()] ];
3800
3801		if (
3802			view.intervalDuration.as('months') == 1 &&
3803			date.month() != view.intervalStart.month()
3804		) {
3805			classes.push('fc-other-month');
3806		}
3807
3808		if (date.isSame(today, 'day')) {
3809			classes.push(
3810				'fc-today',
3811				view.highlightStateClass
3812			);
3813		}
3814		else if (date < today) {
3815			classes.push('fc-past');
3816		}
3817		else {
3818			classes.push('fc-future');
3819		}
3820
3821		return classes;
3822	}
3823
3824});
3825
3826;;
3827
3828/* Event-rendering and event-interaction methods for the abstract Grid class
3829----------------------------------------------------------------------------------------------------------------------*/
3830
3831Grid.mixin({
3832
3833	// self-config, overridable by subclasses
3834	segSelector: '.fc-event-container > *', // what constitutes an event element?
3835
3836	mousedOverSeg: null, // the segment object the user's mouse is over. null if over nothing
3837	isDraggingSeg: false, // is a segment being dragged? boolean
3838	isResizingSeg: false, // is a segment being resized? boolean
3839	isDraggingExternal: false, // jqui-dragging an external element? boolean
3840	segs: null, // the *event* segments currently rendered in the grid. TODO: rename to `eventSegs`
3841
3842
3843	// Renders the given events onto the grid
3844	renderEvents: function(events) {
3845		var bgEvents = [];
3846		var fgEvents = [];
3847		var i;
3848
3849		for (i = 0; i < events.length; i++) {
3850			(isBgEvent(events[i]) ? bgEvents : fgEvents).push(events[i]);
3851		}
3852
3853		this.segs = [].concat( // record all segs
3854			this.renderBgEvents(bgEvents),
3855			this.renderFgEvents(fgEvents)
3856		);
3857	},
3858
3859
3860	renderBgEvents: function(events) {
3861		var segs = this.eventsToSegs(events);
3862
3863		// renderBgSegs might return a subset of segs, segs that were actually rendered
3864		return this.renderBgSegs(segs) || segs;
3865	},
3866
3867
3868	renderFgEvents: function(events) {
3869		var segs = this.eventsToSegs(events);
3870
3871		// renderFgSegs might return a subset of segs, segs that were actually rendered
3872		return this.renderFgSegs(segs) || segs;
3873	},
3874
3875
3876	// Unrenders all events currently rendered on the grid
3877	unrenderEvents: function() {
3878		this.handleSegMouseout(); // trigger an eventMouseout if user's mouse is over an event
3879		this.clearDragListeners();
3880
3881		this.unrenderFgSegs();
3882		this.unrenderBgSegs();
3883
3884		this.segs = null;
3885	},
3886
3887
3888	// Retrieves all rendered segment objects currently rendered on the grid
3889	getEventSegs: function() {
3890		return this.segs || [];
3891	},
3892
3893
3894	/* Foreground Segment Rendering
3895	------------------------------------------------------------------------------------------------------------------*/
3896
3897
3898	// Renders foreground event segments onto the grid. May return a subset of segs that were rendered.
3899	renderFgSegs: function(segs) {
3900		// subclasses must implement
3901	},
3902
3903
3904	// Unrenders all currently rendered foreground segments
3905	unrenderFgSegs: function() {
3906		// subclasses must implement
3907	},
3908
3909
3910	// Renders and assigns an `el` property for each foreground event segment.
3911	// Only returns segments that successfully rendered.
3912	// A utility that subclasses may use.
3913	renderFgSegEls: function(segs, disableResizing) {
3914		var view = this.view;
3915		var html = '';
3916		var renderedSegs = [];
3917		var i;
3918		// console.log(segs);
3919		// console.log(segs.length);
3920
3921		var b = jQuery('#agendacalander').fullCalendar('getDate');
3922		console.log(b);
3923		var date = b.format('L').toString();
3924		var datesplit = date.split('/');
3925		var month = datesplit[1];
3926		month = month.replace(/^0+/, '');
3927		var Year = datesplit[2];
3928
3929		jQuery('.select_month option[value="'+month+'"]').prop('selected', true);
3930		jQuery('.select_year option[value="'+Year+'"]').prop('selected', true);
3931		
3932		if (segs.length) { // don't build an empty html string
3933
3934			// build a large concatenation of event segment HTML
3935			for (i = 0; i < segs.length; i++) {
3936				html += this.fgSegHtml(segs[i], disableResizing);
3937			}
3938
3939			// Grab individual elements from the combined HTML string. Use each as the default rendering.
3940			// Then, compute the 'el' for each segment. An el might be null if the eventRender callback returned false.
3941			$(html).each(function(i, node) {
3942				var seg = segs[i];
3943				var el = view.resolveEventEl(seg.event, $(node));
3944
3945				if (el) {
3946					el.data('fc-seg', seg); // used by handlers
3947					seg.el = el;
3948					renderedSegs.push(seg);
3949				}
3950			});
3951		}
3952
3953		return renderedSegs;
3954	},
3955
3956
3957	// Generates the HTML for the default rendering of a foreground event segment. Used by renderFgSegEls()
3958	fgSegHtml: function(seg, disableResizing) {
3959		// subclasses should implement
3960	},
3961
3962
3963	/* Background Segment Rendering
3964	------------------------------------------------------------------------------------------------------------------*/
3965
3966
3967	// Renders the given background event segments onto the grid.
3968	// Returns a subset of the segs that were actually rendered.
3969	renderBgSegs: function(segs) {
3970		return this.renderFill('bgEvent', segs);
3971	},
3972
3973
3974	// Unrenders all the currently rendered background event segments
3975	unrenderBgSegs: function() {
3976		this.unrenderFill('bgEvent');
3977	},
3978
3979
3980	// Renders a background event element, given the default rendering. Called by the fill system.
3981	bgEventSegEl: function(seg, el) {
3982		return this.view.resolveEventEl(seg.event, el); // will filter through eventRender
3983	},
3984
3985
3986	// Generates an array of classNames to be used for the default rendering of a background event.
3987	// Called by fillSegHtml.
3988	bgEventSegClasses: function(seg) {
3989		var event = seg.event;
3990		var source = event.source || {};
3991
3992		return [ 'fc-bgevent' ].concat(
3993			event.className,
3994			source.className || []
3995		);
3996	},
3997
3998
3999	// Generates a semicolon-separated CSS string to be used for the default rendering of a background event.
4000	// Called by fillSegHtml.
4001	bgEventSegCss: function(seg) {
4002		return {
4003			'background-color': this.getSegSkinCss(seg)['background-color']
4004		};
4005	},
4006
4007
4008	// Generates an array of classNames to be used for the rendering business hours overlay. Called by the fill system.
4009	// Called by fillSegHtml.
4010	businessHoursSegClasses: function(seg) {
4011		return [ 'fc-nonbusiness', 'fc-bgevent' ];
4012	},
4013
4014
4015	/* Business Hours
4016	------------------------------------------------------------------------------------------------------------------*/
4017
4018
4019	// Compute business hour segs for the grid's current date range.
4020	// Caller must ask if whole-day business hours are needed.
4021	buildBusinessHourSegs: function(wholeDay) {
4022		var events = this.view.calendar.getCurrentBusinessHourEvents(wholeDay);
4023
4024		// HACK. Eventually refactor business hours "events" system.
4025		// If no events are given, but businessHours is activated, this means the entire visible range should be
4026		// marked as *not* business-hours, via inverse-background rendering.
4027		if (
4028			!events.length &&
4029			this.view.calendar.options.businessHours // don't access view option. doesn't update with dynamic options
4030		) {
4031			events = [
4032				$.extend({}, BUSINESS_HOUR_EVENT_DEFAULTS, {
4033					start: this.view.end, // guaranteed out-of-range
4034					end: this.view.end,   // "
4035					dow: null
4036				})
4037			];
4038		}
4039
4040		return this.eventsToSegs(events);
4041	},
4042
4043
4044	/* Handlers
4045	------------------------------------------------------------------------------------------------------------------*/
4046
4047
4048	// Attaches event-element-related handlers for *all* rendered event segments of the view.
4049	bindSegHandlers: function() {
4050		this.bindSegHandlersToEl(this.el);
4051	},
4052
4053
4054	// Attaches event-element-related handlers to an arbitrary container element. leverages bubbling.
4055	bindSegHandlersToEl: function(el) {
4056		this.bindSegHandlerToEl(el, 'touchstart', this.handleSegTouchStart);
4057		this.bindSegHandlerToEl(el, 'touchend', this.handleSegTouchEnd);
4058		this.bindSegHandlerToEl(el, 'mouseenter', this.handleSegMouseover);
4059		this.bindSegHandlerToEl(el, 'mouseleave', this.handleSegMouseout);
4060		this.bindSegHandlerToEl(el, 'mousedown', this.handleSegMousedown);
4061		this.bindSegHandlerToEl(el, 'click', this.handleSegClick);
4062	},
4063
4064
4065	// Executes a handler for any a user-interaction on a segment.
4066	// Handler gets called with (seg, ev), and with the `this` context of the Grid
4067	bindSegHandlerToEl: function(el, name, handler) {
4068		var _this = this;
4069
4070		el.on(name, this.segSelector, function(ev) {
4071			var seg = $(this).data('fc-seg'); // grab segment data. put there by View::renderEvents
4072
4073			// only call the handlers if there is not a drag/resize in progress
4074			if (seg && !_this.isDraggingSeg && !_this.isResizingSeg) {
4075				return handler.call(_this, seg, ev); // context will be the Grid
4076			}
4077		});
4078	},
4079
4080
4081	handleSegClick: function(seg, ev) {
4082		var res = this.view.trigger('eventClick', seg.el[0], seg.event, ev); // can return `false` to cancel
4083		if (res === false) {
4084			ev.preventDefault();
4085		}
4086	},
4087
4088
4089	// Updates internal state and triggers handlers for when an event element is moused over
4090	handleSegMouseover: function(seg, ev) {
4091		if (
4092			!this.isIgnoringMouse &&
4093			!this.mousedOverSeg
4094		) {
4095			this.mousedOverSeg = seg;
4096			if (this.view.isEventResizable(seg.event)) {
4097				seg.el.addClass('fc-allow-mouse-resize');
4098			}
4099			this.view.trigger('eventMouseover', seg.el[0], seg.event, ev);
4100		}
4101	},
4102
4103
4104	// Updates internal state and triggers handlers for when an event element is moused out.
4105	// Can be given no arguments, in which case it will mouseout the segment that was previously moused over.
4106	handleSegMouseout: function(seg, ev) {
4107		ev = ev || {}; // if given no args, make a mock mouse event
4108
4109		if (this.mousedOverSeg) {
4110			seg = seg || this.mousedOverSeg; // if given no args, use the currently moused-over segment
4111			this.mousedOverSeg = null;
4112			if (this.view.isEventResizable(seg.event)) {
4113				seg.el.removeClass('fc-allow-mouse-resize');
4114			}
4115			this.view.trigger('eventMouseout', seg.el[0], seg.event, ev);
4116		}
4117	},
4118
4119
4120	handleSegMousedown: function(seg, ev) {
4121		var isResizing = this.startSegResize(seg, ev, { distance: 5 });
4122
4123		if (!isResizing && this.view.isEventDraggable(seg.event)) {
4124			this.buildSegDragListener(seg)
4125				.startInteraction(ev, {
4126					distance: 5
4127				});
4128		}
4129	},
4130
4131
4132	handleSegTouchStart: function(seg, ev) {
4133		var view = this.view;
4134		var event = seg.event;
4135		var isSelected = view.isEventSelected(event);
4136		var isDraggable = view.isEventDraggable(event);
4137		var isResizable = view.isEventResizable(event);
4138		var isResizing = false;
4139		var dragListener;
4140
4141		if (isSelected && isResizable) {
4142			// only allow resizing of the event is selected
4143			isResizing = this.startSegResize(seg, ev);
4144		}
4145
4146		if (!isResizing && (isDraggable || isResizable)) { // allowed to be selected?
4147
4148			dragListener = isDraggable ?
4149				this.buildSegDragListener(seg) :
4150				this.buildSegSelectListener(seg); // seg isn't draggable, but still needs to be selected
4151
4152			dragListener.startInteraction(ev, { // won't start if already started
4153				delay: isSelected ? 0 : this.view.opt('longPressDelay') // do delay if not already selected
4154			});
4155		}
4156
4157		// a long tap simulates a mouseover. ignore this bogus mouseover.
4158		this.tempIgnoreMouse();
4159	},
4160
4161
4162	handleSegTouchEnd: function(seg, ev) {
4163		// touchstart+touchend = click, which simulates a mouseover.
4164		// ignore this bogus mouseover.
4165		this.tempIgnoreMouse();
4166	},
4167
4168
4169	// returns boolean whether resizing actually started or not.
4170	// assumes the seg allows resizing.
4171	// `dragOptions` are optional.
4172	startSegResize: function(seg, ev, dragOptions) {
4173		if ($(ev.target).is('.fc-resizer')) {
4174			this.buildSegResizeListener(seg, $(ev.target).is('.fc-start-resizer'))
4175				.startInteraction(ev, dragOptions);
4176			return true;
4177		}
4178		return false;
4179	},
4180
4181
4182
4183	/* Event Dragging
4184	------------------------------------------------------------------------------------------------------------------*/
4185
4186
4187	// Builds a listener that will track user-dragging on an event segment.
4188	// Generic enough to work with any type of Grid.
4189	// Has side effect of setting/unsetting `segDragListener`
4190	buildSegDragListener: function(seg) {
4191		var _this = this;
4192		var view = this.view;
4193		var calendar = view.calendar;
4194		var el = seg.el;
4195		var event = seg.event;
4196		var isDragging;
4197		var mouseFollower; // A clone of the original element that will move with the mouse
4198		var dropLocation; // zoned event date properties
4199
4200		if (this.segDragListener) {
4201			return this.segDragListener;
4202		}
4203
4204		// Tracks mouse movement over the *view's* coordinate map. Allows dragging and dropping between subcomponents
4205		// of the view.
4206		var dragListener = this.segDragListener = new HitDragListener(view, {
4207			scroll: view.opt('dragScroll'),
4208			subjectEl: el,
4209			subjectCenter: true,
4210			interactionStart: function(ev) {
4211				seg.component = _this; // for renderDrag
4212				isDragging = false;
4213				mouseFollower = new MouseFollower(seg.el, {
4214					additionalClass: 'fc-dragging',
4215					parentEl: view.el,
4216					opacity: dragListener.isTouch ? null : view.opt('dragOpacity'),
4217					revertDuration: view.opt('dragRevertDuration'),
4218					zIndex: 2 // one above the .fc-view
4219				});
4220				mouseFollower.hide(); // don't show until we know this is a real drag
4221				mouseFollower.start(ev);
4222			},
4223			dragStart: function(ev) {
4224				if (dragListener.isTouch && !view.isEventSelected(event)) {
4225					// if not previously selected, will fire after a delay. then, select the event
4226					view.selectEvent(event);
4227				}
4228				isDragging = true;
4229				_this.handleSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
4230				_this.segDragStart(seg, ev);
4231				view.hideEvent(event);
4231 // hide all event segments. our mouseFollower will take over
4232			},
4233			hitOver: function(hit, isOrig, origHit) {
4234				var dragHelperEls;
4235
4236				// starting hit could be forced (DayGrid.limit)
4237				if (seg.hit) {
4238					origHit = seg.hit;
4239				}
4240
4241				// since we are querying the parent view, might not belong to this grid
4242				dropLocation = _this.computeEventDrop(
4243					origHit.component.getHitSpan(origHit),
4244					hit.component.getHitSpan(hit),
4245					event
4246				);
4247
4248				if (dropLocation && !calendar.isEventSpanAllowed(_this.eventToSpan(dropLocation), event)) {
4249					disableCursor();
4250					dropLocation = null;
4251				}
4252
4253				// if a valid drop location, have the subclass render a visual indication
4254				if (dropLocation && (dragHelperEls = view.renderDrag(dropLocation, seg))) {
4255
4256					dragHelperEls.addClass('fc-dragging');
4257					if (!dragListener.isTouch) {
4258						_this.applyDragOpacity(dragHelperEls);
4259					}
4260
4261					mouseFollower.hide(); // if the subclass is already using a mock event "helper", hide our own
4262				}
4263				else {
4264					mouseFollower.show(); // otherwise, have the helper follow the mouse (no snapping)
4265				}
4266
4267				if (isOrig) {
4268					dropLocation = null; // needs to have moved hits to be a valid drop
4269				}
4270			},
4271			hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
4272				view.unrenderDrag(); // unrender whatever was done in renderDrag
4273				mouseFollower.show(); // show in case we are moving out of all hits
4274				dropLocation = null;
4275			},
4276			hitDone: function() { // Called after a hitOut OR before a dragEnd
4277				enableCursor();
4278			},
4279			interactionEnd: function(ev) {
4280				delete seg.component; // prevent side effects
4281
4282				// do revert animation if hasn't changed. calls a callback when finished (whether animation or not)
4283				mouseFollower.stop(!dropLocation, function() {
4284					if (isDragging) {
4285						view.unrenderDrag();
4286						view.showEvent(event);
4287						_this.segDragStop(seg, ev);
4288					}
4289					if (dropLocation) {
4290						view.reportEventDrop(event, dropLocation, this.largeUnit, el, ev);
4291					}
4292				});
4293				_this.segDragListener = null;
4294			}
4295		});
4296
4297		return dragListener;
4298	},
4299
4300
4301	// seg isn't draggable, but let's use a generic DragListener
4302	// simply for the delay, so it can be selected.
4303	// Has side effect of setting/unsetting `segDragListener`
4304	buildSegSelectListener: function(seg) {
4305		var _this = this;
4306		var view = this.view;
4307		var event = seg.event;
4308
4309		if (this.segDragListener) {
4310			return this.segDragListener;
4311		}
4312
4313		var dragListener = this.segDragListener = new DragListener({
4314			dragStart: function(ev) {
4315				if (dragListener.isTouch && !view.isEventSelected(event)) {
4316					// if not previously selected, will fire after a delay. then, select the event
4317					view.selectEvent(event);
4318				}
4319			},
4320			interactionEnd: function(ev) {
4321				_this.segDragListener = null;
4322			}
4323		});
4324
4325		return dragListener;
4326	},
4327
4328
4329	// Called before event segment dragging starts
4330	segDragStart: function(seg, ev) {
4331		this.isDraggingSeg = true;
4332		this.view.trigger('eventDragStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
4333	},
4334
4335
4336	// Called after event segment dragging stops
4337	segDragStop: function(seg, ev) {
4338		this.isDraggingSeg = false;
4339		this.view.trigger('eventDragStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
4340	},
4341
4342
4343	// Given the spans an event drag began, and the span event was dropped, calculates the new zoned start/end/allDay
4344	// values for the event. Subclasses may override and set additional properties to be used by renderDrag.
4345	// A falsy returned value indicates an invalid drop.
4346	// DOES NOT consider overlap/constraint.
4347	computeEventDrop: function(startSpan, endSpan, event) {
4348		var calendar = this.view.calendar;
4349		var dragStart = startSpan.start;
4350		var dragEnd = endSpan.start;
4351		var delta;
4352		var dropLocation; // zoned event date properties
4353
4354		if (dragStart.hasTime() === dragEnd.hasTime()) {
4355			delta = this.diffDates(dragEnd, dragStart);
4356
4357			// if an all-day event was in a timed area and it was dragged to a different time,
4358			// guarantee an end and adjust start/end to have times
4359			if (event.allDay && durationHasTime(delta)) {
4360				dropLocation = {
4361					start: event.start.clone(),
4362					end: calendar.getEventEnd(event), // will be an ambig day
4363					allDay: false // for normalizeEventTimes
4364				};
4365				calendar.normalizeEventTimes(dropLocation);
4366			}
4367			// othewise, work off existing values
4368			else {
4369				dropLocation = pluckEventDateProps(event);
4370			}
4371
4372			dropLocation.start.add(delta);
4373			if (dropLocation.end) {
4374				dropLocation.end.add(delta);
4375			}
4376		}
4377		else {
4378			// if switching from day <-> timed, start should be reset to the dropped date, and the end cleared
4379			dropLocation = {
4380				start: dragEnd.clone(),
4381				end: null, // end should be cleared
4382				allDay: !dragEnd.hasTime()
4383			};
4384		}
4385
4386		return dropLocation;
4387	},
4388
4389
4390	// Utility for apply dragOpacity to a jQuery set
4391	applyDragOpacity: function(els) {
4392		var opacity = this.view.opt('dragOpacity');
4393
4394		if (opacity != null) {
4395			els.css('opacity', opacity);
4396		}
4397	},
4398
4399
4400	/* External Element Dragging
4401	------------------------------------------------------------------------------------------------------------------*/
4402
4403
4404	// Called when a jQuery UI drag is initiated anywhere in the DOM
4405	externalDragStart: function(ev, ui) {
4406		var view = this.view;
4407		var el;
4408		var accept;
4409
4410		if (view.opt('droppable')) { // only listen if this setting is on
4411			el = $((ui ? ui.item : null) || ev.target);
4412
4413			// Test that the dragged element passes the dropAccept selector or filter function.
4414			// FYI, the default is "*" (matches all)
4415			accept = view.opt('dropAccept');
4416			if ($.isFunction(accept) ? accept.call(el[0], el) : el.is(accept)) {
4417				if (!this.isDraggingExternal) { // prevent double-listening if fired twice
4418					this.listenToExternalDrag(el, ev, ui);
4419				}
4420			}
4421		}
4422	},
4423
4424
4425	// Called when a jQuery UI drag starts and it needs to be monitored for dropping
4426	listenToExternalDrag: function(el, ev, ui) {
4427		var _this = this;
4428		var calendar = this.view.calendar;
4429		var meta = getDraggedElMeta(el); // extra data about event drop, including possible event to create
4430		var dropLocation; // a null value signals an unsuccessful drag
4431
4432		// listener that tracks mouse movement over date-associated pixel regions
4433		var dragListener = _this.externalDragListener = new HitDragListener(this, {
4434			interactionStart: function() {
4435				_this.isDraggingExternal = true;
4436			},
4437			hitOver: function(hit) {
4438				dropLocation = _this.computeExternalDrop(
4439					hit.component.getHitSpan(hit), // since we are querying the parent view, might not belong to this grid
4440					meta
4441				);
4442
4443				if ( // invalid hit?
4444					dropLocation &&
4445					!calendar.isExternalSpanAllowed(_this.eventToSpan(dropLocation), dropLocation, meta.eventProps)
4446				) {
4447					disableCursor();
4448					dropLocation = null;
4449				}
4450
4451				if (dropLocation) {
4452					_this.renderDrag(dropLocation); // called without a seg parameter
4453				}
4454			},
4455			hitOut: function() {
4456				dropLocation = null; // signal unsuccessful
4457			},
4458			hitDone: function() { // Called after a hitOut OR before a dragEnd
4459				enableCursor();
4460				_this.unrenderDrag();
4461			},
4462			interactionEnd: function(ev) {
4463				if (dropLocation) { // element was dropped on a valid hit
4464					_this.view.reportExternalDrop(meta, dropLocation, el, ev, ui);
4465				}
4466				_this.isDraggingExternal = false;
4467				_this.externalDragListener = null;
4468			}
4469		});
4470
4471		dragListener.startDrag(ev); // start listening immediately
4472	},
4473
4474
4475	// Given a hit to be dropped upon, and misc data associated with the jqui drag (guaranteed to be a plain object),
4476	// returns the zoned start/end dates for the event that would result from the hypothetical drop. end might be null.
4477	// Returning a null value signals an invalid drop hit.
4478	// DOES NOT consider overlap/constraint.
4479	computeExternalDrop: function(span, meta) {
4480		var calendar = this.view.calendar;
4481		var dropLocation = {
4482			start: calendar.applyTimezone(span.start), // simulate a zoned event start date
4483			end: null
4484		};
4485
4486		// if dropped on an all-day span, and element's metadata specified a time, set it
4487		if (meta.startTime && !dropLocation.start.hasTime()) {
4488			dropLocation.start.time(meta.startTime);
4489		}
4490
4491		if (meta.duration) {
4492			dropLocation.end = dropLocation.start.clone().add(meta.duration);
4493		}
4494
4495		return dropLocation;
4496	},
4497
4498
4499
4500	/* Drag Rendering (for both events and an external elements)
4501	------------------------------------------------------------------------------------------------------------------*/
4502
4503
4504	// Renders a visual indication of an event or external element being dragged.
4505	// `dropLocation` contains hypothetical start/end/allDay values the event would have if dropped. end can be null.
4506	// `seg` is the internal segment object that is being dragged. If dragging an external element, `seg` is null.
4507	// A truthy returned value indicates this method has rendered a helper element.
4508	// Must return elements used for any mock events.
4509	renderDrag: function(dropLocation, seg) {
4510		// subclasses must implement
4511	},
4512
4513
4514	// Unrenders a visual indication of an event or external element being dragged
4515	unrenderDrag: function() {
4516		// subclasses must implement
4517	},
4518
4519
4520	/* Resizing
4521	------------------------------------------------------------------------------------------------------------------*/
4522
4523
4524	// Creates a listener that tracks the user as they resize an event segment.
4525	// Generic enough to work with any type of Grid.
4526	buildSegResizeListener: function(seg, isStart) {
4527		var _this = this;
4528		var view = this.view;
4529		var calendar = view.calendar;
4530		var el = seg.el;
4531		var event = seg.event;
4532		var eventEnd = calendar.getEventEnd(event);
4533		var isDragging;
4534		var resizeLocation; // zoned event date properties. falsy if invalid resize
4535
4536		// Tracks mouse movement over the *grid's* coordinate map
4537		var dragListener = this.segResizeListener = new HitDragListener(this, {
4538			scroll: view.opt('dragScroll'),
4539			subjectEl: el,
4540			interactionStart: function() {
4541				isDragging = false;
4542			},
4543			dragStart: function(ev) {
4544				isDragging = true;
4545				_this.handleSegMouseout(seg, ev); // ensure a mouseout on the manipulated event has been reported
4546				_this.segResizeStart(seg, ev);
4547			},
4548			hitOver: function(hit, isOrig, origHit) {
4549				var origHitSpan = _this.getHitSpan(origHit);
4550				var hitSpan = _this.getHitSpan(hit);
4551
4552				resizeLocation = isStart ?
4553					_this.computeEventStartResize(origHitSpan, hitSpan, event) :
4554					_this.computeEventEndResize(origHitSpan, hitSpan, event);
4555
4556				if (resizeLocation) {
4557					if (!calendar.isEventSpanAllowed(_this.eventToSpan(resizeLocation), event)) {
4558						disableCursor();
4559						resizeLocation = null;
4560					}
4561					// no change? (FYI, event dates might have zones)
4562					else if (
4563						resizeLocation.start.isSame(event.start.clone().stripZone()) &&
4564						resizeLocation.end.isSame(eventEnd.clone().stripZone())
4565					) {
4566						resizeLocation = null;
4567					}
4568				}
4569
4570				if (resizeLocation) {
4571					view.hideEvent(event);
4572					_this.renderEventResize(resizeLocation, seg);
4573				}
4574			},
4575			hitOut: function() { // called before mouse moves to a different hit OR moved out of all hits
4576				resizeLocation = null;
4577			},
4578			hitDone: function() { // resets the rendering to show the original event
4579				_this.unrenderEventResize();
4580				view.showEvent(event);
4581				enableCursor();
4582			},
4583			interactionEnd: function(ev) {
4584				if (isDragging) {
4585					_this.segResizeStop(seg, ev);
4586				}
4587				if (resizeLocation) { // valid date to resize to?
4588					view.reportEventResize(event, resizeLocation, this.largeUnit, el, ev);
4589				}
4590				_this.segResizeListener = null;
4591			}
4592		});
4593
4594		return dragListener;
4595	},
4596
4597
4598	// Called before event segment resizing starts
4599	segResizeStart: function(seg, ev) {
4600		this.isResizingSeg = true;
4601		this.view.trigger('eventResizeStart', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
4602	},
4603
4604
4605	// Called after event segment resizing stops
4606	segResizeStop: function(seg, ev) {
4607		this.isResizingSeg = false;
4608		this.view.trigger('eventResizeStop', seg.el[0], seg.event, ev, {}); // last argument is jqui dummy
4609	},
4610
4611
4612	// Returns new date-information for an event segment being resized from its start
4613	computeEventStartResize: function(startSpan, endSpan, event) {
4614		return this.computeEventResize('start', startSpan, endSpan, event);
4615	},
4616
4617
4618	// Returns new date-information for an event segment being resized from its end
4619	computeEventEndResize: function(startSpan, endSpan, event) {
4620		return this.computeEventResize('end', startSpan, endSpan, event);
4621	},
4622
4623
4624	// Returns new zoned date information for an event segment being resized from its start OR end
4625	// `type` is either 'start' or 'end'.
4626	// DOES NOT consider overlap/constraint.
4627	computeEventResize: function(type, startSpan, endSpan, event) {
4628		var calendar = this.view.calendar;
4629		var delta = this.diffDates(endSpan[type], startSpan[type]);
4630		var resizeLocation; // zoned event date properties
4631		var defaultDuration;
4632
4633		// build original values to work from, guaranteeing a start and end
4634		resizeLocation = {
4635			start: event.start.clone(),
4636			end: calendar.getEventEnd(event),
4637			allDay: event.allDay
4638		};
4639
4640		// if an all-day event was in a timed area and was resized to a time, adjust start/end to have times
4641		if (resizeLocation.allDay && durationHasTime(delta)) {
4642			resizeLocation.allDay = false;
4643			calendar.normalizeEventTimes(resizeLocation);
4644		}
4645
4646		resizeLocation[type].add(delta); // apply delta to start or end
4647
4648		// if the event was compressed too small, find a new reasonable duration for it
4649		if (!resizeLocation.start.isBefore(resizeLocation.end)) {
4650
4651			defaultDuration =
4652				this.minResizeDuration || // TODO: hack
4653				(event.allDay ?
4654					calendar.defaultAllDayEventDuration :
4655					calendar.defaultTimedEventDuration);
4656
4657			if (type == 'start') { // resizing the start?
4658				resizeLocation.start = resizeLocation.end.clone().subtract(defaultDuration);
4659			}
4660			else { // resizing the end?
4661				resizeLocation.end = resizeLocation.start.clone().add(defaultDuration);
4662			}
4663		}
4664
4665		return resizeLocation;
4666	},
4667
4668
4669	// Renders a visual indication of an event being resized.
4670	// `range` has the updated dates of the event. `seg` is the original segment object involved in the drag.
4671	// Must return elements used for any mock events.
4672	renderEventResize: function(range, seg) {
4673		// subclasses must implement
4674	},
4675
4676
4677	// Unrenders a visual indication of an event being resized.
4678	unrenderEventResize: function() {
4679		// subclasses must implement
4680	},
4681
4682
4683	/* Rendering Utils
4684	------------------------------------------------------------------------------------------------------------------*/
4685
4686
4687	// Compute the text that should be displayed on an event's element.
4688	// `range` can be the Event object itself, or something range-like, with at least a `start`.
4689	// If event times are disabled, or the event has no time, will return a blank string.
4690	// If not specified, formatStr will default to the eventTimeFormat setting,
4691	// and displayEnd will default to the displayEventEnd setting.
4692	getEventTimeText: function(range, formatStr, displayEnd) {
4693
4694		if (formatStr == null) {
4695			formatStr = this.eventTimeFormat;
4696		}
4697
4698		if (displayEnd == null) {
4699			displayEnd = this.displayEventEnd;
4700		}
4701
4702		if (this.displayEventTime && range.start.hasTime()) {
4703			if (displayEnd && range.end) {
4704				return this.view.formatRange(range, formatStr);
4705			}
4706			else {
4707				return range.start.format(formatStr);
4708			}
4709		}
4710
4711		return '';
4712	},
4713
4714
4715	// Generic utility for generating the HTML classNames for an event segment's element
4716	getSegClasses: function(seg, isDraggable, isResizable) {
4717		var view = this.view;
4718		var classes = [
4719			'fc-event',
4720			seg.isStart ? 'fc-start' : 'fc-not-start',
4721			seg.isEnd ? 'fc-end' : 'fc-not-end'
4722		].concat(this.getSegCustomClasses(seg));
4723
4724		if (isDraggable) {
4725			classes.push('fc-draggable');
4726		}
4727		if (isResizable) {
4728			classes.push('fc-resizable');
4729		}
4730
4731		// event is currently selected? attach a className.
4732		if (view.isEventSelected(seg.event)) {
4733			classes.push('fc-selected');
4734		}
4735
4736		return classes;
4737	},
4738
4739
4740	// List of classes that were defined by the caller of the API in some way
4741	getSegCustomClasses: function(seg) {
4742		var event = seg.event;
4743
4744		return [].concat(
4745			event.className, // guaranteed to be an array
4746			event.source ? event.source.className : []
4747		);
4748	},
4749
4750
4751	// Utility for generating event skin-related CSS properties
4752	getSegSkinCss: function(seg) {
4753		return {
4754			'background-color': this.getSegBackgroundColor(seg),
4755			'border-color': this.getSegBorderColor(seg),
4756			color: this.getSegTextColor(seg)
4757		};
4758	},
4759
4760
4761	// Queries for caller-specified color, then falls back to default
4762	getSegBackgroundColor: function(seg) {
4763		return seg.event.backgroundColor ||
4764			seg.event.color ||
4765			this.getSegDefaultBackgroundColor(seg);
4766	},
4767
4768
4769	getSegDefaultBackgroundColor: function(seg) {
4770		var source = seg.event.source || {};
4771
4772		return source.backgroundColor ||
4773			source.color ||
4774			this.view.opt('eventBackgroundColor') ||
4775			this.view.opt('eventColor');
4776	},
4777
4778
4779	// Queries for caller-specified color, then falls back to default
4780	getSegBorderColor: function(seg) {
4781		return seg.event.borderColor ||
4782			seg.event.color ||
4783			this.getSegDefaultBorderColor(seg);
4784	},
4785
4786
4787	getSegDefaultBorderColor: function(seg) {
4788		var source = seg.event.source || {};
4789
4790		return source.borderColor ||
4791			source.color ||
4792			this.view.opt('eventBorderColor') ||
4793			this.view.opt('eventColor');
4794	},
4795
4796
4797	// Queries for caller-specified color, then falls back to default
4798	getSegTextColor: function(seg) {
4799		return seg.event.textColor ||
4800			this.getSegDefaultTextColor(seg);
4801	},
4802
4803
4804	getSegDefaultTextColor: function(seg) {
4805		var source = seg.event.source || {};
4806
4807		return source.textColor ||
4808			this.view.opt('eventTextColor');
4809	},
4810
4811
4812	/* Converting events -> eventRange -> eventSpan -> eventSegs
4813	------------------------------------------------------------------------------------------------------------------*/
4814
4815
4816	// Generates an array of segments for the given single event
4817	// Can accept an event "location" as well (which only has start/end and no allDay)
4818	eventToSegs: function(event) {
4819		return this.eventsToSegs([ event ]);
4820	},
4821
4822
4823	eventToSpan: function(event) {
4824		return this.eventToSpans(event)[0];
4825	},
4826
4827
4828	// Generates spans (always unzoned) for the given event.
4829	// Does not do any inverting for inverse-background events.
4830	// Can accept an event "location" as well (which only has start/end and no allDay)
4831	eventToSpans: function(event) {
4832		var range = this.eventToRange(event);
4833		return this.eventRangeToSpans(range, event);
4834	},
4835
4836
4837
4838	// Converts an array of event objects into an array of event segment objects.
4839	// A custom `segSliceFunc` may be given for arbitrarily slicing up events.
4840	// Doesn't guarantee an order for the resulting array.
4841	eventsToSegs: function(allEvents, segSliceFunc) {
4842		var _this = this;
4843		var eventsById = groupEventsById(allEvents);
4844		var segs = [];
4845
4846		$.each(eventsById, function(id, events) {
4847			var ranges = [];
4848			var i;
4849
4850			for (i = 0; i < events.length; i++) {
4851				ranges.push(_this.eventToRange(events[i]));
4852			}
4853
4854			// inverse-background events (utilize only the first event in calculations)
4855			if (isInverseBgEvent(events[0])) {
4856				ranges = _this.invertRanges(ranges);
4857
4858				for (i = 0; i < ranges.length; i++) {
4859					segs.push.apply(segs, // append to
4860						_this.eventRangeToSegs(ranges[i], events[0], segSliceFunc));
4861				}
4862			}
4863			// normal event ranges
4864			else {
4865				for (i = 0; i < ranges.length; i++) {
4866					segs.push.apply(segs, // append to
4867						_this.eventRangeToSegs(ranges[i], events[i], segSliceFunc));
4868				}
4869			}
4870		});
4871
4872		return segs;
4873	},
4874
4875
4876	// Generates the unzoned start/end dates an event appears to occupy
4877	// Can accept an event "location" as well (which only has start/end and no allDay)
4878	eventToRange: function(event) {
4879		var calendar = this.view.calendar;
4880		var start = event.start.clone().stripZone();
4881		var end = (
4882				event.end ?
4883					event.end.clone() :
4884					// derive the end from the start and allDay. compute allDay if necessary
4885					calendar.getDefaultEventEnd(
4886						event.allDay != null ?
4887							event.allDay :
4888							!event.start.hasTime(),
4889						event.start
4890					)
4891			).stripZone();
4892
4893		// hack: dynamic locale change forgets to upate stored event localed
4894		calendar.localizeMoment(start);
4895		calendar.localizeMoment(end);
4896
4897		return { start: start, end: end };
4898	},
4899
4900
4901	// Given an event's range (unzoned start/end), and the event itself,
4902	// slice into segments (using the segSliceFunc function if specified)
4903	eventRangeToSegs: function(range, event, segSliceFunc) {
4904		var spans = this.eventRangeToSpans(range, event);
4905		var segs = [];
4906		var i;
4907
4908		for (i = 0; i < spans.length; i++) {
4909			segs.push.apply(segs, // append to
4910				this.eventSpanToSegs(spans[i], event, segSliceFunc));
4911		}
4912
4913		return segs;
4914	},
4915
4916
4917	// Given an event's unzoned date range, return an array of "span" objects.
4918	// Subclasses can override.
4919	eventRangeToSpans: function(range, event) {
4920		return [ $.extend({}, range) ]; // copy into a single-item array
4921	},
4922
4923
4924	// Given an event's span (unzoned start/end and other misc data), and the event itself,
4925	// slices into segments and attaches event-derived properties to them.
4926	eventSpanToSegs: function(span, event, segSliceFunc) {
4927		var segs = segSliceFunc ? segSliceFunc(span) : this.spanToSegs(span);
4928		var i, seg;
4929
4930		for (i = 0; i < segs.length; i++) {
4931			seg = segs[i];
4932			seg.event = event;
4933			seg.eventStartMS = +span.start; // TODO: not the best name after making spans unzoned
4934			seg.eventDurationMS = span.end - span.start;
4935		}
4936
4937		return segs;
4938	},
4939
4940
4941	// Produces a new array of range objects that will cover all the time NOT covered by the given ranges.
4942	// SIDE EFFECT: will mutate the given array and will use its date references.
4943	invertRanges: function(ranges) {
4944		var view = this.view;
4945		var viewStart = view.start.clone(); // need a copy
4946		var viewEnd = view.end.clone(); // need a copy
4947		var inverseRanges = [];
4948		var start = viewStart; // the end of the previous range. the start of the new range
4949		var i, range;
4950
4951		// ranges need to be in order. required for our date-walking algorithm
4952		ranges.sort(compareRanges);
4953
4954		for (i = 0; i < ranges.length; i++) {
4955			range = ranges[i];
4956
4957			// add the span of time before the event (if there is any)
4958			if (range.start > start) { // compare millisecond time (skip any ambig logic)
4959				inverseRanges.push({
4960					start: start,
4961					end: range.start
4962				});
4963			}
4964
4965			start = range.end;
4966		}
4967
4968		// add the span of time after the last event (if there is any)
4969		if (start < viewEnd) { // compare millisecond time (skip any ambig logic)
4970			inverseRanges.push({
4971				start: start,
4972				end: viewEnd
4973			});
4974		}
4975
4976		return inverseRanges;
4977	},
4978
4979
4980	sortEventSegs: function(segs) {
4981		segs.sort(proxy(this, 'compareEventSegs'));
4982	},
4983
4984
4985	// A cmp function for determining which segments should take visual priority
4986	compareEventSegs: function(seg1, seg2) {
4987		return seg1.eventStartMS - seg2.eventStartMS || // earlier events go first
4988			seg2.eventDurationMS - seg1.eventDurationMS || // tie? longer events go first
4989			seg2.event.allDay - seg1.event.allDay || // tie? put all-day events first (booleans cast to 0/1)
4990			compareByFieldSpecs(seg1.event, seg2.event, this.view.eventOrderSpecs);
4991	}
4992
4993});
4994
4995
4996/* Utilities
4997----------------------------------------------------------------------------------------------------------------------*/
4998
4999
5000function pluckEventDateProps(event) {
5001	return {
5002		start: event.start.clone(),
5003		end: event.end ? event.end.clone() : null,
5004		allDay: event.allDay // keep it the same
5005	};
5006}
5007FC.pluckEventDateProps = pluckEventDateProps;
5008
5009
5010function isBgEvent(event) { // returns true if background OR inverse-background
5011	var rendering = getEventRendering(event);
5012	return rendering === 'background' || rendering === 'inverse-background';
5013}
5014FC.isBgEvent = isBgEvent; // export
5015
5016
5017function isInverseBgEvent(event) {
5018	return getEventRendering(event) === 'inverse-background';
5019}
5020
5021
5022function getEventRendering(event) {
5023	return firstDefined((event.source || {}).rendering, event.rendering);
5024}
5025
5026
5027function groupEventsById(events) {
5028	var eventsById = {};
5029	var i, event;
5030
5031	for (i = 0; i < events.length; i++) {
5032		event = events[i];
5033		(eventsById[event._id] || (eventsById[event._id] = [])).push(event);
5034	}
5035
5036	return eventsById;
5037}
5038
5039
5040// A cmp function for determining which non-inverted "ranges" (see above) happen earlier
5041function compareRanges(range1, range2) {
5042	return range1.start - range2.start; // earlier ranges go first
5043}
5044
5045
5046/* External-Dragging-Element Data
5047----------------------------------------------------------------------------------------------------------------------*/
5048
5049// Require all HTML5 data-* attributes used by FullCalendar to have this prefix.
5050// A value of '' will query attributes like data-event. A value of 'fc' will query attributes like data-fc-event.
5051FC.dataAttrPrefix = '';
5052
5053// Given a jQuery element that might represent a dragged FullCalendar event, returns an intermediate data structure
5054// to be used for Event Object creation.
5055// A defined `.eventProps`, even when empty, indicates that an event should be created.
5056function getDraggedElMeta(el) {
5057	var prefix = FC.dataAttrPrefix;
5058	var eventProps; // properties for creating the event, not related to date/time
5059	var startTime; // a Duration
5060	var duration;
5061	var stick;
5062
5063	if (prefix) { prefix += '-'; }
5064	eventProps = el.data(prefix + 'event') || null;
5065
5066	if (eventProps) {
5067		if (typeof eventProps === 'object') {
5068			eventProps = $.extend({}, eventProps); // make a copy
5069		}
5070		else { // something like 1 or true. still signal event creation
5071			eventProps = {};
5072		}
5073
5074		// pluck special-cased date/time properties
5075		startTime = eventProps.start;
5076		if (startTime == null) { startTime = eventProps.time; } // accept 'time' as well
5077		duration = eventProps.duration;
5078		stick = eventProps.stick;
5079		delete eventProps.start;
5080		delete eventProps.time;
5081		delete eventProps.duration;
5082		delete eventProps.stick;
5083	}
5084
5085	// fallback to standalone attribute values for each of the date/time properties
5086	if (startTime == null) { startTime = el.data(prefix + 'start'); }
5087	if (startTime == null) { startTime = el.data(prefix + 'time'); } // accept 'time' as well
5088	if (duration == null) { duration = el.data(prefix + 'duration'); }
5089	if (stick == null) { stick = el.data(prefix + 'stick'); }
5090
5091	// massage into correct data types
5092	startTime = startTime != null ? moment.duration(startTime) : null;
5093	duration = duration != null ? moment.duration(duration) : null;
5094	stick = Boolean(stick);
5095
5096	return { eventProps: eventProps, startTime: startTime, duration: duration, stick: stick };
5097}
5098
5099
5100;;
5101
5102/*
5103A set of rendering and date-related methods for a visual component comprised of one or more rows of day columns.
5104Prerequisite: the object being mixed into needs to be a *Grid*
5105*/
5106var DayTableMixin = FC.DayTableMixin = {
5107
5108	breakOnWeeks: false, // should create a new row for each week?
5109	dayDates: null, // whole-day dates for each column. left to right
5110	dayIndices: null, // for each day from start, the offset
5111	daysPerRow: null,
5112	rowCnt: null,
5113	colCnt: null,
5114	colHeadFormat: null,
5115
5116
5117	// Populates internal variables used for date calculation and rendering
5118	updateDayTable: function() {
5119		var view = this.view;
5120		var date = this.start.clone();
5121		var dayIndex = -1;
5122		var dayIndices = [];
5123		var dayDates = [];
5124		var daysPerRow;
5125		var firstDay;
5126		var rowCnt;
5127
5128		while (date.isBefore(this.end)) { // loop each day from start to end
5129			if (view.isHiddenDay(date)) {
5130				dayIndices.push(dayIndex + 0.5); // mark that it's between indices
5131			}
5132			else {
5133				dayIndex++;
5134				dayIndices.push(dayIndex);
5135				dayDates.push(date.clone());
5136			}
5137			date.add(1, 'days');
5138		}
5139
5140		if (this.breakOnWeeks) {
5141			// count columns until the day-of-week repeats
5142			firstDay = dayDates[0].day();
5143			for (daysPerRow = 1; daysPerRow < dayDates.length; daysPerRow++) {
5144				if (dayDates[daysPerRow].day() == firstDay) {
5145					break;
5146				}
5147			}
5148			rowCnt = Math.ceil(dayDates.length / daysPerRow);
5149		}
5150		else {
5151			rowCnt = 1;
5152			daysPerRow = dayDates.length;
5153		}
5154
5155		this.dayDates = dayDates;
5156		this.dayIndices = dayIndices;
5157		this.daysPerRow = daysPerRow;
5158		this.rowCnt = rowCnt;
5159		
5160		this.updateDayTableCols();
5161	},
5162
5163
5164	// Computes and assigned the colCnt property and updates any options that may be computed from it
5165	updateDayTableCols: function() {
5166		this.colCnt = this.computeColCnt();
5167		this.colHeadFormat = this.view.opt('columnFormat') || this.computeColHeadFormat();
5168	},
5169
5170
5171	// Determines how many columns there should be in the table
5172	computeColCnt: function() {
5173		return this.daysPerRow;
5174	},
5175
5176
5177	// Computes the ambiguously-timed moment for the given cell
5178	getCellDate: function(row, col) {
5179		return this.dayDates[
5180				this.getCellDayIndex(row, col)
5181			].clone();
5182	},
5183
5184
5185	// Computes the ambiguously-timed date range for the given cell
5186	getCellRange: function(row, col) {
5187		var start = this.getCellDate(row, col);
5188		var end = start.clone().add(1, 'days');
5189
5190		return { start: start, end: end };
5191	},
5192
5193
5194	// Returns the number of day cells, chronologically, from the first of the grid (0-based)
5195	getCellDayIndex: function(row, col) {
5196		return row * this.daysPerRow + this.getColDayIndex(col);
5197	},
5198
5199
5200	// Returns the numner of day cells, chronologically, from the first cell in *any given row*
5201	getColDayIndex: function(col) {
5202		if (this.isRTL) {
5203			return this.colCnt - 1 - col;
5204		}
5205		else {
5206			return col;
5207		}
5208	},
5209
5210
5211	// Given a date, returns its chronolocial cell-index from the first cell of the grid.
5212	// If the date lies between cells (because of hiddenDays), returns a floating-point value between offsets.
5213	// If before the first offset, returns a negative number.
5214	// If after the last offset, returns an offset past the last cell offset.
5215	// Only works for *start* dates of cells. Will not work for exclusive end dates for cells.
5216	getDateDayIndex: function(date) {
5217		var dayIndices = this.dayIndices;
5218		var dayOffset = date.diff(this.start, 'days');
5219
5220		if (dayOffset < 0) {
5221			return dayIndices[0] - 1;
5222		}
5223		else if (dayOffset >= dayIndices.length) {
5224			return dayIndices[dayIndices.length - 1] + 1;
5225		}
5226		else {
5227			return dayIndices[dayOffset];
5228		}
5229	},
5230
5231
5232	/* Options
5233	------------------------------------------------------------------------------------------------------------------*/
5234
5235
5236	// Computes a default column header formatting string if `colFormat` is not explicitly defined
5237	computeColHeadFormat: function() {
5238		// if more than one week row, or if there are a lot of columns with not much space,
5239		// put just the day numbers will be in each cell
5240		if (this.rowCnt > 1 || this.colCnt > 10) {
5241			return 'ddd'; // "Sat"
5242		}
5243		// multiple days, so full single date string WON'T be in title text
5244		else if (this.colCnt > 1) {
5245			return this.view.opt('dayOfMonthFormat'); // "Sat 12/10"
5246		}
5247		// single day, so full single date string will probably be in title text
5248		else {
5249			return 'dddd'; // "Saturday"
5250		}
5251	},
5252
5253
5254	/* Slicing
5255	------------------------------------------------------------------------------------------------------------------*/
5256
5257
5258	// Slices up a date range into a segment for every week-row it intersects with
5259	sliceRangeByRow: function(range) {
5260		var daysPerRow = this.daysPerRow;
5261		var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
5262		var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
5263		var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
5264		var segs = [];
5265		var row;
5266		var rowFirst, rowLast; // inclusive day-index range for current row
5267		var segFirst, segLast; // inclusive day-index range for segment
5268
5269		for (row = 0; row < this.rowCnt; row++) {
5270			rowFirst = row * daysPerRow;
5271			rowLast = rowFirst + daysPerRow - 1;
5272
5273			// intersect segment's offset range with the row's
5274			segFirst = Math.max(rangeFirst, rowFirst);
5275			segLast = Math.min(rangeLast, rowLast);
5276
5277			// deal with in-between indices
5278			segFirst = Math.ceil(segFirst); // in-between starts round to next cell
5279			segLast = Math.floor(segLast); // in-between ends round to prev cell
5280
5281			if (segFirst <= segLast) { // was there any intersection with the current row?
5282				segs.push({
5283					row: row,
5284
5285					// normalize to start of row
5286					firstRowDayIndex: segFirst - rowFirst,
5287					lastRowDayIndex: segLast - rowFirst,
5288
5289					// must be matching integers to be the segment's start/end
5290					isStart: segFirst === rangeFirst,
5291					isEnd: segLast === rangeLast
5292				});
5293			}
5294		}
5295
5296		return segs;
5297	},
5298
5299
5300	// Slices up a date range into a segment for every day-cell it intersects with.
5301	// TODO: make more DRY with sliceRangeByRow somehow.
5302	sliceRangeByDay: function(range) {
5303		var daysPerRow = this.daysPerRow;
5304		var normalRange = this.view.computeDayRange(range); // make whole-day range, considering nextDayThreshold
5305		var rangeFirst = this.getDateDayIndex(normalRange.start); // inclusive first index
5306		var rangeLast = this.getDateDayIndex(normalRange.end.clone().subtract(1, 'days')); // inclusive last index
5307		var segs = [];
5308		var row;
5309		var rowFirst, rowLast; // inclusive day-index range for current row
5310		var i;
5311		var segFirst, segLast; // inclusive day-index range for segment
5312
5313		for (row = 0; row < this.rowCnt; row++) {
5314			rowFirst = row * daysPerRow;
5315			rowLast = rowFirst + daysPerRow - 1;
5316
5317			for (i = rowFirst; i <= rowLast; i++) {
5318
5319				// intersect segment's offset range with the row's
5320				segFirst = Math.max(rangeFirst, i);
5321				segLast = Math.min(rangeLast, i);
5322
5323				// deal with in-between indices
5324				segFirst = Math.ceil(segFirst); // in-between starts round to next cell
5325				segLast = Math.floor(segLast); // in-between ends round to prev cell
5326
5327				if (segFirst <= segLast) { // was there any intersection with the current row?
5328					segs.push({
5329						row: row,
5330
5331						// normalize to start of row
5332						firstRowDayIndex: segFirst - rowFirst,
5333						lastRowDayIndex: segLast - rowFirst,
5334
5335						// must be matching integers to be the segment's start/end
5336						isStart: segFirst === rangeFirst,
5337						isEnd: segLast === rangeLast
5338					});
5339				}
5340			}
5341		}
5342
5343		return segs;
5344	},
5345
5346
5347	/* Header Rendering
5348	------------------------------------------------------------------------------------------------------------------*/
5349
5350
5351	renderHeadHtml: function() {
5352		var view = this.view;
5353
5354		return '' +
5355			'<div class="fc-row ' + view.widgetHeaderClass + '">' +
5356				'<table>' +
5357					'<thead>' +
5358						this.renderHeadTrHtml() +
5359					'</thead>' +
5360				'</table>' +
5361			'</div>';
5362	},
5363
5364
5365	renderHeadIntroHtml: function() {
5366		return this.renderIntroHtml(); // fall back to generic
5367	},
5368
5369
5370	renderHeadTrHtml: function() {
5371		return '' +
5372			'<tr>' +
5373				(this.isRTL ? '' : this.renderHeadIntroHtml()) +
5374				this.renderHeadDateCellsHtml() +
5375				(this.isRTL ? this.renderHeadIntroHtml() : '') +
5376			'</tr>';
5377	},
5378
5379
5380	renderHeadDateCellsHtml: function() {
5381		var htmls = [];
5382		var col, date;
5383
5384		for (col = 0; col < this.colCnt; col++) {
5385			date = this.getCellDate(0, col);
5386			htmls.push(this.renderHeadDateCellHtml(date));
5387		}
5388
5389		return htmls.join('');
5390	},
5391
5392
5393	// TODO: when internalApiVersion, accept an object for HTML attributes
5394	// (colspan should be no different)
5395	renderHeadDateCellHtml: function(date, colspan, otherAttrs) {
5396		var view = this.view;
5397
5398		return '' +
5399			'<th class="fc-day-header ' + view.widgetHeaderClass + ' fc-' + dayIDs[date.day()] + '"' +
5400				(this.rowCnt === 1 ?
5401					' data-date="' + date.format('YYYY-MM-DD') + '"' :
5402					'') +
5403				(colspan > 1 ?
5404					' colspan="' + colspan + '"' :
5405					'') +
5406				(otherAttrs ?
5407					' ' + otherAttrs :
5408					'') +
5409				'>' +
5410				// don't make a link if the heading could represent multiple days, or if there's only one day (forceOff)
5411				view.buildGotoAnchorHtml(
5412					{ date: date, forceOff: this.rowCnt > 1 || this.colCnt === 1 },
5413					htmlEscape(date.format(this.colHeadFormat)) // inner HTML
5414				) +
5415			'</th>';
5416	},
5417
5418
5419	/* Background Rendering
5420	------------------------------------------------------------------------------------------------------------------*/
5421
5422
5423	renderBgTrHtml: function(row) {
5424		return '' +
5425			'<tr>' +
5426				(this.isRTL ? '' : this.renderBgIntroHtml(row)) +
5427				this.renderBgCellsHtml(row) +
5428				(this.isRTL ? this.renderBgIntroHtml(row) : '') +
5429			'</tr>';
5430	},
5431
5432
5433	renderBgIntroHtml: function(row) {
5434		return this.renderIntroHtml(); // fall back to generic
5435	},
5436
5437
5438	renderBgCellsHtml: function(row) {
5439		var htmls = [];
5440		var col, date;
5441
5442		for (col = 0; col < this.colCnt; col++) {
5443			date = this.getCellDate(row, col);
5444			htmls.push(this.renderBgCellHtml(date));
5445		}
5446
5447		return htmls.join('');
5448	},
5449
5450
5451	renderBgCellHtml: function(date, otherAttrs) {
5452		var view = this.view;
5453		var classes = this.getDayClasses(date);
5454
5455		classes.unshift('fc-day', view.widgetContentClass);
5456
5457		return '<td class="' + classes.join(' ') + '"' +
5458			' data-date="' + date.format('YYYY-MM-DD') + '"' + // if date has a time, won't format it
5459			(otherAttrs ?
5460				' ' + otherAttrs :
5461				'') +
5462			'></td>';
5463	},
5464
5465
5466	/* Generic
5467	------------------------------------------------------------------------------------------------------------------*/
5468
5469
5470	// Generates the default HTML intro for any row. User classes should override
5471	renderIntroHtml: function() {
5472	},
5473
5474
5475	// TODO: a generic method for dealing with <tr>, RTL, intro
5476	// when increment internalApiVersion
5477	// wrapTr (scheduler)
5478
5479
5480	/* Utils
5481	------------------------------------------------------------------------------------------------------------------*/
5482
5483
5484	// Applies the generic "intro" and "outro" HTML to the given cells.
5485	// Intro means the leftmost cell when the calendar is LTR and the rightmost cell when RTL. Vice-versa for outro.
5486	bookendCells: function(trEl) {
5487		var introHtml = this.renderIntroHtml();
5488
5489		if (introHtml) {
5490			if (this.isRTL) {
5491				trEl.append(introHtml);
5492			}
5493			else {
5494				trEl.prepend(introHtml);
5495			}
5496		}
5497	}
5498
5499};
5500
5501;;
5502
5503/* A component that renders a grid of whole-days that runs horizontally. There can be multiple rows, one per week.
5504----------------------------------------------------------------------------------------------------------------------*/
5505
5506var DayGrid = FC.DayGrid = Grid.extend(DayTableMixin, {
5507
5508	numbersVisible: false, // should render a row for day/week numbers? set by outside view. TODO: make internal
5509	bottomCoordPadding: 0, // hack for extending the hit area for the last row of the coordinate grid
5510
5511	rowEls: null, // set of fake row elements
5512	cellEls: null, // set of whole-day elements comprising the row's background
5513	helperEls: null, // set of cell skeleton elements for rendering the mock event "helper"
5514
5515	rowCoordCache: null,
5516	colCoordCache: null,
5517
5518
5519	// Renders the rows and columns into the component's `this.el`, which should already be assigned.
5520	// isRigid determins whether the individual rows should ignore the contents and be a constant height.
5521	// Relies on the view's colCnt and rowCnt. In the future, this component should probably be self-sufficient.
5522	renderDates: function(isRigid) {
5523		var view = this.view;
5524		var rowCnt = this.rowCnt;
5525		var colCnt = this.colCnt;
5526		var html = '';
5527		var row;
5528		var col;
5529
5530		for (row = 0; row < rowCnt; row++) {
5531			html += this.renderDayRowHtml(row, isRigid);
5532		}
5533		this.el.html(html);
5534
5535		this.rowEls = this.el.find('.fc-row');
5536		this.cellEls = this.el.find('.fc-day');
5537
5538		this.rowCoordCache = new CoordCache({
5539			els: this.rowEls,
5540			isVertical: true
5541		});
5542		this.colCoordCache = new CoordCache({
5543			els: this.cellEls.slice(0, this.colCnt), // only the first row
5544			isHorizontal: true
5545		});
5546
5547		// trigger dayRender with each cell's element
5548		for (row = 0; row < rowCnt; row++) {
5549			for (col = 0; col < colCnt; col++) {
5550				view.trigger(
5551					'dayRender',
5552					null,
5553					this.getCellDate(row, col),
5554					this.getCellEl(row, col)
5555				);
5556			}
5557		}
5558	},
5559
5560
5561	unrenderDates: function() {
5562		this.removeSegPopover();
5563	},
5564
5565
5566	renderBusinessHours: function() {
5567		var segs = this.buildBusinessHourSegs(true); // wholeDay=true
5568		this.renderFill('businessHours', segs, 'bgevent');
5569	},
5570
5571
5572	unrenderBusinessHours: function() {
5573		this.unrenderFill('businessHours');
5574	},
5575
5576
5577	// Generates the HTML for a single row, which is a div that wraps a table.
5578	// `row` is the row number.
5579	renderDayRowHtml: function(row, isRigid) {
5580		var view = this.view;
5581		var classes = [ 'fc-row', 'fc-week', view.widgetContentClass ];
5582
5583		if (isRigid) {
5584			classes.push('fc-rigid');
5585		}
5586
5587		return '' +
5588			'<div class="' + classes.join(' ') + '">' +
5589				'<div class="fc-bg">' +
5590					'<table>' +
5591						this.renderBgTrHtml(row) +
5592					'</table>' +
5593				'</div>' +
5594				'<div class="fc-content-skeleton">' +
5595					'<table>' +
5596						(this.numbersVisible ?
5597							'<thead>' +
5598								this.renderNumberTrHtml(row) +
5599							'</thead>' :
5600							''
5601							) +
5602					'</table>' +
5603				'</div>' +
5604			'</div>';
5605	},
5606
5607
5608	/* Grid Number Rendering
5609	------------------------------------------------------------------------------------------------------------------*/
5610
5611
5612	renderNumberTrHtml: function(row) {
5613		return '' +
5614			'<tr>' +
5615				(this.isRTL ? '' : this.renderNumberIntroHtml(row)) +
5616				this.renderNumberCellsHtml(row) +
5617				(this.isRTL ? this.renderNumberIntroHtml(row) : '') +
5618			'</tr>';
5619	},
5620
5621
5622	renderNumberIntroHtml: function(row) {
5623		return this.renderIntroHtml();
5624	},
5625
5626
5627	renderNumberCellsHtml: function(row) {
5628		var htmls = [];
5629		var col, date;
5630
5631		for (col = 0; col < this.colCnt; col++) {
5632			date = this.getCellDate(row, col);
5633			htmls.push(this.renderNumberCellHtml(date));
5634		}
5635
5636		return htmls.join('');
5637	},
5638
5639
5640	// Generates the HTML for the <td>s of the "number" row in the DayGrid's content skeleton.
5641	// The number row will only exist if either day numbers or week numbers are turned on.
5642	renderNumberCellHtml: function(date) {
5643		var html = '';
5644		var classes;
5645		var weekCalcFirstDoW;
5646
5647		if (!this.view.dayNumbersVisible && !this.view.cellWeekNumbersVisible) {
5648			// no numbers in day cell (week number must be along the side)
5649			return '<td/>'; //  will create an empty space above events :(
5650		}
5651
5652		classes = this.getDayClasses(date);
5653		classes.unshift('fc-day-top');
5654
5655		if (this.view.cellWeekNumbersVisible) {
5656			// To determine the day of week number change under ISO, we cannot
5657			// rely on moment.js methods such as firstDayOfWeek() or weekday(),
5658			// because they rely on the locale's dow (possibly overridden by
5659			// our firstDay option), which may not be Monday. We cannot change
5660			// dow, because that would affect the calendar start day as well.
5661			if (date._locale._fullCalendar_weekCalc === 'ISO') {
5662				weekCalcFirstDoW = 1;  // Monday by ISO 8601 definition
5663			}
5664			else {
5665				weekCalcFirstDoW = date._locale.firstDayOfWeek();
5666			}
5667		}
5668
5669		html += '<td class="' + classes.join(' ') + '" data-date="' + date.format() + '">';
5670
5671		if (this.view.cellWeekNumbersVisible && (date.day() == weekCalcFirstDoW)) {
5672			html += this.view.buildGotoAnchorHtml(
5673				{ date: date, type: 'week' },
5674				{ 'class': 'fc-week-number' },
5675				date.format('w') // inner HTML
5676			);
5677		}
5678
5679		if (this.view.dayNumbersVisible) {
5680			html += this.view.buildGotoAnchorHtml(
5681				date,
5682				{ 'class': 'fc-day-number' },
5683				date.date() // inner HTML
5684			);
5685		}
5686
5687		html += '</td>';
5688
5689		return html;
5690	},
5691
5692
5693	/* Options
5694	------------------------------------------------------------------------------------------------------------------*/
5695
5696
5697	// Computes a default event time formatting string if `timeFormat` is not explicitly defined
5698	computeEventTimeFormat: function() {
5699		return this.view.opt('extraSmallTimeFormat'); // like "6p" or "6:30p"
5700	},
5701
5702
5703	// Computes a default `displayEventEnd` value if one is not expliclty defined
5704	computeDisplayEventEnd: function() {
5705		return this.colCnt == 1; // we'll likely have space if there's only one day
5706	},
5707
5708
5709	/* Dates
5710	------------------------------------------------------------------------------------------------------------------*/
5711
5712
5713	rangeUpdated: function() {
5714		this.updateDayTable();
5715	},
5716
5717
5718	// Slices up the given span (unzoned start/end with other misc data) into an array of segments
5719	spanToSegs: function(span) {
5720		var segs = this.sliceRangeByRow(span);
5721		var i, seg;
5722
5723		for (i = 0; i < segs.length; i++) {
5724			seg = segs[i];
5725			if (this.isRTL) {
5726				seg.leftCol = this.daysPerRow - 1 - seg.lastRowDayIndex;
5727				seg.rightCol = this.daysPerRow - 1 - seg.firstRowDayIndex;
5728			}
5729			else {
5730				seg.leftCol = seg.firstRowDayIndex;
5731				seg.rightCol = seg.lastRowDayIndex;
5732			}
5733		}
5734
5735		return segs;
5736	},
5737
5738
5739	/* Hit System
5740	------------------------------------------------------------------------------------------------------------------*/
5741
5742
5743	prepareHits: function() {
5744		this.colCoordCache.build();
5745		this.rowCoordCache.build();
5746		this.rowCoordCache.bottoms[this.rowCnt - 1] += this.bottomCoordPadding; // hack
5747	},
5748
5749
5750	releaseHits: function() {
5751		this.colCoordCache.clear();
5752		this.rowCoordCache.clear();
5753	},
5754
5755
5756	queryHit: function(leftOffset, topOffset) {
5757		if (this.colCoordCache.isLeftInBounds(leftOffset) && this.rowCoordCache.isTopInBounds(topOffset)) {
5758			var col = this.colCoordCache.getHorizontalIndex(leftOffset);
5759			var row = this.rowCoordCache.getVerticalIndex(topOffset);
5760
5761			if (row != null && col != null) {
5762				return this.getCellHit(row, col);
5763			}
5764		}
5765	},
5766
5767
5768	getHitSpan: function(hit) {
5769		return this.getCellRange(hit.row, hit.col);
5770	},
5771
5772
5773	getHitEl: function(hit) {
5774		return this.getCellEl(hit.row, hit.col);
5775	},
5776
5777
5778	/* Cell System
5779	------------------------------------------------------------------------------------------------------------------*/
5780	// FYI: the first column is the leftmost column, regardless of date
5781
5782
5783	getCellHit: function(row, col) {
5784		return {
5785			row: row,
5786			col: col,
5787			component: this, // needed unfortunately :(
5788			left: this.colCoordCache.getLeftOffset(col),
5789			right: this.colCoordCache.getRightOffset(col),
5790			top: this.rowCoordCache.getTopOffset(row),
5791			bottom: this.rowCoordCache.getBottomOffset(row)
5792		};
5793	},
5794
5795
5796	getCellEl: function(row, col) {
5797		return this.cellEls.eq(row * this.colCnt + col);
5798	},
5799
5800
5801	/* Event Drag Visualization
5802	------------------------------------------------------------------------------------------------------------------*/
5803	// TODO: move to DayGrid.event, similar to what we did with Grid's drag methods
5804
5805
5806	// Renders a visual indication of an event or external element being dragged.
5807	// `eventLocation` has zoned start and end (optional)
5808	renderDrag: function(eventLocation, seg) {
5809
5810		// always render a highlight underneath
5811		this.renderHighlight(this.eventToSpan(eventLocation));
5812
5813		// if a segment from the same calendar but another component is being dragged, render a helper event
5814		if (seg && seg.component !== this) {
5815			return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
5816		}
5817	},
5818
5819
5820	// Unrenders any visual indication of a hovering event
5821	unrenderDrag: function() {
5822		this.unrenderHighlight();
5823		this.unrenderHelper();
5824	},
5825
5826
5827	/* Event Resize Visualization
5828	------------------------------------------------------------------------------------------------------------------*/
5829
5830
5831	// Renders a visual indication of an event being resized
5832	renderEventResize: function(eventLocation, seg) {
5833		this.renderHighlight(this.eventToSpan(eventLocation));
5834		return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
5835	},
5836
5837
5838	// Unrenders a visual indication of an event being resized
5839	unrenderEventResize: function() {
5840		this.unrenderHighlight();
5841		this.unrenderHelper();
5842	},
5843
5844
5845	/* Event Helper
5846	------------------------------------------------------------------------------------------------------------------*/
5847
5848
5849	// Renders a mock "helper" event. `sourceSeg` is the associated internal segment object. It can be null.
5850	renderHelper: function(event, sourceSeg) {
5851		var helperNodes = [];
5852		var segs = this.eventToSegs(event);
5853		var rowStructs;
5854
5855		segs = this.renderFgSegEls(segs); // assigns each seg's el and returns a subset of segs that were rendered
5856		rowStructs = this.renderSegRows(segs);
5857
5858		// inject each new event skeleton into each associated row
5859		this.rowEls.each(function(row, rowNode) {
5860			var rowEl = $(rowNode); // the .fc-row
5861			var skeletonEl = $('<div class="fc-helper-skeleton"><table/></div>'); // will be absolutely positioned
5862			var skeletonTop;
5863
5864			// If there is an original segment, match the top position. Otherwise, put it at the row's top level
5865			if (sourceSeg && sourceSeg.row === row) {
5866				skeletonTop = sourceSeg.el.position().top;
5867			}
5868			else {
5869				skeletonTop = rowEl.find('.fc-content-skeleton tbody').position().top;
5870			}
5871
5872			skeletonEl.css('top', skeletonTop)
5873				.find('table')
5874					.append(rowStructs[row].tbodyEl);
5875
5876			rowEl.append(skeletonEl);
5877			helperNodes.push(skeletonEl[0]);
5878		});
5879
5880		return ( // must return the elements rendered
5881			this.helperEls = $(helperNodes) // array -> jQuery set
5882		);
5883	},
5884
5885
5886	// Unrenders any visual indication of a mock helper event
5887	unrenderHelper: function() {
5888		if (this.helperEls) {
5889			this.helperEls.remove();
5890			this.helperEls = null;
5891		}
5892	},
5893
5894
5895	/* Fill System (highlight, background events, business hours)
5896	------------------------------------------------------------------------------------------------------------------*/
5897
5898
5899	fillSegTag: 'td', // override the default tag name
5900
5901
5902	// Renders a set of rectangles over the given segments of days.
5903	// Only returns segments that successfully rendered.
5904	renderFill: function(type, segs, className) {
5905		var nodes = [];
5906		var i, seg;
5907		var skeletonEl;
5908
5909		segs = this.renderFillSegEls(type, segs); // assignes `.el` to each seg. returns successfully rendered segs
5910
5911		for (i = 0; i < segs.length; i++) {
5912			seg = segs[i];
5913			skeletonEl = this.renderFillRow(type, seg, className);
5914			this.rowEls.eq(seg.row).append(skeletonEl);
5915			nodes.push(skeletonEl[0]);
5916		}
5917
5918		this.elsByFill[type] = $(nodes);
5919
5920		return segs;
5921	},
5922
5923
5924	// Generates the HTML needed for one row of a fill. Requires the seg's el to be rendered.
5925	renderFillRow: function(type, seg, className) {
5926		var colCnt = this.colCnt;
5927		var startCol = seg.leftCol;
5928		var endCol = seg.rightCol + 1;
5929		var skeletonEl;
5930		var trEl;
5931
5932		className = className || type.toLowerCase();
5933
5934		skeletonEl = $(
5935			'<div class="fc-' + className + '-skeleton">' +
5936				'<table><tr/></table>' +
5937			'</div>'
5938		);
5939		trEl = skeletonEl.find('tr');
5940
5941		if (startCol > 0) {
5942			trEl.append('<td colspan="' + startCol + '"/>');
5943		}
5944
5945		trEl.append(
5946			seg.el.attr('colspan', endCol - startCol)
5947		);
5948
5949		if (endCol < colCnt) {
5950			trEl.append('<td colspan="' + (colCnt - endCol) + '"/>');
5951		}
5952
5953		this.bookendCells(trEl);
5954
5955		return skeletonEl;
5956	}
5957
5958});
5959
5960;;
5961
5962/* Event-rendering methods for the DayGrid class
5963----------------------------------------------------------------------------------------------------------------------*/
5964
5965DayGrid.mixin({
5966
5967	rowStructs: null, // an array of objects, each holding information about a row's foreground event-rendering
5968
5969
5970	// Unrenders all events currently rendered on the grid
5971	unrenderEvents: function() {
5972		this.removeSegPopover(); // removes the "more.." events popover
5973		Grid.prototype.unrenderEvents.apply(this, arguments); // calls the super-method
5974	},
5975
5976
5977	// Retrieves all rendered segment objects currently rendered on the grid
5978	getEventSegs: function() {
5979		return Grid.prototype.getEventSegs.call(this) // get the segments from the super-method
5980			.concat(this.popoverSegs || []); // append the segments from the "more..." popover
5981	},
5982
5983
5984	// Renders the given background event segments onto the grid
5985	renderBgSegs: function(segs) {
5986
5987		// don't render timed background events
5988		var allDaySegs = $.grep(segs, function(seg) {
5989			return seg.event.allDay;
5990		});
5991
5992		return Grid.prototype.renderBgSegs.call(this, allDaySegs); // call the super-method
5993	},
5994
5995
5996	// Renders the given foreground event segments onto the grid
5997	renderFgSegs: function(segs) {
5998		var rowStructs;
5999
6000		// render an `.el` on each seg
6001		// returns a subset of the segs. segs that were actually rendered
6002		segs = this.renderFgSegEls(segs);
6003
6004		rowStructs = this.rowStructs = this.renderSegRows(segs);
6005
6006		// append to each row's content skeleton
6007		this.rowEls.each(function(i, rowNode) {
6008			$(rowNode).find('.fc-content-skeleton > table').append(
6009				rowStructs[i].tbodyEl
6010			);
6011		});
6012
6013		return segs; // return only the segs that were actually rendered
6014	},
6015
6016
6017	// Unrenders all currently rendered foreground event segments
6018	unrenderFgSegs: function() {
6019		var rowStructs = this.rowStructs || [];
6020		var rowStruct;
6021
6022		while ((rowStruct = rowStructs.pop())) {
6023			rowStruct.tbodyEl.remove();
6024		}
6025
6026		this.rowStructs = null;
6027	},
6028
6029
6030	// Uses the given events array to generate <tbody> elements that should be appended to each row's content skeleton.
6031	// Returns an array of rowStruct objects (see the bottom of `renderSegRow`).
6032	// PRECONDITION: each segment shoud already have a rendered and assigned `.el`
6033	renderSegRows: function(segs) {
6034		var rowStructs = [];
6035		var segRows;
6036		var row;
6037
6038		segRows = this.groupSegRows(segs); // group into nested arrays
6039
6040		// iterate each row of segment groupings
6041		for (row = 0; row < segRows.length; row++) {
6042			rowStructs.push(
6043				this.renderSegRow(row, segRows[row])
6044			);
6045		}
6046
6047		return rowStructs;
6048	},
6049
6050
6051	// Builds the HTML to be used for the default element for an individual segment
6052	fgSegHtml: function(seg, disableResizing) {
6053		var view = this.view;
6054		var event = seg.event;
6055		var isDraggable = view.isEventDraggable(event);
6056		var isResizableFromStart = !disableResizing && event.allDay &&
6057			seg.isStart && view.isEventResizableFromStart(event);
6058		var isResizableFromEnd = !disableResizing && event.allDay &&
6059			seg.isEnd && view.isEventResizableFromEnd(event);
6060		var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
6061		var skinCss = cssToStr(this.getSegSkinCss(seg));
6062		var timeHtml = '';
6063		var timeText;
6064		var titleHtml;
6065
6066		classes.unshift('fc-day-grid-event', 'fc-h-event');
6067
6068		// Only display a timed events time if it is the starting segment
6069		if (seg.isStart) {
6070			timeText = this.getEventTimeText(event);
6071			if (timeText) {
6072				timeHtml = '<span class="fc-time">' + htmlEscape(timeText) + '</span>';
6073			}
6074		}
6075
6076		titleHtml =
6077			'<span class="fc-title">' +
6078				(htmlEscape(event.title || '') || '&nbsp;') + // we always want one line of height
6079			'</span>';
6080		
6081		return '<a class="' + classes.join(' ') + '"' +
6082				(event.url ?
6083					' href="' + htmlEscape(event.url) + '"' :
6084					''
6085					) +
6086				(skinCss ?
6087					' style="' + skinCss + '"' :
6088					''
6089					) +
6090			'>' +
6091				'<div class="fc-content">' +
6092					(this.isRTL ?
6093						titleHtml + ' ' + timeHtml : // put a natural space in between
6094						timeHtml + ' ' + titleHtml   //
6095						) +
6096				'</div>' +
6097				(isResizableFromStart ?
6098					'<div class="fc-resizer fc-start-resizer" />' :
6099					''
6100					) +
6101				(isResizableFromEnd ?
6102					'<div class="fc-resizer fc-end-resizer" />' :
6103					''
6104					) +
6105			'</a>';
6106	},
6107
6108
6109	// Given a row # and an array of segments all in the same row, render a <tbody> element, a skeleton that contains
6110	// the segments. Returns object with a bunch of internal data about how the render was calculated.
6111	// NOTE: modifies rowSegs
6112	renderSegRow: function(row, rowSegs) {
6113		var colCnt = this.colCnt;
6114		var segLevels = this.buildSegLevels(rowSegs); // group into sub-arrays of levels
6115		var levelCnt = Math.max(1, segLevels.length); // ensure at least one level
6116		var tbody = $('<tbody/>');
6117		var segMatrix = []; // lookup for which segments are rendered into which level+col cells
6118		var cellMatrix = []; // lookup for all <td> elements of the level+col matrix
6119		var loneCellMatrix = []; // lookup for <td> elements that only take up a single column
6120		var i, levelSegs;
6121		var col;
6122		var tr;
6123		var j, seg;
6124		var td;
6125
6126		// populates empty cells from the current column (`col`) to `endCol`
6127		function emptyCellsUntil(endCol) {
6128			while (col < endCol) {
6129				// try to grab a cell from the level above and extend its rowspan. otherwise, create a fresh cell
6130				td = (loneCellMatrix[i - 1] || [])[col];
6131				if (td) {
6132					td.attr(
6133						'rowspan',
6134						parseInt(td.attr('rowspan') || 1, 10) + 1
6135					);
6136				}
6137				else {
6138					td = $('<td/>');
6139					tr.append(td);
6140				}
6141				cellMatrix[i][col] = td;
6142				loneCellMatrix[i][col] = td;
6143				col++;
6144			}
6145		}
6146
6147		for (i = 0; i < levelCnt; i++) { // iterate through all levels
6148			levelSegs = segLevels[i];
6149			col = 0;
6150			tr = $('<tr/>');
6151
6152			segMatrix.push([]);
6153			cellMatrix.push([]);
6154			loneCellMatrix.push([]);
6155
6156			// levelCnt might be 1 even though there are no actual levels. protect against this.
6157			// this single empty row is useful for styling.
6158			if (levelSegs) {
6159				for (j = 0; j < levelSegs.length; j++) { // iterate through segments in level
6160					seg = levelSegs[j];
6161
6162					emptyCellsUntil(seg.leftCol);
6163
6164					// create a container that occupies or more columns. append the event element.
6165					td = $('<td class="fc-event-container"/>').append(seg.el);
6166					if (seg.leftCol != seg.rightCol) {
6167						td.attr('colspan', seg.rightCol - seg.leftCol + 1);
6168					}
6169					else { // a single-column segment
6170						loneCellMatrix[i][col] = td;
6171					}
6172
6173					while (col <= seg.rightCol) {
6174						cellMatrix[i][col] = td;
6175						segMatrix[i][col] = seg;
6176						col++;
6177					}
6178
6179					tr.append(td);
6180				}
6181			}
6182
6183			emptyCellsUntil(colCnt); // finish off the row
6184			this.bookendCells(tr);
6185			tbody.append(tr);
6186		}
6187
6188		return { // a "rowStruct"
6189			row: row, // the row number
6190			tbodyEl: tbody,
6191			cellMatrix: cellMatrix,
6192			segMatrix: segMatrix,
6193			segLevels: segLevels,
6194			segs: rowSegs
6195		};
6196	},
6197
6198
6199	// Stacks a flat array of segments, which are all assumed to be in the same row, into subarrays of vertical levels.
6200	// NOTE: modifies segs
6201	buildSegLevels: function(segs) {
6202		var levels = [];
6203		var i, seg;
6204		var j;
6205
6206		// Give preference to elements with certain criteria, so they have
6207		// a chance to be closer to the top.
6208		this.sortEventSegs(segs);
6209		
6210		for (i = 0; i < segs.length; i++) {
6211			seg = segs[i];
6212
6213			// loop through levels, starting with the topmost, until the segment doesn't collide with other segments
6214			for (j = 0; j < levels.length; j++) {
6215				if (!isDaySegCollision(seg, levels[j])) {
6216					break;
6217				}
6218			}
6219			// `j` now holds the desired subrow index
6220			seg.level = j;
6221
6222			// create new level array if needed and append segment
6223			(levels[j] || (levels[j] = [])).push(seg);
6224		}
6225
6226		// order segments left-to-right. very important if calendar is RTL
6227		for (j = 0; j < levels.length; j++) {
6228			levels[j].sort(compareDaySegCols);
6229		}
6230
6231		return levels;
6232	},
6233
6234
6235	// Given a flat array of segments, return an array of sub-arrays, grouped by each segment's row
6236	groupSegRows: function(segs) {
6237		var segRows = [];
6238		var i;
6239
6240		for (i = 0; i < this.rowCnt; i++) {
6241			segRows.push([]);
6242		}
6243
6244		for (i = 0; i < segs.length; i++) {
6245			segRows[segs[i].row].push(segs[i]);
6246		}
6247
6248		return segRows;
6249	}
6250
6251});
6252
6253
6254// Computes whether two segments' columns collide. They are assumed to be in the same row.
6255function isDaySegCollision(seg, otherSegs) {
6256	var i, otherSeg;
6257
6258	for (i = 0; i < otherSegs.length; i++) {
6259		otherSeg = otherSegs[i];
6260
6261		if (
6262			otherSeg.leftCol <= seg.rightCol &&
6263			otherSeg.rightCol >= seg.leftCol
6264		) {
6265			return true;
6266		}
6267	}
6268
6269	return false;
6270}
6271
6272
6273// A cmp function for determining the leftmost event
6274function compareDaySegCols(a, b) {
6275	return a.leftCol - b.leftCol;
6276}
6277
6278;;
6279
6280/* Methods relate to limiting the number events for a given day on a DayGrid
6281----------------------------------------------------------------------------------------------------------------------*/
6282// NOTE: all the segs being passed around in here are foreground segs
6283
6284DayGrid.mixin({
6285
6286	segPopover: null, // the Popover that holds events that can't fit in a cell. null when not visible
6287	popoverSegs: null, // an array of segment objects that the segPopover holds. null when not visible
6288
6289
6290	removeSegPopover: function() {
6291		if (this.segPopover) {
6292			this.segPopover.hide(); // in handler, will call segPopover's removeElement
6293		}
6294	},
6295
6296
6297	// Limits the number of "levels" (vertically stacking layers of events) for each row of the grid.
6298	// `levelLimit` can be false (don't limit), a number, or true (should be computed).
6299	limitRows: function(levelLimit) {
6300		var rowStructs = this.rowStructs || [];
6301		var row; // row #
6302		var rowLevelLimit;
6303
6304		for (row = 0; row < rowStructs.length; row++) {
6305			this.unlimitRow(row);
6306
6307			if (!levelLimit) {
6308				rowLevelLimit = false;
6309			}
6310			else if (typeof levelLimit === 'number') {
6311				rowLevelLimit = levelLimit;
6312			}
6313			else {
6314				rowLevelLimit = this.computeRowLevelLimit(row);
6315			}
6316
6317			if (rowLevelLimit !== false) {
6318				this.limitRow(row, rowLevelLimit);
6319			}
6320		}
6321	},
6322
6323
6324	// Computes the number of levels a row will accomodate without going outside its bounds.
6325	// Assumes the row is "rigid" (maintains a constant height regardless of what is inside).
6326	// `row` is the row number.
6327	computeRowLevelLimit: function(row) {
6328		var rowEl = this.rowEls.eq(row); // the containing "fake" row div
6329		var rowHeight = rowEl.height(); // TODO: cache somehow?
6330		var trEls = this.rowStructs[row].tbodyEl.children();
6331		var i, trEl;
6332		var trHeight;
6333
6334		function iterInnerHeights(i, childNode) {
6335			trHeight = Math.max(trHeight, $(childNode).outerHeight());
6336		}
6337
6338		// Reveal one level <tr> at a time and stop when we find one out of bounds
6339		for (i = 0; i < trEls.length; i++) {
6340			trEl = trEls.eq(i).removeClass('fc-limited'); // reset to original state (reveal)
6341
6342			// with rowspans>1 and IE8, trEl.outerHeight() would return the height of the largest cell,
6343			// so instead, find the tallest inner content element.
6344			trHeight = 0;
6345			trEl.find('> td > :first-child').each(iterInnerHeights);
6346
6347			if (trEl.position().top + trHeight > rowHeight) {
6348				return i;
6349			}
6350		}
6351
6352		return false; // should not limit at all
6353	},
6354
6355
6356	// Limits the given grid row to the maximum number of levels and injects "more" links if necessary.
6357	// `row` is the row number.
6358	// `levelLimit` is a number for the maximum (inclusive) number of levels allowed.
6359	limitRow: function(row, levelLimit) {
6360		var _this = this;
6361		var rowStruct = this.rowStructs[row];
6362		var moreNodes = []; // array of "more" <a> links and <td> DOM nodes
6363		var col = 0; // col #, left-to-right (not chronologically)
6364		var levelSegs; // array of segment objects in the last allowable level, ordered left-to-right
6365		var cellMatrix; // a matrix (by level, then column) of all <td> jQuery elements in the row
6366		var limitedNodes; // array of temporarily hidden level <tr> and segment <td> DOM nodes
6367		var i, seg;
6368		var segsBelow; // array of segment objects below `seg` in the current `col`
6369		var totalSegsBelow; // total number of segments below `seg` in any of the columns `seg` occupies
6370		var colSegsBelow; // array of segment arrays, below seg, one for each column (offset from segs's first column)
6371		var td, rowspan;
6372		var segMoreNodes; // array of "more" <td> cells that will stand-in for the current seg's cell
6373		var j;
6374		var moreTd, moreWrap, moreLink;
6375
6376		// Iterates through empty level cells and places "more" links inside if need be
6377		function emptyCellsUntil(endCol) { // goes from current `col` to `endCol`
6378			while (col < endCol) {
6379				segsBelow = _this.getCellSegs(row, col, levelLimit);
6380				if (segsBelow.length) {
6381					td = cellMatrix[levelLimit - 1][col];
6382					moreLink = _this.renderMoreLink(row, col, segsBelow);
6383					moreWrap = $('<div/>').append(moreLink);
6384					td.append(moreWrap);
6385					moreNodes.push(moreWrap[0]);
6386				}
6387				col++;
6388			}
6389		}
6390
6391		if (levelLimit && levelLimit < rowStruct.segLevels.length) { // is it actually over the limit?
6392			levelSegs = rowStruct.segLevels[levelLimit - 1];
6393			cellMatrix = rowStruct.cellMatrix;
6394
6395			limitedNodes = rowStruct.tbodyEl.children().slice(levelLimit) // get level <tr> elements past the limit
6396				.addClass('fc-limited').get(); // hide elements and get a simple DOM-nodes array
6397
6398			// iterate though segments in the last allowable level
6399			for (i = 0; i < levelSegs.length; i++) {
6400				seg = levelSegs[i];
6401				emptyCellsUntil(seg.leftCol); // process empty cells before the segment
6402
6403				// determine *all* segments below `seg` that occupy the same columns
6404				colSegsBelow = [];
6405				totalSegsBelow = 0;
6406				while (col <= seg.rightCol) {
6407					segsBelow = this.getCellSegs(row, col, levelLimit);
6408					colSegsBelow.push(segsBelow);
6409					totalSegsBelow += segsBelow.length;
6410					col++;
6411				}
6412
6413				if (totalSegsBelow) { // do we need to replace this segment with one or many "more" links?
6414					td = cellMatrix[levelLimit - 1][seg.leftCol]; // the segment's parent cell
6415					rowspan = td.attr('rowspan') || 1;
6416					segMoreNodes = [];
6417
6418					// make a replacement <td> for each column the segment occupies. will be one for each colspan
6419					for (j = 0; j < colSegsBelow.length; j++) {
6420						moreTd = $('<td class="fc-more-cell"/>').attr('rowspan', rowspan);
6421						segsBelow = colSegsBelow[j];
6422						moreLink = this.renderMoreLink(
6423							row,
6424							seg.leftCol + j,
6425							[ seg ].concat(segsBelow) // count seg as hidden too
6426						);
6427						moreWrap = $('<div/>').append(moreLink);
6428						moreTd.append(moreWrap);
6429						segMoreNodes.push(moreTd[0]);
6430						moreNodes.push(moreTd[0]);
6431					}
6432
6433					td.addClass('fc-limited').after($(segMoreNodes)); // hide original <td> and inject replacements
6434					limitedNodes.push(td[0]);
6435				}
6436			}
6437
6438			emptyCellsUntil(this.colCnt); // finish off the level
6439			rowStruct.moreEls = $(moreNodes); // for easy undoing later
6440			rowStruct.limitedEls = $(limitedNodes); // for easy undoing later
6441		}
6442	},
6443
6444
6445	// Reveals all levels and removes all "more"-related elements for a grid's row.
6446	// `row` is a row number.
6447	unlimitRow: function(row) {
6448		var rowStruct = this.rowStructs[row];
6449
6450		if (rowStruct.moreEls) {
6451			rowStruct.moreEls.remove();
6452			rowStruct.moreEls = null;
6453		}
6454
6455		if (rowStruct.limitedEls) {
6456			rowStruct.limitedEls.removeClass('fc-limited');
6457			rowStruct.limitedEls = null;
6458		}
6459	},
6460
6461
6462	// Renders an <a> element that represents hidden event element for a cell.
6463	// Responsible for attaching click handler as well.
6464	renderMoreLink: function(row, col, hiddenSegs) {
6465		var _this = this;
6466		var view = this.view;
6467
6468		return $('<a class="fc-more"/>')
6469			.text(
6470				this.getMoreLinkText(hiddenSegs.length)
6471			)
6472			.on('click', function(ev) {
6473				var clickOption = view.opt('eventLimitClick');
6474				var date = _this.getCellDate(row, col);
6475				var moreEl = $(this);
6476				var dayEl = _this.getCellEl(row, col);
6477				var allSegs = _this.getCellSegs(row, col);
6478
6479				// rescope the segments to be within the cell's date
6480				var reslicedAllSegs = _this.resliceDaySegs(allSegs, date);
6481				var reslicedHiddenSegs = _this.resliceDaySegs(hiddenSegs, date);
6482
6483				if (typeof clickOption === 'function') {
6484					// the returned value can be an atomic option
6485					clickOption = view.trigger('eventLimitClick', null, {
6486						date: date,
6487						dayEl: dayEl,
6488						moreEl: moreEl,
6489						segs: reslicedAllSegs,
6490						hiddenSegs: reslicedHiddenSegs
6491					}, ev);
6492				}
6493
6494				if (clickOption === 'popover') {
6495					_this.showSegPopover(row, col, moreEl, reslicedAllSegs);
6496				}
6497				else if (typeof clickOption === 'string') { // a view name
6498					view.calendar.zoomTo(date, clickOption);
6499				}
6500			});
6501	},
6502
6503
6504	// Reveals the popover that displays all events within a cell
6505	showSegPopover: function(row, col, moreLink, segs) {
6506		var _this = this;
6507		var view = this.view;
6508		var moreWrap = moreLink.parent(); // the <div> wrapper around the <a>
6509		var topEl; // the element we want to match the top coordinate of
6510		var options;
6511
6512		if (this.rowCnt == 1) {
6513			topEl = view.el; // will cause the popover to cover any sort of header
6514		}
6515		else {
6516			topEl = this.rowEls.eq(row); // will align with top of row
6517		}
6518
6519		options = {
6520			className: 'fc-more-popover',
6521			content: this.renderSegPopoverContent(row, col, segs),
6522			parentEl: this.view.el, // attach to root of view. guarantees outside of scrollbars.
6523			top: topEl.offset().top,
6524			autoHide: true, // when the user clicks elsewhere, hide the popover
6525			viewportConstrain: view.opt('popoverViewportConstrain'),
6526			hide: function() {
6527				// kill everything when the popover is hidden
6528				_this.segPopover.removeElement();
6529				_this.segPopover = null;
6530				_this.popoverSegs = null;
6531			}
6532		};
6533
6534		// Determine horizontal coordinate.
6535		// We use the moreWrap instead of the <td> to avoid border confusion.
6536		if (this.isRTL) {
6537			options.right = moreWrap.offset().left + moreWrap.outerWidth() + 1; // +1 to be over cell border
6538		}
6539		else {
6540			options.left = moreWrap.offset().left - 1; // -1 to be over cell border
6541		}
6542
6543		this.segPopover = new Popover(options);
6544		this.segPopover.show();
6545
6546		// the popover doesn't live within the grid's container element, and thus won't get the event
6547		// delegated-handlers for free. attach event-related handlers to the popover.
6548		this.bindSegHandlersToEl(this.segPopover.el);
6549	},
6550
6551
6552	// Builds the inner DOM contents of the segment popover
6553	renderSegPopoverContent: function(row, col, segs) {
6554		var view = this.view;
6555		var isTheme = view.opt('theme');
6556		var title = this.getCellDate(row, col).format(view.opt('dayPopoverFormat'));
6557		var content = $(
6558			'<div class="fc-header ' + view.widgetHeaderClass + '">' +
6559				'<span class="fc-close ' +
6560					(isTheme ? 'ui-icon ui-icon-closethick' : 'fc-icon fc-icon-x') +
6561				'"></span>' +
6562				'<span class="fc-title">' +
6563					htmlEscape(title) +
6564				'</span>' +
6565				'<div class="fc-clear"/>' +
6566			'</div>' +
6567			'<div class="fc-body ' + view.widgetContentClass + '">' +
6568				'<div class="fc-event-container"></div>' +
6569			'</div>'
6570		);
6571		var segContainer = content.find('.fc-event-container');
6572		var i;
6573
6574		// render each seg's `el` and only return the visible segs
6575		segs = this.renderFgSegEls(segs, true); // disableResizing=true
6576		this.popoverSegs = segs;
6577
6578		for (i = 0; i < segs.length; i++) {
6579
6580			// because segments in the popover are not part of a grid coordinate system, provide a hint to any
6581			// grids that want to do drag-n-drop about which cell it came from
6582			this.prepareHits();
6583			segs[i].hit = this.getCellHit(row, col);
6584			this.releaseHits();
6585
6586			segContainer.append(segs[i].el);
6587		}
6588
6589		return content;
6590	},
6591
6592
6593	// Given the events within an array of segment objects, reslice them to be in a single day
6594	resliceDaySegs: function(segs, dayDate) {
6595
6596		// build an array of the original events
6597		var events = $.map(segs, function(seg) {
6598			return seg.event;
6599		});
6600
6601		var dayStart = dayDate.clone();
6602		var dayEnd = dayStart.clone().add(1, 'days');
6603		var dayRange = { start: dayStart, end: dayEnd };
6604
6605		// slice the events with a custom slicing function
6606		segs = this.eventsToSegs(
6607			events,
6608			function(range) {
6609				var seg = intersectRanges(range, dayRange); // undefind if no intersection
6610				return seg ? [ seg ] : []; // must return an array of segments
6611			}
6612		);
6613
6614		// force an order because eventsToSegs doesn't guarantee one
6615		this.sortEventSegs(segs);
6616
6617		return segs;
6618	},
6619
6620
6621	// Generates the text that should be inside a "more" link, given the number of events it represents
6622	getMoreLinkText: function(num) {
6623		var opt = this.view.opt('eventLimitText');
6624
6625		if (typeof opt === 'function') {
6626			return opt(num);
6627		}
6628		else {
6629			return '+' + num + ' ' + opt;
6630		}
6631	},
6632
6633
6634	// Returns segments within a given cell.
6635	// If `startLevel` is specified, returns only events including and below that level. Otherwise returns all segs.
6636	getCellSegs: function(row, col, startLevel) {
6637		var segMatrix = this.rowStructs[row].segMatrix;
6638		var level = startLevel || 0;
6639		var segs = [];
6640		var seg;
6641
6642		while (level < segMatrix.length) {
6643			seg = segMatrix[level][col];
6644			if (seg) {
6645				segs.push(seg);
6646			}
6647			level++;
6648		}
6649
6650		return segs;
6651	}
6652
6653});
6654
6655;;
6656
6657/* A component that renders one or more columns of vertical time slots
6658----------------------------------------------------------------------------------------------------------------------*/
6659// We mixin DayTable, even though there is only a single row of days
6660
6661var TimeGrid = FC.TimeGrid = Grid.extend(DayTableMixin, {
6662
6663	slotDuration: null, // duration of a "slot", a distinct time segment on given day, visualized by lines
6664	snapDuration: null, // granularity of time for dragging and selecting
6665	snapsPerSlot: null,
6666	minTime: null, // Duration object that denotes the first visible time of any given day
6667	maxTime: null, // Duration object that denotes the exclusive visible end time of any given day
6668	labelFormat: null, // formatting string for times running along vertical axis
6669	labelInterval: null, // duration of how often a label should be displayed for a slot
6670
6671	colEls: null, // cells elements in the day-row background
6672	slatContainerEl: null, // div that wraps all the slat rows
6673	slatEls: null, // elements running horizontally across all columns
6674	nowIndicatorEls: null,
6675
6676	colCoordCache: null,
6677	slatCoordCache: null,
6678
6679
6680	constructor: function() {
6681		Grid.apply(this, arguments); // call the super-constructor
6682
6683		this.processOptions();
6684	},
6685
6686
6687	// Renders the time grid into `this.el`, which should already be assigned.
6688	// Relies on the view's colCnt. In the future, this component should probably be self-sufficient.
6689	renderDates: function() {
6690		this.el.html(this.renderHtml());
6691		this.colEls = this.el.find('.fc-day');
6692		this.slatContainerEl = this.el.find('.fc-slats');
6693		this.slatEls = this.slatContainerEl.find('tr');
6694
6695		this.colCoordCache = new CoordCache({
6696			els: this.colEls,
6697			isHorizontal: true
6698		});
6699		this.slatCoordCache = new CoordCache({
6700			els: this.slatEls,
6701			isVertical: true
6702		});
6703
6704		this.renderContentSkeleton();
6705	},
6706
6707
6708	// Renders the basic HTML skeleton for the grid
6709	renderHtml: function() {
6710		return '' +
6711			'<div class="fc-bg">' +
6712				'<table>' +
6713					this.renderBgTrHtml(0) + // row=0
6714				'</table>' +
6715			'</div>' +
6716			'<div class="fc-slats">' +
6717				'<table>' +
6718					this.renderSlatRowHtml() +
6719				'</table>' +
6720			'</div>';
6721	},
6722
6723
6724	// Generates the HTML for the horizontal "slats" that run width-wise. Has a time axis on a side. Depends on RTL.
6725	renderSlatRowHtml: function() {
6726		var view = this.view;
6727		var isRTL = this.isRTL;
6728		var html = '';
6729		var slotTime = moment.duration(+this.minTime); // wish there was .clone() for durations
6730		var slotDate; // will be on the view's first day, but we only care about its time
6731		var isLabeled;
6732		var axisHtml;
6733
6734		// Calculate the time for each slot
6735		while (slotTime < this.maxTime) {
6736			slotDate = this.start.clone().time(slotTime);
6737			isLabeled = isInt(divideDurationByDuration(slotTime, this.labelInterval));
6738
6739			axisHtml =
6740				'<td class="fc-axis fc-time ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
6741					(isLabeled ?
6742						'<span>' + // for matchCellWidths
6743							htmlEscape(slotDate.format(this.labelFormat)) +
6744						'</span>' :
6745						''
6746						) +
6747				'</td>';
6748
6749			html +=
6750				'<tr data-time="' + slotDate.format('HH:mm:ss') + '"' +
6751					(isLabeled ? '' : ' class="fc-minor"') +
6752					'>' +
6753					(!isRTL ? axisHtml : '') +
6754					'<td class="' + view.widgetContentClass + '"/>' +
6755					(isRTL ? axisHtml : '') +
6756				"</tr>";
6757
6758			slotTime.add(this.slotDuration);
6759		}
6760
6761		return html;
6762	},
6763
6764
6765	/* Options
6766	------------------------------------------------------------------------------------------------------------------*/
6767
6768
6769	// Parses various options into properties of this object
6770	processOptions: function() {
6771		var view = this.view;
6772		var slotDuration = view.opt('slotDuration');
6773		var snapDuration = view.opt('snapDuration');
6774		var input;
6775
6776		slotDuration = moment.duration(slotDuration);
6777		snapDuration = snapDuration ? moment.duration(snapDuration) : slotDuration;
6778
6779		this.slotDuration = slotDuration;
6780		this.snapDuration = snapDuration;
6781		this.snapsPerSlot = slotDuration / snapDuration; // TODO: ensure an integer multiple?
6782
6783		this.minResizeDuration = snapDuration; // hack
6784
6785		this.minTime = moment.duration(view.opt('minTime'));
6786		this.maxTime = moment.duration(view.opt('maxTime'));
6787
6788		// might be an array value (for TimelineView).
6789		// if so, getting the most granular entry (the last one probably).
6790		input = view.opt('slotLabelFormat');
6791		if ($.isArray(input)) {
6792			input = input[input.length - 1];
6793		}
6794
6795		this.labelFormat =
6796			input ||
6797			view.opt('smallTimeFormat'); // the computed default
6798
6799		input = view.opt('slotLabelInterval');
6800		this.labelInterval = input ?
6801			moment.duration(input) :
6802			this.computeLabelInterval(slotDuration);
6803	},
6804
6805
6806	// Computes an automatic value for slotLabelInterval
6807	computeLabelInterval: function(slotDuration) {
6808		var i;
6809		var labelInterval;
6810		var slotsPerLabel;
6811
6812		// find the smallest stock label interval that results in more than one slots-per-label
6813		for (i = AGENDA_STOCK_SUB_DURATIONS.length - 1; i >= 0; i--) {
6814			labelInterval = moment.duration(AGENDA_STOCK_SUB_DURATIONS[i]);
6815			slotsPerLabel = divideDurationByDuration(labelInterval, slotDuration);
6816			if (isInt(slotsPerLabel) && slotsPerLabel > 1) {
6817				return labelInterval;
6818			}
6819		}
6820
6821		return moment.duration(slotDuration); // fall back. clone
6822	},
6823
6824
6825	// Computes a default event time formatting string if `timeFormat` is not explicitly defined
6826	computeEventTimeFormat: function() {
6827		return this.view.opt('noMeridiemTimeFormat'); // like "6:30" (no AM/PM)
6828	},
6829
6830
6831	// Computes a default `displayEventEnd` value if one is not expliclty defined
6832	computeDisplayEventEnd: function() {
6833		return true;
6834	},
6835
6836
6837	/* Hit System
6838	------------------------------------------------------------------------------------------------------------------*/
6839
6840
6841	prepareHits: function() {
6842		this.colCoordCache.build();
6843		this.slatCoordCache.build();
6844	},
6845
6846
6847	releaseHits: function() {
6848		this.colCoordCache.clear();
6849		// NOTE: don't clear slatCoordCache because we rely on it for computeTimeTop
6850	},
6851
6852
6853	queryHit: function(leftOffset, topOffset) {
6854		var snapsPerSlot = this.snapsPerSlot;
6855		var colCoordCache = this.colCoordCache;
6856		var slatCoordCache = this.slatCoordCache;
6857
6858		if (colCoordCache.isLeftInBounds(leftOffset) && slatCoordCache.isTopInBounds(topOffset)) {
6859			var colIndex = colCoordCache.getHorizontalIndex(leftOffset);
6860			var slatIndex = slatCoordCache.getVerticalIndex(topOffset);
6861
6862			if (colIndex != null && slatIndex != null) {
6863				var slatTop = slatCoordCache.getTopOffset(slatIndex);
6864				var slatHeight = slatCoordCache.getHeight(slatIndex);
6865				var partial = (topOffset - slatTop) / slatHeight; // floating point number between 0 and 1
6866				var localSnapIndex = Math.floor(partial * snapsPerSlot); // the snap # relative to start of slat
6867				var snapIndex = slatIndex * snapsPerSlot + localSnapIndex;
6868				var snapTop = slatTop + (localSnapIndex / snapsPerSlot) * slatHeight;
6869				var snapBottom = slatTop + ((localSnapIndex + 1) / snapsPerSlot) * slatHeight;
6870
6871				return {
6872					col: colIndex,
6873					snap: snapIndex,
6874					component: this, // needed unfortunately :(
6875					left: colCoordCache.getLeftOffset(colIndex),
6876					right: colCoordCache.getRightOffset(colIndex),
6877					top: snapTop,
6878					bottom: snapBottom
6879				};
6880			}
6881		}
6882	},
6883
6884
6885	getHitSpan: function(hit) {
6886		var start = this.getCellDate(0, hit.col); // row=0
6887		var time = this.computeSnapTime(hit.snap); // pass in the snap-index
6888		var end;
6889
6890		start.time(time);
6891		end = start.clone().add(this.snapDuration);
6892
6893		return { start: start, end: end };
6894	},
6895
6896
6897	getHitEl: function(hit) {
6898		return this.colEls.eq(hit.col);
6899	},
6900
6901
6902	/* Dates
6903	------------------------------------------------------------------------------------------------------------------*/
6904
6905
6906	rangeUpdated: function() {
6907		this.updateDayTable();
6908	},
6909
6910
6911	// Given a row number of the grid, representing a "snap", returns a time (Duration) from its start-of-day
6912	computeSnapTime: function(snapIndex) {
6913		return moment.duration(this.minTime + this.snapDuration * snapIndex);
6914	},
6915
6916
6917	// Slices up the given span (unzoned start/end with other misc data) into an array of segments
6918	spanToSegs: function(span) {
6919		var segs = this.sliceRangeByTimes(span);
6920		var i;
6921
6922		for (i = 0; i < segs.length; i++) {
6923			if (this.isRTL) {
6924				segs[i].col = this.daysPerRow - 1 - segs[i].dayIndex;
6925			}
6926			else {
6927				segs[i].col = segs[i].dayIndex;
6928			}
6929		}
6930
6931		return segs;
6932	},
6933
6934
6935	sliceRangeByTimes: function(range) {
6936		var segs = [];
6937		var seg;
6938		var dayIndex;
6939		var dayDate;
6940		var dayRange;
6941
6942		for (dayIndex = 0; dayIndex < this.daysPerRow; dayIndex++) {
6943			dayDate = this.dayDates[dayIndex].clone(); // TODO: better API for this?
6944			dayRange = {
6945				start: dayDate.clone().time(this.minTime),
6946				end: dayDate.clone().time(this.maxTime)
6947			};
6948			seg = intersectRanges(range, dayRange); // both will be ambig timezone
6949			if (seg) {
6950				seg.dayIndex = dayIndex;
6951				segs.push(seg);
6952			}
6953		}
6954
6955		return segs;
6956	},
6957
6958
6959	/* Coordinates
6960	------------------------------------------------------------------------------------------------------------------*/
6961
6962
6963	updateSize: function(isResize) { // NOT a standard Grid method
6964		this.slatCoordCache.build();
6965
6966		if (isResize) {
6967			this.updateSegVerticals(
6968				[].concat(this.fgSegs || [], this.bgSegs || [], this.businessSegs || [])
6969			);
6970		}
6971	},
6972
6973
6974	getTotalSlatHeight: function() {
6975		return this.slatContainerEl.outerHeight();
6976	},
6977
6978
6979	// Computes the top coordinate, relative to the bounds of the grid, of the given date.
6980	// A `startOfDayDate` must be given for avoiding ambiguity over how to treat midnight.
6981	computeDateTop: function(date, startOfDayDate) {
6982		return this.computeTimeTop(
6983			moment.duration(
6984				date - startOfDayDate.clone().stripTime()
6985			)
6986		);
6987	},
6988
6989
6990	// Computes the top coordinate, relative to the bounds of the grid, of the given time (a Duration).
6991	computeTimeTop: function(time) {
6992		var len = this.slatEls.length;
6993		var slatCoverage = (time - this.minTime) / this.slotDuration; // floating-point value of # of slots covered
6994		var slatIndex;
6995		var slatRemainder;
6996
6997		// compute a floating-point number for how many slats should be progressed through.
6998		// from 0 to number of slats (inclusive)
6999		// constrained because minTime/maxTime might be customized.
7000		slatCoverage = Math.max(0, slatCoverage);
7001		slatCoverage = Math.min(len, slatCoverage);
7002
7003		// an integer index of the furthest whole slat
7004		// from 0 to number slats (*exclusive*, so len-1)
7005		slatIndex = Math.floor(slatCoverage);
7006		slatIndex = Math.min(slatIndex, len - 1);
7007
7008		// how much further through the slatIndex slat (from 0.0-1.0) must be covered in addition.
7009		// could be 1.0 if slatCoverage is covering *all* the slots
7010		slatRemainder = slatCoverage - slatIndex;
7011
7012		return this.slatCoordCache.getTopPosition(slatIndex) +
7013			this.slatCoordCache.getHeight(slatIndex) * slatRemainder;
7014	},
7015
7016
7017
7018	/* Event Drag Visualization
7019	------------------------------------------------------------------------------------------------------------------*/
7020
7021
7022	// Renders a visual indication of an event being dragged over the specified date(s).
7023	// A returned value of `true` signals that a mock "helper" event has been rendered.
7024	renderDrag: function(eventLocation, seg) {
7025
7026		if (seg) { // if there is event information for this drag, render a helper event
7027
7028			// returns mock event elements
7029			// signal that a helper has been rendered
7030			return this.renderEventLocationHelper(eventLocation, seg);
7031		}
7032		else {
7033			// otherwise, just render a highlight
7034			this.renderHighlight(this.eventToSpan(eventLocation));
7035		}
7036	},
7037
7038
7039	// Unrenders any visual indication of an event being dragged
7040	unrenderDrag: function() {
7041		this.unrenderHelper();
7042		this.unrenderHighlight();
7043	},
7044
7045
7046	/* Event Resize Visualization
7047	------------------------------------------------------------------------------------------------------------------*/
7048
7049
7050	// Renders a visual indication of an event being resized
7051	renderEventResize: function(eventLocation, seg) {
7052		return this.renderEventLocationHelper(eventLocation, seg); // returns mock event elements
7053	},
7054
7055
7056	// Unrenders any visual indication of an event being resized
7057	unrenderEventResize: function() {
7058		this.unrenderHelper();
7059	},
7060
7061
7062	/* Event Helper
7063	------------------------------------------------------------------------------------------------------------------*/
7064
7065
7066	// Renders a mock "helper" event. `sourceSeg` is the original segment object and might be null (an external drag)
7067	renderHelper: function(event, sourceSeg) {
7068		return this.renderHelperSegs(this.eventToSegs(event), sourceSeg); // returns mock event elements
7069	},
7070
7071
7072	// Unrenders any mock helper event
7073	unrenderHelper: function() {
7074		this.unrenderHelperSegs();
7075	},
7076
7077
7078	/* Business Hours
7079	------------------------------------------------------------------------------------------------------------------*/
7080
7081
7082	renderBusinessHours: function() {
7083		this.renderBusinessSegs(
7084			this.buildBusinessHourSegs()
7085		);
7086	},
7087
7088
7089	unrenderBusinessHours: function() {
7090		this.unrenderBusinessSegs();
7091	},
7092
7093
7094	/* Now Indicator
7095	------------------------------------------------------------------------------------------------------------------*/
7096
7097
7098	getNowIndicatorUnit: function() {
7099		return 'minute'; // will refresh on the minute
7100	},
7101
7102
7103	renderNowIndicator: function(date) {
7104		// seg system might be overkill, but it handles scenario where line needs to be rendered
7105		//  more than once because of columns with the same date (resources columns for example)
7106		var segs = this.spanToSegs({ start: date, end: date });
7107		var top = this.computeDateTop(date, date);
7108		var nodes = [];
7109		var i;
7110
7111		// render lines within the columns
7112		for (i = 0; i < segs.length; i++) {
7113			nodes.push($('<div class="fc-now-indicator fc-now-indicator-line"></div>')
7114				.css('top', top)
7115				.appendTo(this.colContainerEls.eq(segs[i].col))[0]);
7116		}
7117
7118		// render an arrow over the axis
7119		if (segs.length > 0) { // is the current time in view?
7120			nodes.push($('<div class="fc-now-indicator fc-now-indicator-arrow"></div>')
7121				.css('top', top)
7122				.appendTo(this.el.find('.fc-content-skeleton'))[0]);
7123		}
7124
7125		this.nowIndicatorEls = $(nodes);
7126	},
7127
7128
7129	unrenderNowIndicator: function() {
7130		if (this.nowIndicatorEls) {
7131			this.nowIndicatorEls.remove();
7132			this.nowIndicatorEls = null;
7133		}
7134	},
7135
7136
7137	/* Selection
7138	------------------------------------------------------------------------------------------------------------------*/
7139
7140
7141	// Renders a visual indication of a selection. Overrides the default, which was to simply render a highlight.
7142	renderSelection: function(span) {
7143		if (this.view.opt('selectHelper')) { // this setting signals that a mock helper event should be rendered
7144
7145			// normally acceps an eventLocation, span has a start/end, which is good enough
7146			this.renderEventLocationHelper(span);
7147		}
7148		else {
7149			this.renderHighlight(span);
7150		}
7151	},
7152
7153
7154	// Unrenders any visual indication of a selection
7155	unrenderSelection: function() {
7156		this.unrenderHelper();
7157		this.unrenderHighlight();
7158	},
7159
7160
7161	/* Highlight
7162	------------------------------------------------------------------------------------------------------------------*/
7163
7164
7165	renderHighlight: function(span) {
7166		this.renderHighlightSegs(this.spanToSegs(span));
7167	},
7168
7169
7170	unrenderHighlight: function() {
7171		this.unrenderHighlightSegs();
7172	}
7173
7174});
7175
7176;;
7177
7178/* Methods for rendering SEGMENTS, pieces of content that live on the view
7179 ( this file is no longer just for events )
7180----------------------------------------------------------------------------------------------------------------------*/
7181
7182TimeGrid.mixin({
7183
7184	colContainerEls: null, // containers for each column
7185
7186	// inner-containers for each column where different types of segs live
7187	fgContainerEls: null,
7188	bgContainerEls: null,
7189	helperContainerEls: null,
7190	highlightContainerEls: null,
7191	businessContainerEls: null,
7192
7193	// arrays of different types of displayed segments
7194	fgSegs: null,
7195	bgSegs: null,
7196	helperSegs: null,
7197	highlightSegs: null,
7198	businessSegs: null,
7199
7200
7201	// Renders the DOM that the view's content will live in
7202	renderContentSkeleton: function() {
7203		var cellHtml = '';
7204		var i;
7205		var skeletonEl;
7206
7207		for (i = 0; i < this.colCnt; i++) {
7208			cellHtml +=
7209				'<td>' +
7210					'<div class="fc-content-col">' +
7211						'<div class="fc-event-container fc-helper-container"></div>' +
7212						'<div class="fc-event-container"></div>' +
7213						'<div class="fc-highlight-container"></div>' +
7214						'<div class="fc-bgevent-container"></div>' +
7215						'<div class="fc-business-container"></div>' +
7216					'</div>' +
7217				'</td>';
7218		}
7219
7220		skeletonEl = $(
7221			'<div class="fc-content-skeleton">' +
7222				'<table>' +
7223					'<tr>' + cellHtml + '</tr>' +
7224				'</table>' +
7225			'</div>'
7226		);
7227
7228		this.colContainerEls = skeletonEl.find('.fc-content-col');
7229		this.helperContainerEls = skeletonEl.find('.fc-helper-container');
7230		this.fgContainerEls = skeletonEl.find('.fc-event-container:not(.fc-helper-container)');
7231		this.bgContainerEls = skeletonEl.find('.fc-bgevent-container');
7232		this.highlightContainerEls = skeletonEl.find('.fc-highlight-container');
7233		this.businessContainerEls = skeletonEl.find('.fc-business-container');
7234
7235		this.bookendCells(skeletonEl.find('tr')); // TODO: do this on string level
7236		this.el.append(skeletonEl);
7237	},
7238
7239
7240	/* Foreground Events
7241	------------------------------------------------------------------------------------------------------------------*/
7242
7243
7244	renderFgSegs: function(segs) {
7245		segs = this.renderFgSegsIntoContainers(segs, this.fgContainerEls);
7246		this.fgSegs = segs;
7247		return segs; // needed for Grid::renderEvents
7248	},
7249
7250
7251	unrenderFgSegs: function() {
7252		this.unrenderNamedSegs('fgSegs');
7253	},
7254
7255
7256	/* Foreground Helper Events
7257	------------------------------------------------------------------------------------------------------------------*/
7258
7259
7260	renderHelperSegs: function(segs, sourceSeg) {
7261		var helperEls = [];
7262		var i, seg;
7263		var sourceEl;
7264
7265		segs = this.renderFgSegsIntoContainers(segs, this.helperContainerEls);
7266
7267		// Try to make the segment that is in the same row as sourceSeg look the same
7268		for (i = 0; i < segs.length; i++) {
7269			seg = segs[i];
7270			if (sourceSeg && sourceSeg.col === seg.col) {
7271				sourceEl = sourceSeg.el;
7272				seg.el.css({
7273					left: sourceEl.css('left'),
7274					right: sourceEl.css('right'),
7275					'margin-left': sourceEl.css('margin-left'),
7276					'margin-right': sourceEl.css('margin-right')
7277				});
7278			}
7279			helperEls.push(seg.el[0]);
7280		}
7281
7282		this.helperSegs = segs;
7283
7284		return $(helperEls); // must return rendered helpers
7285	},
7286
7287
7288	unrenderHelperSegs: function() {
7289		this.unrenderNamedSegs('helperSegs');
7290	},
7291
7292
7293	/* Background Events
7294	------------------------------------------------------------------------------------------------------------------*/
7295
7296
7297	renderBgSegs: function(segs) {
7298		segs = this.renderFillSegEls('bgEvent', segs); // TODO: old fill system
7299		this.updateSegVerticals(segs);
7300		this.attachSegsByCol(this.groupSegsByCol(segs), this.bgContainerEls);
7301		this.bgSegs = segs;
7302		return segs; // needed for Grid::renderEvents
7303	},
7304
7305
7306	unrenderBgSegs: function() {
7307		this.unrenderNamedSegs('bgSegs');
7308	},
7309
7310
7311	/* Highlight
7312	------------------------------------------------------------------------------------------------------------------*/
7313
7314
7315	renderHighlightSegs: function(segs) {
7316		segs = this.renderFillSegEls('highlight', segs); // TODO: old fill system
7317		this.updateSegVerticals(segs);
7318		this.attachSegsByCol(this.groupSegsByCol(segs), this.highlightContainerEls);
7319		this.highlightSegs = segs;
7320	},
7321
7322
7323	unrenderHighlightSegs: function() {
7324		this.unrenderNamedSegs('highlightSegs');
7325	},
7326
7327
7328	/* Business Hours
7329	------------------------------------------------------------------------------------------------------------------*/
7330
7331
7332	renderBusinessSegs: function(segs) {
7333		segs = this.renderFillSegEls('businessHours', segs); // TODO: old fill system
7334		this.updateSegVerticals(segs);
7335		this.attachSegsByCol(this.groupSegsByCol(segs), this.businessContainerEls);
7336		this.businessSegs = segs;
7337	},
7338
7339
7340	unrenderBusinessSegs: function() {
7341		this.unrenderNamedSegs('businessSegs');
7342	},
7343
7344
7345	/* Seg Rendering Utils
7346	------------------------------------------------------------------------------------------------------------------*/
7347
7348
7349	// Given a flat array of segments, return an array of sub-arrays, grouped by each segment's col
7350	groupSegsByCol: function(segs) {
7351		var segsByCol = [];
7352		var i;
7353
7354		for (i = 0; i < this.colCnt; i++) {
7355			segsByCol.push([]);
7356		}
7357
7358		for (i = 0; i < segs.length; i++) {
7359			segsByCol[segs[i].col].push(segs[i]);
7360		}
7361
7362		return segsByCol;
7363	},
7364
7365
7366	// Given segments grouped by column, insert the segments' elements into a parallel array of container
7367	// elements, each living within a column.
7368	attachSegsByCol: function(segsByCol, containerEls) {
7369		var col;
7370		var segs;
7371		var i;
7372
7373		for (col = 0; col < this.colCnt; col++) { // iterate each column grouping
7374			segs = segsByCol[col];
7375
7376			for (i = 0; i < segs.length; i++) {
7377				containerEls.eq(col).append(segs[i].el);
7378			}
7379		}
7380	},
7381
7382
7383	// Given the name of a property of `this` object, assumed to be an array of segments,
7384	// loops through each segment and removes from DOM. Will null-out the property afterwards.
7385	unrenderNamedSegs: function(propName) {
7386		var segs = this[propName];
7387		var i;
7388
7389		if (segs) {
7390			for (i = 0; i < segs.length; i++) {
7391				segs[i].el.remove();
7392			}
7393			this[propName] = null;
7394		}
7395	},
7396
7397
7398
7399	/* Foreground Event Rendering Utils
7400	------------------------------------------------------------------------------------------------------------------*/
7401
7402
7403	// Given an array of foreground segments, render a DOM element for each, computes position,
7404	// and attaches to the column inner-container elements.
7405	renderFgSegsIntoContainers: function(segs, containerEls) {
7406		var segsByCol;
7407		var col;
7408
7409		segs = this.renderFgSegEls(segs); // will call fgSegHtml
7410		segsByCol = this.groupSegsByCol(segs);
7411
7412		for (col = 0; col < this.colCnt; col++) {
7413			this.updateFgSegCoords(segsByCol[col]);
7414		}
7415
7416		this.attachSegsByCol(segsByCol, containerEls);
7417
7418		return segs;
7419	},
7420
7421
7422	// Renders the HTML for a single event segment's default rendering
7423	fgSegHtml: function(seg, disableResizing) {
7424		var view = this.view;
7425		var event = seg.event;
7426		var isDraggable = view.isEventDraggable(event);
7427		var isResizableFromStart = !disableResizing && seg.isStart && view.isEventResizableFromStart(event);
7428		var isResizableFromEnd = !disableResizing && seg.isEnd && view.isEventResizableFromEnd(event);
7429		var classes = this.getSegClasses(seg, isDraggable, isResizableFromStart || isResizableFromEnd);
7430		var skinCss = cssToStr(this.getSegSkinCss(seg));
7431		var timeText;
7432		var fullTimeText; // more verbose time text. for the print stylesheet
7433		var startTimeText; // just the start time text
7434
7435		classes.unshift('fc-time-grid-event', 'fc-v-event');
7436
7437		if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day...
7438			// Don't display time text on segments that run entirely through a day.
7439			// That would appear as midnight-midnight and would look dumb.
7440			// Otherwise, display the time text for the *segment's* times (like 6pm-midnight or midnight-10am)
7441			if (seg.isStart || seg.isEnd) {
7442				timeText = this.getEventTimeText(seg);
7443				fullTimeText = this.getEventTimeText(seg, 'LT');
7444				startTimeText = this.getEventTimeText(seg, null, false); // displayEnd=false
7445			}
7446		} else {
7447			// Display the normal time text for the *event's* times
7448			timeText = this.getEventTimeText(event);
7449			fullTimeText = this.getEventTimeText(event, 'LT');
7450			startTimeText = this.getEventTimeText(event, null, false); // displayEnd=false
7451		}
7452
7453		return '<a class="' + classes.join(' ') + '"' +
7454			(event.url ?
7455				' href="' + htmlEscape(event.url) + '"' :
7456				''
7457				) +
7458			(skinCss ?
7459				' style="' + skinCss + '"' :
7460				''
7461				) +
7462			'>' +
7463				'<div class="fc-content">' +
7464					(timeText ?
7465						'<div class="fc-time"' +
7466						' data-start="' + htmlEscape(startTimeText) + '"' +
7467						' data-full="' + htmlEscape(fullTimeText) + '"' +
7468						'>' +
7469							'<span>' + htmlEscape(timeText) + '</span>' +
7470						'</div>' :
7471						''
7472						) +
7473					(event.title ?
7474						'<div class="fc-title">' +
7475							htmlEscape(event.title) +
7476						'</div>' :
7477						''
7478						) +
7479				'</div>' +
7480				'<div class="fc-bg"/>' +
7481				/* TODO: write CSS for this
7482				(isResizableFromStart ?
7483					'<div class="fc-resizer fc-start-resizer" />' :
7484					''
7485					) +
7486				*/
7487				(isResizableFromEnd ?
7488					'<div class="fc-resizer fc-end-resizer" />' :
7489					''
7490					) +
7491			'</a>';
7492	},
7493
7494
7495	/* Seg Position Utils
7496	------------------------------------------------------------------------------------------------------------------*/
7497
7498
7499	// Refreshes the CSS top/bottom coordinates for each segment element.
7500	// Works when called after initial render, after a window resize/zoom for example.
7501	updateSegVerticals: function(segs) {
7502		this.computeSegVerticals(segs);
7503		this.assignSegVerticals(segs);
7504	},
7505
7506
7507	// For each segment in an array, computes and assigns its top and bottom properties
7508	computeSegVerticals: function(segs) {
7509		var i, seg;
7510
7511		for (i = 0; i < segs.length; i++) {
7512			seg = segs[i];
7513			seg.top = this.computeDateTop(seg.start, seg.start);
7514			seg.bottom = this.computeDateTop(seg.end, seg.start);
7515		}
7516	},
7517
7518
7519	// Given segments that already have their top/bottom properties computed, applies those values to
7520	// the segments' elements.
7521	assignSegVerticals: function(segs) {
7522		var i, seg;
7523
7524		for (i = 0; i < segs.length; i++) {
7525			seg = segs[i];
7526			seg.el.css(this.generateSegVerticalCss(seg));
7527		}
7528	},
7529
7530
7531	// Generates an object with CSS properties for the top/bottom coordinates of a segment element
7532	generateSegVerticalCss: function(seg) {
7533		return {
7534			top: seg.top,
7535			bottom: -seg.bottom // flipped because needs to be space beyond bottom edge of event container
7536		};
7537	},
7538
7539
7540	/* Foreground Event Positioning Utils
7541	------------------------------------------------------------------------------------------------------------------*/
7542
7543
7544	// Given segments that are assumed to all live in the *same column*,
7545	// compute their verical/horizontal coordinates and assign to their elements.
7546	updateFgSegCoords: function(segs) {
7547		this.computeSegVerticals(segs); // horizontals relies on this
7548		this.computeFgSegHorizontals(segs); // compute horizontal coordinates, z-index's, and reorder the array
7549		this.assignSegVerticals(segs);
7550		this.assignFgSegHorizontals(segs);
7551	},
7552
7553
7554	// Given an array of segments that are all in the same column, sets the backwardCoord and forwardCoord on each.
7555	// NOTE: Also reorders the given array by date!
7556	computeFgSegHorizontals: function(segs) {
7557		var levels;
7558		var level0;
7559		var i;
7560
7561		this.sortEventSegs(segs); // order by certain criteria
7562		levels = buildSlotSegLevels(segs);
7563		computeForwardSlotSegs(levels);
7564
7565		if ((level0 = levels[0])) {
7566
7567			for (i = 0; i < level0.length; i++) {
7568				computeSlotSegPressures(level0[i]);
7569			}
7570
7571			for (i = 0; i < level0.length; i++) {
7572				this.computeFgSegForwardBack(level0[i], 0, 0);
7573			}
7574		}
7575	},
7576
7577
7578	// Calculate seg.forwardCoord and seg.backwardCoord for the segment, where both values range
7579	// from 0 to 1. If the calendar is left-to-right, the seg.backwardCoord maps to "left" and
7580	// seg.forwardCoord maps to "right" (via percentage). Vice-versa if the calendar is right-to-left.
7581	//
7582	// The segment might be part of a "series", which means consecutive segments with the same pressure
7583	// who's width is unknown until an edge has been hit. `seriesBackwardPressure` is the number of
7584	// segments behind this one in the current series, and `seriesBackwardCoord` is the starting
7585	// coordinate of the first segment in the series.
7586	computeFgSegForwardBack: function(seg, seriesBackwardPressure, seriesBackwardCoord) {
7587		var forwardSegs = seg.forwardSegs;
7588		var i;
7589
7590		if (seg.forwardCoord === undefined) { // not already computed
7591
7592			if (!forwardSegs.length) {
7593
7594				// if there are no forward segments, this segment should butt up against the edge
7595				seg.forwardCoord = 1;
7596			}
7597			else {
7598
7599				// sort highest pressure first
7600				this.sortForwardSegs(forwardSegs);
7601
7602				// this segment's forwardCoord will be calculated from the backwardCoord of the
7603				// highest-pressure forward segment.
7604				this.computeFgSegForwardBack(forwardSegs[0], seriesBackwardPressure + 1, seriesBackwardCoord);
7605				seg.forwardCoord = forwardSegs[0].backwardCoord;
7606			}
7607
7608			// calculate the backwardCoord from the forwardCoord. consider the series
7609			seg.backwardCoord = seg.forwardCoord -
7610				(seg.forwardCoord - seriesBackwardCoord) / // available width for series
7611				(seriesBackwardPressure + 1); // # of segments in the series
7612
7613			// use this segment's coordinates to computed the coordinates of the less-pressurized
7614			// forward segments
7615			for (i=0; i<forwardSegs.length; i++) {
7616				this.computeFgSegForwardBack(forwardSegs[i], 0, seg.forwardCoord);
7617			}
7618		}
7619	},
7620
7621
7622	sortForwardSegs: function(forwardSegs) {
7623		forwardSegs.sort(proxy(this, 'compareForwardSegs'));
7624	},
7625
7626
7627	// A cmp function for determining which forward segment to rely on more when computing coordinates.
7628	compareForwardSegs: function(seg1, seg2) {
7629		// put higher-pressure first
7630		return seg2.forwardPressure - seg1.forwardPressure ||
7631			// put segments that are closer to initial edge first (and favor ones with no coords yet)
7632			(seg1.backwardCoord || 0) - (seg2.backwardCoord || 0) ||
7633			// do normal sorting...
7634			this.compareEventSegs(seg1, seg2);
7635	},
7636
7637
7638	// Given foreground event segments that have already had their position coordinates computed,
7639	// assigns position-related CSS values to their elements.
7640	assignFgSegHorizontals: function(segs) {
7641		var i, seg;
7642
7643		for (i = 0; i < segs.length; i++) {
7644			seg = segs[i];
7645			seg.el.css(this.generateFgSegHorizontalCss(seg));
7646
7647			// if the height is short, add a className for alternate styling
7648			if (seg.bottom - seg.top < 30) {
7649				seg.el.addClass('fc-short');
7650			}
7651		}
7652	},
7653
7654
7655	// Generates an object with CSS properties/values that should be applied to an event segment element.
7656	// Contains important positioning-related properties that should be applied to any event element, customized or not.
7657	generateFgSegHorizontalCss: function(seg) {
7658		var shouldOverlap = this.view.opt('slotEventOverlap');
7659		var backwardCoord = seg.backwardCoord; // the left side if LTR. the right side if RTL. floating-point
7660		var forwardCoord = seg.forwardCoord; // the right side if LTR. the left side if RTL. floating-point
7661		var props = this.generateSegVerticalCss(seg); // get top/bottom first
7662		var left; // amount of space from left edge, a fraction of the total width
7663		var right; // amount of space from right edge, a fraction of the total width
7664
7665		if (shouldOverlap) {
7666			// double the width, but don't go beyond the maximum forward coordinate (1.0)
7667			forwardCoord = Math.min(1, backwardCoord + (forwardCoord - backwardCoord) * 2);
7668		}
7669
7670		if (this.isRTL) {
7671			left = 1 - forwardCoord;
7672			right = backwardCoord;
7673		}
7674		else {
7675			left = backwardCoord;
7676			right = 1 - forwardCoord;
7677		}
7678
7679		props.zIndex = seg.level + 1; // convert from 0-base to 1-based
7680		props.left = left * 100 + '%';
7681		props.right = right * 100 + '%';
7682
7683		if (shouldOverlap && seg.forwardPressure) {
7684			// add padding to the edge so that forward stacked events don't cover the resizer's icon
7685			props[this.isRTL ? 'marginLeft' : 'marginRight'] = 10 * 2; // 10 is a guesstimate of the icon's width
7686		}
7687
7688		return props;
7689	}
7690
7691});
7692
7693
7694// Builds an array of segments "levels". The first level will be the leftmost tier of segments if the calendar is
7695// left-to-right, or the rightmost if the calendar is right-to-left. Assumes the segments are already ordered by date.
7696function buildSlotSegLevels(segs) {
7697	var levels = [];
7698	var i, seg;
7699	var j;
7700
7701	for (i=0; i<segs.length; i++) {
7702		seg = segs[i];
7703
7704		// go through all the levels and stop on the first level where there are no collisions
7705		for (j=0; j<levels.length; j++) {
7706			if (!computeSlotSegCollisions(seg, levels[j]).length) {
7707				break;
7708			}
7709		}
7710
7711		seg.level = j;
7712
7713		(levels[j] || (levels[j] = [])).push(seg);
7714	}
7715
7716	return levels;
7717}
7718
7719
7720// For every segment, figure out the other segments that are in subsequent
7721// levels that also occupy the same vertical space. Accumulate in seg.forwardSegs
7722function computeForwardSlotSegs(levels) {
7723	var i, level;
7724	var j, seg;
7725	var k;
7726
7727	for (i=0; i<levels.length; i++) {
7728		level = levels[i];
7729
7730		for (j=0; j<level.length; j++) {
7731			seg = level[j];
7732
7733			seg.forwardSegs = [];
7734			for (k=i+1; k<levels.length; k++) {
7735				computeSlotSegCollisions(seg, levels[k], seg.forwardSegs);
7736			}
7737		}
7738	}
7739}
7740
7741
7742// Figure out which path forward (via seg.forwardSegs) results in the longest path until
7743// the furthest edge is reached. The number of segments in this path will be seg.forwardPressure
7744function computeSlotSegPressures(seg) {
7745	var forwardSegs = seg.forwardSegs;
7746	var forwardPressure = 0;
7747	var i, forwardSeg;
7748
7749	if (seg.forwardPressure === undefined) { // not already computed
7750
7751		for (i=0; i<forwardSegs.length; i++) {
7752			forwardSeg = forwardSegs[i];
7753
7754			// figure out the child's maximum forward path
7755			computeSlotSegPressures(forwardSeg);
7756
7757			// either use the existing maximum, or use the child's forward pressure
7758			// plus one (for the forwardSeg itself)
7759			forwardPressure = Math.max(
7760				forwardPressure,
7761				1 + forwardSeg.forwardPressure
7762			);
7763		}
7764
7765		seg.forwardPressure = forwardPressure;
7766	}
7767}
7768
7769
7770// Find all the segments in `otherSegs` that vertically collide with `seg`.
7771// Append into an optionally-supplied `results` array and return.
7772function computeSlotSegCollisions(seg, otherSegs, results) {
7773	results = results || [];
7774
7775	for (var i=0; i<otherSegs.length; i++) {
7776		if (isSlotSegCollision(seg, otherSegs[i])) {
7777			results.push(otherSegs[i]);
7778		}
7779	}
7780
7781	return results;
7782}
7783
7784
7785// Do these segments occupy the same vertical space?
7786function isSlotSegCollision(seg1, seg2) {
7787	return seg1.bottom > seg2.top && seg1.top < seg2.bottom;
7788}
7789
7790;;
7791
7792/* An abstract class from which other views inherit from
7793----------------------------------------------------------------------------------------------------------------------*/
7794
7795var View = FC.View = Class.extend(EmitterMixin, ListenerMixin, {
7796
7797	type: null, // subclass' view name (string)
7798	name: null, // deprecated. use `type` instead
7799	title: null, // the text that will be displayed in the header's title
7800
7801	calendar: null, // owner Calendar object
7802	options: null, // hash containing all options. already merged with view-specific-options
7803	el: null, // the view's containing element. set by Calendar
7804
7805	displaying: null, // a promise representing the state of rendering. null if no render requested
7806	isSkeletonRendered: false,
7807	isEventsRendered: false,
7808
7809	// range the view is actually displaying (moments)
7810	start: null,
7811	end: null, // exclusive
7812
7813	// range the view is formally responsible for (moments)
7814	// may be different from start/end. for example, a month view might have 1st-31st, excluding padded dates
7815	intervalStart: null,
7816	intervalEnd: null, // exclusive
7817	intervalDuration: null,
7818	intervalUnit: null, // name of largest unit being displayed, like "month" or "week"
7819
7820	isRTL: false,
7821	isSelected: false, // boolean whether a range of time is user-selected or not
7822	selectedEvent: null,
7823
7824	eventOrderSpecs: null, // criteria for ordering events when they have same date/time
7825
7826	// classNames styled by jqui themes
7827	widgetHeaderClass: null,
7828	widgetContentClass: null,
7829	highlightStateClass: null,
7830
7831	// for date utils, computed from options
7832	nextDayThreshold: null,
7833	isHiddenDayHash: null,
7834
7835	// now indicator
7836	isNowIndicatorRendered: null,
7837	initialNowDate: null, // result first getNow call
7838	initialNowQueriedMs: null, // ms time the getNow was called
7839	nowIndicatorTimeoutID: null, // for refresh timing of now indicator
7840	nowIndicatorIntervalID: null, // "
7841
7842
7843	constructor: function(calendar, type, options, intervalDuration) {
7844
7845		this.calendar = calendar;
7846		this.type = this.name = type; // .name is deprecated
7847		this.options = options;
7848		this.intervalDuration = intervalDuration || moment.duration(1, 'day');
7849
7850		this.nextDayThreshold = moment.duration(this.opt('nextDayThreshold'));
7851		this.initThemingProps();
7852		this.initHiddenDays();
7853		this.isRTL = this.opt('isRTL');
7854
7855		this.eventOrderSpecs = parseFieldSpecs(this.opt('eventOrder'));
7856
7857		this.initialize();
7858	},
7859
7860
7861	// A good place for subclasses to initialize member variables
7862	initialize: function() {
7863		// subclasses can implement
7864	},
7865
7866
7867	// Retrieves an option with the given name
7868	opt: function(name) {
7869		return this.options[name];
7870	},
7871
7872
7873	// Triggers handlers that are view-related. Modifies args before passing to calendar.
7874	trigger: function(name, thisObj) { // arguments beyond thisObj are passed along
7875		var calendar = this.calendar;
7876
7877		return calendar.trigger.apply(
7878			calendar,
7879			[name, thisObj || this].concat(
7880				Array.prototype.slice.call(arguments, 2), // arguments beyond thisObj
7881				[ this ] // always make the last argument a reference to the view. TODO: deprecate
7882			)
7883		);
7884	},
7885
7886
7887	/* Dates
7888	------------------------------------------------------------------------------------------------------------------*/
7889
7890
7891	// Updates all internal dates to center around the given current unzoned date.
7892	setDate: function(date) {
7893		this.setRange(this.computeRange(date));
7894	},
7895
7896
7897	// Updates all internal dates for displaying the given unzoned range.
7898	setRange: function(range) {
7899		$.extend(this, range); // assigns every property to this object's member variables
7900		this.updateTitle();
7901	},
7902
7903
7904	// Given a single current unzoned date, produce information about what range to display.
7905	// Subclasses can override. Must return all properties.
7906	computeRange: function(date) {
7907		var intervalUnit = computeIntervalUnit(this.intervalDuration);
7908		var intervalStart = date.clone().startOf(intervalUnit);
7909		var intervalEnd = intervalStart.clone().add(this.intervalDuration);
7910		var start, end;
7911
7912		// normalize the range's time-ambiguity
7913		if (/year|month|week|day/.test(intervalUnit)) { // whole-days?
7914			intervalStart.stripTime();
7915			intervalEnd.stripTime();
7916		}
7917		else { // needs to have a time?
7918			if (!intervalStart.hasTime()) {
7919				intervalStart = this.calendar.time(0); // give 00:00 time
7920			}
7921			if (!intervalEnd.hasTime()) {
7922				intervalEnd = this.calendar.time(0); // give 00:00 time
7923			}
7924		}
7925
7926		start = intervalStart.clone();
7927		start = this.skipHiddenDays(start);
7928		end = intervalEnd.clone();
7929		end = this.skipHiddenDays(end, -1, true); // exclusively move backwards
7930
7931		return {
7932			intervalUnit: intervalUnit,
7933			intervalStart: intervalStart,
7934			intervalEnd: intervalEnd,
7935			start: start,
7936			end: end
7937		};
7938	},
7939
7940
7941	// Computes the new date when the user hits the prev button, given the current date
7942	computePrevDate: function(date) {
7943		return this.massageCurrentDate(
7944			date.clone().startOf(this.intervalUnit).subtract(this.intervalDuration), -1
7945		);
7946	},
7947
7948
7949	// Computes the new date when the user hits the next button, given the current date
7950	computeNextDate: function(date) {
7951		return this.massageCurrentDate(
7952			date.clone().startOf(this.intervalUnit).add(this.intervalDuration)
7953		);
7954	},
7955
7956
7957	// Given an arbitrarily calculated current date of the calendar, returns a date that is ensured to be completely
7958	// visible. `direction` is optional and indicates which direction the current date was being
7959	// incremented or decremented (1 or -1).
7960	massageCurrentDate: function(date, direction) {
7961		if (this.intervalDuration.as('days') <= 1) { // if the view displays a single day or smaller
7962			if (this.isHiddenDay(date)) {
7963				date = this.skipHiddenDays(date, direction);
7964				date.startOf('day');
7965			}
7966		}
7967
7968		return date;
7969	},
7970
7971
7972	/* Title and Date Formatting
7973	------------------------------------------------------------------------------------------------------------------*/
7974
7975
7976	// Sets the view's title property to the most updated computed value
7977	updateTitle: function() {
7978		this.title = this.computeTitle();
7979	},
7980
7981
7982	// Computes what the title at the top of the calendar should be for this view
7983	computeTitle: function() {
7984		return this.formatRange(
7985			{
7986				// in case intervalStart/End has a time, make sure timezone is correct
7987				start: this.calendar.applyTimezone(this.intervalStart),
7988				end: this.calendar.applyTimezone(this.intervalEnd)
7989			},
7990			this.opt('titleFormat') || this.computeTitleFormat(),
7991			this.opt('titleRangeSeparator')
7992		);
7993	},
7994
7995
7996	// Generates the format string that should be used to generate the title for the current date range.
7997	// Attempts to compute the most appropriate format if not explicitly specified with `titleFormat`.
7998	computeTitleFormat: function() {
7999		if (this.intervalUnit == 'year') {
8000			return 'YYYY';
8001		}
8002		else if (this.intervalUnit == 'month') {
8003			return this.opt('monthYearFormat'); // like "September 2014"
8004		}
8005		else if (this.intervalDuration.as('days') > 1) {
8006			return 'll'; // multi-day range. shorter, like "Sep 9 - 10 2014"
8007		}
8008		else {
8009			return 'LL'; // one day. longer, like "September 9 2014"
8010		}
8011	},
8012
8013
8014	// Utility for formatting a range. Accepts a range object, formatting string, and optional separator.
8015	// Displays all-day ranges naturally, with an inclusive end. Takes the current isRTL into account.
8016	// The timezones of the dates within `range` will be respected.
8017	formatRange: function(range, formatStr, separator) {
8018		var end = range.end;
8019
8020		if (!end.hasTime()) { // all-day?
8021			end = end.clone().subtract(1); // convert to inclusive. last ms of previous day
8022		}
8023
8024		return formatRange(range.start, end, formatStr, separator, this.opt('isRTL'));
8025	},
8026
8027
8028	getAllDayHtml: function() {
8029		return this.opt('allDayHtml') || htmlEscape(this.opt('allDayText'));
8030	},
8031
8032
8033	/* Navigation
8034	------------------------------------------------------------------------------------------------------------------*/
8035
8036
8037	// Generates HTML for an anchor to another view into the calendar.
8038	// Will either generate an <a> tag or a non-clickable <span> tag, depending on enabled settings.
8039	// `gotoOptions` can either be a moment input, or an object with the form:
8040	// { date, type, forceOff }
8041	// `type` is a view-type like "day" or "week". default value is "day".
8042	// `attrs` and `innerHtml` are use to generate the rest of the HTML tag.
8043	buildGotoAnchorHtml: function(gotoOptions, attrs, innerHtml) {
8044		var date, type, forceOff;
8045		var finalOptions;
8046
8047		if ($.isPlainObject(gotoOptions)) {
8048			date = gotoOptions.date;
8049			type = gotoOptions.type;
8050			forceOff = gotoOptions.forceOff;
8051		}
8052		else {
8053			date = gotoOptions; // a single moment input
8054		}
8055		date = FC.moment(date); // if a string, parse it
8056
8057		finalOptions = { // for serialization into the link
8058			date: date.format('YYYY-MM-DD'),
8059			type: type || 'day'
8060		};
8061
8062		if (typeof attrs === 'string') {
8063			innerHtml = attrs;
8064			attrs = null;
8065		}
8066
8067		attrs = attrs ? ' ' + attrsToStr(attrs) : ''; // will have a leading space
8068		innerHtml = innerHtml || '';
8069
8070		if (!forceOff && this.opt('navLinks')) {
8071			return '<a' + attrs +
8072				' data-goto="' + htmlEscape(JSON.stringify(finalOptions)) + '">' +
8073				innerHtml +
8074				'</a>';
8075		}
8076		else {
8077			return '<span' + attrs + '>' +
8078				innerHtml +
8079				'</span>';
8080		}
8081	},
8082
8083
8084	/* Rendering
8085	------------------------------------------------------------------------------------------------------------------*/
8086
8087
8088	// Sets the container element that the view should render inside of.
8089	// Does other DOM-related initializations.
8090	setElement: function(el) {
8091		this.el = el;
8092		this.bindGlobalHandlers();
8093	},
8094
8095
8096	// Removes the view's container element from the DOM, clearing any content beforehand.
8097	// Undoes any other DOM-related attachments.
8098	removeElement: function() {
8099		this.clear(); // clears all content
8100
8101		// clean up the skeleton
8102		if (this.isSkeletonRendered) {
8103			this.unrenderSkeleton();
8104			this.isSkeletonRendered = false;
8105		}
8106
8107		this.unbindGlobalHandlers();
8108
8109		this.el.remove();
8110
8111		// NOTE: don't null-out this.el in case the View was destroyed within an API callback.
8112		// We don't null-out the View's other jQuery element references upon destroy,
8113		//  so we shouldn't kill this.el either.
8114	},
8115
8116
8117	// Does everything necessary to display the view centered around the given unzoned date.
8118	// Does every type of rendering EXCEPT rendering events.
8119	// Is asychronous and returns a promise.
8120	display: function(date, explicitScrollState) {
8121		var _this = this;
8122		var prevScrollState = null;
8123
8124		if (explicitScrollState != null && this.displaying) { // don't need prevScrollState if explicitScrollState
8125			prevScrollState = this.queryScroll();
8126		}
8127
8128		this.calendar.freezeContentHeight();
8129
8130		return syncThen(this.clear(), function() { // clear the content first
8131			return (
8132				_this.displaying =
8133					syncThen(_this.displayView(date), function() { // displayView might return a promise
8134
8135						// caller of display() wants a specific scroll state?
8136						if (explicitScrollState != null) {
8137							// we make an assumption that this is NOT the initial render,
8138							// and thus don't need forceScroll (is inconveniently asynchronous)
8139							_this.setScroll(explicitScrollState);
8140						}
8141						else {
8142							_this.forceScroll(_this.computeInitialScroll(prevScrollState));
8143						}
8144
8145						_this.calendar.unfreezeContentHeight();
8146						_this.triggerRender();
8147					})
8148			);
8149		});
8150	},
8151
8152
8153	// Does everything necessary to clear the content of the view.
8154	// Clears dates and events. Does not clear the skeleton.
8155	// Is asychronous and returns a promise.
8156	clear: function() {
8157		var _this = this;
8158		var displaying = this.displaying;
8159
8160		if (displaying) { // previously displayed, or in the process of being displayed?
8161			return syncThen(displaying, function() { // wait for the display to finish
8162				_this.displaying = null;
8163				_this.clearEvents();
8164				return _this.clearView(); // might return a promise. chain it
8165			});
8166		}
8167		else {
8168			return $.when(); // an immediately-resolved promise
8169		}
8170	},
8171
8172
8173	// Displays the view's non-event content, such as date-related content or anything required by events.
8174	// Renders the view's non-content skeleton if necessary.
8175	// Can be asynchronous and return a promise.
8176	displayView: function(date) {
8177		if (!this.isSkeletonRendered) {
8178			this.renderSkeleton();
8179			this.isSkeletonRendered = true;
8180		}
8181		if (date) {
8182			this.setDate(date);
8183		}
8184		if (this.render) {
8185			this.render(); // TODO: deprecate
8186		}
8187		this.renderDates();
8188		this.updateSize();
8189		this.renderBusinessHours(); // might need coordinates, so should go after updateSize()
8190		this.startNowIndicator();
8191	},
8192
8193
8194	// Unrenders the view content that was rendered in displayView.
8195	// Can be asynchronous and return a promise.
8196	clearView: function() {
8197		this.unselect();
8198		this.stopNowIndicator();
8199		this.triggerUnrender();
8200		this.unrenderBusinessHours();
8201		this.unrenderDates();
8202		if (this.destroy) {
8203			this.destroy(); // TODO: deprecate
8204		}
8205	},
8206
8207
8208	// Renders the basic structure of the view before any content is rendered
8209	renderSkeleton: function() {
8210		// subclasses should implement
8211	},
8212
8213
8214	// Unrenders the basic structure of the view
8215	unrenderSkeleton: function() {
8216		// subclasses should implement
8217	},
8218
8219
8220	// Renders the view's date-related content.
8221	// Assumes setRange has already been called and the skeleton has already been rendered.
8222	renderDates: function() {
8223		// subclasses should implement
8224	},
8225
8226
8227	// Unrenders the view's date-related content
8228	unrenderDates: function() {
8229		// subclasses should override
8230	},
8231
8232
8233	// Signals that the view's content has been rendered
8234	triggerRender: function() {
8235		this.trigger('viewRender', this, this, this.el);
8236	},
8237
8238
8239	// Signals that the view's content is about to be unrendered
8240	triggerUnrender: function() {
8241		this.trigger('viewDestroy', this, this, this.el);
8242	},
8243
8244
8245	// Binds DOM handlers to elements that reside outside the view container, such as the document
8246	bindGlobalHandlers: function() {
8247		this.listenTo($(document), 'mousedown', this.handleDocumentMousedown);
8248		this.listenTo($(document), 'touchstart', this.processUnselect);
8249	},
8250
8251
8252	// Unbinds DOM handlers from elements that reside outside the view container
8253	unbindGlobalHandlers: function() {
8254		this.stopListeningTo($(document));
8255	},
8256
8257
8258	// Initializes internal variables related to theming
8259	initThemingProps: function() {
8260		var tm = this.opt('theme') ? 'ui' : 'fc';
8261
8262		this.widgetHeaderClass = tm + '-widget-header';
8263		this.widgetContentClass = tm + '-widget-content';
8264		this.highlightStateClass = tm + '-state-highlight';
8265	},
8266
8267
8268	/* Business Hours
8269	------------------------------------------------------------------------------------------------------------------*/
8270
8271
8272	// Renders business-hours onto the view. Assumes updateSize has already been called.
8273	renderBusinessHours: function() {
8274		// subclasses should implement
8275	},
8276
8277
8278	// Unrenders previously-rendered business-hours
8279	unrenderBusinessHours: function() {
8280		// subclasses should implement
8281	},
8282
8283
8284	/* Now Indicator
8285	------------------------------------------------------------------------------------------------------------------*/
8286
8287
8288	// Immediately render the current time indicator and begins re-rendering it at an interval,
8289	// which is defined by this.getNowIndicatorUnit().
8290	// TODO: somehow do this for the current whole day's background too
8291	startNowIndicator: function() {
8292		var _this = this;
8293		var unit;
8294		var update;
8295		var delay; // ms wait value
8296
8297		if (this.opt('nowIndicator')) {
8298			unit = this.getNowIndicatorUnit();
8299			if (unit) {
8300				update = proxy(this, 'updateNowIndicator'); // bind to `this`
8301
8302				this.initialNowDate = this.calendar.getNow();
8303				this.initialNowQueriedMs = +new Date();
8304				this.renderNowIndicator(this.initialNowDate);
8305				this.isNowIndicatorRendered = true;
8306
8307				// wait until the beginning of the next interval
8308				delay = this.initialNowDate.clone().startOf(unit).add(1, unit) - this.initialNowDate;
8309				this.nowIndicatorTimeoutID = setTimeout(function() {
8310					_this.nowIndicatorTimeoutID = null;
8311					update();
8312					delay = +moment.duration(1, unit);
8313					delay = Math.max(100, delay); // prevent too frequent
8314					_this.nowIndicatorIntervalID = setInterval(update, delay); // update every interval
8315				}, delay);
8316			}
8317		}
8318	},
8319
8320
8321	// rerenders the now indicator, computing the new current time from the amount of time that has passed
8322	// since the initial getNow call.
8323	updateNowIndicator: function() {
8324		if (this.isNowIndicatorRendered) {
8325			this.unrenderNowIndicator();
8326			this.renderNowIndicator(
8327				this.initialNowDate.clone().add(new Date() - this.initialNowQueriedMs) // add ms
8328			);
8329		}
8330	},
8331
8332
8333	// Immediately unrenders the view's current time indicator and stops any re-rendering timers.
8334	// Won't cause side effects if indicator isn't rendered.
8335	stopNowIndicator: function() {
8336		if (this.isNowIndicatorRendered) {
8337
8338			if (this.nowIndicatorTimeoutID) {
8339				clearTimeout(this.nowIndicatorTimeoutID);
8340				this.nowIndicatorTimeoutID = null;
8341			}
8342			if (this.nowIndicatorIntervalID) {
8343				clearTimeout(this.nowIndicatorIntervalID);
8344				this.nowIndicatorIntervalID = null;
8345			}
8346
8347			this.unrenderNowIndicator();
8348			this.isNowIndicatorRendered = false;
8349		}
8350	},
8351
8352
8353	// Returns a string unit, like 'second' or 'minute' that defined how often the current time indicator
8354	// should be refreshed. If something falsy is returned, no time indicator is rendered at all.
8355	getNowIndicatorUnit: function() {
8356		// subclasses should implement
8357	},
8358
8359
8360	// Renders a current time indicator at the given datetime
8361	renderNowIndicator: function(date) {
8362		// subclasses should implement
8363	},
8364
8365
8366	// Undoes the rendering actions from renderNowIndicator
8367	unrenderNowIndicator: function() {
8368		// subclasses should implement
8369	},
8370
8371
8372	/* Dimensions
8373	------------------------------------------------------------------------------------------------------------------*/
8374
8375
8376	// Refreshes anything dependant upon sizing of the container element of the grid
8377	updateSize: function(isResize) {
8378		var scrollState;
8379
8380		if (isResize) {
8381			scrollState = this.queryScroll();
8382		}
8383
8384		this.updateHeight(isResize);
8385		this.updateWidth(isResize);
8386		this.updateNowIndicator();
8387
8388		if (isResize) {
8389			this.setScroll(scrollState);
8390		}
8391	},
8392
8393
8394	// Refreshes the horizontal dimensions of the calendar
8395	updateWidth: function(isResize) {
8396		// subclasses should implement
8397	},
8398
8399
8400	// Refreshes the vertical dimensions of the calendar
8401	updateHeight: function(isResize) {
8402		var calendar = this.calendar; // we poll the calendar for height information
8403
8404		this.setHeight(
8405			calendar.getSuggestedViewHeight(),
8406			calendar.isHeightAuto()
8407		);
8408	},
8409
8410
8411	// Updates the vertical dimensions of the calendar to the specified height.
8412	// if `isAuto` is set to true, height becomes merely a suggestion and the view should use its "natural" height.
8413	setHeight: function(height, isAuto) {
8414		// subclasses should implement
8415	},
8416
8417
8418	/* Scroller
8419	------------------------------------------------------------------------------------------------------------------*/
8420
8421
8422	// Computes the initial pre-configured scroll state prior to allowing the user to change it.
8423	// Given the scroll state from the previous rendering. If first time rendering, given null.
8424	computeInitialScroll: function(previousScrollState) {
8425		return 0;
8426	},
8427
8428
8429	// Retrieves the view's current natural scroll state. Can return an arbitrary format.
8430	queryScroll: function() {
8431		// subclasses must implement
8432	},
8433
8434
8435	// Sets the view's scroll state. Will accept the same format computeInitialScroll and queryScroll produce.
8436	setScroll: function(scrollState) {
8437		// subclasses must implement
8438	},
8439
8440
8441	// Sets the scroll state, making sure to overcome any predefined scroll value the browser has in mind
8442	forceScroll: function(scrollState) {
8443		var _this = this;
8444
8445		this.setScroll(scrollState);
8446		setTimeout(function() {
8447			_this.setScroll(scrollState);
8448		}, 0);
8449	},
8450
8451
8452	/* Event Elements / Segments
8453	------------------------------------------------------------------------------------------------------------------*/
8454
8455
8456	// Does everything necessary to display the given events onto the current view
8457	displayEvents: function(events) {
8458		var scrollState = this.queryScroll();
8459
8460		this.clearEvents();
8461		this.renderEvents(events);
8462		this.isEventsRendered = true;
8463		this.setScroll(scrollState);
8464		this.triggerEventRender();
8465	},
8466
8467
8468	// Does everything necessary to clear the view's currently-rendered events
8469	clearEvents: function() {
8470		var scrollState;
8471
8472		if (this.isEventsRendered) {
8473
8474			// TODO: optimize: if we know this is part of a displayEvents call, don't queryScroll/setScroll
8475			scrollState = this.queryScroll();
8476
8477			this.triggerEventUnrender();
8478			if (this.destroyEvents) {
8479				this.destroyEvents(); // TODO: deprecate
8480			}
8481			this.unrenderEvents();
8482			this.setScroll(scrollState);
8483			this.isEventsRendered = false;
8484		}
8485	},
8486
8487
8488	// Renders the events onto the view.
8489	renderEvents: function(events) {
8490		// subclasses should implement
8491	},
8492
8493
8494	// Removes event elements from the view.
8495	unrenderEvents: function() {
8496		// subclasses should implement
8497	},
8498
8499
8500	// Signals that all events have been rendered
8501	triggerEventRender: function() {
8502		this.renderedEventSegEach(function(seg) {
8503			this.trigger('eventAfterRender', seg.event, seg.event, seg.el);
8504		});
8505		this.trigger('eventAfterAllRender');
8506	},
8507
8508
8509	// Signals that all event elements are about to be removed
8510	triggerEventUnrender: function() {
8511		this.renderedEventSegEach(function(seg) {
8512			this.trigger('eventDestroy', seg.event, seg.event, seg.el);
8513		});
8514	},
8515
8516
8517	// Given an event and the default element used for rendering, returns the element that should actually be used.
8518	// Basically runs events and elements through the eventRender hook.
8519	resolveEventEl: function(event, el) {
8520		var custom = this.trigger('eventRender', event, event, el);
8521
8522		if (custom === false) { // means don't render at all
8523			el = null;
8524		}
8525		else if (custom && custom !== true) {
8526			el = $(custom);
8527		}
8528
8529		return el;
8530	},
8531
8532
8533	// Hides all rendered event segments linked to the given event
8534	showEvent: function(event) {
8535		this.renderedEventSegEach(function(seg) {
8536			seg.el.css('visibility', '');
8537		}, event);
8538	},
8539
8540
8541	// Shows all rendered event segments linked to the given event
8542	hideEvent: function(event) {
8543		this.renderedEventSegEach(function(seg) {
8544			seg.el.css('visibility', 'hidden');
8545		}, event);
8546	},
8547
8548
8549	// Iterates through event segments that have been rendered (have an el). Goes through all by default.
8550	// If the optional `event` argument is specified, only iterates through segments linked to that event.
8551	// The `this` value of the callback function will be the view.
8552	renderedEventSegEach: function(func, event) {
8553		var segs = this.getEventSegs();
8554		var i;
8555
8556		for (i = 0; i < segs.length; i++) {
8557			if (!event || segs[i].event._id === event._id) {
8558				if (segs[i].el) {
8559					func.call(this, segs[i]);
8560				}
8561			}
8562		}
8563	},
8564
8565
8566	// Retrieves all the rendered segment objects for the view
8567	getEventSegs: function() {
8568		// subclasses must implement
8569		return [];
8570	},
8571
8572
8573	/* Event Drag-n-Drop
8574	------------------------------------------------------------------------------------------------------------------*/
8575
8576
8577	// Computes if the given event is allowed to be dragged by the user
8578	isEventDraggable: function(event) {
8579		return this.isEventStartEditable(event);
8580	},
8581
8582
8583	isEventStartEditable: function(event) {
8584		return firstDefined(
8585			event.startEditable,
8586			(event.source || {}).startEditable,
8587			this.opt('eventStartEditable'),
8588			this.isEventGenerallyEditable(event)
8589		);
8590	},
8591
8592
8593	isEventGenerallyEditable: function(event) {
8594		return firstDefined(
8595			event.editable,
8596			(event.source || {}).editable,
8597			this.opt('editable')
8598		);
8599	},
8600
8601
8602	// Must be called when an event in the view is dropped onto new location.
8603	// `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
8604	reportEventDrop: function(event, dropLocation, largeUnit, el, ev) {
8605		var calendar = this.calendar;
8606		var mutateResult = calendar.mutateEvent(event, dropLocation, largeUnit);
8607		var undoFunc = function() {
8608			mutateResult.undo();
8609			calendar.reportEventChange();
8610		};
8611
8612		this.triggerEventDrop(event, mutateResult.dateDelta, undoFunc, el, ev);
8613		calendar.reportEventChange(); // will rerender events
8614	},
8615
8616
8617	// Triggers event-drop handlers that have subscribed via the API
8618	triggerEventDrop: function(event, dateDelta, undoFunc, el, ev) {
8619		this.trigger('eventDrop', el[0], event, dateDelta, undoFunc, ev, {}); // {} = jqui dummy
8620	},
8621
8622
8623	/* External Element Drag-n-Drop
8624	------------------------------------------------------------------------------------------------------------------*/
8625
8626
8627	// Must be called when an external element, via jQuery UI, has been dropped onto the calendar.
8628	// `meta` is the parsed data that has been embedded into the dragging event.
8629	// `dropLocation` is an object that contains the new zoned start/end/allDay values for the event.
8630	reportExternalDrop: function(meta, dropLocation, el, ev, ui) {
8631		var eventProps = meta.eventProps;
8632		var eventInput;
8633		var event;
8634
8635		// Try to build an event object and render it. TODO: decouple the two
8636		if (eventProps) {
8637			eventInput = $.extend({}, eventProps, dropLocation);
8638			event = this.calendar.renderEvent(eventInput, meta.stick)[0]; // renderEvent returns an array
8639		}
8640
8641		this.triggerExternalDrop(event, dropLocation, el, ev, ui);
8642	},
8643
8644
8645	// Triggers external-drop handlers that have subscribed via the API
8646	triggerExternalDrop: function(event, dropLocation, el, ev, ui) {
8647
8648		// trigger 'drop' regardless of whether element represents an event
8649		this.trigger('drop', el[0], dropLocation.start, ev, ui);
8650
8651		if (event) {
8652			this.trigger('eventReceive', null, event); // signal an external event landed
8653		}
8654	},
8655
8656
8657	/* Drag-n-Drop Rendering (for both events and external elements)
8658	------------------------------------------------------------------------------------------------------------------*/
8659
8660
8661	// Renders a visual indication of a event or external-element drag over the given drop zone.
8662	// If an external-element, seg will be `null`.
8663	// Must return elements used for any mock events.
8664	renderDrag: function(dropLocation, seg) {
8665		// subclasses must implement
8666	},
8667
8668
8669	// Unrenders a visual indication of an event or external-element being dragged.
8670	unrenderDrag: function() {
8671		// subclasses must implement
8672	},
8673
8674
8675	/* Event Resizing
8676	------------------------------------------------------------------------------------------------------------------*/
8677
8678
8679	// Computes if the given event is allowed to be resized from its starting edge
8680	isEventResizableFromStart: function(event) {
8681		return this.opt('eventResizableFromStart') && this.isEventResizable(event);
8682	},
8683
8684
8685	// Computes if the given event is allowed to be resized from its ending edge
8686	isEventResizableFromEnd: function(event) {
8687		return this.isEventResizable(event);
8688	},
8689
8690
8691	// Computes if the given event is allowed to be resized by the user at all
8692	isEventResizable: function(event) {
8693		var source = event.source || {};
8694
8695		return firstDefined(
8696			event.durationEditable,
8697			source.durationEditable,
8698			this.opt('eventDurationEditable'),
8699			event.editable,
8700			source.editable,
8701			this.opt('editable')
8702		);
8703	},
8704
8705
8706	// Must be called when an event in the view has been resized to a new length
8707	reportEventResize: function(event, resizeLocation, largeUnit, el, ev) {
8708		var calendar = this.calendar;
8709		var mutateResult = calendar.mutateEvent(event, resizeLocation, largeUnit);
8710		var undoFunc = function() {
8711			mutateResult.undo();
8712			calendar.reportEventChange();
8713		};
8714
8715		this.triggerEventResize(event, mutateResult.durationDelta, undoFunc, el, ev);
8716		calendar.reportEventChange(); // will rerender events
8717	},
8718
8719
8720	// Triggers event-resize handlers that have subscribed via the API
8721	triggerEventResize: function(event, durationDelta, undoFunc, el, ev) {
8722		this.trigger('eventResize', el[0], event, durationDelta, undoFunc, ev, {}); // {} = jqui dummy
8723	},
8724
8725
8726	/* Selection (time range)
8727	------------------------------------------------------------------------------------------------------------------*/
8728
8729
8730	// Selects a date span on the view. `start` and `end` are both Moments.
8731	// `ev` is the native mouse event that begin the interaction.
8732	select: function(span, ev) {
8733		this.unselect(ev);
8734		this.renderSelection(span);
8735		this.reportSelection(span, ev);
8736	},
8737
8738
8739	// Renders a visual indication of the selection
8740	renderSelection: function(span) {
8741		// subclasses should implement
8742	},
8743
8744
8745	// Called when a new selection is made. Updates internal state and triggers handlers.
8746	reportSelection: function(span, ev) {
8747		this.isSelected = true;
8748		this.triggerSelect(span, ev);
8749	},
8750
8751
8752	// Triggers handlers to 'select'
8753	triggerSelect: function(span, ev) {
8754		this.trigger(
8755			'select',
8756			null,
8757			this.calendar.applyTimezone(span.start), // convert to calendar's tz for external API
8758			this.calendar.applyTimezone(span.end), // "
8759			ev
8760		);
8761	},
8762
8763
8764	// Undoes a selection. updates in the internal state and triggers handlers.
8765	// `ev` is the native mouse event that began the interaction.
8766	unselect: function(ev) {
8767		if (this.isSelected) {
8768			this.isSelected = false;
8769			if (this.destroySelection) {
8770				this.destroySelection(); // TODO: deprecate
8771			}
8772			this.unrenderSelection();
8773			this.trigger('unselect', null, ev);
8774		}
8775	},
8776
8777
8778	// Unrenders a visual indication of selection
8779	unrenderSelection: function() {
8780		// subclasses should implement
8781	},
8782
8783
8784	/* Event Selection
8785	------------------------------------------------------------------------------------------------------------------*/
8786
8787
8788	selectEvent: function(event) {
8789		if (!this.selectedEvent || this.selectedEvent !== event) {
8790			this.unselectEvent();
8791			this.renderedEventSegEach(function(seg) {
8792				seg.el.addClass('fc-selected');
8793			}, event);
8794			this.selectedEvent = event;
8795		}
8796	},
8797
8798
8799	unselectEvent: function() {
8800		if (this.selectedEvent) {
8801			this.renderedEventSegEach(function(seg) {
8802				seg.el.removeClass('fc-selected');
8803			}, this.selectedEvent);
8804			this.selectedEvent = null;
8805		}
8806	},
8807
8808
8809	isEventSelected: function(event) {
8810		// event references might change on refetchEvents(), while selectedEvent doesn't,
8811		// so compare IDs
8812		return this.selectedEvent && this.selectedEvent._id === event._id;
8813	},
8814
8815
8816	/* Mouse / Touch Unselecting (time range & event unselection)
8817	------------------------------------------------------------------------------------------------------------------*/
8818	// TODO: move consistently to down/start or up/end?
8819	// TODO: don't kill previous selection if touch scrolling
8820
8821
8822	handleDocumentMousedown: function(ev) {
8823		if (isPrimaryMouseButton(ev)) {
8824			this.processUnselect(ev);
8825		}
8826	},
8827
8828
8829	processUnselect: function(ev) {
8830		this.processRangeUnselect(ev);
8831		this.processEventUnselect(ev);
8832	},
8833
8834
8835	processRangeUnselect: function(ev) {
8836		var ignore;
8837
8838		// is there a time-range selection?
8839		if (this.isSelected && this.opt('unselectAuto')) {
8840			// only unselect if the clicked element is not identical to or inside of an 'unselectCancel' element
8841			ignore = this.opt('unselectCancel');
8842			if (!ignore || !$(ev.target).closest(ignore).length) {
8843				this.unselect(ev);
8844			}
8845		}
8846	},
8847
8848
8849	processEventUnselect: function(ev) {
8850		if (this.selectedEvent) {
8851			if (!$(ev.target).closest('.fc-selected').length) {
8852				this.unselectEvent();
8853			}
8854		}
8855	},
8856
8857
8858	/* Day Click
8859	------------------------------------------------------------------------------------------------------------------*/
8860
8861
8862	// Triggers handlers to 'dayClick'
8863	// Span has start/end of the clicked area. Only the start is useful.
8864	triggerDayClick: function(span, dayEl, ev) {
8865		this.trigger(
8866			'dayClick',
8867			dayEl,
8868			this.calendar.applyTimezone(span.start), // convert to calendar's timezone for external API
8869			ev
8870		);
8871	},
8872
8873
8874	/* Date Utils
8875	------------------------------------------------------------------------------------------------------------------*/
8876
8877
8878	// Initializes internal variables related to calculating hidden days-of-week
8879	initHiddenDays: function() {
8880		var hiddenDays = this.opt('hiddenDays') || []; // array of day-of-week indices that are hidden
8881		var isHiddenDayHash = []; // is the day-of-week hidden? (hash with day-of-week-index -> bool)
8882		var dayCnt = 0;
8883		var i;
8884
8885		if (this.opt('weekends') === false) {
8886			hiddenDays.push(0, 6); // 0=sunday, 6=saturday
8887		}
8888
8889		for (i = 0; i < 7; i++) {
8890			if (
8891				!(isHiddenDayHash[i] = $.inArray(i, hiddenDays) !== -1)
8892			) {
8893				dayCnt++;
8894			}
8895		}
8896
8897		if (!dayCnt) {
8898			throw 'invalid hiddenDays'; // all days were hidden? bad.
8899		}
8900
8901		this.isHiddenDayHash = isHiddenDayHash;
8902	},
8903
8904
8905	// Is the current day hidden?
8906	// `day` is a day-of-week index (0-6), or a Moment
8907	isHiddenDay: function(day) {
8908		if (moment.isMoment(day)) {
8909			day = day.day();
8910		}
8911		return this.isHiddenDayHash[day];
8912	},
8913
8914
8915	// Incrementing the current day until it is no longer a hidden day, returning a copy.
8916	// If the initial value of `date` is not a hidden day, don't do anything.
8917	// Pass `isExclusive` as `true` if you are dealing with an end date.
8918	// `inc` defaults to `1` (increment one day forward each time)
8919	skipHiddenDays: function(date, inc, isExclusive) {
8920		var out = date.clone();
8921		inc = inc || 1;
8922		while (
8923			this.isHiddenDayHash[(out.day() + (isExclusive ? inc : 0) + 7) % 7]
8924		) {
8925			out.add(inc, 'days');
8926		}
8927		return out;
8928	},
8929
8930
8931	// Returns the date range of the full days the given range visually appears to occupy.
8932	// Returns a new range object.
8933	computeDayRange: function(range) {
8934		var startDay = range.start.clone().stripTime(); // the beginning of the day the range starts
8935		var end = range.end;
8936		var endDay = null;
8937		var endTimeMS;
8938
8939		if (end) {
8940			endDay = end.clone().stripTime(); // the beginning of the day the range exclusively ends
8941			endTimeMS = +end.time(); // # of milliseconds into `endDay`
8942
8943			// If the end time is actually inclusively part of the next day and is equal to or
8944			// beyond the next day threshold, adjust the end to be the exclusive end of `endDay`.
8945			// Otherwise, leaving it as inclusive will cause it to exclude `endDay`.
8946			if (endTimeMS && endTimeMS >= this.nextDayThreshold) {
8947				endDay.add(1, 'days');
8948			}
8949		}
8950
8951		// If no end was specified, or if it is within `startDay` but not past nextDayThreshold,
8952		// assign the default duration of one day.
8953		if (!end || endDay <= startDay) {
8954			endDay = startDay.clone().add(1, 'days');
8955		}
8956
8957		return { start: startDay, end: endDay };
8958	},
8959
8960
8961	// Does the given event visually appear to occupy more than one day?
8962	isMultiDayEvent: function(event) {
8963		var range = this.computeDayRange(event); // event is range-ish
8964
8965		return range.end.diff(range.start, 'days') > 1;
8966	}
8967
8968});
8969
8970;;
8971
8972/*
8973Embodies a div that has potential scrollbars
8974*/
8975var Scroller = FC.Scroller = Class.extend({
8976
8977	el: null, // the guaranteed outer element
8978	scrollEl: null, // the element with the scrollbars
8979	overflowX: null,
8980	overflowY: null,
8981
8982
8983	constructor: function(options) {
8984		options = options || {};
8985		this.overflowX = options.overflowX || options.overflow || 'auto';
8986		this.overflowY = options.overflowY || options.overflow || 'auto';
8987	},
8988
8989
8990	render: function() {
8991		this.el = this.renderEl();
8992		this.applyOverflow();
8993	},
8994
8995
8996	renderEl: function() {
8997		return (this.scrollEl = $('<div class="fc-scroller"></div>'));
8998	},
8999
9000
9001	// sets to natural height, unlocks overflow
9002	clear: function() {
9003		this.setHeight('auto');
9004		this.applyOverflow();
9005	},
9006
9007
9008	destroy: function() {
9009		this.el.remove();
9010	},
9011
9012
9013	// Overflow
9014	// -----------------------------------------------------------------------------------------------------------------
9015
9016
9017	applyOverflow: function() {
9018		this.scrollEl.css({
9019			'overflow-x': this.overflowX,
9020			'overflow-y': this.overflowY
9021		});
9022	},
9023
9024
9025	// Causes any 'auto' overflow values to resolves to 'scroll' or 'hidden'.
9026	// Useful for preserving scrollbar widths regardless of future resizes.
9027	// Can pass in scrollbarWidths for optimization.
9028	lockOverflow: function(scrollbarWidths) {
9029		var overflowX = this.overflowX;
9030		var overflowY = this.overflowY;
9031
9032		scrollbarWidths = scrollbarWidths || this.getScrollbarWidths();
9033
9034		if (overflowX === 'auto') {
9035			overflowX = (
9036					scrollbarWidths.top || scrollbarWidths.bottom || // horizontal scrollbars?
9037					// OR scrolling pane with massless scrollbars?
9038					this.scrollEl[0].scrollWidth - 1 > this.scrollEl[0].clientWidth
9039						// subtract 1 because of IE off-by-one issue
9040				) ? 'scroll' : 'hidden';
9041		}
9042
9043		if (overflowY === 'auto') {
9044			overflowY = (
9045					scrollbarWidths.left || scrollbarWidths.right || // vertical scrollbars?
9046					// OR scrolling pane with massless scrollbars?
9047					this.scrollEl[0].scrollHeight - 1 > this.scrollEl[0].clientHeight
9048						// subtract 1 because of IE off-by-one issue
9049				) ? 'scroll' : 'hidden';
9050		}
9051
9052		this.scrollEl.css({ 'overflow-x': overflowX, 'overflow-y': overflowY });
9053	},
9054
9055
9056	// Getters / Setters
9057	// -----------------------------------------------------------------------------------------------------------------
9058
9059
9060	setHeight: function(height) {
9061		this.scrollEl.height(height);
9062	},
9063
9064
9065	getScrollTop: function() {
9066		return this.scrollEl.scrollTop();
9067	},
9068
9069
9070	setScrollTop: function(top) {
9071		this.scrollEl.scrollTop(top);
9072	},
9073
9074
9075	getClientWidth: function() {
9076		return this.scrollEl[0].clientWidth;
9077	},
9078
9079
9080	getClientHeight: function() {
9081		return this.scrollEl[0].clientHeight;
9082	},
9083
9084
9085	getScrollbarWidths: function() {
9086		return getScrollbarWidths(this.scrollEl);
9087	}
9088
9089});
9090
9091;;
9092
9093var Calendar = FC.Calendar = Class.extend({
9094
9095	dirDefaults: null, // option defaults related to LTR or RTL
9096	localeDefaults: null, // option defaults related to current locale
9097	overrides: null, // option overrides given to the fullCalendar constructor
9098	dynamicOverrides: null, // options set with dynamic setter method. higher precedence than view overrides.
9099	options: null, // all defaults combined with overrides
9100	viewSpecCache: null, // cache of view definitions
9101	view: null, // current View object
9102	header: null,
9103	loadingLevel: 0, // number of simultaneous loading tasks
9104
9105
9106	// a lot of this class' OOP logic is scoped within this constructor function,
9107	// but in the future, write individual methods on the prototype.
9108	constructor: Calendar_constructor,
9109
9110
9111	// Subclasses can override this for initialization logic after the constructor has been called
9112	initialize: function() {
9113	},
9114
9115
9116	// Computes the flattened options hash for the calendar and assigns to `this.options`.
9117	// Assumes this.overrides and this.dynamicOverrides have already been initialized.
9118	populateOptionsHash: function() {
9119		var locale, localeDefaults;
9120		var isRTL, dirDefaults;
9121
9122		locale = firstDefined( // explicit locale option given?
9123			this.dynamicOverrides.locale,
9124			this.overrides.locale
9125		);
9126		localeDefaults = localeOptionHash[locale];
9127		if (!localeDefaults) { // explicit locale option not given or invalid?
9128			locale = Calendar.defaults.locale;
9129			localeDefaults = localeOptionHash[locale] || {};
9130		}
9131
9132		isRTL = firstDefined( // based on options computed so far, is direction RTL?
9133			this.dynamicOverrides.isRTL,
9134			this.overrides.isRTL,
9135			localeDefaults.isRTL,
9136			Calendar.defaults.isRTL
9137		);
9138		dirDefaults = isRTL ? Calendar.rtlDefaults : {};
9139
9140		this.dirDefaults = dirDefaults;
9141		this.localeDefaults = localeDefaults;
9142		this.options = mergeOptions([ // merge defaults and overrides. lowest to highest precedence
9143			Calendar.defaults, // global defaults
9144			dirDefaults,
9145			localeDefaults,
9146			this.overrides,
9147			this.dynamicOverrides
9148		]);
9149		populateInstanceComputableOptions(this.options); // fill in gaps with computed options
9150	},
9151
9152
9153	// Gets information about how to create a view. Will use a cache.
9154	getViewSpec: function(viewType) {
9155		var cache = this.viewSpecCache;
9156
9157		return cache[viewType] || (cache[viewType] = this.buildViewSpec(viewType));
9158	},
9159
9160
9161	// Given a duration singular unit, like "week" or "day", finds a matching view spec.
9162	// Preference is given to views that have corresponding buttons.
9163	getUnitViewSpec: function(unit) {
9164		var viewTypes;
9165		var i;
9166		var spec;
9167
9168		if ($.inArray(unit, intervalUnits) != -1) {
9169
9170			// put views that have buttons first. there will be duplicates, but oh well
9171			viewTypes = this.header.getViewsWithButtons();
9172			$.each(FC.views, function(viewType) { // all views
9173				viewTypes.push(viewType);
9174			});
9175
9176			for (i = 0; i < viewTypes.length; i++) {
9177				spec = this.getViewSpec(viewTypes[i]);
9178				if (spec) {
9179					if (spec.singleUnit == unit) {
9180						return spec;
9181					}
9182				}
9183			}
9184		}
9185	},
9186
9187
9188	// Builds an object with information on how to create a given view
9189	buildViewSpec: function(requestedViewType) {
9190		var viewOverrides = this.overrides.views || {};
9191		var specChain = []; // for the view. lowest to highest priority
9192		var defaultsChain = []; // for the view. lowest to highest priority
9193		var overridesChain = []; // for the view. lowest to highest priority
9194		var viewType = requestedViewType;
9195		var spec; // for the view
9196		var overrides; // for the view
9197		var duration;
9198		var unit;
9199
9200		// iterate from the specific view definition to a more general one until we hit an actual View class
9201		while (viewType) {
9202			spec = fcViews[viewType];
9203			overrides = viewOverrides[viewType];
9204			viewType = null; // clear. might repopulate for another iteration
9205
9206			if (typeof spec === 'function') { // TODO: deprecate
9207				spec = { 'class': spec };
9208			}
9209
9210			if (spec) {
9211				specChain.unshift(spec);
9212				defaultsChain.unshift(spec.defaults || {});
9213				duration = duration || spec.duration;
9214				viewType = viewType || spec.type;
9215			}
9216
9217			if (overrides) {
9218				overridesChain.unshift(overrides); // view-specific option hashes have options at zero-level
9219				duration = duration || overrides.duration;
9220				viewType = viewType || overrides.type;
9221			}
9222		}
9223
9224		spec = mergeProps(specChain);
9225		spec.type = requestedViewType;
9226		if (!spec['class']) {
9227			return false;
9228		}
9229
9230		if (duration) {
9231			duration = moment.duration(duration);
9232			if (duration.valueOf()) { // valid?
9233				spec.duration = duration;
9234				unit = computeIntervalUnit(duration);
9235
9236				// view is a single-unit duration, like "week" or "day"
9237				// incorporate options for this. lowest priority
9238				if (duration.as(unit) === 1) {
9239					spec.singleUnit = unit;
9240					overridesChain.unshift(viewOverrides[unit] || {});
9241				}
9242			}
9243		}
9244
9245		spec.defaults = mergeOptions(defaultsChain);
9246		spec.overrides = mergeOptions(overridesChain);
9247
9248		this.buildViewSpecOptions(spec);
9249		this.buildViewSpecButtonText(spec, requestedViewType);
9250
9251		return spec;
9252	},
9253
9254
9255	// Builds and assigns a view spec's options object from its already-assigned defaults and overrides
9256	buildViewSpecOptions: function(spec) {
9257		spec.options = mergeOptions([ // lowest to highest priority
9258			Calendar.defaults, // global defaults
9259			spec.defaults, // view's defaults (from ViewSubclass.defaults)
9260			this.dirDefaults,
9261			this.localeDefaults, // locale and dir take precedence over view's defaults!
9262			this.overrides, // calendar's overrides (options given to constructor)
9263			spec.overrides, // view's overrides (view-specific options)
9264			this.dynamicOverrides // dynamically set via setter. highest precedence
9265		]);
9266		populateInstanceComputableOptions(spec.options);
9267	},
9268
9269
9270	// Computes and assigns a view spec's buttonText-related options
9271	buildViewSpecButtonText: function(spec, requestedViewType) {
9272
9273		// given an options object with a possible `buttonText` hash, lookup the buttonText for the
9274		// requested view, falling back to a generic unit entry like "week" or "day"
9275		function queryButtonText(options) {
9276			var buttonText = options.buttonText || {};
9277			return buttonText[requestedViewType] ||
9278				// view can decide to look up a certain key
9279				(spec.buttonTextKey ? buttonText[spec.buttonTextKey] : null) ||
9280				// a key like "month"
9281				(spec.singleUnit ? buttonText[spec.singleUnit] : null);
9282		}
9283
9284		// highest to lowest priority
9285		spec.buttonTextOverride =
9286			queryButtonText(this.dynamicOverrides) ||
9287			queryButtonText(this.overrides) || // constructor-specified buttonText lookup hash takes precedence
9288			spec.overrides.buttonText; // `buttonText` for view-specific options is a string
9289
9290		// highest to lowest priority. mirrors buildViewSpecOptions
9291		spec.buttonTextDefault =
9292			queryButtonText(this.localeDefaults) ||
9293			queryButtonText(this.dirDefaults) ||
9294			spec.defaults.buttonText || // a single string. from ViewSubclass.defaults
9295			queryButtonText(Calendar.defaults) ||
9296			(spec.duration ? this.humanizeDuration(spec.duration) : null) || // like "3 days"
9297			requestedViewType; // fall back to given view name
9298	},
9299
9300
9301	// Given a view name for a custom view or a standard view, creates a ready-to-go View object
9302	instantiateView: function(viewType) {
9303		var spec = this.getViewSpec(viewType);
9304
9305		return new spec['class'](this, viewType, spec.options, spec.duration);
9306	},
9307
9308
9309	// Returns a boolean about whether the view is okay to instantiate at some point
9310	isValidViewType: function(viewType) {
9311		return Boolean(this.getViewSpec(viewType));
9312	},
9313
9314
9315	// Should be called when any type of async data fetching begins
9316	pushLoading: function() {
9317		if (!(this.loadingLevel++)) {
9318			this.trigger('loading', null, true, this.view);
9319		}
9320	},
9321
9322
9323	// Should be called when any type of async data fetching completes
9324	popLoading: function() {
9325		if (!(--this.loadingLevel)) {
9326			this.trigger('loading', null, false, this.view);
9327		}
9328	},
9329
9330
9331	// Given arguments to the select method in the API, returns a span (unzoned start/end and other info)
9332	buildSelectSpan: function(zonedStartInput, zonedEndInput) {
9333		var start = this.moment(zonedStartInput).stripZone();
9334		var end;
9335
9336		if (zonedEndInput) {
9337			end = this.moment(zonedEndInput).stripZone();
9338		}
9339		else if (start.hasTime()) {
9340			end = start.clone().add(this.defaultTimedEventDuration);
9341		}
9342		else {
9343			end = start.clone().add(this.defaultAllDayEventDuration);
9344		}
9345
9346		return { start: start, end: end };
9347	}
9348
9349});
9350
9351
9352Calendar.mixin(EmitterMixin);
9353
9354
9355function Calendar_constructor(element, overrides) {
9356	var t = this;
9357
9358
9359	// Exports
9360	// -----------------------------------------------------------------------------------
9361
9362	t.render = render;
9363	t.destroy = destroy;
9364	t.refetchEvents = refetchEvents;
9365	t.refetchEventSources = refetchEventSources;
9366	t.reportEvents = reportEvents;
9367	t.reportEventChange = reportEventChange;
9368	t.rerenderEvents = renderEvents; // `renderEvents` serves as a rerender. an API method
9369	t.changeView = renderView; // `renderView` will switch to another view
9370	t.select = select;
9371	t.unselect = unselect;
9372	t.prev = prev;
9373	t.next = next;
9374	t.prevYear = prevYear;
9375	t.nextYear = nextYear;
9376	t.today = today;
9377	t.gotoDate = gotoDate;
9378	t.incrementDate = incrementDate;
9379	t.zoomTo = zoomTo;
9380	t.getDate = getDate;
9381	t.getCalendar = getCalendar;
9382	t.getView = getView;
9383	t.option = option; // getter/setter method
9384	t.trigger = trigger;
9385
9386
9387	// Options
9388	// -----------------------------------------------------------------------------------
9389
9390	t.dynamicOverrides = {};
9391	t.viewSpecCache = {};
9392	t.optionHandlers = {}; // for Calendar.options.js
9393	t.overrides = $.extend({}, overrides); // make a copy
9394
9395	t.populateOptionsHash(); // sets this.options
9396
9397
9398
9399	// Locale-data Internals
9400	// -----------------------------------------------------------------------------------
9401	// Apply overrides to the current locale's data
9402
9403	var localeData;
9404
9405	// Called immediately, and when any of the options change.
9406	// Happens before any internal objects rebuild or rerender, because this is very core.
9407	t.bindOptions([
9408		'locale', 'monthNames', 'monthNamesShort', 'dayNames', 'dayNamesShort', 'firstDay', 'weekNumberCalculation'
9409	], function(locale, monthNames, monthNamesShort, dayNames, dayNamesShort, firstDay, weekNumberCalculation) {
9410
9411		// normalize
9412		if (weekNumberCalculation === 'iso') {
9413			weekNumberCalculation = 'ISO'; // normalize
9414		}
9415
9416		localeData = createObject( // make a cheap copy
9417			getMomentLocaleData(locale) // will fall back to en
9418		);
9419
9420		if (monthNames) {
9421			localeData._months = monthNames;
9422		}
9423		if (monthNamesShort) {
9424			localeData._monthsShort = monthNamesShort;
9425		}
9426		if (dayNames) {
9427			localeData._weekdays = dayNames;
9428		}
9429		if (dayNamesShort) {
9430			localeData._weekdaysShort = dayNamesShort;
9431		}
9432
9433		if (firstDay == null && weekNumberCalculation === 'ISO') {
9434			firstDay = 1;
9435		}
9436		if (firstDay != null) {
9437			var _week = createObject(localeData._week); // _week: { dow: # }
9438			_week.dow = firstDay;
9439			localeData._week = _week;
9440		}
9441
9442		if ( // whitelist certain kinds of input
9443			weekNumberCalculation === 'ISO' ||
9444			weekNumberCalculation === 'local' ||
9445			typeof weekNumberCalculation === 'function'
9446		) {
9447			localeData._fullCalendar_weekCalc = weekNumberCalculation; // moment-ext will know what to do with it
9448		}
9449
9450		// If the internal current date object already exists, move to new locale.
9451		// We do NOT need to do this technique for event dates, because this happens when converting to "segments".
9452		if (date) {
9453			localizeMoment(date); // sets to localeData
9454		}
9455	});
9456
9457
9458	// Calendar-specific Date Utilities
9459	// -----------------------------------------------------------------------------------
9460
9461
9462	t.defaultAllDayEventDuration = moment.duration(t.options.defaultAllDayEventDuration);
9463	t.defaultTimedEventDuration = moment.duration(t.options.defaultTimedEventDuration);
9464
9465
9466	// Builds a moment using the settings of the current calendar: timezone and locale.
9467	// Accepts anything the vanilla moment() constructor accepts.
9468	t.moment = function() {
9469		var mom;
9470
9471		if (t.options.timezone === 'local') {
9472			mom = FC.moment.apply(null, arguments);
9473
9474			// Force the moment to be local, because FC.moment doesn't guarantee it.
9475			if (mom.hasTime()) { // don't give ambiguously-timed moments a local zone
9476				mom.local();
9477			}
9478		}
9479		else if (t.options.timezone === 'UTC') {
9480			mom = FC.moment.utc.apply(null, arguments); // process as UTC
9481		}
9482		else {
9483			mom = FC.moment.parseZone.apply(null, arguments); // let the input decide the zone
9484		}
9485
9486		localizeMoment(mom);
9487
9488		return mom;
9489	};
9490
9491
9492	// Updates the given moment's locale settings to the current calendar locale settings.
9493	function localizeMoment(mom) {
9494		mom._locale = localeData;
9495	}
9496	t.localizeMoment = localizeMoment;
9497
9498
9499	// Returns a boolean about whether or not the calendar knows how to calculate
9500	// the timezone offset of arbitrary dates in the current timezone.
9501	t.getIsAmbigTimezone = function() {
9502		return t.options.timezone !== 'local' && t.options.timezone !== 'UTC';
9503	};
9504
9505
9506	// Returns a copy of the given date in the current timezone. Has no effect on dates without times.
9507	t.applyTimezone = function(date) {
9508		if (!date.hasTime()) {
9509			return date.clone();
9510		}
9511
9512		var zonedDate = t.moment(date.toArray());
9513		var timeAdjust = date.time() - zonedDate.time();
9514		var adjustedZonedDate;
9515
9516		// Safari sometimes has problems with this coersion when near DST. Adjust if necessary. (bug #2396)
9517		if (timeAdjust) { // is the time result different than expected?
9518			adjustedZonedDate = zonedDate.clone().add(timeAdjust); // add milliseconds
9519			if (date.time() - adjustedZonedDate.time() === 0) { // does it match perfectly now?
9520				zonedDate = adjustedZonedDate;
9521			}
9522		}
9523
9524		return zonedDate;
9525	};
9526
9527
9528	// Returns a moment for the current date, as defined by the client's computer or from the `now` option.
9529	// Will return an moment with an ambiguous timezone.
9530	t.getNow = function() {
9531		var now = t.options.now;
9532		if (typeof now === 'function') {
9533			now = now();
9534		}
9535		return t.moment(now).stripZone();
9536	};
9537
9538
9539	// Get an event's normalized end date. If not present, calculate it from the defaults.
9540	t.getEventEnd = function(event) {
9541		if (event.end) {
9542			return event.end.clone();
9543		}
9544		else {
9545			return t.getDefaultEventEnd(event.allDay, event.start);
9546		}
9547	};
9548
9549
9550	// Given an event's allDay status and start date, return what its fallback end date should be.
9551	// TODO: rename to computeDefaultEventEnd
9552	t.getDefaultEventEnd = function(allDay, zonedStart) {
9553		var end = zonedStart.clone();
9554
9555		if (allDay) {
9556			end.stripTime().add(t.defaultAllDayEventDuration);
9557		}
9558		else {
9559			end.add(t.defaultTimedEventDuration);
9560		}
9561
9562		if (t.getIsAmbigTimezone()) {
9563			end.stripZone(); // we don't know what the tzo should be
9564		}
9565
9566		return end;
9567	};
9568
9569
9570	// Produces a human-readable string for the given duration.
9571	// Side-effect: changes the locale of the given duration.
9572	t.humanizeDuration = function(duration) {
9573		return duration.locale(t.options.locale).humanize();
9574	};
9575
9576
9577	
9578	// Imports
9579	// -----------------------------------------------------------------------------------
9580
9581
9582	EventManager.call(t);
9583	var isFetchNeeded = t.isFetchNeeded;
9584	var fetchEvents = t.fetchEvents;
9585	var fetchEventSources = t.fetchEventSources;
9586
9587
9588
9589	// Locals
9590	// -----------------------------------------------------------------------------------
9591
9592
9593	var _element = element[0];
9594	var header;
9595	var content;
9596	var tm; // for making theme classes
9597	var currentView; // NOTE: keep this in sync with this.view
9598	var viewsByType = {}; // holds all instantiated view instances, current or not
9599	var suggestedViewHeight;
9600	var windowResizeProxy; // wraps the windowResize function
9601	var ignoreWindowResize = 0;
9602	var events = [];
9603	var date; // unzoned
9604	
9605	
9606	
9607	// Main Rendering
9608	// -----------------------------------------------------------------------------------
9609
9610
9611	// compute the initial ambig-timezone date
9612	if (t.options.defaultDate != null) {
9613		date = t.moment(t.options.defaultDate).stripZone();
9614	}
9615	else {
9616		date = t.getNow(); // getNow already returns unzoned
9617	}
9618	
9619	
9620	function render() {
9621		if (!content) {
9622			initialRender();
9623		}
9624		else if (elementVisible()) {
9625			// mainly for the public API
9626			calcSize();
9627			renderView();
9628		}
9629	}
9630	
9631	
9632	function initialRender() {
9633		element.addClass('fc');
9634
9635		// event delegation for nav links
9636		element.on('click.fc', 'a[data-goto]', function(ev) {
9637			var anchorEl = $(this);
9638			var gotoOptions = anchorEl.data('goto'); // will automatically parse JSON
9639			var date = t.moment(gotoOptions.date);
9640			var viewType = gotoOptions.type;
9641
9642			// property like "navLinkDayClick". might be a string or a function
9643			var customAction = currentView.opt('navLink' + capitaliseFirstLetter(viewType) + 'Click');
9644
9645			if (typeof customAction === 'function') {
9646				customAction(date, ev);
9647			}
9648			else {
9649				if (typeof customAction === 'string') {
9650					viewType = customAction;
9651				}
9652				zoomTo(date, viewType);
9653			}
9654		});
9655
9656		// called immediately, and upon option change
9657		t.bindOption('theme', function(theme) {
9658			tm = theme ? 'ui' : 'fc'; // affects a larger scope
9659			element.toggleClass('ui-widget', theme);
9660			element.toggleClass('fc-unthemed', !theme);
9661		});
9662
9663		// called immediately, and upon option change.
9664		// HACK: locale often affects isRTL, so we explicitly listen to that too.
9665		t.bindOptions([ 'isRTL', 'locale' ], function(isRTL) {
9666			element.toggleClass('fc-ltr', !isRTL);
9667			element.toggleClass('fc-rtl', isRTL);
9668		});
9669
9670		content = $("<div class='fc-view-container'/>").prependTo(element);
9671
9672		header = t.header = new Header(t);
9673		renderHeader();
9674
9675		renderView(t.options.defaultView);
9676
9677		if (t.options.handleWindowResize) {
9678			windowResizeProxy = debounce(windowResize, t.options.windowResizeDelay); // prevents rapid calls
9679			$(window).resize(windowResizeProxy);
9680		}
9681	}
9682
9683
9684	// can be called repeatedly and Header will rerender
9685	function renderHeader() {
9686		header.render();
9687		if (header.el) {
9688			element.prepend(header.el);
9689		}
9690	}
9691	
9692	
9693	function destroy() {
9694
9695		if (currentView) {
9696			currentView.removeElement();
9697
9698			// NOTE: don't null-out currentView/t.view in case API methods are called after destroy.
9699			// It is still the "current" view, just not rendered.
9700		}
9701
9702		header.removeElement();
9703		content.remove();
9704		element.removeClass('fc fc-ltr fc-rtl fc-unthemed ui-widget');
9705
9706		element.off('.fc'); // unbind nav link handlers
9707
9708		if (windowResizeProxy) {
9709			$(window).unbind('resize', windowResizeProxy);
9710		}
9711	}
9712	
9713	
9714	function elementVisible() {
9715		return element.is(':visible');
9716	}
9717	
9718	
9719
9720	// View Rendering
9721	// -----------------------------------------------------------------------------------
9722
9723
9724	// Renders a view because of a date change, view-type change, or for the first time.
9725	// If not given a viewType, keep the current view but render different dates.
9726	// Accepts an optional scroll state to restore to.
9727	function renderView(viewType, explicitScrollState) {
9728		ignoreWindowResize++;
9729
9730		// if viewType is changing, remove the old view's rendering
9731		if (currentView && viewType && currentView.type !== viewType) {
9732			freezeContentHeight(); // prevent a scroll jump when view element is removed
9733			clearView();
9734		}
9735
9736		// if viewType changed, or the view was never created, create a fresh view
9737		if (!currentView && viewType) {
9738			currentView = t.view =
9739				viewsByType[viewType] ||
9740				(viewsByType[viewType] = t.instantiateView(viewType));
9741
9742			currentView.setElement(
9743				$("<div class='fc-view fc-" + viewType + "-view' />").appendTo(content)
9744			);
9745			header.activateButton(viewType);
9746		}
9747
9748		if (currentView) {
9749
9750			// in case the view should render a period of time that is completely hidden
9751			date = currentView.massageCurrentDate(date);
9752
9753			// render or rerender the view
9754			if (
9755				!currentView.displaying ||
9756				!( // NOT within interval range signals an implicit date window change
9757					date >= currentView.intervalStart &&
9758					date < currentView.intervalEnd
9759				)
9760			) {
9761				if (elementVisible()) {
9762
9763					currentView.display(date, explicitScrollState); // will call freezeContentHeight
9764					unfreezeContentHeight(); // immediately unfreeze regardless of whether display is async
9765
9766					// need to do this after View::render, so dates are calculated
9767					updateHeaderTitle();
9768					updateTodayButton();
9769
9770					getAndRenderEvents();
9771				}
9772			}
9773		}
9774
9775		unfreezeContentHeight(); // undo any lone freezeContentHeight calls
9776		ignoreWindowResize--;
9777	}
9778
9779
9780	// Unrenders the current view and reflects this change in the Header.
9781	// Unregsiters the `currentView`, but does not remove from viewByType hash.
9782	function clearView() {
9783		header.deactivateButton(currentView.type);
9784		currentView.removeElement();
9785		currentView = t.view = null;
9786	}
9787
9788
9789	// Destroys the view, including the view object. Then, re-instantiates it and renders it.
9790	// Maintains the same scroll state.
9791	// TODO: maintain any other user-manipulated state.
9792	function reinitView() {
9793		ignoreWindowResize++;
9794		freezeContentHeight();
9795
9796		var viewType = currentView.type;
9797		var scrollState = currentView.queryScroll();
9798		clearView();
9799		renderView(viewType, scrollState);
9800
9801		unfreezeContentHeight();
9802		ignoreWindowResize--;
9803	}
9804
9805	
9806
9807	// Resizing
9808	// -----------------------------------------------------------------------------------
9809
9810
9811	t.getSuggestedViewHeight = function() {
9812		if (suggestedViewHeight === undefined) {
9813			calcSize();
9814		}
9815		return suggestedViewHeight;
9816	};
9817
9818
9819	t.isHeightAuto = function() {
9820		return t.options.contentHeight === 'auto' || t.options.height === 'auto';
9821	};
9822	
9823	
9824	function updateSize(shouldRecalc) {
9825		if (elementVisible()) {
9826
9827			if (shouldRecalc) {
9828				_calcSize();
9829			}
9830
9831			ignoreWindowResize++;
9832			currentView.updateSize(true); // isResize=true. will poll getSuggestedViewHeight() and isHeightAuto()
9833			ignoreWindowResize--;
9834
9835			return true; // signal success
9836		}
9837	}
9838
9839
9840	function calcSize() {
9841		if (elementVisible()) {
9842			_calcSize();
9843		}
9844	}
9845	
9846	
9847	function _calcSize() { // assumes elementVisible
9848		var contentHeightInput = t.options.contentHeight;
9849		var heightInput = t.options.height;
9850
9851		if (typeof contentHeightInput === 'number') { // exists and not 'auto'
9852			suggestedViewHeight = contentHeightInput;
9853		}
9854		else if (typeof contentHeightInput === 'function') { // exists and is a function
9855			suggestedViewHeight = contentHeightInput();
9856		}
9857		else if (typeof heightInput === 'number') { // exists and not 'auto'
9858			suggestedViewHeight = heightInput - queryHeaderHeight();
9859		}
9860		else if (typeof heightInput === 'function') { // exists and is a function
9861			suggestedViewHeight = heightInput() - queryHeaderHeight();
9862		}
9863		else if (heightInput === 'parent') { // set to height of parent element
9864			suggestedViewHeight = element.parent().height() - queryHeaderHeight();
9865		}
9866		else {
9867			suggestedViewHeight = Math.round(content.width() / Math.max(t.options.aspectRatio, .5));
9868		}
9869	}
9870
9871
9872	function queryHeaderHeight() {
9873		return header.el ? header.el.outerHeight(true) : 0; // includes margin
9874	}
9875	
9876	
9877	function windowResize(ev) {
9878		if (
9879			!ignoreWindowResize &&
9880			ev.target === window && // so we don't process jqui "resize" events that have bubbled up
9881			currentView.start // view has already been rendered
9882		) {
9883			if (updateSize(true)) {
9884				currentView.trigger('windowResize', _element);
9885			}
9886		}
9887	}
9888	
9889	
9890	
9891	/* Event Fetching/Rendering
9892	-----------------------------------------------------------------------------*/
9893	// TODO: going forward, most of this stuff should be directly handled by the view
9894
9895
9896	function refetchEvents() { // can be called as an API method
9897		fetchAndRenderEvents();
9898	}
9899
9900
9901	// TODO: move this into EventManager?
9902	function refetchEventSources(matchInputs) {
9903		fetchEventSources(t.getEventSourcesByMatchArray(matchInputs));
9904	}
9905
9906
9907	function renderEvents() { // destroys old events if previously rendered
9908		if (elementVisible()) {
9909			freezeContentHeight();
9910			currentView.displayEvents(events);
9911			unfreezeContentHeight();
9912		}
9913	}
9914	
9915
9916	function getAndRenderEvents() {
9917		if (!t.options.lazyFetching || isFetchNeeded(currentView.start, currentView.end)) {
9918			fetchAndRenderEvents();
9919		}
9920		else {
9921			renderEvents();
9922		}
9923	}
9924
9925
9926	function fetchAndRenderEvents() {
9927		fetchEvents(currentView.start, currentView.end);
9928			// ... will call reportEvents
9929			// ... which will call renderEvents
9930	}
9931
9932	
9933	// called when event data arrives
9934	function reportEvents(_events) {
9935		events = _events;
9936		renderEvents();
9937	}
9938
9939
9940	// called when a single event's data has been changed
9941	function reportEventChange() {
9942		renderEvents();
9943	}
9944
9945
9946
9947	/* Header Updating
9948	-----------------------------------------------------------------------------*/
9949
9950
9951	function updateHeaderTitle() {
9952		header.updateTitle(currentView.title);
9953	}
9954
9955
9956	function updateTodayButton() {
9957		var now = t.getNow();
9958
9959		if (now >= currentView.intervalStart && now < currentView.intervalEnd) {
9960			header.disableButton('today');
9961		}
9962		else {
9963			header.enableButton('today');
9964		}
9965	}
9966	
9967
9968
9969	/* Selection
9970	-----------------------------------------------------------------------------*/
9971	
9972
9973	// this public method receives start/end dates in any format, with any timezone
9974	function select(zonedStartInput, zonedEndInput) {
9975		currentView.select(
9976			t.buildSelectSpan.apply(t, arguments)
9977		);
9978	}
9979	
9980
9981	function unselect() { // safe to be called before renderView
9982		if (currentView) {
9983			currentView.unselect();
9984		}
9985	}
9986	
9987	
9988	
9989	/* Date
9990	-----------------------------------------------------------------------------*/
9991	
9992	
9993	function prev() {
9994		date = currentView.computePrevDate(date);
9995		renderView();
9996	}
9997	
9998	
9999	function next() {
10000		date = currentView.computeNextDate(date);
10001		renderView();
10002	}
10003	
10004	
10005	function prevYear() {
10006		date.add(-1, 'years');
10007		renderView();
10008	}
10009	
10010	
10011	function nextYear() {
10012		date.add(1, 'years');
10013		renderView();
10014	}
10015	
10016	
10017	function today() {
10018		date = t.getNow();
10019		renderView();
10020	}
10021	
10022	
10023	function gotoDate(zonedDateInput) {
10024		date = t.moment(zonedDateInput).stripZone();
10025		renderView();
10026	}
10027	
10028	
10029	function incrementDate(delta) {
10030		date.add(moment.duration(delta));
10031		renderView();
10032	}
10033
10034
10035	// Forces navigation to a view for the given date.
10036	// `viewType` can be a specific view name or a generic one like "week" or "day".
10037	function zoomTo(newDate, viewType) {
10038		var spec;
10039
10040		viewType = viewType || 'day'; // day is default zoom
10041		spec = t.getViewSpec(viewType) || t.getUnitViewSpec(viewType);
10042
10043		date = newDate.clone();
10044		renderView(spec ? spec.type : null);
10045	}
10046	
10047	
10048	// for external API
10049	function getDate() {
10050		return t.applyTimezone(date); // infuse the calendar's timezone
10051	}
10052
10053
10054
10055	/* Height "Freezing"
10056	-----------------------------------------------------------------------------*/
10057	// TODO: move this into the view
10058
10059	t.freezeContentHeight = freezeContentHeight;
10060	t.unfreezeContentHeight = unfreezeContentHeight;
10061
10062
10063	function freezeContentHeight() {
10064		content.css({
10065			width: '100%',
10066			height: content.height(),
10067			overflow: 'hidden'
10068		});
10069	}
10070
10071
10072	function unfreezeContentHeight() {
10073		content.css({
10074			width: '',
10075			height: '',
10076			overflow: ''
10077		});
10078	}
10079	
10080	
10081	
10082	/* Misc
10083	-----------------------------------------------------------------------------*/
10084	
10085
10086	function getCalendar() {
10087		return t;
10088	}
10089
10090	
10091	function getView() {
10092		return currentView;
10093	}
10094	
10095	
10096	function option(name, value) {
10097		var newOptionHash;
10098
10099		if (typeof name === 'string') {
10100			if (value === undefined) { // getter
10101				return t.options[name];
10102			}
10103			else { // setter for individual option
10104				newOptionHash = {};
10105				newOptionHash[name] = value;
10106				setOptions(newOptionHash);
10107			}
10108		}
10109		else if (typeof name === 'object') { // compound setter with object input
10110			setOptions(name);
10111		}
10112	}
10113
10114
10115	function setOptions(newOptionHash) {
10116		var optionCnt = 0;
10117		var optionName;
10118
10119		for (optionName in newOptionHash) {
10120			t.dynamicOverrides[optionName] = newOptionHash[optionName];
10121		}
10122
10123		t.viewSpecCache = {}; // the dynamic override invalidates the options in this cache, so just clear it
10124		t.populateOptionsHash(); // this.options needs to be recomputed after the dynamic override
10125
10126		// trigger handlers after this.options has been updated
10127		for (optionName in newOptionHash) {
10128			t.triggerOptionHandlers(optionName); // recall bindOption/bindOptions
10129			optionCnt++;
10130		}
10131
10132		// special-case handling of single option change.
10133		// if only one option change, `optionName` will be its name.
10134		if (optionCnt === 1) {
10135			if (optionName === 'height' || optionName === 'contentHeight' || optionName === 'aspectRatio') {
10136				updateSize(true); // true = allow recalculation of height
10137				return;
10138			}
10139			else if (optionName === 'defaultDate') {
10140				return; // can't change date this way. use gotoDate instead
10141			}
10142			else if (optionName === 'businessHours') {
10143				if (currentView) {
10144					currentView.unrenderBusinessHours();
10145					currentView.renderBusinessHours();
10146				}
10147				return;
10148			}
10149			else if (optionName === 'timezone') {
10150				t.rezoneArrayEventSources();
10151				refetchEvents();
10152				return;
10153			}
10154		}
10155
10156		// catch-all. rerender the header and rebuild/rerender the current view
10157		renderHeader();
10158		viewsByType = {}; // even non-current views will be affected by this option change. do before rerender
10159		reinitView();
10160	}
10161	
10162	
10163	function trigger(name, thisObj) { // overrides the Emitter's trigger method :(
10164		var args = Array.prototype.slice.call(arguments, 2);
10165
10166		thisObj = thisObj || _element;
10167		this.triggerWith(name, thisObj, args); // Emitter's method
10168
10169		if (t.options[name]) {
10170			return t.options[name].apply(thisObj, args);
10171		}
10172	}
10173
10174	t.initialize();
10175}
10176
10177;;
10178/*
10179Options binding/triggering system.
10180*/
10181Calendar.mixin({
10182
10183	// A map of option names to arrays of handler objects. Initialized to {} in Calendar.
10184	// Format for a handler object:
10185	// {
10186	//   func // callback function to be called upon change
10187	//   names // option names whose values should be given to func
10188	// }
10189	optionHandlers: null, 
10190
10191	// Calls handlerFunc immediately, and when the given option has changed.
10192	// handlerFunc will be given the option value.
10193	bindOption: function(optionName, handlerFunc) {
10194		this.bindOptions([ optionName ], handlerFunc);
10195	},
10196
10197	// Calls handlerFunc immediately, and when any of the given options change.
10198	// handlerFunc will be given each option value as ordered function arguments.
10199	bindOptions: function(optionNames, handlerFunc) {
10200		var handlerObj = { func: handlerFunc, names: optionNames };
10201		var i;
10202
10203		for (i = 0; i < optionNames.length; i++) {
10204			this.registerOptionHandlerObj(optionNames[i], handlerObj);
10205		}
10206
10207		this.triggerOptionHandlerObj(handlerObj);
10208	},
10209
10210	// Puts the given handler object into the internal hash
10211	registerOptionHandlerObj: function(optionName, handlerObj) {
10212		(this.optionHandlers[optionName] || (this.optionHandlers[optionName] = []))
10213			.push(handlerObj);
10214	},
10215
10216	// Reports that the given option has changed, and calls all appropriate handlers.
10217	triggerOptionHandlers: function(optionName) {
10218		var handlerObjs = this.optionHandlers[optionName] || [];
10219		var i;
10220
10221		for (i = 0; i < handlerObjs.length; i++) {
10222			this.triggerOptionHandlerObj(handlerObjs[i]);
10223		}
10224	},
10225
10226	// Calls the callback for a specific handler object, passing in the appropriate arguments.
10227	triggerOptionHandlerObj: function(handlerObj) {
10228		var optionNames = handlerObj.names;
10229		var optionValues = [];
10230		var i;
10231
10232		for (i = 0; i < optionNames.length; i++) {
10233			optionValues.push(this.options[optionNames[i]]);
10234		}
10235
10236		handlerObj.func.apply(this, optionValues); // maintain the Calendar's `this` context
10237	}
10238
10239});
10240
10241;;
10242
10243Calendar.defaults = {
10244
10245	titleRangeSeparator: ' \u2013 ', // en dash
10246	monthYearFormat: 'MMMM YYYY', // required for en. other locales rely on datepicker computable option
10247
10248	defaultTimedEventDuration: '02:00:00',
10249	defaultAllDayEventDuration: { days: 1 },
10250	forceEventDuration: false,
10251	nextDayThreshold: '09:00:00', // 9am
10252
10253	// display
10254	defaultView: 'month',
10255	aspectRatio: 1.35,
10256	header: {
10257		left: 'title',
10258		center: '',
10259		right: 'today prev,next'
10260	},
10261	weekends: true,
10262	weekNumbers: false,
10263
10264	weekNumberTitle: 'W',
10265	weekNumberCalculation: 'local',
10266	
10267	//editable: false,
10268
10269	//nowIndicator: false,
10270
10271	scrollTime: '06:00:00',
10272	
10273	// event ajax
10274	lazyFetching: true,
10275	startParam: 'start',
10276	endParam: 'end',
10277	timezoneParam: 'timezone',
10278
10279	timezone: false,
10280
10281	//allDayDefault: undefined,
10282
10283	// locale
10284	isRTL: false,
10285	buttonText: {
10286		prev: "prev",
10287		next: "next",
10288		prevYear: "prev year",
10289		nextYear: "next year",
10290		year: 'year', // TODO: locale files need to specify this
10291		today: 'today',
10292		month: 'month',
10293		week: 'week',
10294		day: 'day'
10295	},
10296
10297	buttonIcons: {
10298		prev: 'left-single-arrow',
10299		next: 'right-single-arrow',
10300		prevYear: 'left-double-arrow',
10301		nextYear: 'right-double-arrow'
10302	},
10303
10304	allDayText: 'all-day',
10305	
10306	// jquery-ui theming
10307	theme: false,
10308	themeButtonIcons: {
10309		prev: 'circle-triangle-w',
10310		next: 'circle-triangle-e',
10311		prevYear: 'seek-prev',
10312		nextYear: 'seek-next'
10313	},
10314
10315	//eventResizableFromStart: false,
10316	dragOpacity: .75,
10317	dragRevertDuration: 500,
10318	dragScroll: true,
10319	
10320	//selectable: false,
10321	unselectAuto: true,
10322	
10323	dropAccept: '*',
10324
10325	eventOrder: 'title',
10326
10327	eventLimit: false,
10328	eventLimitText: 'more',
10329	eventLimitClick: 'popover',
10330	dayPopoverFormat: 'LL',
10331	
10332	handleWindowResize: true,
10333	windowResizeDelay: 100, // milliseconds before an updateSize happens
10334
10335	longPressDelay: 1000
10336	
10337};
10338
10339
10340Calendar.englishDefaults = { // used by locale.js
10341	dayPopoverFormat: 'dddd, MMMM D'
10342};
10343
10344
10345Calendar.rtlDefaults = { // right-to-left defaults
10346	header: { // TODO: smarter solution (first/center/last ?)
10347		left: 'next,prev today',
10348		center: '',
10349		right: 'title'
10350	},
10351	buttonIcons: {
10352		prev: 'right-single-arrow',
10353		next: 'left-single-arrow',
10354		prevYear: 'right-double-arrow',
10355		nextYear: 'left-double-arrow'
10356	},
10357	themeButtonIcons: {
10358		prev: 'circle-triangle-e',
10359		next: 'circle-triangle-w',
10360		nextYear: 'seek-prev',
10361		prevYear: 'seek-next'
10362	}
10363};
10364
10365;;
10366
10367var localeOptionHash = FC.locales = {}; // initialize and expose
10368
10369
10370// TODO: document the structure and ordering of a FullCalendar locale file
10371
10372
10373// Initialize jQuery UI datepicker translations while using some of the translations
10374// Will set this as the default locales for datepicker.
10375FC.datepickerLocale = function(localeCode, dpLocaleCode, dpOptions) {
10376
10377	// get the FullCalendar internal option hash for this locale. create if necessary
10378	var fcOptions = localeOptionHash[localeCode] || (localeOptionHash[localeCode] = {});
10379
10380	// transfer some simple options from datepicker to fc
10381	fcOptions.isRTL = dpOptions.isRTL;
10382	fcOptions.weekNumberTitle = dpOptions.weekHeader;
10383
10384	// compute some more complex options from datepicker
10385	$.each(dpComputableOptions, function(name, func) {
10386		fcOptions[name] = func(dpOptions);
10387	});
10388
10389	// is jQuery UI Datepicker is on the page?
10390	if ($.datepicker) {
10391
10392		// Register the locale data.
10393		// FullCalendar and MomentJS use locale codes like "pt-br" but Datepicker
10394		// does it like "pt-BR" or if it doesn't have the locale, maybe just "pt".
10395		// Make an alias so the locale can be referenced either way.
10396		$.datepicker.regional[dpLocaleCode] =
10397			$.datepicker.regional[localeCode] = // alias
10398				dpOptions;
10399
10400		// Alias 'en' to the default locale data. Do this every time.
10401		$.datepicker.regional.en = $.datepicker.regional[''];
10402
10403		// Set as Datepicker's global defaults.
10404		$.datepicker.setDefaults(dpOptions);
10405	}
10406};
10407
10408
10409// Sets FullCalendar-specific translations. Will set the locales as the global default.
10410FC.locale = function(localeCode, newFcOptions) {
10411	var fcOptions;
10412	var momOptions;
10413
10414	// get the FullCalendar internal option hash for this locale. create if necessary
10415	fcOptions = localeOptionHash[localeCode] || (localeOptionHash[localeCode] = {});
10416
10417	// provided new options for this locales? merge them in
10418	if (newFcOptions) {
10419		fcOptions = localeOptionHash[localeCode] = mergeOptions([ fcOptions, newFcOptions ]);
10420	}
10421
10422	// compute locale options that weren't defined.
10423	// always do this. newFcOptions can be undefined when initializing from i18n file,
10424	// so no way to tell if this is an initialization or a default-setting.
10425	momOptions = getMomentLocaleData(localeCode); // will fall back to en
10426	$.each(momComputableOptions, function(name, func) {
10427		if (fcOptions[name] == null) {
10428			fcOptions[name] = func(momOptions, fcOptions);
10429		}
10430	});
10431
10432	// set it as the default locale for FullCalendar
10433	Calendar.defaults.locale = localeCode;
10434};
10435
10436
10437// NOTE: can't guarantee any of these computations will run because not every locale has datepicker
10438// configs, so make sure there are English fallbacks for these in the defaults file.
10439var dpComputableOptions = {
10440
10441	buttonText: function(dpOptions) {
10442		return {
10443			// the translations sometimes wrongly contain HTML entities
10444			prev: stripHtmlEntities(dpOptions.prevText),
10445			next: stripHtmlEntities(dpOptions.nextText),
10446			today: stripHtmlEntities(dpOptions.currentText)
10447		};
10448	},
10449
10450	// Produces format strings like "MMMM YYYY" -> "September 2014"
10451	monthYearFormat: function(dpOptions) {
10452		return dpOptions.showMonthAfterYear ?
10453			'YYYY[' + dpOptions.yearSuffix + '] MMMM' :
10454			'MMMM YYYY[' + dpOptions.yearSuffix + ']';
10455	}
10456
10457};
10458
10459var momComputableOptions = {
10460
10461	// Produces format strings like "ddd M/D" -> "Fri 9/15"
10462	dayOfMonthFormat: function(momOptions, fcOptions) {
10463		var format = momOptions.longDateFormat('l'); // for the format like "M/D/YYYY"
10464
10465		// strip the year off the edge, as well as other misc non-whitespace chars
10466		format = format.replace(/^Y+[^\w\s]*|[^\w\s]*Y+$/g, '');
10467
10468		if (fcOptions.isRTL) {
10469			format += ' ddd'; // for RTL, add day-of-week to end
10470		}
10471		else {
10472			format = 'ddd ' + format; // for LTR, add day-of-week to beginning
10473		}
10474		return format;
10475	},
10476
10477	// Produces format strings like "h:mma" -> "6:00pm"
10478	mediumTimeFormat: function(momOptions) { // can't be called `timeFormat` because collides with option
10479		return momOptions.longDateFormat('LT')
10480			.replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
10481	},
10482
10483	// Produces format strings like "h(:mm)a" -> "6pm" / "6:30pm"
10484	smallTimeFormat: function(momOptions) {
10485		return momOptions.longDateFormat('LT')
10486			.replace(':mm', '(:mm)')
10487			.replace(/(\Wmm)$/, '($1)') // like above, but for foreign locales
10488			.replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
10489	},
10490
10491	// Produces format strings like "h(:mm)t" -> "6p" / "6:30p"
10492	extraSmallTimeFormat: function(momOptions) {
10493		return momOptions.longDateFormat('LT')
10494			.replace(':mm', '(:mm)')
10495			.replace(/(\Wmm)$/, '($1)') // like above, but for foreign locales
10496			.replace(/\s*a$/i, 't'); // convert to AM/PM/am/pm to lowercase one-letter. remove any spaces beforehand
10497	},
10498
10499	// Produces format strings like "ha" / "H" -> "6pm" / "18"
10500	hourFormat: function(momOptions) {
10501		return momOptions.longDateFormat('LT')
10502			.replace(':mm', '')
10503			.replace(/(\Wmm)$/, '') // like above, but for foreign locales
10504			.replace(/\s*a$/i, 'a'); // convert AM/PM/am/pm to lowercase. remove any spaces beforehand
10505	},
10506
10507	// Produces format strings like "h:mm" -> "6:30" (with no AM/PM)
10508	noMeridiemTimeFormat: function(momOptions) {
10509		return momOptions.longDateFormat('LT')
10510			.replace(/\s*a$/i, ''); // remove trailing AM/PM
10511	}
10512
10513};
10514
10515
10516// options that should be computed off live calendar options (considers override options)
10517// TODO: best place for this? related to locale?
10518// TODO: flipping text based on isRTL is a bad idea because the CSS `direction` might want to handle it
10519var instanceComputableOptions = {
10520
10521	// Produces format strings for results like "Mo 16"
10522	smallDayDateFormat: function(options) {
10523		return options.isRTL ?
10524			'D dd' :
10525			'dd D';
10526	},
10527
10528	// Produces format strings for results like "Wk 5"
10529	weekFormat: function(options) {
10530		return options.isRTL ?
10531			'w[ ' + options.weekNumberTitle + ']' :
10532			'[' + options.weekNumberTitle + ' ]w';
10533	},
10534
10535	// Produces format strings for results like "Wk5"
10536	smallWeekFormat: function(options) {
10537		return options.isRTL ?
10538			'w[' + options.weekNumberTitle + ']' :
10539			'[' + options.weekNumberTitle + ']w';
10540	}
10541
10542};
10543
10544function populateInstanceComputableOptions(options) {
10545	$.each(instanceComputableOptions, function(name, func) {
10546		if (options[name] == null) {
10547			options[name] = func(options);
10548		}
10549	});
10550}
10551
10552
10553// Returns moment's internal locale data. If doesn't exist, returns English.
10554function getMomentLocaleData(localeCode) {
10555	return moment.localeData(localeCode) || moment.localeData('en');
10556}
10557
10558
10559// Initialize English by forcing computation of moment-derived options.
10560// Also, sets it as the default.
10561FC.locale('en', Calendar.englishDefaults);
10562
10563;;
10564
10565/* Top toolbar area with buttons and title
10566----------------------------------------------------------------------------------------------------------------------*/
10567// TODO: rename all header-related things to "toolbar"
10568
10569function Header(calendar) {
10570	var t = this;
10571	
10572	// exports
10573	t.render = render;
10574	t.removeElement = removeElement;
10575	t.updateTitle = updateTitle;
10576	t.activateButton = activateButton;
10577	t.deactivateButton = deactivateButton;
10578	t.disableButton = disableButton;
10579	t.enableButton = enableButton;
10580	t.getViewsWithButtons = getViewsWithButtons;
10581	t.el = null; // mirrors local `el`
10582	
10583	// locals
10584	var el;
10585	var viewsWithButtons = [];
10586	var tm;
10587
10588
10589	// can be called repeatedly and will rerender
10590	function render() {
10591		var options = calendar.options;
10592		var sections = options.header;
10593
10594		tm = options.theme ? 'ui' : 'fc';
10595
10596		if (sections) {
10597			if (!el) {
10598				el = this.el = $("<div class='fc-toolbar'/>");
10599			}
10600			else {
10601				el.empty();
10602			}
10603			el.append(renderSection('left'))
10604				.append(renderSection('right'))
10605				.append(renderSection('center'))
10606				.append('<div class="fc-clear"/>');
10607		}
10608		else {
10609			removeElement();
10610		}
10611	}
10612	
10613	
10614	function removeElement() {
10615		if (el) {
10616			el.remove();
10617			el = t.el = null;
10618		}
10619	}
10620	
10621	
10622	function renderSection(position) {
10623		var sectionEl = $('<div class="fc-' + position + '"/>');
10624		var options = calendar.options;
10625		var buttonStr = options.header[position];
10626
10627		if (buttonStr) {
10628			$.each(buttonStr.split(' '), function(i) {
10629				var groupChildren = $();
10630				var isOnlyButtons = true;
10631				var groupEl;
10632
10633				$.each(this.split(','), function(j, buttonName) {
10634					var customButtonProps;
10635					var viewSpec;
10636					var buttonClick;
10637					var overrideText; // text explicitly set by calendar's constructor options. overcomes icons
10638					var defaultText;
10639					var themeIcon;
10640					var normalIcon;
10641					var innerHtml;
10642					var classes;
10643					var button; // the element
10644
10645					if (buttonName == 'title') {
10646						groupChildren = groupChildren.add($('<h2>&nbsp;</h2>')); // we always want it to take up height
10647						isOnlyButtons = false;
10648					}
10649					else {
10650						if ((customButtonProps = (options.customButtons || {})[buttonName])) {
10651							buttonClick = function(ev) {
10652								if (customButtonProps.click) {
10653									customButtonProps.click.call(button[0], ev);
10654								}
10655							};
10656							overrideText = ''; // icons will override text
10657							defaultText = customButtonProps.text;
10658						}
10659						else if ((viewSpec = calendar.getViewSpec(buttonName))) {
10660							buttonClick = function() {
10661								calendar.changeView(buttonName);
10662							};
10663							viewsWithButtons.push(buttonName);
10664							overrideText = viewSpec.buttonTextOverride;
10665							defaultText = viewSpec.buttonTextDefault;
10666						}
10667						else if (calendar[buttonName]) { // a calendar method
10668							buttonClick = function() {
10669								calendar[buttonName]();
10670							};
10671							overrideText = (calendar.overrides.buttonText || {})[buttonName];
10672							defaultText = options.buttonText[buttonName]; // everything else is considered default
10673						}
10674
10675						if (buttonClick) {
10676
10677							themeIcon =
10678								customButtonProps ?
10679									customButtonProps.themeIcon :
10680									options.themeButtonIcons[buttonName];
10681
10682							normalIcon =
10683								customButtonProps ?
10684									customButtonProps.icon :
10685									options.buttonIcons[buttonName];
10686
10687							if (overrideText) {
10688								innerHtml = htmlEscape(overrideText);
10689							}
10690							else if (themeIcon && options.theme) {
10691								innerHtml = "<span class='ui-icon ui-icon-" + themeIcon + "'></span>";
10692							}
10693							else if (normalIcon && !options.theme) {
10694								innerHtml = "<span class='fc-icon fc-icon-" + normalIcon + "'></span>";
10695							}
10696							else {
10697								innerHtml = htmlEscape(defaultText);
10698							}
10699
10700							classes = [
10701								'fc-' + buttonName + '-button',
10702								tm + '-button',
10703								tm + '-state-default'
10704							];
10705
10706							button = $( // type="button" so that it doesn't submit a form
10707								'<button type="button" class="' + classes.join(' ') + '">' +
10708									innerHtml +
10709								'</button>'
10710								)
10711								.click(function(ev) {
10712									// don't process clicks for disabled buttons
10713									if (!button.hasClass(tm + '-state-disabled')) {
10714
10715										buttonClick(ev);
10716
10717										// after the click action, if the button becomes the "active" tab, or disabled,
10718										// it should never have a hover class, so remove it now.
10719										if (
10720											button.hasClass(tm + '-state-active') ||
10721											button.hasClass(tm + '-state-disabled')
10722										) {
10723											button.removeClass(tm + '-state-hover');
10724										}
10725									}
10726								})
10727								.mousedown(function() {
10728									// the *down* effect (mouse pressed in).
10729									// only on buttons that are not the "active" tab, or disabled
10730									button
10731										.not('.' + tm + '-state-active')
10732										.not('.' + tm + '-state-disabled')
10733										.addClass(tm + '-state-down');
10734								})
10735								.mouseup(function() {
10736									// undo the *down* effect
10737									button.removeClass(tm + '-state-down');
10738								})
10739								.hover(
10740									function() {
10741										// the *hover* effect.
10742										// only on buttons that are not the "active" tab, or disabled
10743										button
10744											.not('.' + tm + '-state-active')
10745											.not('.' + tm + '-state-disabled')
10746											.addClass(tm + '-state-hover');
10747									},
10748									function() {
10749										// undo the *hover* effect
10750										button
10751											.removeClass(tm + '-state-hover')
10752											.removeClass(tm + '-state-down'); // if mouseleave happens before mouseup
10753									}
10754								);
10755
10756							groupChildren = groupChildren.add(button);
10757						}
10758					}
10759				});
10760
10761				if (isOnlyButtons) {
10762					groupChildren
10763						.first().addClass(tm + '-corner-left').end()
10764						.last().addClass(tm + '-corner-right').end();
10765				}
10766
10767				if (groupChildren.length > 1) {
10768					groupEl = $('<div/>');
10769					if (isOnlyButtons) {
10770						groupEl.addClass('fc-button-group');
10771					}
10772					groupEl.append(groupChildren);
10773					sectionEl.append(groupEl);
10774				}
10775				else {
10776					sectionEl.append(groupChildren); // 1 or 0 children
10777				}
10778			});
10779		}
10780
10781		return sectionEl;
10782	}
10783	
10784	
10785	function updateTitle(text) {
10786		if (el) {
10787			el.find('h2').text(text);
10788		}
10789	}
10790	
10791	
10792	function activateButton(buttonName) {
10793		if (el) {
10794			el.find('.fc-' + buttonName + '-button')
10795				.addClass(tm + '-state-active');
10796		}
10797	}
10798	
10799	
10800	function deactivateButton(buttonName) {
10801		if (el) {
10802			el.find('.fc-' + buttonName + '-button')
10803				.removeClass(tm + '-state-active');
10804		}
10805	}
10806	
10807	
10808	function disableButton(buttonName) {
10809		if (el) {
10810			el.find('.fc-' + buttonName + '-button')
10811				.prop('disabled', true)
10812				.addClass(tm + '-state-disabled');
10813		}
10814	}
10815	
10816	
10817	function enableButton(buttonName) {
10818		if (el) {
10819			el.find('.fc-' + buttonName + '-button')
10820				.prop('disabled', false)
10821				.removeClass(tm + '-state-disabled');
10822		}
10823	}
10824
10825
10826	function getViewsWithButtons() {
10827		return viewsWithButtons;
10828	}
10829
10830}
10831
10832;;
10833
10834FC.sourceNormalizers = [];
10835FC.sourceFetchers = [];
10836
10837var ajaxDefaults = {
10838	dataType: 'json',
10839	cache: false
10840};
10841
10842var eventGUID = 1;
10843
10844
10845function EventManager() { // assumed to be a calendar
10846	var t = this;
10847	
10848	
10849	// exports
10850	t.isFetchNeeded = isFetchNeeded;
10851	t.fetchEvents = fetchEvents;
10852	t.fetchEventSources = fetchEventSources;
10853	t.getEventSources = getEventSources;
10854	t.getEventSourceById = getEventSourceById;
10855	t.getEventSourcesByMatchArray = getEventSourcesByMatchArray;
10856	t.getEventSourcesByMatch = getEventSourcesByMatch;
10857	t.addEventSource = addEventSource;
10858	t.removeEventSource = removeEventSource;
10859	t.removeEventSources = removeEventSources;
10860	t.updateEvent = updateEvent;
10861	t.renderEvent = renderEvent;
10862	t.removeEvents = removeEvents;
10863	t.clientEvents = clientEvents;
10864	t.mutateEvent = mutateEvent;
10865	t.normalizeEventDates = normalizeEventDates;
10866	t.normalizeEventTimes = normalizeEventTimes;
10867	
10868	
10869	// imports
10870	var reportEvents = t.reportEvents;
10871	
10872	
10873	// locals
10874	var stickySource = { events: [] };
10875	var sources = [ stickySource ];
10876	var rangeStart, rangeEnd;
10877	var pendingSourceCnt = 0; // outstanding fetch requests, max one per source
10878	var cache = []; // holds events that have already been expanded
10879
10880
10881	$.each(
10882		(t.options.events ? [ t.options.events ] : []).concat(t.options.eventSources || []),
10883		function(i, sourceInput) {
10884			var source = buildEventSource(sourceInput);
10885			if (source) {
10886				sources.push(source);
10887			}
10888		}
10889	);
10890	
10891	
10892	
10893	/* Fetching
10894	-----------------------------------------------------------------------------*/
10895
10896
10897	// start and end are assumed to be unzoned
10898	function isFetchNeeded(start, end) {
10899		return !rangeStart || // nothing has been fetched yet?
10900			start < rangeStart || end > rangeEnd; // is part of the new range outside of the old range?
10901	}
10902	
10903	
10904	function fetchEvents(start, end) {
10905		rangeStart = start;
10906		rangeEnd = end;
10907		fetchEventSources(sources, 'reset');
10908	}
10909
10910
10911	// expects an array of event source objects (the originals, not copies)
10912	// `specialFetchType` is an optimization parameter that affects purging of the event cache.
10913	function fetchEventSources(specificSources, specialFetchType) {
10914		var i, source;
10915
10916		if (specialFetchType === 'reset') {
10917			cache = [];
10918		}
10919		else if (specialFetchType !== 'add') {
10920			cache = excludeEventsBySources(cache, specificSources);
10921		}
10922
10923		for (i = 0; i < specificSources.length; i++) {
10924			source = specificSources[i];
10925
10926			// already-pending sources have already been accounted for in pendingSourceCnt
10927			if (source._status !== 'pending') {
10928				pendingSourceCnt++;
10929			}
10930
10931			source._fetchId = (source._fetchId || 0) + 1;
10932			source._status = 'pending';
10933		}
10934
10935		for (i = 0; i < specificSources.length; i++) {
10936			source = specificSources[i];
10937
10938			tryFetchEventSource(source, source._fetchId);
10939		}
10940	}
10941
10942
10943	// fetches an event source and processes its result ONLY if it is still the current fetch.
10944	// caller is responsible for incrementing pendingSourceCnt first.
10945	function tryFetchEventSource(source, fetchId) {
10946		_fetchEventSource(source, function(eventInputs) {
10947			var isArraySource = $.isArray(source.events);
10948			var i, eventInput;
10949			var abstractEvent;
10950
10951			if (
10952				// is this the source's most recent fetch?
10953				// if not, rely on an upcoming fetch of this source to decrement pendingSourceCnt
10954				fetchId === source._fetchId &&
10955				// event source no longer valid?
10956				source._status !== 'rejected'
10957			) {
10958				source._status = 'resolved';
10959
10960				if (eventInputs) {
10961					for (i = 0; i < eventInputs.length; i++) {
10962						eventInput = eventInputs[i];
10963
10964						if (isArraySource) { // array sources have already been convert to Event Objects
10965							abstractEvent = eventInput;
10966						}
10967						else {
10968							abstractEvent = buildEventFromInput(eventInput, source);
10969						}
10970
10971						if (abstractEvent) { // not false (an invalid event)
10972							cache.push.apply(
10973								cache,
10974								expandEvent(abstractEvent) // add individual expanded events to the cache
10975							);
10976						}
10977					}
10978				}
10979
10980				decrementPendingSourceCnt();
10981			}
10982		});
10983	}
10984
10985
10986	function rejectEventSource(source) {
10987		var wasPending = source._status === 'pending';
10988
10989		source._status = 'rejected';
10990
10991		if (wasPending) {
10992			decrementPendingSourceCnt();
10993		}
10994	}
10995
10996
10997	function decrementPendingSourceCnt() {
10998		pendingSourceCnt--;
10999		if (!pendingSourceCnt) {
11000			reportEvents(cache);
11001		}
11002	}
11003	
11004	
11005	function _fetchEventSource(source, callback) {
11006		var i;
11007		var fetchers = FC.sourceFetchers;
11008		var res;
11009
11010		for (i=0; i<fetchers.length; i++) {
11011			res = fetchers[i].call(
11012				t, // this, the Calendar object
11013				source,
11014				rangeStart.clone(),
11015				rangeEnd.clone(),
11016				t.options.timezone,
11017				callback
11018			);
11019
11020			if (res === true) {
11021				// the fetcher is in charge. made its own async request
11022				return;
11023			}
11024			else if (typeof res == 'object') {
11025				// the fetcher returned a new source. process it
11026				_fetchEventSource(res, callback);
11027				return;
11028			}
11029		}
11030
11031		var events = source.events;
11032		if (events) {
11033			if ($.isFunction(events)) {
11034				t.pushLoading();
11035				events.call(
11036					t, // this, the Calendar object
11037					rangeStart.clone(),
11038					rangeEnd.clone(),
11039					t.options.timezone,
11040					function(events) {
11041						callback(events);
11042						t.popLoading();
11043					}
11044				);
11045			}
11046			else if ($.isArray(events)) {
11047				callback(events);
11048			}
11049			else {
11050				callback();
11051			}
11052		}else{
11053			var url = source.url;
11054			if (url) {
11055				var success = source.success;
11056				var error = source.error;
11057				var complete = source.complete;
11058
11059				// retrieve any outbound GET/POST $.ajax data from the options
11060				var customData;
11061				if ($.isFunction(source.data)) {
11062					// supplied as a function that returns a key/value object
11063					customData = source.data();
11064				}
11065				else {
11066					// supplied as a straight key/value object
11067					customData = source.data;
11068				}
11069
11070				// use a copy of the custom data so we can modify the parameters
11071				// and not affect the passed-in object.
11072				var data = $.extend({}, customData || {});
11073
11074				var startParam = firstDefined(source.startParam, t.options.startParam);
11075				var endParam = firstDefined(source.endParam, t.options.endParam);
11076				var timezoneParam = firstDefined(source.timezoneParam, t.options.timezoneParam);
11077
11078				if (startParam) {
11079					data[startParam] = rangeStart.format();
11080				}
11081				if (endParam) {
11082					data[endParam] = rangeEnd.format();
11083				}
11084				if (t.options.timezone && t.options.timezone != 'local') {
11085					data[timezoneParam] = t.options.timezone;
11086				}
11087
11088				t.pushLoading();
11089				$.ajax($.extend({}, ajaxDefaults, source, {
11090					data: data,
11091					success: function(events) {
11092						events = events || [];
11093						var res = applyAll(success, this, arguments);
11094						if ($.isArray(res)) {
11095							events = res;
11096						}
11097						callback(events);
11098					},
11099					error: function() {
11100						applyAll(error, this, arguments);
11101						callback();
11102					},
11103					complete: function() {
11104						applyAll(complete, this, arguments);
11105						t.popLoading();
11106					}
11107				}));
11108			}else{
11109				callback();
11110			}
11111		}
11112	}
11113	
11114	
11115	
11116	/* Sources
11117	-----------------------------------------------------------------------------*/
11118
11119
11120	function addEventSource(sourceInput) {
11121		var source = buildEventSource(sourceInput);
11122		if (source) {
11123			sources.push(source);
11124			fetchEventSources([ source ], 'add'); // will eventually call reportEvents
11125		}
11126	}
11127
11128
11129	function buildEventSource(sourceInput) { // will return undefined if invalid source
11130		var normalizers = FC.sourceNormalizers;
11131		var source;
11132		var i;
11133
11134		if ($.isFunction(sourceInput) || $.isArray(sourceInput)) {
11135			source = { events: sourceInput };
11136		}
11137		else if (typeof sourceInput === 'string') {
11138			source = { url: sourceInput };
11139		}
11140		else if (typeof sourceInput === 'object') {
11141			source = $.extend({}, sourceInput); // shallow copy
11142		}
11143
11144		if (source) {
11145
11146			// TODO: repeat code, same code for event classNames
11147			if (source.className) {
11148				if (typeof source.className === 'string') {
11149					source.className = source.className.split(/\s+/);
11150				}
11151				// otherwise, assumed to be an array
11152			}
11153			else {
11154				source.className = [];
11155			}
11156
11157			// for array sources, we convert to standard Event Objects up front
11158			if ($.isArray(source.events)) {
11159				source.origArray = source.events; // for removeEventSource
11160				source.events = $.map(source.events, function(eventInput) {
11161					return buildEventFromInput(eventInput, source);
11162				});
11163			}
11164
11165			for (i=0; i<normalizers.length; i++) {
11166				normalizers[i].call(t, source);
11167			}
11168
11169			return source;
11170		}
11171	}
11172
11173
11174	function removeEventSource(matchInput) {
11175		removeSpecificEventSources(
11176			getEventSourcesByMatch(matchInput)
11177		);
11178	}
11179
11180
11181	// if called with no arguments, removes all.
11182	function removeEventSources(matchInputs) {
11183		if (matchInputs == null) {
11184			removeSpecificEventSources(sources, true); // isAll=true
11185		}
11186		else {
11187			removeSpecificEventSources(
11188				getEventSourcesByMatchArray(matchInputs)
11189			);
11190		}
11191	}
11192
11193
11194	function removeSpecificEventSources(targetSources, isAll) {
11195		var i;
11196
11197		// cancel pending requests
11198		for (i = 0; i < targetSources.length; i++) {
11199			rejectEventSource(targetSources[i]);
11200		}
11201
11202		if (isAll) { // an optimization
11203			sources = [];
11204			cache = [];
11205		}
11206		else {
11207			// remove from persisted source list
11208			sources = $.grep(sources, function(source) {
11209				for (i = 0; i < targetSources.length; i++) {
11210					if (source === targetSources[i]) {
11211						return false; // exclude
11212					}
11213				}
11214				return true; // include
11215			});
11216
11217			cache = excludeEventsBySources(cache, targetSources);
11218		}
11219
11220		reportEvents(cache);
11221	}
11222
11223
11224	function getEventSources() {
11225		return sources.slice(1); // returns a shallow copy of sources with stickySource removed
11226	}
11227
11228
11229	function getEventSourceById(id) {
11230		return $.grep(sources, function(source) {
11231			return source.id && source.id === id;
11232		})[0];
11233	}
11234
11235
11236	// like getEventSourcesByMatch, but accepts multple match criteria (like multiple IDs)
11237	function getEventSourcesByMatchArray(matchInputs) {
11238
11239		// coerce into an array
11240		if (!matchInputs) {
11241			matchInputs = [];
11242		}
11243		else if (!$.isArray(matchInputs)) {
11244			matchInputs = [ matchInputs ];
11245		}
11246
11247		var matchingSources = [];
11248		var i;
11249
11250		// resolve raw inputs to real event source objects
11251		for (i = 0; i < matchInputs.length; i++) {
11252			matchingSources.push.apply( // append
11253				matchingSources,
11254				getEventSourcesByMatch(matchInputs[i])
11255			);
11256		}
11257
11258		return matchingSources;
11259	}
11260
11261
11262	// matchInput can either by a real event source object, an ID, or the function/URL for the source.
11263	// returns an array of matching source objects.
11264	function getEventSourcesByMatch(matchInput) {
11265		var i, source;
11266
11267		// given an proper event source object
11268		for (i = 0; i < sources.length; i++) {
11269			source = sources[i];
11270			if (source === matchInput) {
11271				return [ source ];
11272			}
11273		}
11274
11275		// an ID match
11276		source = getEventSourceById(matchInput);
11277		if (source) {
11278			return [ source ];
11279		}
11280
11281		return $.grep(sources, function(source) {
11282			return isSourcesEquivalent(matchInput, source);
11283		});
11284	}
11285
11286
11287	function isSourcesEquivalent(source1, source2) {
11288		return source1 && source2 && getSourcePrimitive(source1) == getSourcePrimitive(source2);
11289	}
11290
11291
11292	function getSourcePrimitive(source) {
11293		return (
11294			(typeof source === 'object') ? // a normalized event source?
11295				(source.origArray || source.googleCalendarId || source.url || source.events) : // get the primitive
11296				null
11297		) ||
11298		source; // the given argument *is* the primitive
11299	}
11300
11301
11302	// util
11303	// returns a filtered array without events that are part of any of the given sources
11304	function excludeEventsBySources(specificEvents, specificSources) {
11305		return $.grep(specificEvents, function(event) {
11306			for (var i = 0; i < specificSources.length; i++) {
11307				if (event.source === specificSources[i]) {
11308					return false; // exclude
11309				}
11310			}
11311			return true; // keep
11312		});
11313	}
11314	
11315	
11316	
11317	/* Manipulation
11318	-----------------------------------------------------------------------------*/
11319
11320
11321	// Only ever called from the externally-facing API
11322	function updateEvent(event) {
11323
11324		// massage start/end values, even if date string values
11325		event.start = t.moment(event.start);
11326		if (event.end) {
11327			event.end = t.moment(event.end);
11328		}
11329		else {
11330			event.end = null;
11331		}
11332
11333		mutateEvent(event, getMiscEventProps(event)); // will handle start/end/allDay normalization
11334		reportEvents(cache); // reports event modifications (so we can redraw)
11335	}
11336
11337
11338	// Returns a hash of misc event properties that should be copied over to related events.
11339	function getMiscEventProps(event) {
11340		var props = {};
11341
11342		$.each(event, function(name, val) {
11343			if (isMiscEventPropName(name)) {
11344				if (val !== undefined && isAtomic(val)) { // a defined non-object
11345					props[name] = val;
11346				}
11347			}
11348		});
11349
11350		return props;
11351	}
11352
11353	// non-date-related, non-id-related, non-secret
11354	function isMiscEventPropName(name) {
11355		return !/^_|^(id|allDay|start|end)$/.test(name);
11356	}
11357
11358	
11359	// returns the expanded events that were created
11360	function renderEvent(eventInput, stick) {
11361		var abstractEvent = buildEventFromInput(eventInput);
11362		var events;
11363		var i, event;
11364
11365		if (abstractEvent) { // not false (a valid input)
11366			events = expandEvent(abstractEvent);
11367
11368			for (i = 0; i < events.length; i++) {
11369				event = events[i];
11370
11371				if (!event.source) {
11372					if (stick) {
11373						stickySource.events.push(event);
11374						event.source = stickySource;
11375					}
11376					cache.push(event);
11377				}
11378			}
11379
11380			reportEvents(cache);
11381
11382			return events;
11383		}
11384
11385		return [];
11386	}
11387	
11388	
11389	function removeEvents(filter) {
11390		var eventID;
11391		var i;
11392
11393		if (filter == null) { // null or undefined. remove all events
11394			filter = function() { return true; }; // will always match
11395		}
11396		else if (!$.isFunction(filter)) { // an event ID
11397			eventID = filter + '';
11398			filter = function(event) {
11399				return event._id == eventID;
11400			};
11401		}
11402
11403		// Purge event(s) from our local cache
11404		cache = $.grep(cache, filter, true); // inverse=true
11405
11406		// Remove events from array sources.
11407		// This works because they have been converted to official Event Objects up front.
11408		// (and as a result, event._id has been calculated).
11409		for (i=0; i<sources.length; i++) {
11410			if ($.isArray(sources[i].events)) {
11411				sources[i].events = $.grep(sources[i].events, filter, true);
11412			}
11413		}
11414
11415		reportEvents(cache);
11416	}
11417
11418	
11419	function clientEvents(filter) {
11420		if ($.isFunction(filter)) {
11421			return $.grep(cache, filter);
11422		}
11423		else if (filter != null) { // not null, not undefined. an event ID
11424			filter += '';
11425			return $.grep(cache, function(e) {
11426				return e._id == filter;
11427			});
11428		}
11429		return cache; // else, return all
11430	}
11431
11432
11433	// Makes sure all array event sources have their internal event objects
11434	// converted over to the Calendar's current timezone.
11435	t.rezoneArrayEventSources = function() {
11436		var i;
11437		var events;
11438		var j;
11439
11440		for (i = 0; i < sources.length; i++) {
11441			events = sources[i].events;
11442			if ($.isArray(events)) {
11443
11444				for (j = 0; j < events.length; j++) {
11445					rezoneEventDates(events[j]);
11446				}
11447			}
11448		}
11449	};
11450
11451	function rezoneEventDates(event) {
11452		event.start = t.moment(event.start);
11453		if (event.end) {
11454			event.end = t.moment(event.end);
11455		}
11456		backupEventDates(event);
11457	}
11458	
11459	
11460	/* Event Normalization
11461	-----------------------------------------------------------------------------*/
11462
11463
11464	// Given a raw object with key/value properties, returns an "abstract" Event object.
11465	// An "abstract" event is an event that, if recurring, will not have been expanded yet.
11466	// Will return `false` when input is invalid.
11467	// `source` is optional
11468	function buildEventFromInput(input, source) {
11469		var out = {};
11470		var start, end;
11471		var allDay;
11472
11473		if (t.options.eventDataTransform) {
11474			input = t.options.eventDataTransform(input);
11475		}
11476		if (source && source.eventDataTransform) {
11477			input = source.eventDataTransform(input);
11478		}
11479
11480		// Copy all properties over to the resulting object.
11481		// The special-case properties will be copied over afterwards.
11482		$.extend(out, input);
11483
11484		if (source) {
11485			out.source = source;
11486		}
11487
11488		out._id = input._id || (input.id === undefined ? '_fc' + eventGUID++ : input.id + '');
11489
11490		if (input.className) {
11491			if (typeof input.className == 'string') {
11492				out.className = input.className.split(/\s+/);
11493			}
11494			else { // assumed to be an array
11495				out.className = input.className;
11496			}
11497		}
11498		else {
11499			out.className = [];
11500		}
11501
11502		start = input.start || input.date; // "date" is an alias for "start"
11503		end = input.end;
11504
11505		// parse as a time (Duration) if applicable
11506		if (isTimeString(start)) {
11507			start = moment.duration(start);
11508		}
11509		if (isTimeString(end)) {
11510			end = moment.duration(end);
11511		}
11512
11513		if (input.dow || moment.isDuration(start) || moment.isDuration(end)) {
11514
11515			// the event is "abstract" (recurring) so don't calculate exact start/end dates just yet
11516			out.start = start ? moment.duration(start) : null; // will be a Duration or null
11517			out.end = end ? moment.duration(end) : null; // will be a Duration or null
11518			out._recurring = true; // our internal marker
11519		}
11520		else {
11521
11522			if (start) {
11523				start = t.moment(start);
11524				if (!start.isValid()) {
11525					return false;
11526				}
11527			}
11528
11529			if (end) {
11530				end = t.moment(end);
11531				if (!end.isValid()) {
11532					end = null; // let defaults take over
11533				}
11534			}
11535
11536			allDay = input.allDay;
11537			if (allDay === undefined) { // still undefined? fallback to default
11538				allDay = firstDefined(
11539					source ? source.allDayDefault : undefined,
11540					t.options.allDayDefault
11541				);
11542				// still undefined? normalizeEventDates will calculate it
11543			}
11544
11545			assignDatesToEvent(start, end, allDay, out);
11546		}
11547
11548		t.normalizeEvent(out); // hook for external use. a prototype method
11549
11550		return out;
11551	}
11552	t.buildEventFromInput = buildEventFromInput;
11553
11554
11555	// Normalizes and assigns the given dates to the given partially-formed event object.
11556	// NOTE: mutates the given start/end moments. does not make a copy.
11557	function assignDatesToEvent(start, end, allDay, event) {
11558		event.start = start;
11559		event.end = end;
11560		event.allDay = allDay;
11561		normalizeEventDates(event);
11562		backupEventDates(event);
11563	}
11564
11565
11566	// Ensures proper values for allDay/start/end. Accepts an Event object, or a plain object with event-ish properties.
11567	// NOTE: Will modify the given object.
11568	function normalizeEventDates(eventProps) {
11569
11570		normalizeEventTimes(eventProps);
11571
11572		if (eventProps.end && !eventProps.end.isAfter(eventProps.start)) {
11573			eventProps.end = null;
11574		}
11575
11576		if (!eventProps.end) {
11577			if (t.options.forceEventDuration) {
11578				eventProps.end = t.getDefaultEventEnd(eventProps.allDay, eventProps.start);
11579			}
11580			else {
11581				eventProps.end = null;
11582			}
11583		}
11584	}
11585
11586
11587	// Ensures the allDay property exists and the timeliness of the start/end dates are consistent
11588	function normalizeEventTimes(eventProps) {
11589		if (eventProps.allDay == null) {
11590			eventProps.allDay = !(eventProps.start.hasTime() || (eventProps.end && eventProps.end.hasTime()));
11591		}
11592
11593		if (eventProps.allDay) {
11594			eventProps.start.stripTime();
11595			if (eventProps.end) {
11596				// TODO: consider nextDayThreshold here? If so, will require a lot of testing and adjustment
11597				eventProps.end.stripTime();
11598			}
11599		}
11600		else {
11601			if (!eventProps.start.hasTime()) {
11602				eventProps.start = t.applyTimezone(eventProps.start.time(0)); // will assign a 00:00 time
11603			}
11604			if (eventProps.end && !eventProps.end.hasTime()) {
11605				eventProps.end = t.applyTimezone(eventProps.end.time(0)); // will assign a 00:00 time
11606			}
11607		}
11608	}
11609
11610
11611	// If the given event is a recurring event, break it down into an array of individual instances.
11612	// If not a recurring event, return an array with the single original event.
11613	// If given a falsy input (probably because of a failed buildEventFromInput call), returns an empty array.
11614	// HACK: can override the recurring window by providing custom rangeStart/rangeEnd (for businessHours).
11615	function expandEvent(abstractEvent, _rangeStart, _rangeEnd) {
11616		var events = [];
11617		var dowHash;
11618		var dow;
11619		var i;
11620		var date;
11621		var startTime, endTime;
11622		var start, end;
11623		var event;
11624
11625		_rangeStart = _rangeStart || rangeStart;
11626		_rangeEnd = _rangeEnd || rangeEnd;
11627
11628		if (abstractEvent) {
11629			if (abstractEvent._recurring) {
11630
11631				// make a boolean hash as to whether the event occurs on each day-of-week
11632				if ((dow = abstractEvent.dow)) {
11633					dowHash = {};
11634					for (i = 0; i < dow.length; i++) {
11635						dowHash[dow[i]] = true;
11636					}
11637				}
11638
11639				// iterate through every day in the current range
11640				date = _rangeStart.clone().stripTime(); // holds the date of the current day
11641				while (date.isBefore(_rangeEnd)) {
11642
11643					if (!dowHash || dowHash[date.day()]) { // if everyday, or this particular day-of-week
11644
11645						startTime = abstractEvent.start; // the stored start and end properties are times (Durations)
11646						endTime = abstractEvent.end; // "
11647						start = date.clone();
11648						end = null;
11649
11650						if (startTime) {
11651							start = start.time(startTime);
11652						}
11653						if (endTime) {
11654							end = date.clone().time(endTime);
11655						}
11656
11657						event = $.extend({}, abstractEvent); // make a copy of the original
11658						assignDatesToEvent(
11659							start, end,
11660							!startTime && !endTime, // allDay?
11661							event
11662						);
11663						events.push(event);
11664					}
11665
11666					date.add(1, 'days');
11667				}
11668			}
11669			else {
11670				events.push(abstractEvent); // return the original event. will be a one-item array
11671			}
11672		}
11673
11674		return events;
11675	}
11676	t.expandEvent = expandEvent;
11677
11678
11679
11680	/* Event Modification Math
11681	-----------------------------------------------------------------------------------------*/
11682
11683
11684	// Modifies an event and all related events by applying the given properties.
11685	// Special date-diffing logic is used for manipulation of dates.
11686	// If `props` does not contain start/end dates, the updated values are assumed to be the event's current start/end.
11687	// All date comparisons are done against the event's pristine _start and _end dates.
11688	// Returns an object with delta information and a function to undo all operations.
11689	// For making computations in a granularity greater than day/time, specify largeUnit.
11690	// NOTE: The given `newProps` might be mutated for normalization purposes.
11691	function mutateEvent(event, newProps, largeUnit) {
11692		var miscProps = {};
11693		var oldProps;
11694		var clearEnd;
11695		var startDelta;
11696		var endDelta;
11697		var durationDelta;
11698		var undoFunc;
11699
11700		// diffs the dates in the appropriate way, returning a duration
11701		function diffDates(date1, date0) { // date1 - date0
11702			if (largeUnit) {
11703				return diffByUnit(date1, date0, largeUnit);
11704			}
11705			else if (newProps.allDay) {
11706				return diffDay(date1, date0);
11707			}
11708			else {
11709				return diffDayTime(date1, date0);
11710			}
11711		}
11712
11713		newProps = newProps || {};
11714
11715		// normalize new date-related properties
11716		if (!newProps.start) {
11717			newProps.start = event.start.clone();
11718		}
11719		if (newProps.end === undefined) {
11720			newProps.end = event.end ? event.end.clone() : null;
11721		}
11722		if (newProps.allDay == null) { // is null or undefined?
11723			newProps.allDay = event.allDay;
11724		}
11725		normalizeEventDates(newProps);
11726
11727		// create normalized versions of the original props to compare against
11728		// need a real end value, for diffing
11729		oldProps = {
11730			start: event._start.clone(),
11731			end: event._end ? event._end.clone() : t.getDefaultEventEnd(event._allDay, event._start),
11732			allDay: newProps.allDay // normalize the dates in the same regard as the new properties
11733		};
11734		normalizeEventDates(oldProps);
11735
11736		// need to clear the end date if explicitly changed to null
11737		clearEnd = event._end !== null && newProps.end === null;
11738
11739		// compute the delta for moving the start date
11740		startDelta = diffDates(newProps.start, oldProps.start);
11741
11742		// compute the delta for moving the end date
11743		if (newProps.end) {
11744			endDelta = diffDates(newProps.end, oldProps.end);
11745			durationDelta = endDelta.subtract(startDelta);
11746		}
11747		else {
11748			durationDelta = null;
11749		}
11750
11751		// gather all non-date-related properties
11752		$.each(newProps, function(name, val) {
11753			if (isMiscEventPropName(name)) {
11754				if (val !== undefined) {
11755					miscProps[name] = val;
11756				}
11757			}
11758		});
11759
11760		// apply the operations to the event and all related events
11761		undoFunc = mutateEvents(
11762			clientEvents(event._id), // get events with this ID
11763			clearEnd,
11764			newProps.allDay,
11765			startDelta,
11766			durationDelta,
11767			miscProps
11768		);
11769
11770		return {
11771			dateDelta: startDelta,
11772			durationDelta: durationDelta,
11773			undo: undoFunc
11774		};
11775	}
11776
11777
11778	// Modifies an array of events in the following ways (operations are in order):
11779	// - clear the event's `end`
11780	// - convert the event to allDay
11781	// - add `dateDelta` to the start and end
11782	// - add `durationDelta` to the event's duration
11783	// - assign `miscProps` to the event
11784	//
11785	// Returns a function that can be called to undo all the operations.
11786	//
11787	// TODO: don't use so many closures. possible memory issues when lots of events with same ID.
11788	//
11789	function mutateEvents(events, clearEnd, allDay, dateDelta, durationDelta, miscProps) {
11790		var isAmbigTimezone = t.getIsAmbigTimezone();
11791		var undoFunctions = [];
11792
11793		// normalize zero-length deltas to be null
11794		if (dateDelta && !dateDelta.valueOf()) { dateDelta = null; }
11795		if (durationDelta && !durationDelta.valueOf()) { durationDelta = null; }
11796
11797		$.each(events, function(i, event) {
11798			var oldProps;
11799			var newProps;
11800
11801			// build an object holding all the old values, both date-related and misc.
11802			// for the undo function.
11803			oldProps = {
11804				start: event.start.clone(),
11805				end: event.end ? event.end.clone() : null,
11806				allDay: event.allDay
11807			};
11808			$.each(miscProps, function(name) {
11809				oldProps[name] = event[name];
11810			});
11811
11812			// new date-related properties. work off the original date snapshot.
11813			// ok to use references because they will be thrown away when backupEventDates is called.
11814			newProps = {
11815				start: event._start,
11816				end: event._end,
11817				allDay: allDay // normalize the dates in the same regard as the new properties
11818			};
11819			normalizeEventDates(newProps); // massages start/end/allDay
11820
11821			// strip or ensure the end date
11822			if (clearEnd) {
11823				newProps.end = null;
11824			}
11825			else if (durationDelta && !newProps.end) { // the duration translation requires an end date
11826				newProps.end = t.getDefaultEventEnd(newProps.allDay, newProps.start);
11827			}
11828
11829			if (dateDelta) {
11830				newProps.start.add(dateDelta);
11831				if (newProps.end) {
11832					newProps.end.add(dateDelta);
11833				}
11834			}
11835
11836			if (durationDelta) {
11837				newProps.end.add(durationDelta); // end already ensured above
11838			}
11839
11840			// if the dates have changed, and we know it is impossible to re
11840compute the
11841			// timezone offsets, strip the zone.
11842			if (
11843				isAmbigTimezone &&
11844				!newProps.allDay &&
11845				(dateDelta || durationDelta)
11846			) {
11847				newProps.start.stripZone();
11848				if (newProps.end) {
11849					newProps.end.stripZone();
11850				}
11851			}
11852
11853			$.extend(event, miscProps, newProps); // copy over misc props, then date-related props
11854			backupEventDates(event); // regenerate internal _start/_end/_allDay
11855
11856			undoFunctions.push(function() {
11857				$.extend(event, oldProps);
11858				backupEventDates(event); // regenerate internal _start/_end/_allDay
11859			});
11860		});
11861
11862		return function() {
11863			for (var i = 0; i < undoFunctions.length; i++) {
11864				undoFunctions[i]();
11865			}
11866		};
11867	}
11868
11869
11870	t.getEventCache = function() {
11871		return cache;
11872	};
11873
11874}
11875
11876
11877// hook for external libs to manipulate event properties upon creation.
11878// should manipulate the event in-place.
11879Calendar.prototype.normalizeEvent = function(event) {
11880};
11881
11882
11883// Does the given span (start, end, and other location information)
11884// fully contain the other?
11885Calendar.prototype.spanContainsSpan = function(outerSpan, innerSpan) {
11886	var eventStart = outerSpan.start.clone().stripZone();
11887	var eventEnd = this.getEventEnd(outerSpan).stripZone();
11888
11889	return innerSpan.start >= eventStart && innerSpan.end <= eventEnd;
11890};
11891
11892
11893// Returns a list of events that the given event should be compared against when being considered for a move to
11894// the specified span. Attached to the Calendar's prototype because EventManager is a mixin for a Calendar.
11895Calendar.prototype.getPeerEvents = function(span, event) {
11896	var cache = this.getEventCache();
11897	var peerEvents = [];
11898	var i, otherEvent;
11899
11900	for (i = 0; i < cache.length; i++) {
11901		otherEvent = cache[i];
11902		if (
11903			!event ||
11904			event._id !== otherEvent._id // don't compare the event to itself or other related [repeating] events
11905		) {
11906			peerEvents.push(otherEvent);
11907		}
11908	}
11909
11910	return peerEvents;
11911};
11912
11913
11914// updates the "backup" properties, which are preserved in order to compute diffs later on.
11915function backupEventDates(event) {
11916	event._allDay = event.allDay;
11917	event._start = event.start.clone();
11918	event._end = event.end ? event.end.clone() : null;
11919}
11920
11921
11922/* Overlapping / Constraining
11923-----------------------------------------------------------------------------------------*/
11924
11925
11926// Determines if the given event can be relocated to the given span (unzoned start/end with other misc data)
11927Calendar.prototype.isEventSpanAllowed = function(span, event) {
11928	var source = event.source || {};
11929
11930	var constraint = firstDefined(
11931		event.constraint,
11932		source.constraint,
11933		this.options.eventConstraint
11934	);
11935
11936	var overlap = firstDefined(
11937		event.overlap,
11938		source.overlap,
11939		this.options.eventOverlap
11940	);
11941
11942	return this.isSpanAllowed(span, constraint, overlap, event) &&
11943		(!this.options.eventAllow || this.options.eventAllow(span, event) !== false);
11944};
11945
11946
11947// Determines if an external event can be relocated to the given span (unzoned start/end with other misc data)
11948Calendar.prototype.isExternalSpanAllowed = function(eventSpan, eventLocation, eventProps) {
11949	var eventInput;
11950	var event;
11951
11952	// note: very similar logic is in View's reportExternalDrop
11953	if (eventProps) {
11954		eventInput = $.extend({}, eventProps, eventLocation);
11955		event = this.expandEvent(
11956			this.buildEventFromInput(eventInput)
11957		)[0];
11958	}
11959
11960	if (event) {
11961		return this.isEventSpanAllowed(eventSpan, event);
11962	}
11963	else { // treat it as a selection
11964
11965		return this.isSelectionSpanAllowed(eventSpan);
11966	}
11967};
11968
11969
11970// Determines the given span (unzoned start/end with other misc data) can be selected.
11971Calendar.prototype.isSelectionSpanAllowed = function(span) {
11972	return this.isSpanAllowed(span, this.options.selectConstraint, this.options.selectOverlap) &&
11973		(!this.options.selectAllow || this.options.selectAllow(span) !== false);
11974};
11975
11976
11977// Returns true if the given span (caused by an event drop/resize or a selection) is allowed to exist
11978// according to the constraint/overlap settings.
11979// `event` is not required if checking a selection.
11980Calendar.prototype.isSpanAllowed = function(span, constraint, overlap, event) {
11981	var constraintEvents;
11982	var anyContainment;
11983	var peerEvents;
11984	var i, peerEvent;
11985	var peerOverlap;
11986
11987	// the range must be fully contained by at least one of produced constraint events
11988	if (constraint != null) {
11989
11990		// not treated as an event! intermediate data structure
11991		// TODO: use ranges in the future
11992		constraintEvents = this.constraintToEvents(constraint);
11993		if (constraintEvents) { // not invalid
11994
11995			anyContainment = false;
11996			for (i = 0; i < constraintEvents.length; i++) {
11997				if (this.spanContainsSpan(constraintEvents[i], span)) {
11998					anyContainment = true;
11999					break;
12000				}
12001			}
12002
12003			if (!anyContainment) {
12004				return false;
12005			}
12006		}
12007	}
12008
12009	peerEvents = this.getPeerEvents(span, event);
12010
12011	for (i = 0; i < peerEvents.length; i++)  {
12012		peerEvent = peerEvents[i];
12013
12014		// there needs to be an actual intersection before disallowing anything
12015		if (this.eventIntersectsRange(peerEvent, span)) {
12016
12017			// evaluate overlap for the given range and short-circuit if necessary
12018			if (overlap === false) {
12019				return false;
12020			}
12021			// if the event's overlap is a test function, pass the peer event in question as the first param
12022			else if (typeof overlap === 'function' && !overlap(peerEvent, event)) {
12023				return false;
12024			}
12025
12026			// if we are computing if the given range is allowable for an event, consider the other event's
12027			// EventObject-specific or Source-specific `overlap` property
12028			if (event) {
12029				peerOverlap = firstDefined(
12030					peerEvent.overlap,
12031					(peerEvent.source || {}).overlap
12032					// we already considered the global `eventOverlap`
12033				);
12034				if (peerOverlap === false) {
12035					return false;
12036				}
12037				// if the peer event's overlap is a test function, pass the subject event as the first param
12038				if (typeof peerOverlap === 'function' && !peerOverlap(event, peerEvent)) {
12039					return false;
12040				}
12041			}
12042		}
12043	}
12044
12045	return true;
12046};
12047
12048
12049// Given an event input from the API, produces an array of event objects. Possible event inputs:
12050// 'businessHours'
12051// An event ID (number or string)
12052// An object with specific start/end dates or a recurring event (like what businessHours accepts)
12053Calendar.prototype.constraintToEvents = function(constraintInput) {
12054
12055	if (constraintInput === 'businessHours') {
12056		return this.getCurrentBusinessHourEvents();
12057	}
12058
12059	if (typeof constraintInput === 'object') {
12060		if (constraintInput.start != null) { // needs to be event-like input
12061			return this.expandEvent(this.buildEventFromInput(constraintInput));
12062		}
12063		else {
12064			return null; // invalid
12065		}
12066	}
12067
12068	return this.clientEvents(constraintInput); // probably an ID
12069};
12070
12071
12072// Does the event's date range intersect with the given range?
12073// start/end already assumed to have stripped zones :(
12074Calendar.prototype.eventIntersectsRange = function(event, range) {
12075	var eventStart = event.start.clone().stripZone();
12076	var eventEnd = this.getEventEnd(event).stripZone();
12077
12078	return range.start < eventEnd && range.end > eventStart;
12079};
12080
12081
12082/* Business Hours
12083-----------------------------------------------------------------------------------------*/
12084
12085var BUSINESS_HOUR_EVENT_DEFAULTS = {
12086	id: '_fcBusinessHours', // will relate events from different calls to expandEvent
12087	start: '09:00',
12088	end: '17:00',
12089	dow: [ 1, 2, 3, 4, 5 ], // monday - friday
12090	rendering: 'inverse-background'
12091	// classNames are defined in businessHoursSegClasses
12092};
12093
12094// Return events objects for business hours within the current view.
12095// Abuse of our event system :(
12096Calendar.prototype.getCurrentBusinessHourEvents = function(wholeDay) {
12097	return this.computeBusinessHourEvents(wholeDay, this.options.businessHours);
12098};
12099
12100// Given a raw input value from options, return events objects for business hours within the current view.
12101Calendar.prototype.computeBusinessHourEvents = function(wholeDay, input) {
12102	if (input === true) {
12103		return this.expandBusinessHourEvents(wholeDay, [ {} ]);
12104	}
12105	else if ($.isPlainObject(input)) {
12106		return this.expandBusinessHourEvents(wholeDay, [ input ]);
12107	}
12108	else if ($.isArray(input)) {
12109		return this.expandBusinessHourEvents(wholeDay, input, true);
12110	}
12111	else {
12112		return [];
12113	}
12114};
12115
12116// inputs expected to be an array of objects.
12117// if ignoreNoDow is true, will ignore entries that don't specify a day-of-week (dow) key.
12118Calendar.prototype.expandBusinessHourEvents = function(wholeDay, inputs, ignoreNoDow) {
12119	var view = this.getView();
12120	var events = [];
12121	var i, input;
12122
12123	for (i = 0; i < inputs.length; i++) {
12124		input = inputs[i];
12125
12126		if (ignoreNoDow && !input.dow) {
12127			continue;
12128		}
12129
12130		// give defaults. will make a copy
12131		input = $.extend({}, BUSINESS_HOUR_EVENT_DEFAULTS, input);
12132
12133		// if a whole-day series is requested, clear the start/end times
12134		if (wholeDay) {
12135			input.start = null;
12136			input.end = null;
12137		}
12138
12139		events.push.apply(events, // append
12140			this.expandEvent(
12141				this.buildEventFromInput(input),
12142				view.start,
12143				view.end
12144			)
12145		);
12146	}
12147
12148	return events;
12149};
12150
12151;;
12152
12153/* An abstract class for the "basic" views, as well as month view. Renders one or more rows of day cells.
12154----------------------------------------------------------------------------------------------------------------------*/
12155// It is a manager for a DayGrid subcomponent, which does most of the heavy lifting.
12156// It is responsible for managing width/height.
12157
12158var BasicView = FC.BasicView = View.extend({
12159
12160	scroller: null,
12161
12162	dayGridClass: DayGrid, // class the dayGrid will be instantiated from (overridable by subclasses)
12163	dayGrid: null, // the main subcomponent that does most of the heavy lifting
12164
12165	dayNumbersVisible: false, // display day numbers on each day cell?
12166	colWeekNumbersVisible: false, // display week numbers along the side?
12167	cellWeekNumbersVisible: false, // display week numbers in day cell?
12168
12169	weekNumberWidth: null, // width of all the week-number cells running down the side
12170
12171	headContainerEl: null, // div that hold's the dayGrid's rendered date header
12172	headRowEl: null, // the fake row element of the day-of-week header
12173
12174
12175	initialize: function() {
12176		this.dayGrid = this.instantiateDayGrid();
12177
12178		this.scroller = new Scroller({
12179			overflowX: 'hidden',
12180			overflowY: 'auto'
12181		});
12182	},
12183
12184
12185	// Generates the DayGrid object this view needs. Draws from this.dayGridClass
12186	instantiateDayGrid: function() {
12187		// generate a subclass on the fly with BasicView-specific behavior
12188		// TODO: cache this subclass
12189		var subclass = this.dayGridClass.extend(basicDayGridMethods);
12190
12191		return new subclass(this);
12192	},
12193
12194
12195	// Sets the display range and computes all necessary dates
12196	setRange: function(range) {
12197		View.prototype.setRange.call(this, range); // call the super-method
12198
12199		this.dayGrid.breakOnWeeks = /year|month|week/.test(this.intervalUnit); // do before setRange
12200		this.dayGrid.setRange(range);
12201	},
12202
12203
12204	// Compute the value to feed into setRange. Overrides superclass.
12205	computeRange: function(date) {
12206		var range = View.prototype.computeRange.call(this, date); // get value from the super-method
12207
12208		// year and month views should be aligned with weeks. this is already done for week
12209		if (/year|month/.test(range.intervalUnit)) {
12210			range.start.startOf('week');
12211			range.start = this.skipHiddenDays(range.start);
12212
12213			// make end-of-week if not already
12214			if (range.end.weekday()) {
12215				range.end.add(1, 'week').startOf('week');
12216				range.end = this.skipHiddenDays(range.end, -1, true); // exclusively move backwards
12217			}
12218		}
12219
12220		return range;
12221	},
12222
12223
12224	// Renders the view into `this.el`, which should already be assigned
12225	renderDates: function() {
12226
12227		this.dayNumbersVisible = this.dayGrid.rowCnt > 1; // TODO: make grid responsible
12228		if (this.opt('weekNumbers')) {
12229			if (this.opt('weekNumbersWithinDays')) {
12230				this.cellWeekNumbersVisible = true;
12231				this.colWeekNumbersVisible = false;
12232			}
12233			else {
12234				this.cellWeekNumbersVisible = false;
12235				this.colWeekNumbersVisible = true;
12236			};
12237		}
12238		this.dayGrid.numbersVisible = this.dayNumbersVisible ||
12239			this.cellWeekNumbersVisible || this.colWeekNumbersVisible;
12240
12241		this.el.addClass('fc-basic-view').html(this.renderSkeletonHtml());
12242		this.renderHead();
12243
12244		this.scroller.render();
12245		var dayGridContainerEl = this.scroller.el.addClass('fc-day-grid-container');
12246		var dayGridEl = $('<div class="fc-day-grid" />').appendTo(dayGridContainerEl);
12247		this.el.find('.fc-body > tr > td').append(dayGridContainerEl);
12248
12249		this.dayGrid.setElement(dayGridEl);
12250		this.dayGrid.renderDates(this.hasRigidRows());
12251	},
12252
12253
12254	// render the day-of-week headers
12255	renderHead: function() {
12256		this.headContainerEl =
12257			this.el.find('.fc-head-container')
12258				.html(this.dayGrid.renderHeadHtml());
12259		this.headRowEl = this.headContainerEl.find('.fc-row');
12260	},
12261
12262
12263	// Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
12264	// always completely kill the dayGrid's rendering.
12265	unrenderDates: function() {
12266		this.dayGrid.unrenderDates();
12267		this.dayGrid.removeElement();
12268		this.scroller.destroy();
12269	},
12270
12271
12272	renderBusinessHours: function() {
12273		this.dayGrid.renderBusinessHours();
12274	},
12275
12276
12277	unrenderBusinessHours: function() {
12278		this.dayGrid.unrenderBusinessHours();
12279	},
12280
12281
12282	// Builds the HTML skeleton for the view.
12283	// The day-grid component will render inside of a container defined by this HTML.
12284	renderSkeletonHtml: function() {
12285		return '' +
12286			'<table>' +
12287				'<thead class="fc-head">' +
12288					'<tr>' +
12289						'<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
12290					'</tr>' +
12291				'</thead>' +
12292				'<tbody class="fc-body">' +
12293					'<tr>' +
12294						'<td class="' + this.widgetContentClass + '"></td>' +
12295					'</tr>' +
12296				'</tbody>' +
12297			'</table>';
12298	},
12299
12300
12301	// Generates an HTML attribute string for setting the width of the week number column, if it is known
12302	weekNumberStyleAttr: function() {
12303		if (this.weekNumberWidth !== null) {
12304			return 'style="width:' + this.weekNumberWidth + 'px"';
12305		}
12306		return '';
12307	},
12308
12309
12310	// Determines whether each row should have a constant height
12311	hasRigidRows: function() {
12312		var eventLimit = this.opt('eventLimit');
12313		return eventLimit && typeof eventLimit !== 'number';
12314	},
12315
12316
12317	/* Dimensions
12318	------------------------------------------------------------------------------------------------------------------*/
12319
12320
12321	// Refreshes the horizontal dimensions of the view
12322	updateWidth: function() {
12323		if (this.colWeekNumbersVisible) {
12324			// Make sure all week number cells running down the side have the same width.
12325			// Record the width for cells created later.
12326			this.weekNumberWidth = matchCellWidths(
12327				this.el.find('.fc-week-number')
12328			);
12329		}
12330	},
12331
12332
12333	// Adjusts the vertical dimensions of the view to the specified values
12334	setHeight: function(totalHeight, isAuto) {
12335		var eventLimit = this.opt('eventLimit');
12336		var scrollerHeight;
12337		var scrollbarWidths;
12338
12339		// reset all heights to be natural
12340		this.scroller.clear();
12341		uncompensateScroll(this.headRowEl);
12342
12343		this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
12344
12345		// is the event limit a constant level number?
12346		if (eventLimit && typeof eventLimit === 'number') {
12347			this.dayGrid.limitRows(eventLimit); // limit the levels first so the height can redistribute after
12348		}
12349
12350		// distribute the height to the rows
12351		// (totalHeight is a "recommended" value if isAuto)
12352		scrollerHeight = this.computeScrollerHeight(totalHeight);
12353		this.setGridHeight(scrollerHeight, isAuto);
12354
12355		// is the event limit dynamically calculated?
12356		if (eventLimit && typeof eventLimit !== 'number') {
12357			this.dayGrid.limitRows(eventLimit); // limit the levels after the grid's row heights have been set
12358		}
12359
12360		if (!isAuto) { // should we force dimensions of the scroll container?
12361
12362			this.scroller.setHeight(scrollerHeight);
12363			scrollbarWidths = this.scroller.getScrollbarWidths();
12364
12365			if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
12366
12367				compensateScroll(this.headRowEl, scrollbarWidths);
12368
12369				// doing the scrollbar compensation might have created text overflow which created more height. redo
12370				scrollerHeight = this.computeScrollerHeight(totalHeight);
12371				this.scroller.setHeight(scrollerHeight);
12372			}
12373
12374			// guarantees the same scrollbar widths
12375			this.scroller.lockOverflow(scrollbarWidths);
12376		}
12377	},
12378
12379
12380	// given a desired total height of the view, returns what the height of the scroller should be
12381	computeScrollerHeight: function(totalHeight) {
12382		return totalHeight -
12383			subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
12384	},
12385
12386
12387	// Sets the height of just the DayGrid component in this view
12388	setGridHeight: function(height, isAuto) {
12389		if (isAuto) {
12390			undistributeHeight(this.dayGrid.rowEls); // let the rows be their natural height with no expanding
12391		}
12392		else {
12393			distributeHeight(this.dayGrid.rowEls, height, true); // true = compensate for height-hogging rows
12394		}
12395	},
12396
12397
12398	/* Scroll
12399	------------------------------------------------------------------------------------------------------------------*/
12400
12401
12402	queryScroll: function() {
12403		return this.scroller.getScrollTop();
12404	},
12405
12406
12407	setScroll: function(top) {
12408		this.scroller.setScrollTop(top);
12409	},
12410
12411
12412	/* Hit Areas
12413	------------------------------------------------------------------------------------------------------------------*/
12414	// forward all hit-related method calls to dayGrid
12415
12416
12417	prepareHits: function() {
12418		this.dayGrid.prepareHits();
12419	},
12420
12421
12422	releaseHits: function() {
12423		this.dayGrid.releaseHits();
12424	},
12425
12426
12427	queryHit: function(left, top) {
12428		return this.dayGrid.queryHit(left, top);
12429	},
12430
12431
12432	getHitSpan: function(hit) {
12433		return this.dayGrid.getHitSpan(hit);
12434	},
12435
12436
12437	getHitEl: function(hit) {
12438		return this.dayGrid.getHitEl(hit);
12439	},
12440
12441
12442	/* Events
12443	------------------------------------------------------------------------------------------------------------------*/
12444
12445
12446	// Renders the given events onto the view and populates the segments array
12447	renderEvents: function(events) {
12448		this.dayGrid.renderEvents(events);
12449
12450		this.updateHeight(); // must compensate for events that overflow the row
12451	},
12452
12453
12454	// Retrieves all segment objects that are rendered in the view
12455	getEventSegs: function() {
12456		return this.dayGrid.getEventSegs();
12457	},
12458
12459
12460	// Unrenders all event elements and clears internal segment data
12461	unrenderEvents: function() {
12462		this.dayGrid.unrenderEvents();
12463
12464		// we DON'T need to call updateHeight() because
12465		// a renderEvents() call always happens after this, which will eventually call updateHeight()
12466	},
12467
12468
12469	/* Dragging (for both events and external elements)
12470	------------------------------------------------------------------------------------------------------------------*/
12471
12472
12473	// A returned value of `true` signals that a mock "helper" event has been rendered.
12474	renderDrag: function(dropLocation, seg) {
12475		return this.dayGrid.renderDrag(dropLocation, seg);
12476	},
12477
12478
12479	unrenderDrag: function() {
12480		this.dayGrid.unrenderDrag();
12481	},
12482
12483
12484	/* Selection
12485	------------------------------------------------------------------------------------------------------------------*/
12486
12487
12488	// Renders a visual indication of a selection
12489	renderSelection: function(span) {
12490		this.dayGrid.renderSelection(span);
12491	},
12492
12493
12494	// Unrenders a visual indications of a selection
12495	unrenderSelection: function() {
12496		this.dayGrid.unrenderSelection();
12497	}
12498
12499});
12500
12501
12502// Methods that will customize the rendering behavior of the BasicView's dayGrid
12503var basicDayGridMethods = {
12504
12505
12506	// Generates the HTML that will go before the day-of week header cells
12507	renderHeadIntroHtml: function() {
12508		var view = this.view;
12509
12510		if (view.colWeekNumbersVisible) {
12511			return '' +
12512				'<th class="fc-week-number ' + view.widgetHeaderClass + '" ' + view.weekNumberStyleAttr() + '>' +
12513					'<span>' + // needed for matchCellWidths
12514						htmlEscape(view.opt('weekNumberTitle')) +
12515					'</span>' +
12516				'</th>';
12517		}
12518
12519		return '';
12520	},
12521
12522
12523	// Generates the HTML that will go before content-skeleton cells that display the day/week numbers
12524	renderNumberIntroHtml: function(row) {
12525		var view = this.view;
12526		var weekStart = this.getCellDate(row, 0);
12527
12528		if (view.colWeekNumbersVisible) {
12529			return '' +
12530				'<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '>' +
12531					view.buildGotoAnchorHtml( // aside from link, important for matchCellWidths
12532						{ date: weekStart, type: 'week', forceOff: this.colCnt === 1 },
12533						weekStart.format('w') // inner HTML
12534					) +
12535				'</td>';
12536		}
12537
12538		return '';
12539	},
12540
12541
12542	// Generates the HTML that goes before the day bg cells for each day-row
12543	renderBgIntroHtml: function() {
12544		var view = this.view;
12545
12546		if (view.colWeekNumbersVisible) {
12547			return '<td class="fc-week-number ' + view.widgetContentClass + '" ' +
12548				view.weekNumberStyleAttr() + '></td>';
12549		}
12550
12551		return '';
12552	},
12553
12554
12555	// Generates the HTML that goes before every other type of row generated by DayGrid.
12556	// Affects helper-skeleton and highlight-skeleton rows.
12557	renderIntroHtml: function() {
12558		var view = this.view;
12559
12560		if (view.colWeekNumbersVisible) {
12561			return '<td class="fc-week-number" ' + view.weekNumberStyleAttr() + '></td>';
12562		}
12563
12564		return '';
12565	}
12566
12567};
12568
12569;;
12570
12571/* A month view with day cells running in rows (one-per-week) and columns
12572----------------------------------------------------------------------------------------------------------------------*/
12573
12574var MonthView = FC.MonthView = BasicView.extend({
12575
12576	// Produces information about what range to display
12577	computeRange: function(date) {
12578		var range = BasicView.prototype.computeRange.call(this, date); // get value from super-method
12579		var rowCnt;
12580
12581		// ensure 6 weeks
12582		if (this.isFixedWeeks()) {
12583			rowCnt = Math.ceil(range.end.diff(range.start, 'weeks', true)); // could be partial weeks due to hiddenDays
12584			range.end.add(6 - rowCnt, 'weeks');
12585		}
12586
12587		return range;
12588	},
12589
12590
12591	// Overrides the default BasicView behavior to have special multi-week auto-height logic
12592	setGridHeight: function(height, isAuto) {
12593
12594		// if auto, make the height of each row the height that it would be if there were 6 weeks
12595		if (isAuto) {
12596			height *= this.rowCnt / 6;
12597		}
12598
12599		distributeHeight(this.dayGrid.rowEls, height, !isAuto); // if auto, don't compensate for height-hogging rows
12600	},
12601
12602
12603	isFixedWeeks: function() {
12604		return this.opt('fixedWeekCount');
12605	}
12606
12607});
12608
12609;;
12610
12611fcViews.basic = {
12612	'class': BasicView
12613};
12614
12615fcViews.basicDay = {
12616	type: 'basic',
12617	duration: { days: 1 }
12618};
12619
12620fcViews.basicWeek = {
12621	type: 'basic',
12622	duration: { weeks: 1 }
12623};
12624
12625fcViews.month = {
12626	'class': MonthView,
12627	duration: { months: 1 }, // important for prev/next
12628	defaults: {
12629		fixedWeekCount: true
12630	}
12631};
12632;;
12633
12634/* An abstract class for all agenda-related views. Displays one more columns with time slots running vertically.
12635----------------------------------------------------------------------------------------------------------------------*/
12636// Is a manager for the TimeGrid subcomponent and possibly the DayGrid subcomponent (if allDaySlot is on).
12637// Responsible for managing width/height.
12638
12639var AgendaView = FC.AgendaView = View.extend({
12640
12641	scroller: null,
12642
12643	timeGridClass: TimeGrid, // class used to instantiate the timeGrid. subclasses can override
12644	timeGrid: null, // the main time-grid subcomponent of this view
12645
12646	dayGridClass: DayGrid, // class used to instantiate the dayGrid. subclasses can override
12647	dayGrid: null, // the "all-day" subcomponent. if all-day is turned off, this will be null
12648
12649	axisWidth: null, // the width of the time axis running down the side
12650
12651	headContainerEl: null, // div that hold's the timeGrid's rendered date header
12652	noScrollRowEls: null, // set of fake row elements that must compensate when scroller has scrollbars
12653
12654	// when the time-grid isn't tall enough to occupy the given height, we render an <hr> underneath
12655	bottomRuleEl: null,
12656
12657
12658	initialize: function() {
12659		this.timeGrid = this.instantiateTimeGrid();
12660
12661		if (this.opt('allDaySlot')) { // should we display the "all-day" area?
12662			this.dayGrid = this.instantiateDayGrid(); // the all-day subcomponent of this view
12663		}
12664
12665		this.scroller = new Scroller({
12666			overflowX: 'hidden',
12667			overflowY: 'auto'
12668		});
12669	},
12670
12671
12672	// Instantiates the TimeGrid object this view needs. Draws from this.timeGridClass
12673	instantiateTimeGrid: function() {
12674		var subclass = this.timeGridClass.extend(agendaTimeGridMethods);
12675
12676		return new subclass(this);
12677	},
12678
12679
12680	// Instantiates the DayGrid object this view might need. Draws from this.dayGridClass
12681	instantiateDayGrid: function() {
12682		var subclass = this.dayGridClass.extend(agendaDayGridMethods);
12683
12684		return new subclass(this);
12685	},
12686
12687
12688	/* Rendering
12689	------------------------------------------------------------------------------------------------------------------*/
12690
12691
12692	// Sets the display range and computes all necessary dates
12693	setRange: function(range) {
12694		View.prototype.setRange.call(this, range); // call the super-method
12695
12696		this.timeGrid.setRange(range);
12697		if (this.dayGrid) {
12698			this.dayGrid.setRange(range);
12699		}
12700	},
12701
12702
12703	// Renders the view into `this.el`, which has already been assigned
12704	renderDates: function() {
12705
12706		this.el.addClass('fc-agenda-view').html(this.renderSkeletonHtml());
12707		this.renderHead();
12708
12709		this.scroller.render();
12710		var timeGridWrapEl = this.scroller.el.addClass('fc-time-grid-container');
12711		var timeGridEl = $('<div class="fc-time-grid" />').appendTo(timeGridWrapEl);
12712		this.el.find('.fc-body > tr > td').append(timeGridWrapEl);
12713
12714		this.timeGrid.setElement(timeGridEl);
12715		this.timeGrid.renderDates();
12716
12717		// the <hr> that sometimes displays under the time-grid
12718		this.bottomRuleEl = $('<hr class="fc-divider ' + this.widgetHeaderClass + '"/>')
12719			.appendTo(this.timeGrid.el); // inject it into the time-grid
12720
12721		if (this.dayGrid) {
12722			this.dayGrid.setElement(this.el.find('.fc-day-grid'));
12723			this.dayGrid.renderDates();
12724
12725			// have the day-grid extend it's coordinate area over the <hr> dividing the two grids
12726			this.dayGrid.bottomCoordPadding = this.dayGrid.el.next('hr').outerHeight();
12727		}
12728
12729		this.noScrollRowEls = this.el.find('.fc-row:not(.fc-scroller *)'); // fake rows not within the scroller
12730	},
12731
12732
12733	// render the day-of-week headers
12734	renderHead: function() {
12735		this.headContainerEl =
12736			this.el.find('.fc-head-container')
12737				.html(this.timeGrid.renderHeadHtml());
12738	},
12739
12740
12741	// Unrenders the content of the view. Since we haven't separated skeleton rendering from date rendering,
12742	// always completely kill each grid's rendering.
12743	unrenderDates: function() {
12744		this.timeGrid.unrenderDates();
12745		this.timeGrid.removeElement();
12746
12747		if (this.dayGrid) {
12748			this.dayGrid.unrenderDates();
12749			this.dayGrid.removeElement();
12750		}
12751
12752		this.scroller.destroy();
12753	},
12754
12755
12756	// Builds the HTML skeleton for the view.
12757	// The day-grid and time-grid components will render inside containers defined by this HTML.
12758	renderSkeletonHtml: function() {
12759		return '' +
12760			'<table>' +
12761				'<thead class="fc-head">' +
12762					'<tr>' +
12763						'<td class="fc-head-container ' + this.widgetHeaderClass + '"></td>' +
12764					'</tr>' +
12765				'</thead>' +
12766				'<tbody class="fc-body">' +
12767					'<tr>' +
12768						'<td class="' + this.widgetContentClass + '">' +
12769							(this.dayGrid ?
12770								'<div class="fc-day-grid"/>' +
12771								'<hr class="fc-divider ' + this.widgetHeaderClass + '"/>' :
12772								''
12773								) +
12774						'</td>' +
12775					'</tr>' +
12776				'</tbody>' +
12777			'</table>';
12778	},
12779
12780
12781	// Generates an HTML attribute string for setting the width of the axis, if it is known
12782	axisStyleAttr: function() {
12783		if (this.axisWidth !== null) {
12784			 return 'style="width:' + this.axisWidth + 'px"';
12785		}
12786		return '';
12787	},
12788
12789
12790	/* Business Hours
12791	------------------------------------------------------------------------------------------------------------------*/
12792
12793
12794	renderBusinessHours: function() {
12795		this.timeGrid.renderBusinessHours();
12796
12797		if (this.dayGrid) {
12798			this.dayGrid.renderBusinessHours();
12799		}
12800	},
12801
12802
12803	unrenderBusinessHours: function() {
12804		this.timeGrid.unrenderBusinessHours();
12805
12806		if (this.dayGrid) {
12807			this.dayGrid.unrenderBusinessHours();
12808		}
12809	},
12810
12811
12812	/* Now Indicator
12813	------------------------------------------------------------------------------------------------------------------*/
12814
12815
12816	getNowIndicatorUnit: function() {
12817		return this.timeGrid.getNowIndicatorUnit();
12818	},
12819
12820
12821	renderNowIndicator: function(date) {
12822		this.timeGrid.renderNowIndicator(date);
12823	},
12824
12825
12826	unrenderNowIndicator: function() {
12827		this.timeGrid.unrenderNowIndicator();
12828	},
12829
12830
12831	/* Dimensions
12832	------------------------------------------------------------------------------------------------------------------*/
12833
12834
12835	updateSize: function(isResize) {
12836		this.timeGrid.updateSize(isResize);
12837
12838		View.prototype.updateSize.call(this, isResize); // call the super-method
12839	},
12840
12841
12842	// Refreshes the horizontal dimensions of the view
12843	updateWidth: function() {
12844		// make all axis cells line up, and record the width so newly created axis cells will have it
12845		this.axisWidth = matchCellWidths(this.el.find('.fc-axis'));
12846	},
12847
12848
12849	// Adjusts the vertical dimensions of the view to the specified values
12850	setHeight: function(totalHeight, isAuto) {
12851		var eventLimit;
12852		var scrollerHeight;
12853		var scrollbarWidths;
12854
12855		// reset all dimensions back to the original state
12856		this.bottomRuleEl.hide(); // .show() will be called later if this <hr> is necessary
12857		this.scroller.clear(); // sets height to 'auto' and clears overflow
12858		uncompensateScroll(this.noScrollRowEls);
12859
12860		// limit number of events in the all-day area
12861		if (this.dayGrid) {
12862			this.dayGrid.removeSegPopover(); // kill the "more" popover if displayed
12863
12864			eventLimit = this.opt('eventLimit');
12865			if (eventLimit && typeof eventLimit !== 'number') {
12866				eventLimit = AGENDA_ALL_DAY_EVENT_LIMIT; // make sure "auto" goes to a real number
12867			}
12868			if (eventLimit) {
12869				this.dayGrid.limitRows(eventLimit);
12870			}
12871		}
12872
12873		if (!isAuto) { // should we force dimensions of the scroll container?
12874
12875			scrollerHeight = this.computeScrollerHeight(totalHeight);
12876			this.scroller.setHeight(scrollerHeight);
12877			scrollbarWidths = this.scroller.getScrollbarWidths();
12878
12879			if (scrollbarWidths.left || scrollbarWidths.right) { // using scrollbars?
12880
12881				// make the all-day and header rows lines up
12882				compensateScroll(this.noScrollRowEls, scrollbarWidths);
12883
12884				// the scrollbar compensation might have changed text flow, which might affect height, so recalculate
12885				// and reapply the desired height to the scroller.
12886				scrollerHeight = this.computeScrollerHeight(totalHeight);
12887				this.scroller.setHeight(scrollerHeight);
12888			}
12889
12890			// guarantees the same scrollbar widths
12891			this.scroller.lockOverflow(scrollbarWidths);
12892
12893			// if there's any space below the slats, show the horizontal rule.
12894			// this won't cause any new overflow, because lockOverflow already called.
12895			if (this.timeGrid.getTotalSlatHeight() < scrollerHeight) {
12896				this.bottomRuleEl.show();
12897			}
12898		}
12899	},
12900
12901
12902	// given a desired total height of the view, returns what the height of the scroller should be
12903	computeScrollerHeight: function(totalHeight) {
12904		return totalHeight -
12905			subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
12906	},
12907
12908
12909	/* Scroll
12910	------------------------------------------------------------------------------------------------------------------*/
12911
12912
12913	// Computes the initial pre-configured scroll state prior to allowing the user to change it
12914	computeInitialScroll: function() {
12915		var scrollTime = moment.duration(this.opt('scrollTime'));
12916		var top = this.timeGrid.computeTimeTop(scrollTime);
12917
12918		// zoom can give weird floating-point values. rather scroll a little bit further
12919		top = Math.ceil(top);
12920
12921		if (top) {
12922			top++; // to overcome top border that slots beyond the first have. looks better
12923		}
12924
12925		return top;
12926	},
12927
12928
12929	queryScroll: function() {
12930		return this.scroller.getScrollTop();
12931	},
12932
12933
12934	setScroll: function(top) {
12935		this.scroller.setScrollTop(top);
12936	},
12937
12938
12939	/* Hit Areas
12940	------------------------------------------------------------------------------------------------------------------*/
12941	// forward all hit-related method calls to the grids (dayGrid might not be defined)
12942
12943
12944	prepareHits: function() {
12945		this.timeGrid.prepareHits();
12946		if (this.dayGrid) {
12947			this.dayGrid.prepareHits();
12948		}
12949	},
12950
12951
12952	releaseHits: function() {
12953		this.timeGrid.releaseHits();
12954		if (this.dayGrid) {
12955			this.dayGrid.releaseHits();
12956		}
12957	},
12958
12959
12960	queryHit: function(left, top) {
12961		var hit = this.timeGrid.queryHit(left, top);
12962
12963		if (!hit && this.dayGrid) {
12964			hit = this.dayGrid.queryHit(left, top);
12965		}
12966
12967		return hit;
12968	},
12969
12970
12971	getHitSpan: function(hit) {
12972		// TODO: hit.component is set as a hack to identify where the hit came from
12973		return hit.component.getHitSpan(hit);
12974	},
12975
12976
12977	getHitEl: function(hit) {
12978		// TODO: hit.component is set as a hack to identify where the hit came from
12979		return hit.component.getHitEl(hit);
12980	},
12981
12982
12983	/* Events
12984	------------------------------------------------------------------------------------------------------------------*/
12985
12986
12987	// Renders events onto the view and populates the View's segment array
12988	renderEvents: function(events) {
12989		var dayEvents = [];
12990		var timedEvents = [];
12991		var daySegs = [];
12992		var timedSegs;
12993		var i;
12994
12995		// separate the events into all-day and timed
12996		for (i = 0; i < events.length; i++) {
12997			if (events[i].allDay) {
12998				dayEvents.push(events[i]);
12999			}
13000			else {
13001				timedEvents.push(events[i]);
13002			}
13003		}
13004
13005		// render the events in the subcomponents
13006		timedSegs = this.timeGrid.renderEvents(timedEvents);
13007		if (this.dayGrid) {
13008			daySegs = this.dayGrid.renderEvents(dayEvents);
13009		}
13010
13011		// the all-day area is flexible and might have a lot of events, so shift the height
13012		this.updateHeight();
13013	},
13014
13015
13016	// Retrieves all segment objects that are rendered in the view
13017	getEventSegs: function() {
13018		return this.timeGrid.getEventSegs().concat(
13019			this.dayGrid ? this.dayGrid.getEventSegs() : []
13020		);
13021	},
13022
13023
13024	// Unrenders all event elements and clears internal segment data
13025	unrenderEvents: function() {
13026
13027		// unrender the events in the subcomponents
13028		this.timeGrid.unrenderEvents();
13029		if (this.dayGrid) {
13030			this.dayGrid.unrenderEvents();
13031		}
13032
13033		// we DON'T need to call updateHeight() because
13034		// a renderEvents() call always happens after this, which will eventually call updateHeight()
13035	},
13036
13037
13038	/* Dragging (for events and external elements)
13039	------------------------------------------------------------------------------------------------------------------*/
13040
13041
13042	// A returned value of `true` signals that a mock "helper" event has been rendered.
13043	renderDrag: function(dropLocation, seg) {
13044		if (dropLocation.start.hasTime()) {
13045			return this.timeGrid.renderDrag(dropLocation, seg);
13046		}
13047		else if (this.dayGrid) {
13048			return this.dayGrid.renderDrag(dropLocation, seg);
13049		}
13050	},
13051
13052
13053	unrenderDrag: function() {
13054		this.timeGrid.unrenderDrag();
13055		if (this.dayGrid) {
13056			this.dayGrid.unrenderDrag();
13057		}
13058	},
13059
13060
13061	/* Selection
13062	------------------------------------------------------------------------------------------------------------------*/
13063
13064
13065	// Renders a visual indication of a selection
13066	renderSelection: function(span) {
13067		if (span.start.hasTime() || span.end.hasTime()) {
13068			this.timeGrid.renderSelection(span);
13069		}
13070		else if (this.dayGrid) {
13071			this.dayGrid.renderSelection(span);
13072		}
13073	},
13074
13075
13076	// Unrenders a visual indications of a selection
13077	unrenderSelection: function() {
13078		this.timeGrid.unrenderSelection();
13079		if (this.dayGrid) {
13080			this.dayGrid.unrenderSelection();
13081		}
13082	}
13083
13084});
13085
13086
13087// Methods that will customize the rendering behavior of the AgendaView's timeGrid
13088// TODO: move into TimeGrid
13089var agendaTimeGridMethods = {
13090
13091
13092	// Generates the HTML that will go before the day-of week header cells
13093	renderHeadIntroHtml: function() {
13094		var view = this.view;
13095		var weekText;
13096
13097		if (view.opt('weekNumbers')) {
13098			weekText = this.start.format(view.opt('smallWeekFormat'));
13099
13100			return '' +
13101				'<th class="fc-axis fc-week-number ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '>' +
13102					view.buildGotoAnchorHtml( // aside from link, important for matchCellWidths
13103						{ date: this.start, type: 'week', forceOff: this.colCnt > 1 },
13104						htmlEscape(weekText) // inner HTML
13105					) +
13106				'</th>';
13107		}
13108		else {
13109			return '<th class="fc-axis ' + view.widgetHeaderClass + '" ' + view.axisStyleAttr() + '></th>';
13110		}
13111	},
13112
13113
13114	// Generates the HTML that goes before the bg of the TimeGrid slot area. Long vertical column.
13115	renderBgIntroHtml: function() {
13116		var view = this.view;
13117
13118		return '<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '></td>';
13119	},
13120
13121
13122	// Generates the HTML that goes before all other types of cells.
13123	// Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
13124	renderIntroHtml: function() {
13125		var view = this.view;
13126
13127		return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
13128	}
13129
13130};
13131
13132
13133// Methods that will customize the rendering behavior of the AgendaView's dayGrid
13134var agendaDayGridMethods = {
13135
13136
13137	// Generates the HTML that goes before the all-day cells
13138	renderBgIntroHtml: function() {
13139		var view = this.view;
13140
13141		return '' +
13142			'<td class="fc-axis ' + view.widgetContentClass + '" ' + view.axisStyleAttr() + '>' +
13143				'<span>' + // needed for matchCellWidths
13144					view.getAllDayHtml() +
13145				'</span>' +
13146			'</td>';
13147	},
13148
13149
13150	// Generates the HTML that goes before all other types of cells.
13151	// Affects content-skeleton, helper-skeleton, highlight-skeleton for both the time-grid and day-grid.
13152	renderIntroHtml: function() {
13153		var view = this.view;
13154
13155		return '<td class="fc-axis" ' + view.axisStyleAttr() + '></td>';
13156	}
13157
13158};
13159
13160;;
13161
13162var AGENDA_ALL_DAY_EVENT_LIMIT = 5;
13163
13164// potential nice values for the slot-duration and interval-duration
13165// from largest to smallest
13166var AGENDA_STOCK_SUB_DURATIONS = [
13167	{ hours: 1 },
13168	{ minutes: 30 },
13169	{ minutes: 15 },
13170	{ seconds: 30 },
13171	{ seconds: 15 }
13172];
13173
13174fcViews.agenda = {
13175	'class': AgendaView,
13176	defaults: {
13177		allDaySlot: true,
13178		slotDuration: '00:30:00',
13179		minTime: '00:00:00',
13180		maxTime: '24:00:00',
13181		slotEventOverlap: true // a bad name. confused with overlap/constraint system
13182	}
13183};
13184
13185fcViews.agendaDay = {
13186	type: 'agenda',
13187	duration: { days: 1 }
13188};
13189
13190fcViews.agendaWeek = {
13191	type: 'agenda',
13192	duration: { weeks: 1 }
13193};
13194;;
13195
13196/*
13197Responsible for the scroller, and forwarding event-related actions into the "grid"
13198*/
13199var ListView = View.extend({
13200
13201	grid: null,
13202	scroller: null,
13203
13204	initialize: function() {
13205		this.grid = new ListViewGrid(this);
13206		this.scroller = new Scroller({
13207			overflowX: 'hidden',
13208			overflowY: 'auto'
13209		});
13210	},
13211
13212	setRange: function(range) {
13213		View.prototype.setRange.call(this, range); // super
13214
13215		this.grid.setRange(range); // needs to process range-related options
13216	},
13217
13218	renderSkeleton: function() {
13219		this.el.addClass(
13220			'fc-list-view ' +
13221			this.widgetContentClass
13222		);
13223
13224		this.scroller.render();
13225		this.scroller.el.appendTo(this.el);
13226
13227		this.grid.setElement(this.scroller.scrollEl);
13228	},
13229
13230	unrenderSkeleton: function() {
13231		this.scroller.destroy(); // will remove the Grid too
13232	},
13233
13234	setHeight: function(totalHeight, isAuto) {
13235		this.scroller.setHeight(this.computeScrollerHeight(totalHeight));
13236	},
13237
13238	computeScrollerHeight: function(totalHeight) {
13239		return totalHeight -
13240			subtractInnerElHeight(this.el, this.scroller.el); // everything that's NOT the scroller
13241	},
13242
13243	renderEvents: function(events) {
13244		this.grid.renderEvents(events);
13245	},
13246
13247	unrenderEvents: function() {
13248		this.grid.unrenderEvents();
13249	},
13250
13251	isEventResizable: function(event) {
13252		return false;
13253	},
13254
13255	isEventDraggable: function(event) {
13256		return false;
13257	}
13258
13259});
13260
13261/*
13262Responsible for event rendering and user-interaction.
13263Its "el" is the inner-content of the above view's scroller.
13264*/
13265var ListViewGrid = Grid.extend({
13266
13267	segSelector: '.fc-list-item', // which elements accept event actions
13268	hasDayInteractions: false, // no day selection or day clicking
13269
13270	// slices by day
13271	spanToSegs: function(span) {
13272		var view = this.view;
13273		var dayStart = view.start.clone().time(0); // timed, so segs get times!
13274		var dayIndex = 0;
13275		var seg;
13276		var segs = [];
13277
13278		while (dayStart < view.end) {
13279
13280			seg = intersectRanges(span, {
13281				start: dayStart,
13282				end: dayStart.clone().add(1, 'day')
13283			});
13284
13285			if (seg) {
13286				seg.dayIndex = dayIndex;
13287				segs.push(seg);
13288			}
13289
13290			dayStart.add(1, 'day');
13291			dayIndex++;
13292
13293			// detect when span won't go fully into the next day,
13294			// and mutate the latest seg to the be the end.
13295			if (
13296				seg && !seg.isEnd && span.end.hasTime() &&
13297				span.end < dayStart.clone().add(this.view.nextDayThreshold)
13298			) {
13299				seg.end = span.end.clone();
13300				seg.isEnd = true;
13301				break;
13302			}
13303		}
13304
13305		return segs;
13306	},
13307
13308	// like "4:00am"
13309	computeEventTimeFormat: function() {
13310		return this.view.opt('mediumTimeFormat');
13311	},
13312
13313	// for events with a url, the whole <tr> should be clickable,
13314	// but it's impossible to wrap with an <a> tag. simulate this.
13315	handleSegClick: function(seg, ev) {
13316		var url;
13317
13318		Grid.prototype.handleSegClick.apply(this, arguments); // super. might prevent the default action
13319
13320		// not clicking on or within an <a> with an href
13321		if (!$(ev.target).closest('a[href]').length) {
13322			url = seg.event.url;
13323			if (url && !ev.isDefaultPrevented()) { // jsEvent not cancelled in handler
13324				window.location.href = url; // simulate link click
13325			}
13326		}
13327	},
13328
13329	// returns list of foreground segs that were actually rendered
13330	renderFgSegs: function(segs) {
13331		segs = this.renderFgSegEls(segs); // might filter away hidden events
13332
13333		if (!segs.length) {
13334			this.renderEmptyMessage();
13335		}
13336		else {
13337			this.renderSegList(segs);
13338		}
13339
13340		return segs;
13341	},
13342
13343	renderEmptyMessage: function() {
13344		this.el.html(
13345			'<div class="fc-list-empty-wrap2">' + // TODO: try less wraps
13346			'<div class="fc-list-empty-wrap1">' +
13347			'<div class="fc-list-empty">' +
13348				htmlEscape(this.view.opt('noEventsMessage')) +
13349			'</div>' +
13350			'</div>' +
13351			'</div>'
13352		);
13353	},
13354
13355	// render the event segments in the view
13356	renderSegList: function(allSegs) {
13357		var segsByDay = this.groupSegsByDay(allSegs); // sparse array
13358		var dayIndex;
13359		var daySegs;
13360		var i;
13361		var tableEl = $('<table class="fc-list-table"><tbody/></table>');
13362		var tbodyEl = tableEl.find('tbody');
13363
13364		for (dayIndex = 0; dayIndex < segsByDay.length; dayIndex++) {
13365			daySegs = segsByDay[dayIndex];
13366			if (daySegs) { // sparse array, so might be undefined
13367
13368				// append a day header
13369				tbodyEl.append(this.dayHeaderHtml(
13370					this.view.start.clone().add(dayIndex, 'days')
13371				));
13372
13373				this.sortEventSegs(daySegs);
13374
13375				for (i = 0; i < daySegs.length; i++) {
13376					tbodyEl.append(daySegs[i].el); // append event row
13377				}
13378			}
13379		}
13380
13381		this.el.empty().append(tableEl);
13382	},
13383
13384	// Returns a sparse array of arrays, segs grouped by their dayIndex
13385	groupSegsByDay: function(segs) {
13386		var segsByDay = []; // sparse array
13387		var i, seg;
13388
13389		for (i = 0; i < segs.length; i++) {
13390			seg = segs[i];
13391			(segsByDay[seg.dayIndex] || (segsByDay[seg.dayIndex] = []))
13392				.push(seg);
13393		}
13394
13395		return segsByDay;
13396	},
13397
13398	// generates the HTML for the day headers that live amongst the event rows
13399	dayHeaderHtml: function(dayDate) {
13400		var view = this.view;
13401		var mainFormat = view.opt('listDayFormat');
13402		var altFormat = view.opt('listDayAltFormat');
13403
13404		return '<tr class="fc-list-heading" data-date="' + dayDate.format('YYYY-MM-DD') + '">' +
13405			'<td class="' + view.widgetHeaderClass + '" colspan="3">' +
13406				(mainFormat ?
13407					view.buildGotoAnchorHtml(
13408						dayDate,
13409						{ 'class': 'fc-list-heading-main' },
13410						htmlEscape(dayDate.format(mainFormat)) // inner HTML
13411					) :
13412					'') +
13413				(altFormat ?
13414					view.buildGotoAnchorHtml(
13415						dayDate,
13416						{ 'class': 'fc-list-heading-alt' },
13417						htmlEscape(dayDate.format(altFormat)) // inner HTML
13418					) :
13419					'') +
13420			'</td>' +
13421		'</tr>';
13422	},
13423
13424	// generates the HTML for a single event row
13425	fgSegHtml: function(seg) {
13426		var view = this.view;
13427		var classes = [ 'fc-list-item' ].concat(this.getSegCustomClasses(seg));
13428		var bgColor = this.getSegBackgroundColor(seg);
13429		var event = seg.event;
13430		var url = event.url;
13431		var timeHtml;
13432
13433		if (event.allDay) {
13434			timeHtml = view.getAllDayHtml();
13435		}
13436		else if (view.isMultiDayEvent(event)) { // if the event appears to span more than one day
13437			if (seg.isStart || seg.isEnd) { // outer segment that probably lasts part of the day
13438				timeHtml = htmlEscape(this.getEventTimeText(seg));
13439			}
13440			else { // inner segment that lasts the whole day
13441				timeHtml = view.getAllDayHtml();
13442			}
13443		}
13444		else {
13445			// Display the normal time text for the *event's* times
13446			timeHtml = htmlEscape(this.getEventTimeText(event));
13447		}
13448
13449		if (url) {
13450			classes.push('fc-has-url');
13451		}
13452
13453		return '<tr class="' + classes.join(' ') + '">' +
13454			(this.displayEventTime ?
13455				'<td class="fc-list-item-time ' + view.widgetContentClass + '">' +
13456					(timeHtml || '') +
13457				'</td>' :
13458				'') +
13459			'<td class="fc-list-item-marker ' + view.widgetContentClass + '">' +
13460				'<span class="fc-event-dot"' +
13461				(bgColor ?
13462					' style="background-color:' + bgColor + '"' :
13463					'') +
13464				'></span>' +
13465			'</td>' +
13466			'<td class="fc-list-item-title ' + view.widgetContentClass + '">' +
13467				'<a' + (url ? ' href="' + htmlEscape(url) + '"' : '') + '>' +
13468					htmlEscape(seg.event.title || '') +
13469				'</a>' +
13470			'</td>' +
13471		'</tr>';
13472	}
13473
13474});
13475
13476;;
13477
13478fcViews.list = {
13479	'class': ListView,
13480	buttonTextKey: 'list', // what to lookup in locale files
13481	defaults: {
13482		buttonText: 'list', // text to display for English
13483		listDayFormat: 'LL', // like "January 1, 2016"
13484		noEventsMessage: 'No events to display'
13485	}
13486};
13487
13488fcViews.listDay = {
13489	type: 'list',
13490	duration: { days: 1 },
13491	defaults: {
13492		listDayFormat: 'dddd' // day-of-week is all we need. full date is probably in header
13493	}
13494};
13495
13496fcViews.listWeek = {
13497	type: 'list',
13498	duration: { weeks: 1 },
13499	defaults: {
13500		listDayFormat: 'dddd', // day-of-week is more important
13501		listDayAltFormat: 'LL'
13502	}
13503};
13504
13505fcViews.listMonth = {
13506	type: 'list',
13507	duration: { month: 1 },
13508	defaults: {
13509		listDayAltFormat: 'dddd' // day-of-week is nice-to-have
13510	}
13511};
13512
13513fcViews.listYear = {
13514	type: 'list',
13515	duration: { year: 1 },
13516	defaults: {
13517		listDayAltFormat: 'dddd' // day-of-week is nice-to-have
13518	}
13519};
13520
13521;;
13522
13523return FC; // export for Node/CommonJS
13524});

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.