-
Notifications
You must be signed in to change notification settings - Fork 29
/
jquery.calendrical.js
560 lines (498 loc) · 18.8 KB
/
jquery.calendrical.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
// use UMD module definition from
// https://github.com/umdjs/umd/blob/master/templates/jqueryPlugin.js
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else if (typeof module === 'object' && module.exports) {
// Node/CommonJS
module.exports = function( root, jQuery ) {
if ( jQuery === undefined ) {
// require('jQuery') returns a factory that requires window to
// build a jQuery instance, we normalize how we use modules
// that require this pattern but the window provided is a noop
// if it's defined (how jquery works)
if ( typeof window !== 'undefined' ) {
jQuery = require('jquery');
}
else {
jQuery = require('jquery')(root);
}
}
factory(jQuery);
return jQuery;
};
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
function createDate(year, month, day)
{
var date = new Date();
date.setFullYear(year);
date.setMonth(month || 0);
date.setDate(day || 1);
return date;
}
function getToday()
{
return new Date();
}
function areDatesEqual(date1, date2)
{
return String(date1) == String(date2);
}
function daysInMonth(year, month)
{
if (year instanceof Date) return daysInMonth(year.getFullYear(), year.getMonth());
if (month == 1) {
var leapYear = (year % 4 == 0) &&
(!(year % 100 == 0) || (year % 400 == 0));
return leapYear ? 29 : 28;
} else if (month == 3 || month == 5 || month == 8 || month == 10) {
return 30;
} else {
return 31;
}
}
function dayAfter(date)
{
return createDate(date.getFullYear(), date.getMonth(), date.getDate()+1);
}
function dayBefore(date)
{
return createDate(date.getFullYear(), date.getMonth(), date.getDate()-1);
}
function monthAfter(year, month)
{
return createDate(year, month + 1);
}
function formatDate(date, options)
{
options = options || {};
options.separator = options.separator || '/';
var s;
if (options.iso) {
var m = date.getMonth() + 1;
var d = date.getDate();
return date.getFullYear() + '-' + (m < 10 ? '0'+m : m) + '-' + (d < 10 ? '0'+d : d);
}
if (options.usa) {
s = (date.getMonth() + 1) + options.separator + date.getDate()
} else {
s = date.getDate() + options.separator + (date.getMonth() + 1)
}
return s + options.separator + date.getFullYear();
}
function parseDate(date, options)
{
options = options || {};
var a, day, month, year;
a = date.split(/\D/);
if (options.iso) {
year = a.shift();
month = a.shift();
day = a.shift();
} else {
if (options.usa) {
month = a.shift();
day = a.shift();
} else {
day = a.shift();
month = a.shift();
}
year = a.shift();
}
return new Date(month + '/' + day + '/' + year);
}
function formatTime(hour, minute, options)
{
var printMinute = minute;
if (minute < 10) printMinute = '0' + minute;
if (options.isoTime) {
var printHour = hour
if (printHour < 10) printHour = '0' + hour;
return printHour + ':' + printMinute;
} else {
var printHour = hour % 12;
if (printHour == 0) printHour = 12;
if (options.meridiemUpperCase) {
var half = (hour < 12) ? 'AM' : 'PM';
} else {
var half = (hour < 12) ? 'am' : 'pm';
}
return printHour + ':' + printMinute + half;
}
}
function parseTime(text)
{
var match = match = /(\d+)\s*[:\-\.,]\s*(\d+)\s*(am|pm)?/i.exec(text);
if (match && match.length >= 3) {
var hour = Number(match[1]);
var minute = Number(match[2])
if (hour == 12 && match[3]) hour -= 12;
if (match[3] && match[3].toLowerCase() == 'pm') hour += 12;
return {
hour: hour,
minute: minute
};
} else {
return null;
}
}
function timeToMinutes(time)
{
return time && (time.hour * 60 + time.minute);
}
/**
* Generates calendar header, with month name, << and >> controls, and
* initials for days of the week.
*/
function renderCalendarHeader(element, year, month, options)
{
options = options || {};
//Prepare thead element
var thead = $('<thead />');
var titleRow = $('<tr />').appendTo(thead);
//Generate << (back a month) link
$('<th />').addClass('monthCell').append(
$('<a href="javascript:;">«</a>')
.addClass('prevMonth')
.mousedown(function(e) {
renderCalendarPage(element,
month == 0 ? (year - 1) : year,
month == 0 ? 11 : (month - 1), options
);
e.preventDefault();
})
).appendTo(titleRow);
//Generate month title
var month_label;
if (options.iso) {
month_label = year + '-' + (month < 9 ? '0': '') + (month + 1);
} else {
month_label = monthNames[month] + ' ' + year;
}
$('<th />').addClass('monthCell').attr('colSpan', 5).append(
$('<a href="javascript:;">' + month_label +
'</a>').addClass('monthName')
).appendTo(titleRow);
//Generate >> (forward a month) link
$('<th />').addClass('monthCell').append(
$('<a href="javascript:;">»</a>')
.addClass('nextMonth')
.mousedown(function() {
renderCalendarPage(element,
month == 11 ? (year + 1) : year,
month == 11 ? 0 : (month + 1), options
);
})
).appendTo(titleRow);
//Generate weekday initials row
var dayNames = $('<tr />').appendTo(thead);
$.each(String('SMTWTFS').split(''), function(k, v) {
$('<td />').addClass('dayName').append(v).appendTo(dayNames);
});
return thead;
}
function renderCalendarPage(element, year, month, options)
{
options = options || {};
var today = getToday();
var date = createDate(year, month, 1);
//Wind end date forward to saturday week after month
var endDate = monthAfter(year, month);
var ff = 6 - endDate.getDay();
if (ff < 6) ff += 7;
for (var i = 0; i < ff; i++) endDate = dayAfter(endDate);
var table = $('<table />');
renderCalendarHeader(element, year, month, options).appendTo(table);
var tbody = $('<tbody />').appendTo(table);
var row = $('<tr />');
//Rewind date to monday week before month
var rewind = date.getDay() + 7;
for (var i = 0; i < rewind; i++) date = dayBefore(date);
while (date <= endDate) {
var td = $('<td />')
.addClass('day')
.append(
$('<a href="javascript:;">' +
date.getDate() + '</a>'
).click((function() {
var thisDate = date;
return function() {
if (options && options.selectDate) {
options.selectDate(thisDate);
}
}
}()))
)
.appendTo(row);
var isToday = areDatesEqual(date, today);
var isSelected = options.selected &&
areDatesEqual(options.selected, date);
if (isToday) td.addClass('today');
if (isSelected) td.addClass('selected');
if (isToday && isSelected) td.addClass('today_selected');
if (date.getMonth() != month) td.addClass('nonMonth');
dow = date.getDay();
if (dow == 6) {
tbody.append(row);
row = $('<tr />');
}
date = dayAfter(date);
}
if (row.children().length) {
tbody.append(row);
} else {
row.remove();
}
element.empty().append(table);
}
function renderTimeSelect(element, options)
{
var minTime = timeToMinutes(options.minTime);
var maxTime = timeToMinutes(options.maxTime);
var defaultTime = timeToMinutes(options.defaultTime);
var selection = options.selection && timeToMinutes(parseTime(options.selection));
//Round selection to nearest time interval so that it matches a list item
selection = selection && (
(
Math.floor((selection - minTime) / options.timeInterval) *
options.timeInterval
) + minTime
);
var scrollTo; //Element to scroll the dropdown box to when shown
var ul = $('<ul />');
for (var time = minTime; time <= maxTime; time += options.timeInterval) {
(function(time) {
var hour = Math.floor(time / 60);
var minute = time % 60;
var timeText = formatTime(hour, minute, options);
var fullText = timeText;
if (options.showDuration) {
var duration = time - minTime;
if (duration < 60) {
fullText += ' (' + duration + ' mins)';
} else if (duration == 60) {
fullText += ' (1 hr)';
} else {
//Round partial hours to 1 decimal place
fullText += ' (' + (Math.round(duration / 60.0 * 10.0) / 10.0) + ' hrs)';
}
}
var li = $('<li />').append(
$('<a href="javascript:;">' + fullText + '</a>')
.click(function() {
if (options && options.selectTime) {
options.selectTime(timeText);
}
}).mousemove(function() {
$('li.selected', ul).removeClass('selected');
})
).appendTo(ul);
//Set to scroll to the default hour, unless already set
if (!scrollTo && time == defaultTime) scrollTo = li;
if (selection == time) {
//Highlight selected item
li.addClass('selected');
//Set to scroll to the selected hour
//
//This is set even if scrollTo is already set, since
//scrolling to selected hour is more important than
//scrolling to default hour
scrollTo = li;
}
})(time);
}
if (scrollTo) {
//Set timeout of zero so code runs immediately after any calling
//functions are finished (this is needed, since box hasn't been
//added to the DOM yet)
setTimeout(function() {
//Scroll the dropdown box so that scrollTo item is in
//the middle
element[0].scrollTop =
scrollTo[0].offsetTop - scrollTo.height() * 2;
}, 0);
}
element.empty().append(ul);
}
function positionCalendrical(div, element, options) {
if (options.positionInBody) {
$('body').append(div);
var offset = element.offset();
} else {
element.after(div);
var offset = element.position();
}
div.css({
position: 'absolute',
left: offset.left,
top: offset.top + element.height() +
options.padding * 2
});
}
$.fn.calendricalDate = function(options)
{
options = options || {};
options.padding = options.padding || 4;
return this.each(function() {
var element = $(this);
var div;
var within = false;
element.bind('focus click', function() {
if (div) return;
div = $('<div />')
.addClass('calendricalDatePopup')
.mouseenter(function() { within = true; })
.mouseleave(function() { within = false; })
.mousedown(function(e) {
e.preventDefault();
})
positionCalendrical(div, element, options);
var selected = parseDate(element.val(), options);
if (!selected.getFullYear()) selected = getToday();
renderCalendarPage(
div,
selected.getFullYear(),
selected.getMonth(), $.extend({}, options, {
selected: selected,
selectDate: function(date) {
within = false;
element.val(formatDate(date, options)).change();
div.remove();
div = null;
if (options.endDate) {
var endDate = parseDate(
options.endDate.val(), options
);
if (endDate >= selected) {
options.endDate.val(formatDate(
new Date(
date.getTime() +
endDate.getTime() -
selected.getTime()
),
options
));
}
}
}
})
);
}).blur(function() {
if (within){
if (div) element.focus();
return;
}
if (!div) return;
div.remove();
div = null;
});
});
};
$.fn.calendricalDateRange = function(options)
{
if (this.length >= 2) {
$(this[0]).calendricalDate($.extend({
endDate: $(this[1])
}, options));
$(this[1]).calendricalDate(options);
}
return this;
};
$.fn.calendricalTime = function(options)
{
options = options || {};
options.timeInterval = options.timeInterval || 30;
options.padding = options.padding || 4;
return this.each(function() {
var element = $(this);
var div;
var within = false;
element.attr('autocomplete', 'off');
element.bind('focus click', function() {
if (div) return;
div = $('<div />')
.addClass('calendricalTimePopup')
.mouseenter(function() { within = true; })
.mouseleave(function() { within = false; })
.mousedown(function(e) {
e.preventDefault();
})
positionCalendrical(div, element, options);
var renderOptions = {
selection: element.val(),
selectTime: function(time) {
within = false;
element.val(time).change();
div.remove();
div = null;
},
isoTime: options.isoTime || false,
meridiemUpperCase: options.meridiemUpperCase || false,
defaultTime: options.defaultTime || {hour: 8, minute: 0},
minTime: options.minTime || {hour: 0, minute: 0},
maxTime: options.maxTime || {hour: 23, minute: 59},
timeInterval: options.timeInterval || 30
};
if (options.startTime) {
var startTime = parseTime(options.startTime.val());
//Don't display duration if part of a datetime range,
//and start and end times are on different days
if (options.startDate &&
options.endDate &&
!areDatesEqual(parseDate(options.startDate.val(), options),
parseDate(options.endDate.val(), options))) {
startTime = null;
}
if (startTime) {
renderOptions.minTime = startTime;
renderOptions.defaultTime = startTime;
renderOptions.showDuration = true;
div.addClass('calendricalEndTimePopup');
}
}
renderTimeSelect(div, renderOptions);
}).blur(function() {
if (within){
if (div) element.focus();
return;
}
if (!div) return;
div.remove();
div = null;
});
});
};
$.fn.calendricalTimeRange = function(options)
{
if (this.length >= 2) {
$(this[0]).calendricalTime(options);
$(this[1]).calendricalTime($.extend({
startTime: $(this[0])
}, options));
}
return this;
};
$.fn.calendricalDateTimeRange = function(options)
{
if (this.length >= 4) {
$(this[0]).calendricalDate($.extend({
endDate: $(this[2])
}, options));
$(this[1]).calendricalTime(options);
$(this[2]).calendricalDate(options);
$(this[3]).calendricalTime($.extend({
startTime: $(this[1]),
startDate: $(this[0]),
endDate: $(this[2])
}, options));
}
return this;
};
}));