forked from ehsandanesh/fullcalendar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fullcalendar.js
13622 lines (10458 loc) · 374 KB
/
fullcalendar.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* FullCalendar v3.0.1
* Docs & License: http://fullcalendar.io/
* (c) 2016 Adam Shaw
*/
(function(factory) {
if (typeof define === 'function' && define.amd) {
define([ 'jquery', 'moment' ], factory);
}
else if (typeof exports === 'object') { // Node/CommonJS
module.exports = factory(require('jquery'), require('moment'));
}
else {
factory(jQuery, moment);
}
})(function($, moment) {
;;
var FC = $.fullCalendar = {
version: "3.0.1",
internalApiVersion: 6
};
var fcViews = FC.views = {};
$.fn.fullCalendar = function(options) {
var args = Array.prototype.slice.call(arguments, 1); // for a possible method call
var res = this; // what this function will return (this jQuery object by default)
this.each(function(i, _element) { // loop each DOM element involved
var element = $(_element);
var calendar = element.data('fullCalendar'); // get the existing calendar object (if any)
var singleRes; // the returned value of this single method call
// a method call
if (typeof options === 'string') {
if (calendar && $.isFunction(calendar[options])) {
singleRes = calendar[options].apply(calendar, args);
if (!i) {
res = singleRes; // record the first method call result
}
if (options === 'destroy') { // for the destroy method, must remove Calendar object data
element.removeData('fullCalendar');
}
}
}
// a new calendar initialization
else if (!calendar) { // don't initialize twice
calendar = new Calendar(element, options);
element.data('fullCalendar', calendar);
calendar.render();
}
});
return res;
};
var complexOptions = [ // names of options that are objects whose properties should be combined
'header',
'buttonText',
'buttonIcons',
'themeButtonIcons'
];
function checkArgsForJalaali(args){
for (var i in args){
if ( args[i] === true)
{
return true;
}
}
return false;
}
function delJalaaliFromArgs(args){
var out = [];
for (var i in args){
if ( typeof(args[i]) === "boolean")
{
continue;
}
out.push(args[i]);
}
return out;
}
function persianNumber(enNum){
var c = {
1: "۱",
2: "۲",
3: "۳",
4: "۴",
5: "۵",
6: "۶",
7: "۷",
8: "۸",
9: "۹",
0: "۰"
}
return enNum.toString().replace(/\d/g, function(enNum) {
return c[enNum]
}).replace(/,/g, "،");
}
function noJalaaliUnit(formatStr, isJalaali){
return (isJalaali ? formatStr.replace(/j/g,"") : formatStr);
}
function addJalaaliToArgs(args,isJalaali){
var out = [];
for (var i in args){
out.push(args[i]);
}
out.push(isJalaali);
return out;
}
// Merges an array of option objects into a single object
function mergeOptions(optionObjs) {
return mergeProps(optionObjs, complexOptions);
}
;;
// exports
FC.intersectRanges = intersectRanges;
FC.applyAll = applyAll;
FC.debounce = debounce;
FC.isInt = isInt;
FC.htmlEscape = htmlEscape;
FC.cssToStr = cssToStr;
FC.proxy = proxy;
FC.capitaliseFirstLetter = capitaliseFirstLetter;
/* FullCalendar-specific DOM Utilities
----------------------------------------------------------------------------------------------------------------------*/
// Given the scrollbar widths of some other container, create borders/margins on rowEls in order to match the left
// and right space that was offset by the scrollbars. A 1-pixel border first, then margin beyond that.
function compensateScroll(rowEls, scrollbarWidths) {
if (scrollbarWidths.left) {
rowEls.css({
'border-left-width': 1,
'margin-left': scrollbarWidths.left - 1
});
}
if (scrollbarWidths.right) {
rowEls.css({
'border-right-width': 1,
'margin-right': scrollbarWidths.right - 1
});
}
}
// Undoes compensateScroll and restores all borders/margins
function uncompensateScroll(rowEls) {
rowEls.css({
'margin-left': '',
'margin-right': '',
'border-left-width': '',
'border-right-width': ''
});
}
// Make the mouse cursor express that an event is not allowed in the current area
function disableCursor() {
$('body').addClass('fc-not-allowed');
}
// Returns the mouse cursor to its original look
function enableCursor() {
$('body').removeClass('fc-not-allowed');
}
// Given a total available height to fill, have `els` (essentially child rows) expand to accomodate.
// By default, all elements that are shorter than the recommended height are expanded uniformly, not considering
// any other els that are already too tall. if `shouldRedistribute` is on, it considers these tall rows and
// reduces the available height.
function distributeHeight(els, availableHeight, shouldRedistribute) {
// *FLOORING NOTE*: we floor in certain places because zoom can give inaccurate floating-point dimensions,
// and it is better to be shorter than taller, to avoid creating unnecessary scrollbars.
var minOffset1 = Math.floor(availableHeight / els.length); // for non-last element
var minOffset2 = Math.floor(availableHeight - minOffset1 * (els.length - 1)); // for last element *FLOORING NOTE*
var flexEls = []; // elements that are allowed to expand. array of DOM nodes
var flexOffsets = []; // amount of vertical space it takes up
var flexHeights = []; // actual css height
var usedHeight = 0;
undistributeHeight(els); // give all elements their natural height
// find elements that are below the recommended height (expandable).
// important to query for heights in a single first pass (to avoid reflow oscillation).
els.each(function(i, el) {
var minOffset = i === els.length - 1 ? minOffset2 : minOffset1;
var naturalOffset = $(el).outerHeight(true);
if (naturalOffset < minOffset) {
flexEls.push(el);
flexOffsets.push(naturalOffset);
flexHeights.push($(el).height());
}
else {
// this element stretches past recommended height (non-expandable). mark the space as occupied.
usedHeight += naturalOffset;
}
});
// readjust the recommended height to only consider the height available to non-maxed-out rows.
if (shouldRedistribute) {
availableHeight -= usedHeight;
minOffset1 = Math.floor(availableHeight / flexEls.length);
minOffset2 = Math.floor(availableHeight - minOffset1 * (flexEls.length - 1)); // *FLOORING NOTE*
}
// assign heights to all expandable elements
$(flexEls).each(function(i, el) {
var minOffset = i === flexEls.length - 1 ? minOffset2 : minOffset1;
var naturalOffset = flexOffsets[i];
var naturalHeight = flexHeights[i];
var newHeight = minOffset - (naturalOffset - naturalHeight); // subtract the margin/padding
if (naturalOffset < minOffset) { // we check this again because redistribution might have changed things
$(el).height(newHeight);
}
});
}
// Undoes distrubuteHeight, restoring all els to their natural height
function undistributeHeight(els) {
els.height('');
}
// Given `els`, a jQuery set of <td> cells, find the cell with the largest natural width and set the widths of all the
// cells to be that width.
// PREREQUISITE: if you want a cell to take up width, it needs to have a single inner element w/ display:inline
function matchCellWidths(els) {
var maxInnerWidth = 0;
els.find('> *').each(function(i, innerEl) {
var innerWidth = $(innerEl).outerWidth();
if (innerWidth > maxInnerWidth) {
maxInnerWidth = innerWidth;
}
});
maxInnerWidth++; // sometimes not accurate of width the text needs to stay on one line. insurance
els.width(maxInnerWidth);
return maxInnerWidth;
}
// Given one element that resides inside another,
// Subtracts the height of the inner element from the outer element.
function subtractInnerElHeight(outerEl, innerEl) {
var both = outerEl.add(innerEl);
var diff;
// effin' IE8/9/10/11 sometimes returns 0 for dimensions. this weird hack was the only thing that worked
both.css({
position: 'relative', // cause a reflow, which will force fresh dimension recalculation
left: -1 // ensure reflow in case the el was already relative. negative is less likely to cause new scroll
});
diff = outerEl.outerHeight() - innerEl.outerHeight(); // grab the dimensions
both.css({ position: '', left: '' }); // undo hack
return diff;
}
/* Element Geom Utilities
----------------------------------------------------------------------------------------------------------------------*/
FC.getOuterRect = getOuterRect;
FC.getClientRect = getClientRect;
FC.getContentRect = getContentRect;
FC.getScrollbarWidths = getScrollbarWidths;
// borrowed from https://github.com/jquery/jquery-ui/blob/1.11.0/ui/core.js#L51
function getScrollParent(el) {
var position = el.css('position'),
scrollParent = el.parents().filter(function() {
var parent = $(this);
return (/(auto|scroll)/).test(
parent.css('overflow') + parent.css('overflow-y') + parent.css('overflow-x')
);
}).eq(0);
return position === 'fixed' || !scrollParent.length ? $(el[0].ownerDocument || document) : scrollParent;
}
// Queries the outer bounding area of a jQuery element.
// Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
// Origin is optional.
function getOuterRect(el, origin) {
var offset = el.offset();
var left = offset.left - (origin ? origin.left : 0);
var top = offset.top - (origin ? origin.top : 0);
return {
left: left,
right: left + el.outerWidth(),
top: top,
bottom: top + el.outerHeight()
};
}
// Queries the area within the margin/border/scrollbars of a jQuery element. Does not go within the padding.
// Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
// Origin is optional.
// NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
function getClientRect(el, origin) {
var offset = el.offset();
var scrollbarWidths = getScrollbarWidths(el);
var left = offset.left + getCssFloat(el, 'border-left-width') + scrollbarWidths.left - (origin ? origin.left : 0);
var top = offset.top + getCssFloat(el, 'border-top-width') + scrollbarWidths.top - (origin ? origin.top : 0);
return {
left: left,
right: left + el[0].clientWidth, // clientWidth includes padding but NOT scrollbars
top: top,
bottom: top + el[0].clientHeight // clientHeight includes padding but NOT scrollbars
};
}
// Queries the area within the margin/border/padding of a jQuery element. Assumed not to have scrollbars.
// Returns a rectangle with absolute coordinates: left, right (exclusive), top, bottom (exclusive).
// Origin is optional.
function getContentRect(el, origin) {
var offset = el.offset(); // just outside of border, margin not included
var left = offset.left + getCssFloat(el, 'border-left-width') + getCssFloat(el, 'padding-left') -
(origin ? origin.left : 0);
var top = offset.top + getCssFloat(el, 'border-top-width') + getCssFloat(el, 'padding-top') -
(origin ? origin.top : 0);
return {
left: left,
right: left + el.width(),
top: top,
bottom: top + el.height()
};
}
// Returns the computed left/right/top/bottom scrollbar widths for the given jQuery element.
// NOTE: should use clientLeft/clientTop, but very unreliable cross-browser.
function getScrollbarWidths(el) {
var leftRightWidth = el.innerWidth() - el[0].clientWidth; // the paddings cancel out, leaving the scrollbars
var widths = {
left: 0,
right: 0,
top: 0,
bottom: el.innerHeight() - el[0].clientHeight // the paddings cancel out, leaving the bottom scrollbar
};
if (getIsLeftRtlScrollbars() && el.css('direction') == 'rtl') { // is the scrollbar on the left side?
widths.left = leftRightWidth;
}
else {
widths.right = leftRightWidth;
}
return widths;
}
// Logic for determining if, when the element is right-to-left, the scrollbar appears on the left side
var _isLeftRtlScrollbars = null;
function getIsLeftRtlScrollbars() { // responsible for caching the computation
if (_isLeftRtlScrollbars === null) {
_isLeftRtlScrollbars = computeIsLeftRtlScrollbars();
}
return _isLeftRtlScrollbars;
}
function computeIsLeftRtlScrollbars() { // creates an offscreen test element, then removes it
var el = $('<div><div/></div>')
.css({
position: 'absolute',
top: -1000,
left: 0,
border: 0,
padding: 0,
overflow: 'scroll',
direction: 'rtl'
})
.appendTo('body');
var innerEl = el.children();
var res = innerEl.offset().left > el.offset().left; // is the inner div shifted to accommodate a left scrollbar?
el.remove();
return res;
}
// Retrieves a jQuery element's computed CSS value as a floating-point number.
// If the queried value is non-numeric (ex: IE can return "medium" for border width), will just return zero.
function getCssFloat(el, prop) {
return parseFloat(el.css(prop)) || 0;
}
/* Mouse / Touch Utilities
----------------------------------------------------------------------------------------------------------------------*/
FC.preventDefault = preventDefault;
// Returns a boolean whether this was a left mouse click and no ctrl key (which means right click on Mac)
function isPrimaryMouseButton(ev) {
return ev.which == 1 && !ev.ctrlKey;
}
function getEvX(ev) {
if (ev.pageX !== undefined) {
return ev.pageX;
}
var touches = ev.originalEvent.touches;
if (touches) {
return touches[0].pageX;
}
}
function getEvY(ev) {
if (ev.pageY !== undefined) {
return ev.pageY;
}
var touches = ev.originalEvent.touches;
if (touches) {
return touches[0].pageY;
}
}
function getEvIsTouch(ev) {
return /^touch/.test(ev.type);
}
function preventSelection(el) {
el.addClass('fc-unselectable')
.on('selectstart', preventDefault);
}
// Stops a mouse/touch event from doing it's native browser action
function preventDefault(ev) {
ev.preventDefault();
}
// attach a handler to get called when ANY scroll action happens on the page.
// this was impossible to do with normal on/off because 'scroll' doesn't bubble.
// http://stackoverflow.com/a/32954565/96342
// returns `true` on success.
function bindAnyScroll(handler) {
if (window.addEventListener) {
window.addEventListener('scroll', handler, true); // useCapture=true
return true;
}
return false;
}
// undoes bindAnyScroll. must pass in the original function.
// returns `true` on success.
function unbindAnyScroll(handler) {
if (window.removeEventListener) {
window.removeEventListener('scroll', handler, true); // useCapture=true
return true;
}
return false;
}
/* General Geometry Utils
----------------------------------------------------------------------------------------------------------------------*/
FC.intersectRects = intersectRects;
// Returns a new rectangle that is the intersection of the two rectangles. If they don't intersect, returns false
function intersectRects(rect1, rect2) {
var res = {
left: Math.max(rect1.left, rect2.left),
right: Math.min(rect1.right, rect2.right),
top: Math.max(rect1.top, rect2.top),
bottom: Math.min(rect1.bottom, rect2.bottom)
};
if (res.left < res.right && res.top < res.bottom) {
return res;
}
return false;
}
// Returns a new point that will have been moved to reside within the given rectangle
function constrainPoint(point, rect) {
return {
left: Math.min(Math.max(point.left, rect.left), rect.right),
top: Math.min(Math.max(point.top, rect.top), rect.bottom)
};
}
// Returns a point that is the center of the given rectangle
function getRectCenter(rect) {
return {
left: (rect.left + rect.right) / 2,
top: (rect.top + rect.bottom) / 2
};
}
// Subtracts point2's coordinates from point1's coordinates, returning a delta
function diffPoints(point1, point2) {
return {
left: point1.left - point2.left,
top: point1.top - point2.top
};
}
/* Object Ordering by Field
----------------------------------------------------------------------------------------------------------------------*/
FC.parseFieldSpecs = parseFieldSpecs;
FC.compareByFieldSpecs = compareByFieldSpecs;
FC.compareByFieldSpec = compareByFieldSpec;
FC.flexibleCompare = flexibleCompare;
function parseFieldSpecs(input) {
var specs = [];
var tokens = [];
var i, token;
if (typeof input === 'string') {
tokens = input.split(/\s*,\s*/);
}
else if (typeof input === 'function') {
tokens = [ input ];
}
else if ($.isArray(input)) {
tokens = input;
}
for (i = 0; i < tokens.length; i++) {
token = tokens[i];
if (typeof token === 'string') {
specs.push(
token.charAt(0) == '-' ?
{ field: token.substring(1), order: -1 } :
{ field: token, order: 1 }
);
}
else if (typeof token === 'function') {
specs.push({ func: token });
}
}
return specs;
}
function compareByFieldSpecs(obj1, obj2, fieldSpecs) {
var i;
var cmp;
for (i = 0; i < fieldSpecs.length; i++) {
cmp = compareByFieldSpec(obj1, obj2, fieldSpecs[i]);
if (cmp) {
return cmp;
}
}
return 0;
}
function compareByFieldSpec(obj1, obj2, fieldSpec) {
if (fieldSpec.func) {
return fieldSpec.func(obj1, obj2);
}
return flexibleCompare(obj1[fieldSpec.field], obj2[fieldSpec.field]) *
(fieldSpec.order || 1);
}
function flexibleCompare(a, b) {
if (!a && !b) {
return 0;
}
if (b == null) {
return -1;
}
if (a == null) {
return 1;
}
if ($.type(a) === 'string' || $.type(b) === 'string') {
return String(a).localeCompare(String(b));
}
return a - b;
}
/* FullCalendar-specific Misc Utilities
----------------------------------------------------------------------------------------------------------------------*/
// Computes the intersection of the two ranges. Will return fresh date clones in a range.
// Returns undefined if no intersection.
// Expects all dates to be normalized to the same timezone beforehand.
// TODO: move to date section?
function intersectRanges(subjectRange, constraintRange) {
var subjectStart = subjectRange.start;
var subjectEnd = subjectRange.end;
var constraintStart = constraintRange.start;
var constraintEnd = constraintRange.end;
var segStart, segEnd;
var isStart, isEnd;
if (subjectEnd > constraintStart && subjectStart < constraintEnd) { // in bounds at all?
if (subjectStart >= constraintStart) {
segStart = subjectStart.clone();
isStart = true;
}
else {
segStart = constraintStart.clone();
isStart = false;
}
if (subjectEnd <= constraintEnd) {
segEnd = subjectEnd.clone();
isEnd = true;
}
else {
segEnd = constraintEnd.clone();
isEnd = false;
}
return {
start: segStart,
end: segEnd,
isStart: isStart,
isEnd: isEnd
};
}
}
/* Date Utilities
----------------------------------------------------------------------------------------------------------------------*/
FC.computeIntervalUnit = computeIntervalUnit;
FC.divideRangeByDuration = divideRangeByDuration;
FC.divideDurationByDuration = divideDurationByDuration;
FC.multiplyDuration = multiplyDuration;
FC.durationHasTime = durationHasTime;
var dayIDs = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
var intervalUnits = [ 'year', 'month', 'week', 'day', 'hour', 'minute', 'second', 'millisecond' ];
// Diffs the two moments into a Duration where full-days are recorded first, then the remaining time.
// Moments will have their timezones normalized.
function diffDayTime(a, b) {
return moment.duration({
days: a.clone().stripTime().diff(b.clone().stripTime(), 'days'),
ms: a.time() - b.time() // time-of-day from day start. disregards timezone
});
}
// Diffs the two moments via their start-of-day (regardless of timezone). Produces whole-day durations.
function diffDay(a, b) {
return moment.duration({
days: a.clone().stripTime().diff(b.clone().stripTime(), 'days')
});
}
// Diffs two moments, producing a duration, made of a whole-unit-increment of the given unit. Uses rounding.
function diffByUnit(a, b, unit) {
return moment.duration(
Math.round(a.diff(b, unit, true)), // returnFloat=true
unit
);
}
// Computes the unit name of the largest whole-unit period of time.
// For example, 48 hours will be "days" whereas 49 hours will be "hours".
// Accepts start/end, a range object, or an original duration object.
function computeIntervalUnit(start, end) {
var i, unit;
var val;
for (i = 0; i < intervalUnits.length; i++) {
unit = intervalUnits[i];
val = computeRangeAs(unit, start, end);
if (val >= 1 && isInt(val)) {
break;
}
}
return unit; // will be "milliseconds" if nothing else matches
}
// Computes the number of units (like "hours") in the given range.
// Range can be a {start,end} object, separate start/end args, or a Duration.
// Results are based on Moment's .as() and .diff() methods, so results can depend on internal handling
// of month-diffing logic (which tends to vary from version to version).
function computeRangeAs(unit, start, end) {
if (end != null) { // given start, end
return end.diff(start, unit, true);
}
else if (moment.isDuration(start)) { // given duration
return start.as(unit);
}
else { // given { start, end } range object
return start.end.diff(start.start, unit, true);
}
}
// Intelligently divides a range (specified by a start/end params) by a duration
function divideRangeByDuration(start, end, dur) {
var months;
if (durationHasTime(dur)) {
return (end - start) / dur;
}
months = dur.asMonths();
if (Math.abs(months) >= 1 && isInt(months)) {
return end.diff(start, 'months', true) / months;
}
return end.diff(start, 'days', true) / dur.asDays();
}
// Intelligently divides one duration by another
function divideDurationByDuration(dur1, dur2) {
var months1, months2;
if (durationHasTime(dur1) || durationHasTime(dur2)) {
return dur1 / dur2;
}
months1 = dur1.asMonths();
months2 = dur2.asMonths();
if (
Math.abs(months1) >= 1 && isInt(months1) &&
Math.abs(months2) >= 1 && isInt(months2)
) {
return months1 / months2;
}
return dur1.asDays() / dur2.asDays();
}
// Intelligently multiplies a duration by a number
function multiplyDuration(dur, n) {
var months;
if (durationHasTime(dur)) {
return moment.duration(dur * n);
}
months = dur.asMonths();
if (Math.abs(months) >= 1 && isInt(months)) {
return moment.duration({ months: months * n });
}
return moment.duration({ days: dur.asDays() * n });
}
// Returns a boolean about whether the given duration has any time parts (hours/minutes/seconds/ms)
function durationHasTime(dur) {
return Boolean(dur.hours() || dur.minutes() || dur.seconds() || dur.milliseconds());
}
function isNativeDate(input) {
return Object.prototype.toString.call(input) === '[object Date]' || input instanceof Date;
}
// Returns a boolean about whether the given input is a time string, like "06:40:00" or "06:00"
function isTimeString(str) {
return /^\d+\:\d+(?:\:\d+\.?(?:\d{3})?)?$/.test(str);
}
/* Logging and Debug
----------------------------------------------------------------------------------------------------------------------*/
FC.log = function() {
var console = window.console;
if (console && console.log) {
return console.log.apply(console, arguments);
}
};
FC.warn = function() {
var console = window.console;
if (console && console.warn) {
return console.warn.apply(console, arguments);
}
else {
return FC.log.apply(FC, arguments);
}
};
/* General Utilities
----------------------------------------------------------------------------------------------------------------------*/
var hasOwnPropMethod = {}.hasOwnProperty;
// Merges an array of objects into a single object.
// The second argument allows for an array of property names who's object values will be merged together.
function mergeProps(propObjs, complexProps) {
var dest = {};
var i, name;
var complexObjs;
var j, val;
var props;
if (complexProps) {
for (i = 0; i < complexProps.length; i++) {
name = complexProps[i];
complexObjs = [];
// collect the trailing object values, stopping when a non-object is discovered
for (j = propObjs.length - 1; j >= 0; j--) {
val = propObjs[j][name];
if (typeof val === 'object') {
complexObjs.unshift(val);
}
else if (val !== undefined) {
dest[name] = val; // if there were no objects, this value will be used
break;
}
}
// if the trailing values were objects, use the merged value
if (complexObjs.length) {
dest[name] = mergeProps(complexObjs);
}
}
}
// copy values into the destination, going from last to first
for (i = propObjs.length - 1; i >= 0; i--) {
props = propObjs[i];
for (name in props) {
if (!(name in dest)) { // if already assigned by previous props or complex props, don't reassign
dest[name] = props[name];
}
}
}
return dest;
}
// Create an object that has the given prototype. Just like Object.create
function createObject(proto) {
var f = function() {};
f.prototype = proto;
return new f();
}
function copyOwnProps(src, dest) {
for (var name in src) {
if (hasOwnProp(src, name)) {
dest[name] = src[name];
}
}
}
function hasOwnProp(obj, name) {
return hasOwnPropMethod.call(obj, name);
}
// Is the given value a non-object non-function value?
function isAtomic(val) {
return /undefined|null|boolean|number|string/.test($.type(val));
}
function applyAll(functions, thisObj, args) {
if ($.isFunction(functions)) {
functions = [ functions ];
}
if (functions) {
var i;
var ret;
for (i=0; i<functions.length; i++) {
ret = functions[i].apply(thisObj, args) || ret;
}
return ret;
}
}
function firstDefined() {
for (var i=0; i<arguments.length; i++) {
if (arguments[i] !== undefined) {
return arguments[i];
}
}
}
function htmlEscape(s) {
return (s + '').replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"')
.replace(/\n/g, '<br />');
}
function stripHtmlEntities(text) {
return text.replace(/&.*?;/g, '');
}
// Given a hash of CSS properties, returns a string of CSS.
// Uses property names as-is (no camel-case conversion). Will not make statements for null/undefined values.
function cssToStr(cssProps) {
var statements = [];
$.each(cssProps, function(name, val) {
if (val != null) {
statements.push(name + ':' + val);
}
});
return statements.join(';');
}
// Given an object hash of HTML attribute names to values,
// generates a string that can be injected between < > in HTML
function attrsToStr(attrs) {
var parts = [];
$.each(attrs, function(name, val) {
if (val != null) {
parts.push(name + '="' + htmlEscape(val) + '"');
}
});
return parts.join(' ');
}
function capitaliseFirstLetter(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}