PluginProbe
Easy Hotel – Powerful Hotel Booking / trunk
Easy Hotel – Powerful Hotel Booking vtrunk
2.0.8 2.0.7 2.0.6 2.0.5 2.0.4 2.0.3 2.0.2 2.0.1 2.0.0 1.9.9 1.9.8 1.9.7 1.9.6 1.9.5 1.9.4 1.9.3 1.9.2 1.8.1 1.8.2 1.8.3 1.8.4 1.8.5 1.8.6 1.8.7 1.8.8 All 110 releases
easy-hotel / admin / includes / framework / assets / js / plugins.js

plugins.js in Easy Hotel – Powerful Hotel Booking trunk, at admin/includes/framework/assets/js/plugins.js

4,775 lines 188.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /* flatpickr v4.6.9, @license MIT */
2 (function (global, factory) {
3 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
4 typeof define === 'function' && define.amd ? define(factory) :
5 (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.flatpickr = factory());
6 }(this, (function () { 'use strict';
7
8 /*! *****************************************************************************
9 Copyright (c) Microsoft Corporation.
10
11 Permission to use, copy, modify, and/or distribute this software for any
12 purpose with or without fee is hereby granted.
13
14 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
15 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
16 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
17 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
18 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
19 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
20 PERFORMANCE OF THIS SOFTWARE.
21 ***************************************************************************** */
22
23 var __assign = function() {
24 __assign = Object.assign || function __assign(t) {
25 for (var s, i = 1, n = arguments.length; i < n; i++) {
26 s = arguments[i];
27 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
28 }
29 return t;
30 };
31 return __assign.apply(this, arguments);
32 };
33
34 function __spreadArrays() {
35 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
36 for (var r = Array(s), k = 0, i = 0; i < il; i++)
37 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
38 r[k] = a[j];
39 return r;
40 }
41
42 var HOOKS = [
43 "onChange",
44 "onClose",
45 "onDayCreate",
46 "onDestroy",
47 "onKeyDown",
48 "onMonthChange",
49 "onOpen",
50 "onParseConfig",
51 "onReady",
52 "onValueUpdate",
53 "onYearChange",
54 "onPreCalendarPosition",
55 ];
56 var defaults = {
57 _disable: [],
58 allowInput: false,
59 allowInvalidPreload: false,
60 altFormat: "F j, Y",
61 altInput: false,
62 altInputClass: "form-control input",
63 animate: typeof window === "object" &&
64 window.navigator.userAgent.indexOf("MSIE") === -1,
65 ariaDateFormat: "F j, Y",
66 autoFillDefaultTime: true,
67 clickOpens: true,
68 closeOnSelect: true,
69 conjunction: ", ",
70 dateFormat: "Y-m-d",
71 defaultHour: 12,
72 defaultMinute: 0,
73 defaultSeconds: 0,
74 disable: [],
75 disableMobile: false,
76 enableSeconds: false,
77 enableTime: false,
78 errorHandler: function (err) {
79 return typeof console !== "undefined" && console.warn(err);
80 },
81 getWeek: function (givenDate) {
82 var date = new Date(givenDate.getTime());
83 date.setHours(0, 0, 0, 0);
84 // Thursday in current week decides the year.
85 date.setDate(date.getDate() + 3 - ((date.getDay() + 6) % 7));
86 // January 4 is always in week 1.
87 var week1 = new Date(date.getFullYear(), 0, 4);
88 // Adjust to Thursday in week 1 and count number of weeks from date to week1.
89 return (1 +
90 Math.round(((date.getTime() - week1.getTime()) / 86400000 -
91 3 +
92 ((week1.getDay() + 6) % 7)) /
93 7));
94 },
95 hourIncrement: 1,
96 ignoredFocusElements: [],
97 inline: false,
98 locale: "default",
99 minuteIncrement: 5,
100 mode: "single",
101 monthSelectorType: "dropdown",
102 nextArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M13.207 8.472l-7.854 7.854-0.707-0.707 7.146-7.146-7.146-7.148 0.707-0.707 7.854 7.854z' /></svg>",
103 noCalendar: false,
104 now: new Date(),
105 onChange: [],
106 onClose: [],
107 onDayCreate: [],
108 onDestroy: [],
109 onKeyDown: [],
110 onMonthChange: [],
111 onOpen: [],
112 onParseConfig: [],
113 onReady: [],
114 onValueUpdate: [],
115 onYearChange: [],
116 onPreCalendarPosition: [],
117 plugins: [],
118 position: "auto",
119 positionElement: undefined,
120 prevArrow: "<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 17 17'><g></g><path d='M5.207 8.471l7.146 7.147-0.707 0.707-7.853-7.854 7.854-7.853 0.707 0.707-7.147 7.146z' /></svg>",
121 shorthandCurrentMonth: false,
122 showMonths: 1,
123 static: false,
124 time_24hr: false,
125 weekNumbers: false,
126 wrap: false,
127 };
128
129 var english = {
130 weekdays: {
131 shorthand: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
132 longhand: [
133 "Sunday",
134 "Monday",
135 "Tuesday",
136 "Wednesday",
137 "Thursday",
138 "Friday",
139 "Saturday",
140 ],
141 },
142 months: {
143 shorthand: [
144 "Jan",
145 "Feb",
146 "Mar",
147 "Apr",
148 "May",
149 "Jun",
150 "Jul",
151 "Aug",
152 "Sep",
153 "Oct",
154 "Nov",
155 "Dec",
156 ],
157 longhand: [
158 "January",
159 "February",
160 "March",
161 "April",
162 "May",
163 "June",
164 "July",
165 "August",
166 "September",
167 "October",
168 "November",
169 "December",
170 ],
171 },
172 daysInMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
173 firstDayOfWeek: 0,
174 ordinal: function (nth) {
175 var s = nth % 100;
176 if (s > 3 && s < 21)
177 return "th";
178 switch (s % 10) {
179 case 1:
180 return "st";
181 case 2:
182 return "nd";
183 case 3:
184 return "rd";
185 default:
186 return "th";
187 }
188 },
189 rangeSeparator: " to ",
190 weekAbbreviation: "Wk",
191 scrollTitle: "Scroll to increment",
192 toggleTitle: "Click to toggle",
193 amPM: ["AM", "PM"],
194 yearAriaLabel: "Year",
195 monthAriaLabel: "Month",
196 hourAriaLabel: "Hour",
197 minuteAriaLabel: "Minute",
198 time_24hr: false,
199 };
200
201 var pad = function (number, length) {
202 if (length === void 0) { length = 2; }
203 return ("000" + number).slice(length * -1);
204 };
205 var int = function (bool) { return (bool === true ? 1 : 0); };
206 /* istanbul ignore next */
207 function debounce(fn, wait) {
208 var t;
209 return function () {
210 var _this = this;
211 clearTimeout(t);
212 t = setTimeout(function () { return fn.apply(_this, arguments); }, wait);
213 };
214 }
215 var arrayify = function (obj) {
216 return obj instanceof Array ? obj : [obj];
217 };
218
219 function toggleClass(elem, className, bool) {
220 if (bool === true)
221 return elem.classList.add(className);
222 elem.classList.remove(className);
223 }
224 function createElement(tag, className, content) {
225 var e = window.document.createElement(tag);
226 className = className || "";
227 content = content || "";
228 e.className = className;
229 if (content !== undefined)
230 e.textContent = content;
231 return e;
232 }
233 function clearNode(node) {
234 while (node.firstChild)
235 node.removeChild(node.firstChild);
236 }
237 function findParent(node, condition) {
238 if (condition(node))
239 return node;
240 else if (node.parentNode)
241 return findParent(node.parentNode, condition);
242 return undefined; // nothing found
243 }
244 function createNumberInput(inputClassName, opts) {
245 var wrapper = createElement("div", "numInputWrapper"), numInput = createElement("input", "numInput " + inputClassName), arrowUp = createElement("span", "arrowUp"), arrowDown = createElement("span", "arrowDown");
246 if (navigator.userAgent.indexOf("MSIE 9.0") === -1) {
247 numInput.type = "number";
248 }
249 else {
250 numInput.type = "text";
251 numInput.pattern = "\\d*";
252 }
253 if (opts !== undefined)
254 for (var key in opts)
255 numInput.setAttribute(key, opts[key]);
256 wrapper.appendChild(numInput);
257 wrapper.appendChild(arrowUp);
258 wrapper.appendChild(arrowDown);
259 return wrapper;
260 }
261 function getEventTarget(event) {
262 try {
263 if (typeof event.composedPath === "function") {
264 var path = event.composedPath();
265 return path[0];
266 }
267 return event.target;
268 }
269 catch (error) {
270 return event.target;
271 }
272 }
273
274 var doNothing = function () { return undefined; };
275 var monthToStr = function (monthNumber, shorthand, locale) { return locale.months[shorthand ? "shorthand" : "longhand"][monthNumber]; };
276 var revFormat = {
277 D: doNothing,
278 F: function (dateObj, monthName, locale) {
279 dateObj.setMonth(locale.months.longhand.indexOf(monthName));
280 },
281 G: function (dateObj, hour) {
282 dateObj.setHours(parseFloat(hour));
283 },
284 H: function (dateObj, hour) {
285 dateObj.setHours(parseFloat(hour));
286 },
287 J: function (dateObj, day) {
288 dateObj.setDate(parseFloat(day));
289 },
290 K: function (dateObj, amPM, locale) {
291 dateObj.setHours((dateObj.getHours() % 12) +
292 12 * int(new RegExp(locale.amPM[1], "i").test(amPM)));
293 },
294 M: function (dateObj, shortMonth, locale) {
295 dateObj.setMonth(locale.months.shorthand.indexOf(shortMonth));
296 },
297 S: function (dateObj, seconds) {
298 dateObj.setSeconds(parseFloat(seconds));
299 },
300 U: function (_, unixSeconds) { return new Date(parseFloat(unixSeconds) * 1000); },
301 W: function (dateObj, weekNum, locale) {
302 var weekNumber = parseInt(weekNum);
303 var date = new Date(dateObj.getFullYear(), 0, 2 + (weekNumber - 1) * 7, 0, 0, 0, 0);
304 date.setDate(date.getDate() - date.getDay() + locale.firstDayOfWeek);
305 return date;
306 },
307 Y: function (dateObj, year) {
308 dateObj.setFullYear(parseFloat(year));
309 },
310 Z: function (_, ISODate) { return new Date(ISODate); },
311 d: function (dateObj, day) {
312 dateObj.setDate(parseFloat(day));
313 },
314 h: function (dateObj, hour) {
315 dateObj.setHours(parseFloat(hour));
316 },
317 i: function (dateObj, minutes) {
318 dateObj.setMinutes(parseFloat(minutes));
319 },
320 j: function (dateObj, day) {
321 dateObj.setDate(parseFloat(day));
322 },
323 l: doNothing,
324 m: function (dateObj, month) {
325 dateObj.setMonth(parseFloat(month) - 1);
326 },
327 n: function (dateObj, month) {
328 dateObj.setMonth(parseFloat(month) - 1);
329 },
330 s: function (dateObj, seconds) {
331 dateObj.setSeconds(parseFloat(seconds));
332 },
333 u: function (_, unixMillSeconds) {
334 return new Date(parseFloat(unixMillSeconds));
335 },
336 w: doNothing,
337 y: function (dateObj, year) {
338 dateObj.setFullYear(2000 + parseFloat(year));
339 },
340 };
341 var tokenRegex = {
342 D: "(\\w+)",
343 F: "(\\w+)",
344 G: "(\\d\\d|\\d)",
345 H: "(\\d\\d|\\d)",
346 J: "(\\d\\d|\\d)\\w+",
347 K: "",
348 M: "(\\w+)",
349 S: "(\\d\\d|\\d)",
350 U: "(.+)",
351 W: "(\\d\\d|\\d)",
352 Y: "(\\d{4})",
353 Z: "(.+)",
354 d: "(\\d\\d|\\d)",
355 h: "(\\d\\d|\\d)",
356 i: "(\\d\\d|\\d)",
357 j: "(\\d\\d|\\d)",
358 l: "(\\w+)",
359 m: "(\\d\\d|\\d)",
360 n: "(\\d\\d|\\d)",
361 s: "(\\d\\d|\\d)",
362 u: "(.+)",
363 w: "(\\d\\d|\\d)",
364 y: "(\\d{2})",
365 };
366 var formats = {
367 // get the date in UTC
368 Z: function (date) { return date.toISOString(); },
369 // weekday name, short, e.g. Thu
370 D: function (date, locale, options) {
371 return locale.weekdays.shorthand[formats.w(date, locale, options)];
372 },
373 // full month name e.g. January
374 F: function (date, locale, options) {
375 return monthToStr(formats.n(date, locale, options) - 1, false, locale);
376 },
377 // padded hour 1-12
378 G: function (date, locale, options) {
379 return pad(formats.h(date, locale, options));
380 },
381 // hours with leading zero e.g. 03
382 H: function (date) { return pad(date.getHours()); },
383 // day (1-30) with ordinal suffix e.g. 1st, 2nd
384 J: function (date, locale) {
385 return locale.ordinal !== undefined
386 ? date.getDate() + locale.ordinal(date.getDate())
387 : date.getDate();
388 },
389 // AM/PM
390 K: function (date, locale) { return locale.amPM[int(date.getHours() > 11)]; },
391 // shorthand month e.g. Jan, Sep, Oct, etc
392 M: function (date, locale) {
393 return monthToStr(date.getMonth(), true, locale);
394 },
395 // seconds 00-59
396 S: function (date) { return pad(date.getSeconds()); },
397 // unix timestamp
398 U: function (date) { return date.getTime() / 1000; },
399 W: function (date, _, options) {
400 return options.getWeek(date);
401 },
402 // full year e.g. 2016, padded (0001-9999)
403 Y: function (date) { return pad(date.getFullYear(), 4); },
404 // day in month, padded (01-30)
405 d: function (date) { return pad(date.getDate()); },
406 // hour from 1-12 (am/pm)
407 h: function (date) { return (date.getHours() % 12 ? date.getHours() % 12 : 12); },
408 // minutes, padded with leading zero e.g. 09
409 i: function (date) { return pad(date.getMinutes()); },
410 // day in month (1-30)
411 j: function (date) { return date.getDate(); },
412 // weekday name, full, e.g. Thursday
413 l: function (date, locale) {
414 return locale.weekdays.longhand[date.getDay()];
415 },
416 // padded month number (01-12)
417 m: function (date) { return pad(date.getMonth() + 1); },
418 // the month number (1-12)
419 n: function (date) { return date.getMonth() + 1; },
420 // seconds 0-59
421 s: function (date) { return date.getSeconds(); },
422 // Unix Milliseconds
423 u: function (date) { return date.getTime(); },
424 // number of the day of the week
425 w: function (date) { return date.getDay(); },
426 // last two digits of year e.g. 16 for 2016
427 y: function (date) { return String(date.getFullYear()).substring(2); },
428 };
429
430 var createDateFormatter = function (_a) {
431 var _b = _a.config, config = _b === void 0 ? defaults : _b, _c = _a.l10n, l10n = _c === void 0 ? english : _c, _d = _a.isMobile, isMobile = _d === void 0 ? false : _d;
432 return function (dateObj, frmt, overrideLocale) {
433 var locale = overrideLocale || l10n;
434 if (config.formatDate !== undefined && !isMobile) {
435 return config.formatDate(dateObj, frmt, locale);
436 }
437 return frmt
438 .split("")
439 .map(function (c, i, arr) {
440 return formats[c] && arr[i - 1] !== "\\"
441 ? formats[c](dateObj, locale, config)
442 : c !== "\\"
443 ? c
444 : "";
445 })
446 .join("");
447 };
448 };
449 var createDateParser = function (_a) {
450 var _b = _a.config, config = _b === void 0 ? defaults : _b, _c = _a.l10n, l10n = _c === void 0 ? english : _c;
451 return function (date, givenFormat, timeless, customLocale) {
452 if (date !== 0 && !date)
453 return undefined;
454 var locale = customLocale || l10n;
455 var parsedDate;
456 var dateOrig = date;
457 if (date instanceof Date)
458 parsedDate = new Date(date.getTime());
459 else if (typeof date !== "string" &&
460 date.toFixed !== undefined // timestamp
461 )
462 // create a copy
463 parsedDate = new Date(date);
464 else if (typeof date === "string") {
465 // date string
466 var format = givenFormat || (config || defaults).dateFormat;
467 var datestr = String(date).trim();
468 if (datestr === "today") {
469 parsedDate = new Date();
470 timeless = true;
471 }
472 else if (/Z$/.test(datestr) ||
473 /GMT$/.test(datestr) // datestrings w/ timezone
474 )
475 parsedDate = new Date(date);
476 else if (config && config.parseDate)
477 parsedDate = config.parseDate(date, format);
478 else {
479 parsedDate =
480 !config || !config.noCalendar
481 ? new Date(new Date().getFullYear(), 0, 1, 0, 0, 0, 0)
482 : new Date(new Date().setHours(0, 0, 0, 0));
483 var matched = void 0, ops = [];
484 for (var i = 0, matchIndex = 0, regexStr = ""; i < format.length; i++) {
485 var token_1 = format[i];
486 var isBackSlash = token_1 === "\\";
487 var escaped = format[i - 1] === "\\" || isBackSlash;
488 if (tokenRegex[token_1] && !escaped) {
489 regexStr += tokenRegex[token_1];
490 var match = new RegExp(regexStr).exec(date);
491 if (match && (matched = true)) {
492 ops[token_1 !== "Y" ? "push" : "unshift"]({
493 fn: revFormat[token_1],
494 val: match[++matchIndex],
495 });
496 }
497 }
498 else if (!isBackSlash)
499 regexStr += "."; // don't really care
500 ops.forEach(function (_a) {
501 var fn = _a.fn, val = _a.val;
502 return (parsedDate = fn(parsedDate, val, locale) || parsedDate);
503 });
504 }
505 parsedDate = matched ? parsedDate : undefined;
506 }
507 }
508 /* istanbul ignore next */
509 if (!(parsedDate instanceof Date && !isNaN(parsedDate.getTime()))) {
510 config.errorHandler(new Error("Invalid date provided: " + dateOrig));
511 return undefined;
512 }
513 if (timeless === true)
514 parsedDate.setHours(0, 0, 0, 0);
515 return parsedDate;
516 };
517 };
518 /**
519 * Compute the difference in dates, measured in ms
520 */
521 function compareDates(date1, date2, timeless) {
522 if (timeless === void 0) { timeless = true; }
523 if (timeless !== false) {
524 return (new Date(date1.getTime()).setHours(0, 0, 0, 0) -
525 new Date(date2.getTime()).setHours(0, 0, 0, 0));
526 }
527 return date1.getTime() - date2.getTime();
528 }
529 var isBetween = function (ts, ts1, ts2) {
530 return ts > Math.min(ts1, ts2) && ts < Math.max(ts1, ts2);
531 };
532 var duration = {
533 DAY: 86400000,
534 };
535 function getDefaultHours(config) {
536 var hours = config.defaultHour;
537 var minutes = config.defaultMinute;
538 var seconds = config.defaultSeconds;
539 if (config.minDate !== undefined) {
540 var minHour = config.minDate.getHours();
541 var minMinutes = config.minDate.getMinutes();
542 var minSeconds = config.minDate.getSeconds();
543 if (hours < minHour) {
544 hours = minHour;
545 }
546 if (hours === minHour && minutes < minMinutes) {
547 minutes = minMinutes;
548 }
549 if (hours === minHour && minutes === minMinutes && seconds < minSeconds)
550 seconds = config.minDate.getSeconds();
551 }
552 if (config.maxDate !== undefined) {
553 var maxHr = config.maxDate.getHours();
554 var maxMinutes = config.maxDate.getMinutes();
555 hours = Math.min(hours, maxHr);
556 if (hours === maxHr)
557 minutes = Math.min(maxMinutes, minutes);
558 if (hours === maxHr && minutes === maxMinutes)
559 seconds = config.maxDate.getSeconds();
560 }
561 return { hours: hours, minutes: minutes, seconds: seconds };
562 }
563
564 if (typeof Object.assign !== "function") {
565 Object.assign = function (target) {
566 var args = [];
567 for (var _i = 1; _i < arguments.length; _i++) {
568 args[_i - 1] = arguments[_i];
569 }
570 if (!target) {
571 throw TypeError("Cannot convert undefined or null to object");
572 }
573 var _loop_1 = function (source) {
574 if (source) {
575 Object.keys(source).forEach(function (key) { return (target[key] = source[key]); });
576 }
577 };
578 for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
579 var source = args_1[_a];
580 _loop_1(source);
581 }
582 return target;
583 };
584 }
585
586 var DEBOUNCED_CHANGE_MS = 300;
587 function FlatpickrInstance(element, instanceConfig) {
588 var self = {
589 config: __assign(__assign({}, defaults), flatpickr.defaultConfig),
590 l10n: english,
591 };
592 self.parseDate = createDateParser({ config: self.config, l10n: self.l10n });
593 self._handlers = [];
594 self.pluginElements = [];
595 self.loadedPlugins = [];
596 self._bind = bind;
597 self._setHoursFromDate = setHoursFromDate;
598 self._positionCalendar = positionCalendar;
599 self.changeMonth = changeMonth;
600 self.changeYear = changeYear;
601 self.clear = clear;
602 self.close = close;
603 self._createElement = createElement;
604 self.destroy = destroy;
605 self.isEnabled = isEnabled;
606 self.jumpToDate = jumpToDate;
607 self.open = open;
608 self.redraw = redraw;
609 self.set = set;
610 self.setDate = setDate;
611 self.toggle = toggle;
612 function setupHelperFunctions() {
613 self.utils = {
614 getDaysInMonth: function (month, yr) {
615 if (month === void 0) { month = self.currentMonth; }
616 if (yr === void 0) { yr = self.currentYear; }
617 if (month === 1 && ((yr % 4 === 0 && yr % 100 !== 0) || yr % 400 === 0))
618 return 29;
619 return self.l10n.daysInMonth[month];
620 },
621 };
622 }
623 function init() {
624 self.element = self.input = element;
625 self.isOpen = false;
626 parseConfig();
627 setupLocale();
628 setupInputs();
629 setupDates();
630 setupHelperFunctions();
631 if (!self.isMobile)
632 build();
633 bindEvents();
634 if (self.selectedDates.length || self.config.noCalendar) {
635 if (self.config.enableTime) {
636 setHoursFromDate(self.config.noCalendar ? self.latestSelectedDateObj : undefined);
637 }
638 updateValue(false);
639 }
640 setCalendarWidth();
641 var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
642 /* TODO: investigate this further
643
644 Currently, there is weird positioning behavior in safari causing pages
645 to scroll up. https://github.com/chmln/flatpickr/issues/563
646
647 However, most browsers are not Safari and positioning is expensive when used
648 in scale. https://github.com/chmln/flatpickr/issues/1096
649 */
650 if (!self.isMobile && isSafari) {
651 positionCalendar();
652 }
653 triggerEvent("onReady");
654 }
655 function bindToInstance(fn) {
656 return fn.bind(self);
657 }
658 function setCalendarWidth() {
659 var config = self.config;
660 if (config.weekNumbers === false && config.showMonths === 1) {
661 return;
662 }
663 else if (config.noCalendar !== true) {
664 window.requestAnimationFrame(function () {
665 if (self.calendarContainer !== undefined) {
666 self.calendarContainer.style.visibility = "hidden";
667 self.calendarContainer.style.display = "block";
668 }
669 if (self.daysContainer !== undefined) {
670 var daysWidth = (self.days.offsetWidth + 1) * config.showMonths;
671 self.daysContainer.style.width = daysWidth + "px";
672 self.calendarContainer.style.width =
673 daysWidth +
674 (self.weekWrapper !== undefined
675 ? self.weekWrapper.offsetWidth
676 : 0) +
677 "px";
678 self.calendarContainer.style.removeProperty("visibility");
679 self.calendarContainer.style.removeProperty("display");
680 }
681 });
682 }
683 }
684 /**
685 * The handler for all events targeting the time inputs
686 */
687 function updateTime(e) {
688 if (self.selectedDates.length === 0) {
689 var defaultDate = self.config.minDate === undefined ||
690 compareDates(new Date(), self.config.minDate) >= 0
691 ? new Date()
692 : new Date(self.config.minDate.getTime());
693 var defaults = getDefaultHours(self.config);
694 defaultDate.setHours(defaults.hours, defaults.minutes, defaults.seconds, defaultDate.getMilliseconds());
695 self.selectedDates = [defaultDate];
696 self.latestSelectedDateObj = defaultDate;
697 }
698 if (e !== undefined && e.type !== "blur") {
699 timeWrapper(e);
700 }
701 var prevValue = self._input.value;
702 setHoursFromInputs();
703 updateValue();
704 if (self._input.value !== prevValue) {
705 self._debouncedChange();
706 }
707 }
708 function ampm2military(hour, amPM) {
709 return (hour % 12) + 12 * int(amPM === self.l10n.amPM[1]);
710 }
711 function military2ampm(hour) {
712 switch (hour % 24) {
713 case 0:
714 case 12:
715 return 12;
716 default:
717 return hour % 12;
718 }
719 }
720 /**
721 * Syncs the selected date object time with user's time input
722 */
723 function setHoursFromInputs() {
724 if (self.hourElement === undefined || self.minuteElement === undefined)
725 return;
726 var hours = (parseInt(self.hourElement.value.slice(-2), 10) || 0) % 24, minutes = (parseInt(self.minuteElement.value, 10) || 0) % 60, seconds = self.secondElement !== undefined
727 ? (parseInt(self.secondElement.value, 10) || 0) % 60
728 : 0;
729 if (self.amPM !== undefined) {
730 hours = ampm2military(hours, self.amPM.textContent);
731 }
732 var limitMinHours = self.config.minTime !== undefined ||
733 (self.config.minDate &&
734 self.minDateHasTime &&
735 self.latestSelectedDateObj &&
736 compareDates(self.latestSelectedDateObj, self.config.minDate, true) ===
737 0);
738 var limitMaxHours = self.config.maxTime !== undefined ||
739 (self.config.maxDate &&
740 self.maxDateHasTime &&
741 self.latestSelectedDateObj &&
742 compareDates(self.latestSelectedDateObj, self.config.maxDate, true) ===
743 0);
744 if (limitMaxHours) {
745 var maxTime = self.config.maxTime !== undefined
746 ? self.config.maxTime
747 : self.config.maxDate;
748 hours = Math.min(hours, maxTime.getHours());
749 if (hours === maxTime.getHours())
750 minutes = Math.min(minutes, maxTime.getMinutes());
751 if (minutes === maxTime.getMinutes())
752 seconds = Math.min(seconds, maxTime.getSeconds());
753 }
754 if (limitMinHours) {
755 var minTime = self.config.minTime !== undefined
756 ? self.config.minTime
757 : self.config.minDate;
758 hours = Math.max(hours, minTime.getHours());
759 if (hours === minTime.getHours() && minutes < minTime.getMinutes())
760 minutes = minTime.getMinutes();
761 if (minutes === minTime.getMinutes())
762 seconds = Math.max(seconds, minTime.getSeconds());
763 }
764 setHours(hours, minutes, seconds);
765 }
766 /**
767 * Syncs time input values with a date
768 */
769 function setHoursFromDate(dateObj) {
770 var date = dateObj || self.latestSelectedDateObj;
771 if (date) {
772 setHours(date.getHours(), date.getMinutes(), date.getSeconds());
773 }
774 }
775 /**
776 * Sets the hours, minutes, and optionally seconds
777 * of the latest selected date object and the
778 * corresponding time inputs
779 * @param {Number} hours the hour. whether its military
780 * or am-pm gets inferred from config
781 * @param {Number} minutes the minutes
782 * @param {Number} seconds the seconds (optional)
783 */
784 function setHours(hours, minutes, seconds) {
785 if (self.latestSelectedDateObj !== undefined) {
786 self.latestSelectedDateObj.setHours(hours % 24, minutes, seconds || 0, 0);
787 }
788 if (!self.hourElement || !self.minuteElement || self.isMobile)
789 return;
790 self.hourElement.value = pad(!self.config.time_24hr
791 ? ((12 + hours) % 12) + 12 * int(hours % 12 === 0)
792 : hours);
793 self.minuteElement.value = pad(minutes);
794 if (self.amPM !== undefined)
795 self.amPM.textContent = self.l10n.amPM[int(hours >= 12)];
796 if (self.secondElement !== undefined)
797 self.secondElement.value = pad(seconds);
798 }
799 /**
800 * Handles the year input and incrementing events
801 * @param {Event} event the keyup or increment event
802 */
803 function onYearInput(event) {
804 var eventTarget = getEventTarget(event);
805 var year = parseInt(eventTarget.value) + (event.delta || 0);
806 if (year / 1000 > 1 ||
807 (event.key === "Enter" && !/[^\d]/.test(year.toString()))) {
808 changeYear(year);
809 }
810 }
811 /**
812 * Essentially addEventListener + tracking
813 * @param {Element} element the element to addEventListener to
814 * @param {String} event the event name
815 * @param {Function} handler the event handler
816 */
817 function bind(element, event, handler, options) {
818 if (event instanceof Array)
819 return event.forEach(function (ev) { return bind(element, ev, handler, options); });
820 if (element instanceof Array)
821 return element.forEach(function (el) { return bind(el, event, handler, options); });
822 element.addEventListener(event, handler, options);
823 self._handlers.push({
824 remove: function () { return element.removeEventListener(event, handler); },
825 });
826 }
827 function triggerChange() {
828 triggerEvent("onChange");
829 }
830 /**
831 * Adds all the necessary event listeners
832 */
833 function bindEvents() {
834 if (self.config.wrap) {
835 ["open", "close", "toggle", "clear"].forEach(function (evt) {
836 Array.prototype.forEach.call(self.element.querySelectorAll("[data-" + evt + "]"), function (el) {
837 return bind(el, "click", self[evt]);
838 });
839 });
840 }
841 if (self.isMobile) {
842 setupMobile();
843 return;
844 }
845 var debouncedResize = debounce(onResize, 50);
846 self._debouncedChange = debounce(triggerChange, DEBOUNCED_CHANGE_MS);
847 if (self.daysContainer && !/iPhone|iPad|iPod/i.test(navigator.userAgent))
848 bind(self.daysContainer, "mouseover", function (e) {
849 if (self.config.mode === "range")
850 onMouseOver(getEventTarget(e));
851 });
852 bind(window.document.body, "keydown", onKeyDown);
853 if (!self.config.inline && !self.config.static)
854 bind(window, "resize", debouncedResize);
855 if (window.ontouchstart !== undefined)
856 bind(window.document, "touchstart", documentClick);
857 else
858 bind(window.document, "mousedown", documentClick);
859 bind(window.document, "focus", documentClick, { capture: true });
860 if (self.config.clickOpens === true) {
861 bind(self._input, "focus", self.open);
862 bind(self._input, "click", self.open);
863 }
864 if (self.daysContainer !== undefined) {
865 bind(self.monthNav, "click", onMonthNavClick);
866 bind(self.monthNav, ["keyup", "increment"], onYearInput);
867 bind(self.daysContainer, "click", selectDate);
868 }
869 if (self.timeContainer !== undefined &&
870 self.minuteElement !== undefined &&
871 self.hourElement !== undefined) {
872 var selText = function (e) {
873 return getEventTarget(e).select();
874 };
875 bind(self.timeContainer, ["increment"], updateTime);
876 bind(self.timeContainer, "blur", updateTime, { capture: true });
877 bind(self.timeContainer, "click", timeIncrement);
878 bind([self.hourElement, self.minuteElement], ["focus", "click"], selText);
879 if (self.secondElement !== undefined)
880 bind(self.secondElement, "focus", function () { return self.secondElement && self.secondElement.select(); });
881 if (self.amPM !== undefined) {
882 bind(self.amPM, "click", function (e) {
883 updateTime(e);
884 triggerChange();
885 });
886 }
887 }
888 if (self.config.allowInput) {
889 bind(self._input, "blur", onBlur);
890 }
891 }
892 /**
893 * Set the calendar view to a particular date.
894 * @param {Date} jumpDate the date to set the view to
895 * @param {boolean} triggerChange if change events should be triggered
896 */
897 function jumpToDate(jumpDate, triggerChange) {
898 var jumpTo = jumpDate !== undefined
899 ? self.parseDate(jumpDate)
900 : self.latestSelectedDateObj ||
901 (self.config.minDate && self.config.minDate > self.now
902 ? self.config.minDate
903 : self.config.maxDate && self.config.maxDate < self.now
904 ? self.config.maxDate
905 : self.now);
906 var oldYear = self.currentYear;
907 var oldMonth = self.currentMonth;
908 try {
909 if (jumpTo !== undefined) {
910 self.currentYear = jumpTo.getFullYear();
911 self.currentMonth = jumpTo.getMonth();
912 }
913 }
914 catch (e) {
915 /* istanbul ignore next */
916 e.message = "Invalid date supplied: " + jumpTo;
917 self.config.errorHandler(e);
918 }
919 if (triggerChange && self.currentYear !== oldYear) {
920 triggerEvent("onYearChange");
921 buildMonthSwitch();
922 }
923 if (triggerChange &&
924 (self.currentYear !== oldYear || self.currentMonth !== oldMonth)) {
925 triggerEvent("onMonthChange");
926 }
927 self.redraw();
928 }
929 /**
930 * The up/down arrow handler for time inputs
931 * @param {Event} e the click event
932 */
933 function timeIncrement(e) {
934 var eventTarget = getEventTarget(e);
935 if (~eventTarget.className.indexOf("arrow"))
936 incrementNumInput(e, eventTarget.classList.contains("arrowUp") ? 1 : -1);
937 }
938 /**
939 * Increments/decrements the value of input associ-
940 * ated with the up/down arrow by dispatching an
941 * "increment" event on the input.
942 *
943 * @param {Event} e the click event
944 * @param {Number} delta the diff (usually 1 or -1)
945 * @param {Element} inputElem the input element
946 */
947 function incrementNumInput(e, delta, inputElem) {
948 var target = e && getEventTarget(e);
949 var input = inputElem ||
950 (target && target.parentNode && target.parentNode.firstChild);
951 var event = createEvent("increment");
952 event.delta = delta;
953 input && input.dispatchEvent(event);
954 }
955 function build() {
956 var fragment = window.document.createDocumentFragment();
957 self.calendarContainer = createElement("div", "flatpickr-calendar");
958 self.calendarContainer.tabIndex = -1;
959 if (!self.config.noCalendar) {
960 fragment.appendChild(buildMonthNav());
961 self.innerContainer = createElement("div", "flatpickr-innerContainer");
962 if (self.config.weekNumbers) {
963 var _a = buildWeeks(), weekWrapper = _a.weekWrapper, weekNumbers = _a.weekNumbers;
964 self.innerContainer.appendChild(weekWrapper);
965 self.weekNumbers = weekNumbers;
966 self.weekWrapper = weekWrapper;
967 }
968 self.rContainer = createElement("div", "flatpickr-rContainer");
969 self.rContainer.appendChild(buildWeekdays());
970 if (!self.daysContainer) {
971 self.daysContainer = createElement("div", "flatpickr-days");
972 self.daysContainer.tabIndex = -1;
973 }
974 buildDays();
975 self.rContainer.appendChild(self.daysContainer);
976 self.innerContainer.appendChild(self.rContainer);
977 fragment.appendChild(self.innerContainer);
978 }
979 if (self.config.enableTime) {
980 fragment.appendChild(buildTime());
981 }
982 toggleClass(self.calendarContainer, "rangeMode", self.config.mode === "range");
983 toggleClass(self.calendarContainer, "animate", self.config.animate === true);
984 toggleClass(self.calendarContainer, "multiMonth", self.config.showMonths > 1);
985 self.calendarContainer.appendChild(fragment);
986 var customAppend = self.config.appendTo !== undefined &&
987 self.config.appendTo.nodeType !== undefined;
988 if (self.config.inline || self.config.static) {
989 self.calendarContainer.classList.add(self.config.inline ? "inline" : "static");
990 if (self.config.inline) {
991 if (!customAppend && self.element.parentNode)
992 self.element.parentNode.insertBefore(self.calendarContainer, self._input.nextSibling);
993 else if (self.config.appendTo !== undefined)
994 self.config.appendTo.appendChild(self.calendarContainer);
995 }
996 if (self.config.static) {
997 var wrapper = createElement("div", "flatpickr-wrapper");
998 if (self.element.parentNode)
999 self.element.parentNode.insertBefore(wrapper, self.element);
1000 wrapper.appendChild(self.element);
1001 if (self.altInput)
1002 wrapper.appendChild(self.altInput);
1003 wrapper.appendChild(self.calendarContainer);
1004 }
1005 }
1006 if (!self.config.static && !self.config.inline)
1007 (self.config.appendTo !== undefined
1008 ? self.config.appendTo
1009 : window.document.body).appendChild(self.calendarContainer);
1010 }
1011 function createDay(className, date, dayNumber, i) {
1012 var dateIsEnabled = isEnabled(date, true), dayElement = createElement("span", "flatpickr-day " + className, date.getDate().toString());
1013 dayElement.dateObj = date;
1014 dayElement.$i = i;
1015 dayElement.setAttribute("aria-label", self.formatDate(date, self.config.ariaDateFormat));
1016 if (className.indexOf("hidden") === -1 &&
1017 compareDates(date, self.now) === 0) {
1018 self.todayDateElem = dayElement;
1019 dayElement.classList.add("today");
1020 dayElement.setAttribute("aria-current", "date");
1021 }
1022 if (dateIsEnabled) {
1023 dayElement.tabIndex = -1;
1024 if (isDateSelected(date)) {
1025 dayElement.classList.add("selected");
1026 self.selectedDateElem = dayElement;
1027 if (self.config.mode === "range") {
1028 toggleClass(dayElement, "startRange", self.selectedDates[0] &&
1029 compareDates(date, self.selectedDates[0], true) === 0);
1030 toggleClass(dayElement, "endRange", self.selectedDates[1] &&
1031 compareDates(date, self.selectedDates[1], true) === 0);
1032 if (className === "nextMonthDay")
1033 dayElement.classList.add("inRange");
1034 }
1035 }
1036 }
1037 else {
1038 dayElement.classList.add("flatpickr-disabled");
1039 }
1040 if (self.config.mode === "range") {
1041 if (isDateInRange(date) && !isDateSelected(date))
1042 dayElement.classList.add("inRange");
1043 }
1044 if (self.weekNumbers &&
1045 self.config.showMonths === 1 &&
1046 className !== "prevMonthDay" &&
1047 dayNumber % 7 === 1) {
1048 self.weekNumbers.insertAdjacentHTML("beforeend", "<span class='flatpickr-day'>" + self.config.getWeek(date) + "</span>");
1049 }
1050 triggerEvent("onDayCreate", dayElement);
1051 return dayElement;
1052 }
1053 function focusOnDayElem(targetNode) {
1054 targetNode.focus();
1055 if (self.config.mode === "range")
1056 onMouseOver(targetNode);
1057 }
1058 function getFirstAvailableDay(delta) {
1059 var startMonth = delta > 0 ? 0 : self.config.showMonths - 1;
1060 var endMonth = delta > 0 ? self.config.showMonths : -1;
1061 for (var m = startMonth; m != endMonth; m += delta) {
1062 var month = self.daysContainer.children[m];
1063 var startIndex = delta > 0 ? 0 : month.children.length - 1;
1064 var endIndex = delta > 0 ? month.children.length : -1;
1065 for (var i = startIndex; i != endIndex; i += delta) {
1066 var c = month.children[i];
1067 if (c.className.indexOf("hidden") === -1 && isEnabled(c.dateObj))
1068 return c;
1069 }
1070 }
1071 return undefined;
1072 }
1073 function getNextAvailableDay(current, delta) {
1074 var givenMonth = current.className.indexOf("Month") === -1
1075 ? current.dateObj.getMonth()
1076 : self.currentMonth;
1077 var endMonth = delta > 0 ? self.config.showMonths : -1;
1078 var loopDelta = delta > 0 ? 1 : -1;
1079 for (var m = givenMonth - self.currentMonth; m != endMonth; m += loopDelta) {
1080 var month = self.daysContainer.children[m];
1081 var startIndex = givenMonth - self.currentMonth === m
1082 ? current.$i + delta
1083 : delta < 0
1084 ? month.children.length - 1
1085 : 0;
1086 var numMonthDays = month.children.length;
1087 for (var i = startIndex; i >= 0 && i < numMonthDays && i != (delta > 0 ? numMonthDays : -1); i += loopDelta) {
1088 var c = month.children[i];
1089 if (c.className.indexOf("hidden") === -1 &&
1090 isEnabled(c.dateObj) &&
1091 Math.abs(current.$i - i) >= Math.abs(delta))
1092 return focusOnDayElem(c);
1093 }
1094 }
1095 self.changeMonth(loopDelta);
1096 focusOnDay(getFirstAvailableDay(loopDelta), 0);
1097 return undefined;
1098 }
1099 function focusOnDay(current, offset) {
1100 var dayFocused = isInView(document.activeElement || document.body);
1101 var startElem = current !== undefined
1102 ? current
1103 : dayFocused
1104 ? document.activeElement
1105 : self.selectedDateElem !== undefined && isInView(self.selectedDateElem)
1106 ? self.selectedDateElem
1107 : self.todayDateElem !== undefined && isInView(self.todayDateElem)
1108 ? self.todayDateElem
1109 : getFirstAvailableDay(offset > 0 ? 1 : -1);
1110 if (startElem === undefined) {
1111 self._input.focus();
1112 }
1113 else if (!dayFocused) {
1114 focusOnDayElem(startElem);
1115 }
1116 else {
1117 getNextAvailableDay(startElem, offset);
1118 }
1119 }
1120 function buildMonthDays(year, month) {
1121 var firstOfMonth = (new Date(year, month, 1).getDay() - self.l10n.firstDayOfWeek + 7) % 7;
1122 var prevMonthDays = self.utils.getDaysInMonth((month - 1 + 12) % 12, year);
1123 var daysInMonth = self.utils.getDaysInMonth(month, year), days = window.document.createDocumentFragment(), isMultiMonth = self.config.showMonths > 1, prevMonthDayClass = isMultiMonth ? "prevMonthDay hidden" : "prevMonthDay", nextMonthDayClass = isMultiMonth ? "nextMonthDay hidden" : "nextMonthDay";
1124 var dayNumber = prevMonthDays + 1 - firstOfMonth, dayIndex = 0;
1125 // prepend days from the ending of previous month
1126 for (; dayNumber <= prevMonthDays; dayNumber++, dayIndex++) {
1127 days.appendChild(createDay(prevMonthDayClass, new Date(year, month - 1, dayNumber), dayNumber, dayIndex));
1128 }
1129 // Start at 1 since there is no 0th day
1130 for (dayNumber = 1; dayNumber <= daysInMonth; dayNumber++, dayIndex++) {
1131 days.appendChild(createDay("", new Date(year, month, dayNumber), dayNumber, dayIndex));
1132 }
1133 // append days from the next month
1134 for (var dayNum = daysInMonth + 1; dayNum <= 42 - firstOfMonth &&
1135 (self.config.showMonths === 1 || dayIndex % 7 !== 0); dayNum++, dayIndex++) {
1136 days.appendChild(createDay(nextMonthDayClass, new Date(year, month + 1, dayNum % daysInMonth), dayNum, dayIndex));
1137 }
1138 //updateNavigationCurrentMonth();
1139 var dayContainer = createElement("div", "dayContainer");
1140 dayContainer.appendChild(days);
1141 return dayContainer;
1142 }
1143 function buildDays() {
1144 if (self.daysContainer === undefined) {
1145 return;
1146 }
1147 clearNode(self.daysContainer);
1148 // TODO: week numbers for each month
1149 if (self.weekNumbers)
1150 clearNode(self.weekNumbers);
1151 var frag = document.createDocumentFragment();
1152 for (var i = 0; i < self.config.showMonths; i++) {
1153 var d = new Date(self.currentYear, self.currentMonth, 1);
1154 d.setMonth(self.currentMonth + i);
1155 frag.appendChild(buildMonthDays(d.getFullYear(), d.getMonth()));
1156 }
1157 self.daysContainer.appendChild(frag);
1158 self.days = self.daysContainer.firstChild;
1159 if (self.config.mode === "range" && self.selectedDates.length === 1) {
1160 onMouseOver();
1161 }
1162 }
1163 function buildMonthSwitch() {
1164 if (self.config.showMonths > 1 ||
1165 self.config.monthSelectorType !== "dropdown")
1166 return;
1167 var shouldBuildMonth = function (month) {
1168 if (self.config.minDate !== undefined &&
1169 self.currentYear === self.config.minDate.getFullYear() &&
1170 month < self.config.minDate.getMonth()) {
1171 return false;
1172 }
1173 return !(self.config.maxDate !== undefined &&
1174 self.currentYear === self.config.maxDate.getFullYear() &&
1175 month > self.config.maxDate.getMonth());
1176 };
1177 self.monthsDropdownContainer.tabIndex = -1;
1178 self.monthsDropdownContainer.innerHTML = "";
1179 for (var i = 0; i < 12; i++) {
1180 if (!shouldBuildMonth(i))
1181 continue;
1182 var month = createElement("option", "flatpickr-monthDropdown-month");
1183 month.value = new Date(self.currentYear, i).getMonth().toString();
1184 month.textContent = monthToStr(i, self.config.shorthandCurrentMonth, self.l10n);
1185 month.tabIndex = -1;
1186 if (self.currentMonth === i) {
1187 month.selected = true;
1188 }
1189 self.monthsDropdownContainer.appendChild(month);
1190 }
1191 }
1192 function buildMonth() {
1193 var container = createElement("div", "flatpickr-month");
1194 var monthNavFragment = window.document.createDocumentFragment();
1195 var monthElement;
1196 if (self.config.showMonths > 1 ||
1197 self.config.monthSelectorType === "static") {
1198 monthElement = createElement("span", "cur-month");
1199 }
1200 else {
1201 self.monthsDropdownContainer = createElement("select", "flatpickr-monthDropdown-months");
1202 self.monthsDropdownContainer.setAttribute("aria-label", self.l10n.monthAriaLabel);
1203 bind(self.monthsDropdownContainer, "change", function (e) {
1204 var target = getEventTarget(e);
1205 var selectedMonth = parseInt(target.value, 10);
1206 self.changeMonth(selectedMonth - self.currentMonth);
1207 triggerEvent("onMonthChange");
1208 });
1209 buildMonthSwitch();
1210 monthElement = self.monthsDropdownContainer;
1211 }
1212 var yearInput = createNumberInput("cur-year", { tabindex: "-1" });
1213 var yearElement = yearInput.getElementsByTagName("input")[0];
1214 yearElement.setAttribute("aria-label", self.l10n.yearAriaLabel);
1215 if (self.config.minDate) {
1216 yearElement.setAttribute("min", self.config.minDate.getFullYear().toString());
1217 }
1218 if (self.config.maxDate) {
1219 yearElement.setAttribute("max", self.config.maxDate.getFullYear().toString());
1220 yearElement.disabled =
1221 !!self.config.minDate &&
1222 self.config.minDate.getFullYear() === self.config.maxDate.getFullYear();
1223 }
1224 var currentMonth = createElement("div", "flatpickr-current-month");
1225 currentMonth.appendChild(monthElement);
1226 currentMonth.appendChild(yearInput);
1227 monthNavFragment.appendChild(currentMonth);
1228 container.appendChild(monthNavFragment);
1229 return {
1230 container: container,
1231 yearElement: yearElement,
1232 monthElement: monthElement,
1233 };
1234 }
1235 function buildMonths() {
1236 clearNode(self.monthNav);
1237 self.monthNav.appendChild(self.prevMonthNav);
1238 if (self.config.showMonths) {
1239 self.yearElements = [];
1240 self.monthElements = [];
1241 }
1242 for (var m = self.config.showMonths; m--;) {
1243 var month = buildMonth();
1244 self.yearElements.push(month.yearElement);
1245 self.monthElements.push(month.monthElement);
1246 self.monthNav.appendChild(month.container);
1247 }
1248 self.monthNav.appendChild(self.nextMonthNav);
1249 }
1250 function buildMonthNav() {
1251 self.monthNav = createElement("div", "flatpickr-months");
1252 self.yearElements = [];
1253 self.monthElements = [];
1254 self.prevMonthNav = createElement("span", "flatpickr-prev-month");
1255 self.prevMonthNav.innerHTML = self.config.prevArrow;
1256 self.nextMonthNav = createElement("span", "flatpickr-next-month");
1257 self.nextMonthNav.innerHTML = self.config.nextArrow;
1258 buildMonths();
1259 Object.defineProperty(self, "_hidePrevMonthArrow", {
1260 get: function () { return self.__hidePrevMonthArrow; },
1261 set: function (bool) {
1262 if (self.__hidePrevMonthArrow !== bool) {
1263 toggleClass(self.prevMonthNav, "flatpickr-disabled", bool);
1264 self.__hidePrevMonthArrow = bool;
1265 }
1266 },
1267 });
1268 Object.defineProperty(self, "_hideNextMonthArrow", {
1269 get: function () { return self.__hideNextMonthArrow; },
1270 set: function (bool) {
1271 if (self.__hideNextMonthArrow !== bool) {
1272 toggleClass(self.nextMonthNav, "flatpickr-disabled", bool);
1273 self.__hideNextMonthArrow = bool;
1274 }
1275 },
1276 });
1277 self.currentYearElement = self.yearElements[0];
1278 updateNavigationCurrentMonth();
1279 return self.monthNav;
1280 }
1281 function buildTime() {
1282 self.calendarContainer.classList.add("hasTime");
1283 if (self.config.noCalendar)
1284 self.calendarContainer.classList.add("noCalendar");
1285 var defaults = getDefaultHours(self.config);
1286 self.timeContainer = createElement("div", "flatpickr-time");
1287 self.timeContainer.tabIndex = -1;
1288 var separator = createElement("span", "flatpickr-time-separator", ":");
1289 var hourInput = createNumberInput("flatpickr-hour", {
1290 "aria-label": self.l10n.hourAriaLabel,
1291 });
1292 self.hourElement = hourInput.getElementsByTagName("input")[0];
1293 var minuteInput = createNumberInput("flatpickr-minute", {
1294 "aria-label": self.l10n.minuteAriaLabel,
1295 });
1296 self.minuteElement = minuteInput.getElementsByTagName("input")[0];
1297 self.hourElement.tabIndex = self.minuteElement.tabIndex = -1;
1298 self.hourElement.value = pad(self.latestSelectedDateObj
1299 ? self.latestSelectedDateObj.getHours()
1300 : self.config.time_24hr
1301 ? defaults.hours
1302 : military2ampm(defaults.hours));
1303 self.minuteElement.value = pad(self.latestSelectedDateObj
1304 ? self.latestSelectedDateObj.getMinutes()
1305 : defaults.minutes);
1306 self.hourElement.setAttribute("step", self.config.hourIncrement.toString());
1307 self.minuteElement.setAttribute("step", self.config.minuteIncrement.toString());
1308 self.hourElement.setAttribute("min", self.config.time_24hr ? "0" : "1");
1309 self.hourElement.setAttribute("max", self.config.time_24hr ? "23" : "12");
1310 self.hourElement.setAttribute("maxlength", "2");
1311 self.minuteElement.setAttribute("min", "0");
1312 self.minuteElement.setAttribute("max", "59");
1313 self.minuteElement.setAttribute("maxlength", "2");
1314 self.timeContainer.appendChild(hourInput);
1315 self.timeContainer.appendChild(separator);
1316 self.timeContainer.appendChild(minuteInput);
1317 if (self.config.time_24hr)
1318 self.timeContainer.classList.add("time24hr");
1319 if (self.config.enableSeconds) {
1320 self.timeContainer.classList.add("hasSeconds");
1321 var secondInput = createNumberInput("flatpickr-second");
1322 self.secondElement = secondInput.getElementsByTagName("input")[0];
1323 self.secondElement.value = pad(self.latestSelectedDateObj
1324 ? self.latestSelectedDateObj.getSeconds()
1325 : defaults.seconds);
1326 self.secondElement.setAttribute("step", self.minuteElement.getAttribute("step"));
1327 self.secondElement.setAttribute("min", "0");
1328 self.secondElement.setAttribute("max", "59");
1329 self.secondElement.setAttribute("maxlength", "2");
1330 self.timeContainer.appendChild(createElement("span", "flatpickr-time-separator", ":"));
1331 self.timeContainer.appendChild(secondInput);
1332 }
1333 if (!self.config.time_24hr) {
1334 // add self.amPM if appropriate
1335 self.amPM = createElement("span", "flatpickr-am-pm", self.l10n.amPM[int((self.latestSelectedDateObj
1336 ? self.hourElement.value
1337 : self.config.defaultHour) > 11)]);
1338 self.amPM.title = self.l10n.toggleTitle;
1339 self.amPM.tabIndex = -1;
1340 self.timeContainer.appendChild(self.amPM);
1341 }
1342 return self.timeContainer;
1343 }
1344 function buildWeekdays() {
1345 if (!self.weekdayContainer)
1346 self.weekdayContainer = createElement("div", "flatpickr-weekdays");
1347 else
1348 clearNode(self.weekdayContainer);
1349 for (var i = self.config.showMonths; i--;) {
1350 var container = createElement("div", "flatpickr-weekdaycontainer");
1351 self.weekdayContainer.appendChild(container);
1352 }
1353 updateWeekdays();
1354 return self.weekdayContainer;
1355 }
1356 function updateWeekdays() {
1357 if (!self.weekdayContainer) {
1358 return;
1359 }
1360 var firstDayOfWeek = self.l10n.firstDayOfWeek;
1361 var weekdays = __spreadArrays(self.l10n.weekdays.shorthand);
1362 if (firstDayOfWeek > 0 && firstDayOfWeek < weekdays.length) {
1363 weekdays = __spreadArrays(weekdays.splice(firstDayOfWeek, weekdays.length), weekdays.splice(0, firstDayOfWeek));
1364 }
1365 for (var i = self.config.showMonths; i--;) {
1366 self.weekdayContainer.children[i].innerHTML = "\n <span class='flatpickr-weekday'>\n " + weekdays.join("</span><span class='flatpickr-weekday'>") + "\n </span>\n ";
1367 }
1368 }
1369 /* istanbul ignore next */
1370 function buildWeeks() {
1371 self.calendarContainer.classList.add("hasWeeks");
1372 var weekWrapper = createElement("div", "flatpickr-weekwrapper");
1373 weekWrapper.appendChild(createElement("span", "flatpickr-weekday", self.l10n.weekAbbreviation));
1374 var weekNumbers = createElement("div", "flatpickr-weeks");
1375 weekWrapper.appendChild(weekNumbers);
1376 return {
1377 weekWrapper: weekWrapper,
1378 weekNumbers: weekNumbers,
1379 };
1380 }
1381 function changeMonth(value, isOffset) {
1382 if (isOffset === void 0) { isOffset = true; }
1383 var delta = isOffset ? value : value - self.currentMonth;
1384 if ((delta < 0 && self._hidePrevMonthArrow === true) ||
1385 (delta > 0 && self._hideNextMonthArrow === true))
1386 return;
1387 self.currentMonth += delta;
1388 if (self.currentMonth < 0 || self.currentMonth > 11) {
1389 self.currentYear += self.currentMonth > 11 ? 1 : -1;
1390 self.currentMonth = (self.currentMonth + 12) % 12;
1391 triggerEvent("onYearChange");
1392 buildMonthSwitch();
1393 }
1394 buildDays();
1395 triggerEvent("onMonthChange");
1396 updateNavigationCurrentMonth();
1397 }
1398 function clear(triggerChangeEvent, toInitial) {
1399 if (triggerChangeEvent === void 0) { triggerChangeEvent = true; }
1400 if (toInitial === void 0) { toInitial = true; }
1401 self.input.value = "";
1402 if (self.altInput !== undefined)
1403 self.altInput.value = "";
1404 if (self.mobileInput !== undefined)
1405 self.mobileInput.value = "";
1406 self.selectedDates = [];
1407 self.latestSelectedDateObj = undefined;
1408 if (toInitial === true) {
1409 self.currentYear = self._initialDate.getFullYear();
1410 self.currentMonth = self._initialDate.getMonth();
1411 }
1412 if (self.config.enableTime === true) {
1413 var _a = getDefaultHours(self.config), hours = _a.hours, minutes = _a.minutes, seconds = _a.seconds;
1414 setHours(hours, minutes, seconds);
1415 }
1416 self.redraw();
1417 if (triggerChangeEvent)
1418 // triggerChangeEvent is true (default) or an Event
1419 triggerEvent("onChange");
1420 }
1421 function close() {
1422 self.isOpen = false;
1423 if (!self.isMobile) {
1424 if (self.calendarContainer !== undefined) {
1425 self.calendarContainer.classList.remove("open");
1426 }
1427 if (self._input !== undefined) {
1428 self._input.classList.remove("active");
1429 }
1430 }
1431 triggerEvent("onClose");
1432 }
1433 function destroy() {
1434 if (self.config !== undefined)
1435 triggerEvent("onDestroy");
1436 for (var i = self._handlers.length; i--;) {
1437 self._handlers[i].remove();
1438 }
1439 self._handlers = [];
1440 if (self.mobileInput) {
1441 if (self.mobileInput.parentNode)
1442 self.mobileInput.parentNode.removeChild(self.mobileInput);
1443 self.mobileInput = undefined;
1444 }
1445 else if (self.calendarContainer && self.calendarContainer.parentNode) {
1446 if (self.config.static && self.calendarContainer.parentNode) {
1447 var wrapper = self.calendarContainer.parentNode;
1448 wrapper.lastChild && wrapper.removeChild(wrapper.lastChild);
1449 if (wrapper.parentNode) {
1450 while (wrapper.firstChild)
1451 wrapper.parentNode.insertBefore(wrapper.firstChild, wrapper);
1452 wrapper.parentNode.removeChild(wrapper);
1453 }
1454 }
1455 else
1456 self.calendarContainer.parentNode.removeChild(self.calendarContainer);
1457 }
1458 if (self.altInput) {
1459 self.input.type = "text";
1460 if (self.altInput.parentNode)
1461 self.altInput.parentNode.removeChild(self.altInput);
1462 delete self.altInput;
1463 }
1464 if (self.input) {
1465 self.input.type = self.input._type;
1466 self.input.classList.remove("flatpickr-input");
1467 self.input.removeAttribute("readonly");
1468 }
1469 [
1470 "_showTimeInput",
1471 "latestSelectedDateObj",
1472 "_hideNextMonthArrow",
1473 "_hidePrevMonthArrow",
1474 "__hideNextMonthArrow",
1475 "__hidePrevMonthArrow",
1476 "isMobile",
1477 "isOpen",
1478 "selectedDateElem",
1479 "minDateHasTime",
1480 "maxDateHasTime",
1481 "days",
1482 "daysContainer",
1483 "_input",
1484 "_positionElement",
1485 "innerContainer",
1486 "rContainer",
1487 "monthNav",
1488 "todayDateElem",
1489 "calendarContainer",
1490 "weekdayContainer",
1491 "prevMonthNav",
1492 "nextMonthNav",
1493 "monthsDropdownContainer",
1494 "currentMonthElement",
1495 "currentYearElement",
1496 "navigationCurrentMonth",
1497 "selectedDateElem",
1498 "config",
1499 ].forEach(function (k) {
1500 try {
1501 delete self[k];
1502 }
1503 catch (_) { }
1504 });
1505 }
1506 function isCalendarElem(elem) {
1507 if (self.config.appendTo && self.config.appendTo.contains(elem))
1508 return true;
1509 return self.calendarContainer.contains(elem);
1510 }
1511 function documentClick(e) {
1512 if (self.isOpen && !self.config.inline) {
1513 var eventTarget_1 = getEventTarget(e);
1514 var isCalendarElement = isCalendarElem(eventTarget_1);
1515 var isInput = eventTarget_1 === self.input ||
1516 eventTarget_1 === self.altInput ||
1517 self.element.contains(eventTarget_1) ||
1518 // web components
1519 // e.path is not present in all browsers. circumventing typechecks
1520 (e.path &&
1521 e.path.indexOf &&
1522 (~e.path.indexOf(self.input) ||
1523 ~e.path.indexOf(self.altInput)));
1524 var lostFocus = e.type === "blur"
1525 ? isInput &&
1526 e.relatedTarget &&
1527 !isCalendarElem(e.relatedTarget)
1528 : !isInput &&
1529 !isCalendarElement &&
1530 !isCalendarElem(e.relatedTarget);
1531 var isIgnored = !self.config.ignoredFocusElements.some(function (elem) {
1532 return elem.contains(eventTarget_1);
1533 });
1534 if (lostFocus && isIgnored) {
1535 if (self.timeContainer !== undefined &&
1536 self.minuteElement !== undefined &&
1537 self.hourElement !== undefined &&
1538 self.input.value !== "" &&
1539 self.input.value !== undefined) {
1540 updateTime();
1541 }
1542 self.close();
1543 if (self.config &&
1544 self.config.mode === "range" &&
1545 self.selectedDates.length === 1) {
1546 self.clear(false);
1547 self.redraw();
1548 }
1549 }
1550 }
1551 }
1552 function changeYear(newYear) {
1553 if (!newYear ||
1554 (self.config.minDate && newYear < self.config.minDate.getFullYear()) ||
1555 (self.config.maxDate && newYear > self.config.maxDate.getFullYear()))
1556 return;
1557 var newYearNum = newYear, isNewYear = self.currentYear !== newYearNum;
1558 self.currentYear = newYearNum || self.currentYear;
1559 if (self.config.maxDate &&
1560 self.currentYear === self.config.maxDate.getFullYear()) {
1561 self.currentMonth = Math.min(self.config.maxDate.getMonth(), self.currentMonth);
1562 }
1563 else if (self.config.minDate &&
1564 self.currentYear === self.config.minDate.getFullYear()) {
1565 self.currentMonth = Math.max(self.config.minDate.getMonth(), self.currentMonth);
1566 }
1567 if (isNewYear) {
1568 self.redraw();
1569 triggerEvent("onYearChange");
1570 buildMonthSwitch();
1571 }
1572 }
1573 function isEnabled(date, timeless) {
1574 var _a;
1575 if (timeless === void 0) { timeless = true; }
1576 var dateToCheck = self.parseDate(date, undefined, timeless); // timeless
1577 if ((self.config.minDate &&
1578 dateToCheck &&
1579 compareDates(dateToCheck, self.config.minDate, timeless !== undefined ? timeless : !self.minDateHasTime) < 0) ||
1580 (self.config.maxDate &&
1581 dateToCheck &&
1582 compareDates(dateToCheck, self.config.maxDate, timeless !== undefined ? timeless : !self.maxDateHasTime) > 0))
1583 return false;
1584 if (!self.config.enable && self.config.disable.length === 0)
1585 return true;
1586 if (dateToCheck === undefined)
1587 return false;
1588 var bool = !!self.config.enable, array = (_a = self.config.enable) !== null && _a !== void 0 ? _a : self.config.disable;
1589 for (var i = 0, d = void 0; i < array.length; i++) {
1590 d = array[i];
1591 if (typeof d === "function" &&
1592 d(dateToCheck) // disabled by function
1593 )
1594 return bool;
1595 else if (d instanceof Date &&
1596 dateToCheck !== undefined &&
1597 d.getTime() === dateToCheck.getTime())
1598 // disabled by date
1599 return bool;
1600 else if (typeof d === "string") {
1601 // disabled by date string
1602 var parsed = self.parseDate(d, undefined, true);
1603 return parsed && parsed.getTime() === dateToCheck.getTime()
1604 ? bool
1605 : !bool;
1606 }
1607 else if (
1608 // disabled by range
1609 typeof d === "object" &&
1610 dateToCheck !== undefined &&
1611 d.from &&
1612 d.to &&
1613 dateToCheck.getTime() >= d.from.getTime() &&
1614 dateToCheck.getTime() <= d.to.getTime())
1615 return bool;
1616 }
1617 return !bool;
1618 }
1619 function isInView(elem) {
1620 if (self.daysContainer !== undefined)
1621 return (elem.className.indexOf("hidden") === -1 &&
1622 elem.className.indexOf("flatpickr-disabled") === -1 &&
1623 self.daysContainer.contains(elem));
1624 return false;
1625 }
1626 function onBlur(e) {
1627 var isInput = e.target === self._input;
1628 if (isInput &&
1629 (self.selectedDates.length > 0 || self._input.value.length > 0) &&
1630 !(e.relatedTarget && isCalendarElem(e.relatedTarget))) {
1631 self.setDate(self._input.value, true, e.target === self.altInput
1632 ? self.config.altFormat
1633 : self.config.dateFormat);
1634 }
1635 }
1636 function onKeyDown(e) {
1637 // e.key e.keyCode
1638 // "Backspace" 8
1639 // "Tab" 9
1640 // "Enter" 13
1641 // "Escape" (IE "Esc") 27
1642 // "ArrowLeft" (IE "Left") 37
1643 // "ArrowUp" (IE "Up") 38
1644 // "ArrowRight" (IE "Right") 39
1645 // "ArrowDown" (IE "Down") 40
1646 // "Delete" (IE "Del") 46
1647 var eventTarget = getEventTarget(e);
1648 var isInput = self.config.wrap
1649 ? element.contains(eventTarget)
1650 : eventTarget === self._input;
1651 var allowInput = self.config.allowInput;
1652 var allowKeydown = self.isOpen && (!allowInput || !isInput);
1653 var allowInlineKeydown = self.config.inline && isInput && !allowInput;
1654 if (e.keyCode === 13 && isInput) {
1655 if (allowInput) {
1656 self.setDate(self._input.value, true, eventTarget === self.altInput
1657 ? self.config.altFormat
1658 : self.config.dateFormat);
1659 return eventTarget.blur();
1660 }
1661 else {
1662 self.open();
1663 }
1664 }
1665 else if (isCalendarElem(eventTarget) ||
1666 allowKeydown ||
1667 allowInlineKeydown) {
1668 var isTimeObj = !!self.timeContainer &&
1669 self.timeContainer.contains(eventTarget);
1670 switch (e.keyCode) {
1671 case 13:
1672 if (isTimeObj) {
1673 e.preventDefault();
1674 updateTime();
1675 focusAndClose();
1676 }
1677 else
1678 selectDate(e);
1679 break;
1680 case 27: // escape
1681 e.preventDefault();
1682 focusAndClose();
1683 break;
1684 case 8:
1685 case 46:
1686 if (isInput && !self.config.allowInput) {
1687 e.preventDefault();
1688 self.clear();
1689 }
1690 break;
1691 case 37:
1692 case 39:
1693 if (!isTimeObj && !isInput) {
1694 e.preventDefault();
1695 if (self.daysContainer !== undefined &&
1696 (allowInput === false ||
1697 (document.activeElement && isInView(document.activeElement)))) {
1698 var delta_1 = e.keyCode === 39 ? 1 : -1;
1699 if (!e.ctrlKey)
1700 focusOnDay(undefined, delta_1);
1701 else {
1702 e.stopPropagation();
1703 changeMonth(delta_1);
1704 focusOnDay(getFirstAvailableDay(1), 0);
1705 }
1706 }
1707 }
1708 else if (self.hourElement)
1709 self.hourElement.focus();
1710 break;
1711 case 38:
1712 case 40:
1713 e.preventDefault();
1714 var delta = e.keyCode === 40 ? 1 : -1;
1715 if ((self.daysContainer &&
1716 eventTarget.$i !== undefined) ||
1717 eventTarget === self.input ||
1718 eventTarget === self.altInput) {
1719 if (e.ctrlKey) {
1720 e.stopPropagation();
1721 changeYear(self.currentYear - delta);
1722 focusOnDay(getFirstAvailableDay(1), 0);
1723 }
1724 else if (!isTimeObj)
1725 focusOnDay(undefined, delta * 7);
1726 }
1727 else if (eventTarget === self.currentYearElement) {
1728 changeYear(self.currentYear - delta);
1729 }
1730 else if (self.config.enableTime) {
1731 if (!isTimeObj && self.hourElement)
1732 self.hourElement.focus();
1733 updateTime(e);
1734 self._debouncedChange();
1735 }
1736 break;
1737 case 9:
1738 if (isTimeObj) {
1739 var elems = [
1740 self.hourElement,
1741 self.minuteElement,
1742 self.secondElement,
1743 self.amPM,
1744 ]
1745 .concat(self.pluginElements)
1746 .filter(function (x) { return x; });
1747 var i = elems.indexOf(eventTarget);
1748 if (i !== -1) {
1749 var target = elems[i + (e.shiftKey ? -1 : 1)];
1750 e.preventDefault();
1751 (target || self._input).focus();
1752 }
1753 }
1754 else if (!self.config.noCalendar &&
1755 self.daysContainer &&
1756 self.daysContainer.contains(eventTarget) &&
1757 e.shiftKey) {
1758 e.preventDefault();
1759 self._input.focus();
1760 }
1761 break;
1762 }
1763 }
1764 if (self.amPM !== undefined && eventTarget === self.amPM) {
1765 switch (e.key) {
1766 case self.l10n.amPM[0].charAt(0):
1767 case self.l10n.amPM[0].charAt(0).toLowerCase():
1768 self.amPM.textContent = self.l10n.amPM[0];
1769 setHoursFromInputs();
1770 updateValue();
1771 break;
1772 case self.l10n.amPM[1].charAt(0):
1773 case self.l10n.amPM[1].charAt(0).toLowerCase():
1774 self.amPM.textContent = self.l10n.amPM[1];
1775 setHoursFromInputs();
1776 updateValue();
1777 break;
1778 }
1779 }
1780 if (isInput || isCalendarElem(eventTarget)) {
1781 triggerEvent("onKeyDown", e);
1782 }
1783 }
1784 function onMouseOver(elem) {
1785 if (self.selectedDates.length !== 1 ||
1786 (elem &&
1787 (!elem.classList.contains("flatpickr-day") ||
1788 elem.classList.contains("flatpickr-disabled"))))
1789 return;
1790 var hoverDate = elem
1791 ? elem.dateObj.getTime()
1792 : self.days.firstElementChild.dateObj.getTime(), initialDate = self.parseDate(self.selectedDates[0], undefined, true).getTime(), rangeStartDate = Math.min(hoverDate, self.selectedDates[0].getTime()), rangeEndDate = Math.max(hoverDate, self.selectedDates[0].getTime());
1793 var containsDisabled = false;
1794 var minRange = 0, maxRange = 0;
1795 for (var t = rangeStartDate; t < rangeEndDate; t += duration.DAY) {
1796 if (!isEnabled(new Date(t), true)) {
1797 containsDisabled =
1798 containsDisabled || (t > rangeStartDate && t < rangeEndDate);
1799 if (t < initialDate && (!minRange || t > minRange))
1800 minRange = t;
1801 else if (t > initialDate && (!maxRange || t < maxRange))
1802 maxRange = t;
1803 }
1804 }
1805 for (var m = 0; m < self.config.showMonths; m++) {
1806 var month = self.daysContainer.children[m];
1807 var _loop_1 = function (i, l) {
1808 var dayElem = month.children[i], date = dayElem.dateObj;
1809 var timestamp = date.getTime();
1810 var outOfRange = (minRange > 0 && timestamp < minRange) ||
1811 (maxRange > 0 && timestamp > maxRange);
1812 if (outOfRange) {
1813 dayElem.classList.add("notAllowed");
1814 ["inRange", "startRange", "endRange"].forEach(function (c) {
1815 dayElem.classList.remove(c);
1816 });
1817 return "continue";
1818 }
1819 else if (containsDisabled && !outOfRange)
1820 return "continue";
1821 ["startRange", "inRange", "endRange", "notAllowed"].forEach(function (c) {
1822 dayElem.classList.remove(c);
1823 });
1824 if (elem !== undefined) {
1825 elem.classList.add(hoverDate <= self.selectedDates[0].getTime()
1826 ? "startRange"
1827 : "endRange");
1828 if (initialDate < hoverDate && timestamp === initialDate)
1829 dayElem.classList.add("startRange");
1830 else if (initialDate > hoverDate && timestamp === initialDate)
1831 dayElem.classList.add("endRange");
1832 if (timestamp >= minRange &&
1833 (maxRange === 0 || timestamp <= maxRange) &&
1834 isBetween(timestamp, initialDate, hoverDate))
1835 dayElem.classList.add("inRange");
1836 }
1837 };
1838 for (var i = 0, l = month.children.length; i < l; i++) {
1839 _loop_1(i, l);
1840 }
1841 }
1842 }
1843 function onResize() {
1844 if (self.isOpen && !self.config.static && !self.config.inline)
1845 positionCalendar();
1846 }
1847 function open(e, positionElement) {
1848 if (positionElement === void 0) { positionElement = self._positionElement; }
1849 if (self.isMobile === true) {
1850 if (e) {
1851 e.preventDefault();
1852 var eventTarget = getEventTarget(e);
1853 if (eventTarget) {
1854 eventTarget.blur();
1855 }
1856 }
1857 if (self.mobileInput !== undefined) {
1858 self.mobileInput.focus();
1859 self.mobileInput.click();
1860 }
1861 triggerEvent("onOpen");
1862 return;
1863 }
1864 else if (self._input.disabled || self.config.inline) {
1865 return;
1866 }
1867 var wasOpen = self.isOpen;
1868 self.isOpen = true;
1869 if (!wasOpen) {
1870 self.calendarContainer.classList.add("open");
1871 self._input.classList.add("active");
1872 triggerEvent("onOpen");
1873 positionCalendar(positionElement);
1874 }
1875 if (self.config.enableTime === true && self.config.noCalendar === true) {
1876 if (self.config.allowInput === false &&
1877 (e === undefined ||
1878 !self.timeContainer.contains(e.relatedTarget))) {
1879 setTimeout(function () { return self.hourElement.select(); }, 50);
1880 }
1881 }
1882 }
1883 function minMaxDateSetter(type) {
1884 return function (date) {
1885 var dateObj = (self.config["_" + type + "Date"] = self.parseDate(date, self.config.dateFormat));
1886 var inverseDateObj = self.config["_" + (type === "min" ? "max" : "min") + "Date"];
1887 if (dateObj !== undefined) {
1888 self[type === "min" ? "minDateHasTime" : "maxDateHasTime"] =
1889 dateObj.getHours() > 0 ||
1890 dateObj.getMinutes() > 0 ||
1891 dateObj.getSeconds() > 0;
1892 }
1893 if (self.selectedDates) {
1894 self.selectedDates = self.selectedDates.filter(function (d) { return isEnabled(d); });
1895 if (!self.selectedDates.length && type === "min")
1896 setHoursFromDate(dateObj);
1897 updateValue();
1898 }
1899 if (self.daysContainer) {
1900 redraw();
1901 if (dateObj !== undefined)
1902 self.currentYearElement[type] = dateObj.getFullYear().toString();
1903 else
1904 self.currentYearElement.removeAttribute(type);
1905 self.currentYearElement.disabled =
1906 !!inverseDateObj &&
1907 dateObj !== undefined &&
1908 inverseDateObj.getFullYear() === dateObj.getFullYear();
1909 }
1910 };
1911 }
1912 function parseConfig() {
1913 var boolOpts = [
1914 "wrap",
1915 "weekNumbers",
1916 "allowInput",
1917 "allowInvalidPreload",
1918 "clickOpens",
1919 "time_24hr",
1920 "enableTime",
1921 "noCalendar",
1922 "altInput",
1923 "shorthandCurrentMonth",
1924 "inline",
1925 "static",
1926 "enableSeconds",
1927 "disableMobile",
1928 ];
1929 var userConfig = __assign(__assign({}, JSON.parse(JSON.stringify(element.dataset || {}))), instanceConfig);
1930 var formats = {};
1931 self.config.parseDate = userConfig.parseDate;
1932 self.config.formatDate = userConfig.formatDate;
1933 Object.defineProperty(self.config, "enable", {
1934 get: function () { return self.config._enable; },
1935 set: function (dates) {
1936 self.config._enable = parseDateRules(dates);
1937 },
1938 });
1939 Object.defineProperty(self.config, "disable", {
1940 get: function () { return self.config._disable; },
1941 set: function (dates) {
1942 self.config._disable = parseDateRules(dates);
1943 },
1944 });
1945 var timeMode = userConfig.mode === "time";
1946 if (!userConfig.dateFormat && (userConfig.enableTime || timeMode)) {
1947 var defaultDateFormat = flatpickr.defaultConfig.dateFormat || defaults.dateFormat;
1948 formats.dateFormat =
1949 userConfig.noCalendar || timeMode
1950 ? "H:i" + (userConfig.enableSeconds ? ":S" : "")
1951 : defaultDateFormat + " H:i" + (userConfig.enableSeconds ? ":S" : "");
1952 }
1953 if (userConfig.altInput &&
1954 (userConfig.enableTime || timeMode) &&
1955 !userConfig.altFormat) {
1956 var defaultAltFormat = flatpickr.defaultConfig.altFormat || defaults.altFormat;
1957 formats.altFormat =
1958 userConfig.noCalendar || timeMode
1959 ? "h:i" + (userConfig.enableSeconds ? ":S K" : " K")
1960 : defaultAltFormat + (" h:i" + (userConfig.enableSeconds ? ":S" : "") + " K");
1961 }
1962 Object.defineProperty(self.config, "minDate", {
1963 get: function () { return self.config._minDate; },
1964 set: minMaxDateSetter("min"),
1965 });
1966 Object.defineProperty(self.config, "maxDate", {
1967 get: function () { return self.config._maxDate; },
1968 set: minMaxDateSetter("max"),
1969 });
1970 var minMaxTimeSetter = function (type) { return function (val) {
1971 self.config[type === "min" ? "_minTime" : "_maxTime"] = self.parseDate(val, "H:i:S");
1972 }; };
1973 Object.defineProperty(self.config, "minTime", {
1974 get: function () { return self.config._minTime; },
1975 set: minMaxTimeSetter("min"),
1976 });
1977 Object.defineProperty(self.config, "maxTime", {
1978 get: function () { return self.config._maxTime; },
1979 set: minMaxTimeSetter("max"),
1980 });
1981 if (userConfig.mode === "time") {
1982 self.config.noCalendar = true;
1983 self.config.enableTime = true;
1984 }
1985 Object.assign(self.config, formats, userConfig);
1986 for (var i = 0; i < boolOpts.length; i++)
1987 // https://github.com/microsoft/TypeScript/issues/31663
1988 self.config[boolOpts[i]] =
1989 self.config[boolOpts[i]] === true ||
1990 self.config[boolOpts[i]] === "true";
1991 HOOKS.filter(function (hook) { return self.config[hook] !== undefined; }).forEach(function (hook) {
1992 self.config[hook] = arrayify(self.config[hook] || []).map(bindToInstance);
1993 });
1994 self.isMobile =
1995 !self.config.disableMobile &&
1996 !self.config.inline &&
1997 self.config.mode === "single" &&
1998 !self.config.disable.length &&
1999 !self.config.enable &&
2000 !self.config.weekNumbers &&
2001 /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
2002 for (var i = 0; i < self.config.plugins.length; i++) {
2003 var pluginConf = self.config.plugins[i](self) || {};
2004 for (var key in pluginConf) {
2005 if (HOOKS.indexOf(key) > -1) {
2006 self.config[key] = arrayify(pluginConf[key])
2007 .map(bindToInstance)
2008 .concat(self.config[key]);
2009 }
2010 else if (typeof userConfig[key] === "undefined")
2011 self.config[key] = pluginConf[key];
2012 }
2013 }
2014 if (!userConfig.altInputClass) {
2015 self.config.altInputClass =
2016 getInputElem().className + " " + self.config.altInputClass;
2017 }
2018 triggerEvent("onParseConfig");
2019 }
2020 function getInputElem() {
2021 return self.config.wrap
2022 ? element.querySelector("[data-input]")
2023 : element;
2024 }
2025 function setupLocale() {
2026 if (typeof self.config.locale !== "object" &&
2027 typeof flatpickr.l10ns[self.config.locale] === "undefined")
2028 self.config.errorHandler(new Error("flatpickr: invalid locale " + self.config.locale));
2029 self.l10n = __assign(__assign({}, flatpickr.l10ns.default), (typeof self.config.locale === "object"
2030 ? self.config.locale
2031 : self.config.locale !== "default"
2032 ? flatpickr.l10ns[self.config.locale]
2033 : undefined));
2034 tokenRegex.K = "(" + self.l10n.amPM[0] + "|" + self.l10n.amPM[1] + "|" + self.l10n.amPM[0].toLowerCase() + "|" + self.l10n.amPM[1].toLowerCase() + ")";
2035 var userConfig = __assign(__assign({}, instanceConfig), JSON.parse(JSON.stringify(element.dataset || {})));
2036 if (userConfig.time_24hr === undefined &&
2037 flatpickr.defaultConfig.time_24hr === undefined) {
2038 self.config.time_24hr = self.l10n.time_24hr;
2039 }
2040 self.formatDate = createDateFormatter(self);
2041 self.parseDate = createDateParser({ config: self.config, l10n: self.l10n });
2042 }
2043 function positionCalendar(customPositionElement) {
2044 if (typeof self.config.position === "function") {
2045 return void self.config.position(self, customPositionElement);
2046 }
2047 if (self.calendarContainer === undefined)
2048 return;
2049 triggerEvent("onPreCalendarPosition");
2050 var positionElement = customPositionElement || self._positionElement;
2051 var calendarHeight = Array.prototype.reduce.call(self.calendarContainer.children, (function (acc, child) { return acc + child.offsetHeight; }), 0), calendarWidth = self.calendarContainer.offsetWidth, configPos = self.config.position.split(" "), configPosVertical = configPos[0], configPosHorizontal = configPos.length > 1 ? configPos[1] : null, inputBounds = positionElement.getBoundingClientRect(), distanceFromBottom = window.innerHeight - inputBounds.bottom, showOnTop = configPosVertical === "above" ||
2052 (configPosVertical !== "below" &&
2053 distanceFromBottom < calendarHeight &&
2054 inputBounds.top > calendarHeight);
2055 var top = window.pageYOffset +
2056 inputBounds.top +
2057 (!showOnTop ? positionElement.offsetHeight + 2 : -calendarHeight - 2);
2058 toggleClass(self.calendarContainer, "arrowTop", !showOnTop);
2059 toggleClass(self.calendarContainer, "arrowBottom", showOnTop);
2060 if (self.config.inline)
2061 return;
2062 var left = window.pageXOffset + inputBounds.left;
2063 var isCenter = false;
2064 var isRight = false;
2065 if (configPosHorizontal === "center") {
2066 left -= (calendarWidth - inputBounds.width) / 2;
2067 isCenter = true;
2068 }
2069 else if (configPosHorizontal === "right") {
2070 left -= calendarWidth - inputBounds.width;
2071 isRight = true;
2072 }
2073 toggleClass(self.calendarContainer, "arrowLeft", !isCenter && !isRight);
2074 toggleClass(self.calendarContainer, "arrowCenter", isCenter);
2075 toggleClass(self.calendarContainer, "arrowRight", isRight);
2076 var right = window.document.body.offsetWidth -
2077 (window.pageXOffset + inputBounds.right);
2078 var rightMost = left + calendarWidth > window.document.body.offsetWidth;
2079 var centerMost = right + calendarWidth > window.document.body.offsetWidth;
2080 toggleClass(self.calendarContainer, "rightMost", rightMost);
2081 if (self.config.static)
2082 return;
2083 self.calendarContainer.style.top = top + "px";
2084 if (!rightMost) {
2085 self.calendarContainer.style.left = left + "px";
2086 self.calendarContainer.style.right = "auto";
2087 }
2088 else if (!centerMost) {
2089 self.calendarContainer.style.left = "auto";
2090 self.calendarContainer.style.right = right + "px";
2091 }
2092 else {
2093 var doc = getDocumentStyleSheet();
2094 // some testing environments don't have css support
2095 if (doc === undefined)
2096 return;
2097 var bodyWidth = window.document.body.offsetWidth;
2098 var centerLeft = Math.max(0, bodyWidth / 2 - calendarWidth / 2);
2099 var centerBefore = ".flatpickr-calendar.centerMost:before";
2100 var centerAfter = ".flatpickr-calendar.centerMost:after";
2101 var centerIndex = doc.cssRules.length;
2102 var centerStyle = "{left:" + inputBounds.left + "px;right:auto;}";
2103 toggleClass(self.calendarContainer, "rightMost", false);
2104 toggleClass(self.calendarContainer, "centerMost", true);
2105 doc.insertRule(centerBefore + "," + centerAfter + centerStyle, centerIndex);
2106 self.calendarContainer.style.left = centerLeft + "px";
2107 self.calendarContainer.style.right = "auto";
2108 }
2109 }
2110 function getDocumentStyleSheet() {
2111 var editableSheet = null;
2112 for (var i = 0; i < document.styleSheets.length; i++) {
2113 var sheet = document.styleSheets[i];
2114 try {
2115 sheet.cssRules;
2116 }
2117 catch (err) {
2118 continue;
2119 }
2120 editableSheet = sheet;
2121 break;
2122 }
2123 return editableSheet != null ? editableSheet : createStyleSheet();
2124 }
2125 function createStyleSheet() {
2126 var style = document.createElement("style");
2127 document.head.appendChild(style);
2128 return style.sheet;
2129 }
2130 function redraw() {
2131 if (self.config.noCalendar || self.isMobile)
2132 return;
2133 buildMonthSwitch();
2134 updateNavigationCurrentMonth();
2135 buildDays();
2136 }
2137 function focusAndClose() {
2138 self._input.focus();
2139 if (window.navigator.userAgent.indexOf("MSIE") !== -1 ||
2140 navigator.msMaxTouchPoints !== undefined) {
2141 // hack - bugs in the way IE handles focus keeps the calendar open
2142 setTimeout(self.close, 0);
2143 }
2144 else {
2145 self.close();
2146 }
2147 }
2148 function selectDate(e) {
2149 e.preventDefault();
2150 e.stopPropagation();
2151 var isSelectable = function (day) {
2152 return day.classList &&
2153 day.classList.contains("flatpickr-day") &&
2154 !day.classList.contains("flatpickr-disabled") &&
2155 !day.classList.contains("notAllowed");
2156 };
2157 var t = findParent(getEventTarget(e), isSelectable);
2158 if (t === undefined)
2159 return;
2160 var target = t;
2161 var selectedDate = (self.latestSelectedDateObj = new Date(target.dateObj.getTime()));
2162 var shouldChangeMonth = (selectedDate.getMonth() < self.currentMonth ||
2163 selectedDate.getMonth() >
2164 self.currentMonth + self.config.showMonths - 1) &&
2165 self.config.mode !== "range";
2166 self.selectedDateElem = target;
2167 if (self.config.mode === "single")
2168 self.selectedDates = [selectedDate];
2169 else if (self.config.mode === "multiple") {
2170 var selectedIndex = isDateSelected(selectedDate);
2171 if (selectedIndex)
2172 self.selectedDates.splice(parseInt(selectedIndex), 1);
2173 else
2174 self.selectedDates.push(selectedDate);
2175 }
2176 else if (self.config.mode === "range") {
2177 if (self.selectedDates.length === 2) {
2178 self.clear(false, false);
2179 }
2180 self.latestSelectedDateObj = selectedDate;
2181 self.selectedDates.push(selectedDate);
2182 // unless selecting same date twice, sort ascendingly
2183 if (compareDates(selectedDate, self.selectedDates[0], true) !== 0)
2184 self.selectedDates.sort(function (a, b) { return a.getTime() - b.getTime(); });
2185 }
2186 setHoursFromInputs();
2187 if (shouldChangeMonth) {
2188 var isNewYear = self.currentYear !== selectedDate.getFullYear();
2189 self.currentYear = selectedDate.getFullYear();
2190 self.currentMonth = selectedDate.getMonth();
2191 if (isNewYear) {
2192 triggerEvent("onYearChange");
2193 buildMonthSwitch();
2194 }
2195 triggerEvent("onMonthChange");
2196 }
2197 updateNavigationCurrentMonth();
2198 buildDays();
2199 updateValue();
2200 // maintain focus
2201 if (!shouldChangeMonth &&
2202 self.config.mode !== "range" &&
2203 self.config.showMonths === 1)
2204 focusOnDayElem(target);
2205 else if (self.selectedDateElem !== undefined &&
2206 self.hourElement === undefined) {
2207 self.selectedDateElem && self.selectedDateElem.focus();
2208 }
2209 if (self.hourElement !== undefined)
2210 self.hourElement !== undefined && self.hourElement.focus();
2211 if (self.config.closeOnSelect) {
2212 var single = self.config.mode === "single" && !self.config.enableTime;
2213 var range = self.config.mode === "range" &&
2214 self.selectedDates.length === 2 &&
2215 !self.config.enableTime;
2216 if (single || range) {
2217 focusAndClose();
2218 }
2219 }
2220 triggerChange();
2221 }
2222 var CALLBACKS = {
2223 locale: [setupLocale, updateWeekdays],
2224 showMonths: [buildMonths, setCalendarWidth, buildWeekdays],
2225 minDate: [jumpToDate],
2226 maxDate: [jumpToDate],
2227 clickOpens: [
2228 function () {
2229 if (self.config.clickOpens === true) {
2230 bind(self._input, "focus", self.open);
2231 bind(self._input, "click", self.open);
2232 }
2233 else {
2234 self._input.removeEventListener("focus", self.open);
2235 self._input.removeEventListener("click", self.open);
2236 }
2237 },
2238 ],
2239 };
2240 function set(option, value) {
2241 if (option !== null && typeof option === "object") {
2242 Object.assign(self.config, option);
2243 for (var key in option) {
2244 if (CALLBACKS[key] !== undefined)
2245 CALLBACKS[key].forEach(function (x) { return x(); });
2246 }
2247 }
2248 else {
2249 self.config[option] = value;
2250 if (CALLBACKS[option] !== undefined)
2251 CALLBACKS[option].forEach(function (x) { return x(); });
2252 else if (HOOKS.indexOf(option) > -1)
2253 self.config[option] = arrayify(value);
2254 }
2255 self.redraw();
2256 updateValue(true);
2257 }
2258 function setSelectedDate(inputDate, format) {
2259 var dates = [];
2260 if (inputDate instanceof Array)
2261 dates = inputDate.map(function (d) { return self.parseDate(d, format); });
2262 else if (inputDate instanceof Date || typeof inputDate === "number")
2263 dates = [self.parseDate(inputDate, format)];
2264 else if (typeof inputDate === "string") {
2265 switch (self.config.mode) {
2266 case "single":
2267 case "time":
2268 dates = [self.parseDate(inputDate, format)];
2269 break;
2270 case "multiple":
2271 dates = inputDate
2272 .split(self.config.conjunction)
2273 .map(function (date) { return self.parseDate(date, format); });
2274 break;
2275 case "range":
2276 dates = inputDate
2277 .split(self.l10n.rangeSeparator)
2278 .map(function (date) { return self.parseDate(date, format); });
2279 break;
2280 }
2281 }
2282 else
2283 self.config.errorHandler(new Error("Invalid date supplied: " + JSON.stringify(inputDate)));
2284 self.selectedDates = (self.config.allowInvalidPreload
2285 ? dates
2286 : dates.filter(function (d) { return d instanceof Date && isEnabled(d, false); }));
2287 if (self.config.mode === "range")
2288 self.selectedDates.sort(function (a, b) { return a.getTime() - b.getTime(); });
2289 }
2290 function setDate(date, triggerChange, format) {
2291 if (triggerChange === void 0) { triggerChange = false; }
2292 if (format === void 0) { format = self.config.dateFormat; }
2293 if ((date !== 0 && !date) || (date instanceof Array && date.length === 0))
2294 return self.clear(triggerChange);
2295 setSelectedDate(date, format);
2296 self.latestSelectedDateObj =
2297 self.selectedDates[self.selectedDates.length - 1];
2298 self.redraw();
2299 jumpToDate(undefined, triggerChange);
2300 setHoursFromDate();
2301 if (self.selectedDates.length === 0) {
2302 self.clear(false);
2303 }
2304 updateValue(triggerChange);
2305 if (triggerChange)
2306 triggerEvent("onChange");
2307 }
2308 function parseDateRules(arr) {
2309 return arr
2310 .slice()
2311 .map(function (rule) {
2312 if (typeof rule === "string" ||
2313 typeof rule === "number" ||
2314 rule instanceof Date) {
2315 return self.parseDate(rule, undefined, true);
2316 }
2317 else if (rule &&
2318 typeof rule === "object" &&
2319 rule.from &&
2320 rule.to)
2321 return {
2322 from: self.parseDate(rule.from, undefined),
2323 to: self.parseDate(rule.to, undefined),
2324 };
2325 return rule;
2326 })
2327 .filter(function (x) { return x; }); // remove falsy values
2328 }
2329 function setupDates() {
2330 self.selectedDates = [];
2331 self.now = self.parseDate(self.config.now) || new Date();
2332 // Workaround IE11 setting placeholder as the input's value
2333 var preloadedDate = self.config.defaultDate ||
2334 ((self.input.nodeName === "INPUT" ||
2335 self.input.nodeName === "TEXTAREA") &&
2336 self.input.placeholder &&
2337 self.input.value === self.input.placeholder
2338 ? null
2339 : self.input.value);
2340 if (preloadedDate)
2341 setSelectedDate(preloadedDate, self.config.dateFormat);
2342 self._initialDate =
2343 self.selectedDates.length > 0
2344 ? self.selectedDates[0]
2345 : self.config.minDate &&
2346 self.config.minDate.getTime() > self.now.getTime()
2347 ? self.config.minDate
2348 : self.config.maxDate &&
2349 self.config.maxDate.getTime() < self.now.getTime()
2350 ? self.config.maxDate
2351 : self.now;
2352 self.currentYear = self._initialDate.getFullYear();
2353 self.currentMonth = self._initialDate.getMonth();
2354 if (self.selectedDates.length > 0)
2355 self.latestSelectedDateObj = self.selectedDates[0];
2356 if (self.config.minTime !== undefined)
2357 self.config.minTime = self.parseDate(self.config.minTime, "H:i");
2358 if (self.config.maxTime !== undefined)
2359 self.config.maxTime = self.parseDate(self.config.maxTime, "H:i");
2360 self.minDateHasTime =
2361 !!self.config.minDate &&
2362 (self.config.minDate.getHours() > 0 ||
2363 self.config.minDate.getMinutes() > 0 ||
2364 self.config.minDate.getSeconds() > 0);
2365 self.maxDateHasTime =
2366 !!self.config.maxDate &&
2367 (self.config.maxDate.getHours() > 0 ||
2368 self.config.maxDate.getMinutes() > 0 ||
2369 self.config.maxDate.getSeconds() > 0);
2370 }
2371 function setupInputs() {
2372 self.input = getInputElem();
2373 /* istanbul ignore next */
2374 if (!self.input) {
2375 self.config.errorHandler(new Error("Invalid input element specified"));
2376 return;
2377 }
2378 // hack: store previous type to restore it after destroy()
2379 self.input._type = self.input.type;
2380 self.input.type = "text";
2381 self.input.classList.add("flatpickr-input");
2382 self._input = self.input;
2383 if (self.config.altInput) {
2384 // replicate self.element
2385 self.altInput = createElement(self.input.nodeName, self.config.altInputClass);
2386 self._input = self.altInput;
2387 self.altInput.placeholder = self.input.placeholder;
2388 self.altInput.disabled = self.input.disabled;
2389 self.altInput.required = self.input.required;
2390 self.altInput.tabIndex = self.input.tabIndex;
2391 self.altInput.type = "text";
2392 self.input.setAttribute("type", "hidden");
2393 if (!self.config.static && self.input.parentNode)
2394 self.input.parentNode.insertBefore(self.altInput, self.input.nextSibling);
2395 }
2396 if (!self.config.allowInput)
2397 self._input.setAttribute("readonly", "readonly");
2398 self._positionElement = self.config.positionElement || self._input;
2399 }
2400 function setupMobile() {
2401 var inputType = self.config.enableTime
2402 ? self.config.noCalendar
2403 ? "time"
2404 : "datetime-local"
2405 : "date";
2406 self.mobileInput = createElement("input", self.input.className + " flatpickr-mobile");
2407 self.mobileInput.tabIndex = 1;
2408 self.mobileInput.type = inputType;
2409 self.mobileInput.disabled = self.input.disabled;
2410 self.mobileInput.required = self.input.required;
2411 self.mobileInput.placeholder = self.input.placeholder;
2412 self.mobileFormatStr =
2413 inputType === "datetime-local"
2414 ? "Y-m-d\\TH:i:S"
2415 : inputType === "date"
2416 ? "Y-m-d"
2417 : "H:i:S";
2418 if (self.selectedDates.length > 0) {
2419 self.mobileInput.defaultValue = self.mobileInput.value = self.formatDate(self.selectedDates[0], self.mobileFormatStr);
2420 }
2421 if (self.config.minDate)
2422 self.mobileInput.min = self.formatDate(self.config.minDate, "Y-m-d");
2423 if (self.config.maxDate)
2424 self.mobileInput.max = self.formatDate(self.config.maxDate, "Y-m-d");
2425 if (self.input.getAttribute("step"))
2426 self.mobileInput.step = String(self.input.getAttribute("step"));
2427 self.input.type = "hidden";
2428 if (self.altInput !== undefined)
2429 self.altInput.type = "hidden";
2430 try {
2431 if (self.input.parentNode)
2432 self.input.parentNode.insertBefore(self.mobileInput, self.input.nextSibling);
2433 }
2434 catch (_a) { }
2435 bind(self.mobileInput, "change", function (e) {
2436 self.setDate(getEventTarget(e).value, false, self.mobileFormatStr);
2437 triggerEvent("onChange");
2438 triggerEvent("onClose");
2439 });
2440 }
2441 function toggle(e) {
2442 if (self.isOpen === true)
2443 return self.close();
2444 self.open(e);
2445 }
2446 function triggerEvent(event, data) {
2447 // If the instance has been destroyed already, all hooks have been removed
2448 if (self.config === undefined)
2449 return;
2450 var hooks = self.config[event];
2451 if (hooks !== undefined && hooks.length > 0) {
2452 for (var i = 0; hooks[i] && i < hooks.length; i++)
2453 hooks[i](self.selectedDates, self.input.value, self, data);
2454 }
2455 if (event === "onChange") {
2456 self.input.dispatchEvent(createEvent("change"));
2457 // many front-end frameworks bind to the input event
2458 self.input.dispatchEvent(createEvent("input"));
2459 }
2460 }
2461 function createEvent(name) {
2462 var e = document.createEvent("Event");
2463 e.initEvent(name, true, true);
2464 return e;
2465 }
2466 function isDateSelected(date) {
2467 for (var i = 0; i < self.selectedDates.length; i++) {
2468 if (compareDates(self.selectedDates[i], date) === 0)
2469 return "" + i;
2470 }
2471 return false;
2472 }
2473 function isDateInRange(date) {
2474 if (self.config.mode !== "range" || self.selectedDates.length < 2)
2475 return false;
2476 return (compareDates(date, self.selectedDates[0]) >= 0 &&
2477 compareDates(date, self.selectedDates[1]) <= 0);
2478 }
2479 function updateNavigationCurrentMonth() {
2480 if (self.config.noCalendar || self.isMobile || !self.monthNav)
2481 return;
2482 self.yearElements.forEach(function (yearElement, i) {
2483 var d = new Date(self.currentYear, self.currentMonth, 1);
2484 d.setMonth(self.currentMonth + i);
2485 if (self.config.showMonths > 1 ||
2486 self.config.monthSelectorType === "static") {
2487 self.monthElements[i].textContent =
2488 monthToStr(d.getMonth(), self.config.shorthandCurrentMonth, self.l10n) + " ";
2489 }
2490 else {
2491 self.monthsDropdownContainer.value = d.getMonth().toString();
2492 }
2493 yearElement.value = d.getFullYear().toString();
2494 });
2495 self._hidePrevMonthArrow =
2496 self.config.minDate !== undefined &&
2497 (self.currentYear === self.config.minDate.getFullYear()
2498 ? self.currentMonth <= self.config.minDate.getMonth()
2499 : self.currentYear < self.config.minDate.getFullYear());
2500 self._hideNextMonthArrow =
2501 self.config.maxDate !== undefined &&
2502 (self.currentYear === self.config.maxDate.getFullYear()
2503 ? self.currentMonth + 1 > self.config.maxDate.getMonth()
2504 : self.currentYear > self.config.maxDate.getFullYear());
2505 }
2506 function getDateStr(format) {
2507 return self.selectedDates
2508 .map(function (dObj) { return self.formatDate(dObj, format); })
2509 .filter(function (d, i, arr) {
2510 return self.config.mode !== "range" ||
2511 self.config.enableTime ||
2512 arr.indexOf(d) === i;
2513 })
2514 .join(self.config.mode !== "range"
2515 ? self.config.conjunction
2516 : self.l10n.rangeSeparator);
2517 }
2518 /**
2519 * Updates the values of inputs associated with the calendar
2520 */
2521 function updateValue(triggerChange) {
2522 if (triggerChange === void 0) { triggerChange = true; }
2523 if (self.mobileInput !== undefined && self.mobileFormatStr) {
2524 self.mobileInput.value =
2525 self.latestSelectedDateObj !== undefined
2526 ? self.formatDate(self.latestSelectedDateObj, self.mobileFormatStr)
2527 : "";
2528 }
2529 self.input.value = getDateStr(self.config.dateFormat);
2530 if (self.altInput !== undefined) {
2531 self.altInput.value = getDateStr(self.config.altFormat);
2532 }
2533 if (triggerChange !== false)
2534 triggerEvent("onValueUpdate");
2535 }
2536 function onMonthNavClick(e) {
2537 var eventTarget = getEventTarget(e);
2538 var isPrevMonth = self.prevMonthNav.contains(eventTarget);
2539 var isNextMonth = self.nextMonthNav.contains(eventTarget);
2540 if (isPrevMonth || isNextMonth) {
2541 changeMonth(isPrevMonth ? -1 : 1);
2542 }
2543 else if (self.yearElements.indexOf(eventTarget) >= 0) {
2544 eventTarget.select();
2545 }
2546 else if (eventTarget.classList.contains("arrowUp")) {
2547 self.changeYear(self.currentYear + 1);
2548 }
2549 else if (eventTarget.classList.contains("arrowDown")) {
2550 self.changeYear(self.currentYear - 1);
2551 }
2552 }
2553 function timeWrapper(e) {
2554 e.preventDefault();
2555 var isKeyDown = e.type === "keydown", eventTarget = getEventTarget(e), input = eventTarget;
2556 if (self.amPM !== undefined && eventTarget === self.amPM) {
2557 self.amPM.textContent =
2558 self.l10n.amPM[int(self.amPM.textContent === self.l10n.amPM[0])];
2559 }
2560 var min = parseFloat(input.getAttribute("min")), max = parseFloat(input.getAttribute("max")), step = parseFloat(input.getAttribute("step")), curValue = parseInt(input.value, 10), delta = e.delta ||
2561 (isKeyDown ? (e.which === 38 ? 1 : -1) : 0);
2562 var newValue = curValue + step * delta;
2563 if (typeof input.value !== "undefined" && input.value.length === 2) {
2564 var isHourElem = input === self.hourElement, isMinuteElem = input === self.minuteElement;
2565 if (newValue < min) {
2566 newValue =
2567 max +
2568 newValue +
2569 int(!isHourElem) +
2570 (int(isHourElem) && int(!self.amPM));
2571 if (isMinuteElem)
2572 incrementNumInput(undefined, -1, self.hourElement);
2573 }
2574 else if (newValue > max) {
2575 newValue =
2576 input === self.hourElement ? newValue - max - int(!self.amPM) : min;
2577 if (isMinuteElem)
2578 incrementNumInput(undefined, 1, self.hourElement);
2579 }
2580 if (self.amPM &&
2581 isHourElem &&
2582 (step === 1
2583 ? newValue + curValue === 23
2584 : Math.abs(newValue - curValue) > step)) {
2585 self.amPM.textContent =
2586 self.l10n.amPM[int(self.amPM.textContent === self.l10n.amPM[0])];
2587 }
2588 input.value = pad(newValue);
2589 }
2590 }
2591 init();
2592 return self;
2593 }
2594 /* istanbul ignore next */
2595 function _flatpickr(nodeList, config) {
2596 // static list
2597 var nodes = Array.prototype.slice
2598 .call(nodeList)
2599 .filter(function (x) { return x instanceof HTMLElement; });
2600 var instances = [];
2601 for (var i = 0; i < nodes.length; i++) {
2602 var node = nodes[i];
2603 try {
2604 if (node.getAttribute("data-fp-omit") !== null)
2605 continue;
2606 if (node._flatpickr !== undefined) {
2607 node._flatpickr.destroy();
2608 node._flatpickr = undefined;
2609 }
2610 node._flatpickr = FlatpickrInstance(node, config || {});
2611 instances.push(node._flatpickr);
2612 }
2613 catch (e) {
2614 console.error(e);
2615 }
2616 }
2617 return instances.length === 1 ? instances[0] : instances;
2618 }
2619 /* istanbul ignore next */
2620 if (typeof HTMLElement !== "undefined" &&
2621 typeof HTMLCollection !== "undefined" &&
2622 typeof NodeList !== "undefined") {
2623 // browser env
2624 HTMLCollection.prototype.flatpickr = NodeList.prototype.flatpickr = function (config) {
2625 return _flatpickr(this, config);
2626 };
2627 HTMLElement.prototype.flatpickr = function (config) {
2628 return _flatpickr([this], config);
2629 };
2630 }
2631 /* istanbul ignore next */
2632 var flatpickr = function (selector, config) {
2633 if (typeof selector === "string") {
2634 return _flatpickr(window.document.querySelectorAll(selector), config);
2635 }
2636 else if (selector instanceof Node) {
2637 return _flatpickr([selector], config);
2638 }
2639 else {
2640 return _flatpickr(selector, config);
2641 }
2642 };
2643 /* istanbul ignore next */
2644 flatpickr.defaultConfig = {};
2645 flatpickr.l10ns = {
2646 en: __assign({}, english),
2647 default: __assign({}, english),
2648 };
2649 flatpickr.localize = function (l10n) {
2650 flatpickr.l10ns.default = __assign(__assign({}, flatpickr.l10ns.default), l10n);
2651 };
2652 flatpickr.setDefaults = function (config) {
2653 flatpickr.defaultConfig = __assign(__assign({}, flatpickr.defaultConfig), config);
2654 };
2655 flatpickr.parseDate = createDateParser({});
2656 flatpickr.formatDate = createDateFormatter({});
2657 flatpickr.compareDates = compareDates;
2658 /* istanbul ignore next */
2659 if (typeof jQuery !== "undefined" && typeof jQuery.fn !== "undefined") {
2660 jQuery.fn.flatpickr = function (config) {
2661 return _flatpickr(this, config);
2662 };
2663 }
2664 Date.prototype.fp_incr = function (days) {
2665 return new Date(this.getFullYear(), this.getMonth(), this.getDate() + (typeof days === "string" ? parseInt(days, 10) : days));
2666 };
2667 if (typeof window !== "undefined") {
2668 window.flatpickr = flatpickr;
2669 }
2670
2671 return flatpickr;
2672
2673 })));
2674 ;/**
2675 *
2676 * jQuery Chosen AJAX Autocomplete Library
2677 *
2678 * https://github.com/meltingice/ajax-chosen
2679 * https://github.com/michaelperrin/ajax-chosen
2680 *
2681 * MIT License
2682 *
2683 * Customized by Codestar
2684 *
2685 */
2686 (function($) {
2687
2688 function CSFAjaxChosen(element, options) {
2689 this.element = $(element);
2690 this.options = options;
2691 this.init();
2692 };
2693
2694 CSFAjaxChosen.prototype.init = function() {
2695 this.element.chosen(this.options);
2696 this.container = this.element.next('.chosen-container');
2697 this.search_field = this.container.find('.chosen-search-input');
2698 this.is_multiple = this.container.hasClass('chosen-container-multi');
2699 this.is_typing = false;
2700 this.chosenXhr = null;
2701 this.events();
2702 };
2703
2704 CSFAjaxChosen.prototype.events = function() {
2705
2706 var _this = this;
2707
2708 this.search_field.on('compositionstart', function() {
2709 _this.is_typing = true;
2710 });
2711
2712 this.search_field.on('compositionend', function() {
2713 _this.is_typing = false;
2714 _this.update_list();
2715 });
2716
2717 this.search_field.on('keyup', function() {
2718 _this.update_list();
2719 });
2720
2721 this.search_field.on('focus', function() {
2722 _this.search_field_focused();
2723 });
2724
2725 };
2726
2727 CSFAjaxChosen.prototype.search_field_focused = function() {
2728 this.search_welcome_message();
2729 if ( this.options.min_length === 0 && this.search_field.val().length === 0 ) {
2730 this.update_list();
2731 }
2732 };
2733
2734 CSFAjaxChosen.prototype.search_welcome_message = function() {
2735
2736 var value = $.trim(this.search_field.val());
2737 var results = this.container.find('.chosen-results');
2738
2739 if ( results.children().length === 0 && value.length === 0 ) {
2740 results.html('<li class="no-results">' + this.options.typing_text.replace('%s', this.options.min_length - value.length) + '</li>');
2741 }
2742
2743 };
2744
2745 CSFAjaxChosen.prototype.update_list = function() {
2746
2747 var _this = this;
2748
2749 this.search_welcome_message();
2750
2751 if ( this.is_typing ) { return; }
2752
2753 var value = $.trim(this.search_field.val());
2754 var message = ( value.length < this.options.min_length ) ? this.options.typing_text.replace('%s', this.options.min_length - value.length) : this.options.searching_text;
2755
2756 this.container.find('.no-results').text(message);
2757
2758 if ( value === this.search_field.data('prevVal') ) { return; }
2759
2760 this.search_field.data('prevVal', value);
2761
2762 if (this.timer) {
2763 clearTimeout(this.timer);
2764 }
2765
2766 if ( value.length < this.options.min_length ) { return; }
2767
2768 this.timer = setTimeout( function() {
2769
2770 if ( _this.chosenXhr ) {
2771 _this.chosenXhr.abort();
2772 }
2773
2774 _this.options.data['term'] = value;
2775
2776 _this.chosenXhr = window.wp.ajax.post('eshb-chosen', _this.options.data).done( function( response ) {
2777 _this.show_results( response );
2778 console.log(response);
2779
2780 }).fail( function( response ) {
2781 _this.container.find('.no-results').text(response.error);
2782 });
2783
2784 }, this.options.type_delay );
2785
2786 };
2787
2788 CSFAjaxChosen.prototype.show_results = function( items ) {
2789
2790 var _this = this;
2791
2792 if ( this.is_typing || items === null ) { return; }
2793
2794 if ( items.length === 0 ) {
2795 this.element.data().chosen.no_results_clear();
2796 this.element.data().chosen.no_results(this.search_field.val());
2797 return;
2798 }
2799
2800 var selected_values = [];
2801
2802 this.element.find('option').each(function() {
2803 if ( $(this).is(':selected') ) {
2804 selected_values.push( $(this).val() + "-" + $(this).text() );
2805 } else {
2806 if( $(this).attr('value').length ) {
2807 $(this).remove();
2808 }
2809 }
2810 });
2811
2812
2813
2814
2815 $.each(items, function(i, item) {
2816 if ( $.inArray( item.value + "-" + item.text, selected_values ) === -1 ) {
2817 $('<option />').attr('value', item.value).html(item.text).appendTo(_this.element);
2818 }
2819 });
2820
2821 var value_before_trigger = this.search_field.val();
2822 var width_before_trigger = this.search_field.innerWidth();
2823
2824 this.element.trigger('chosen:updated');
2825
2826 if( this.is_multiple ) {
2827
2828 var $hidden_select = this.element.parent().find('.csf-hide-select');
2829 var $hidden_value = $hidden_select.val() || [];
2830
2831 this.element.CSFChosenOrder($hidden_value, true);
2832 this.search_field.css('width', width_before_trigger);
2833
2834 }
2835
2836 this.search_field.val(value_before_trigger);
2837
2838 if ( this.chosenXhr.done !== null ) {
2839 this.chosenXhr.done(items);
2840 }
2841
2842 };
2843
2844 $.fn.CSFAjaxChosen = function(chosenOptions) {
2845 return this.each(function() {
2846 new CSFAjaxChosen(this, chosenOptions);
2847 });
2848 };
2849
2850 })(jQuery);
2851 ;// Chosen Order v1.2.1
2852 // This plugin allows you to handle the order of the selection for Chosen multiple <select> dropdowns
2853 // Full source at https://github.com/tristanjahier/chosen-order
2854 // Copyright (c) 2013 - Tristan Jahier, http://tristan-jahier.fr
2855 (function() {
2856 var $, CSFAbstractChosenOrder, _ref,
2857 __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
2858 __hasProp = {}.hasOwnProperty,
2859 __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
2860
2861 CSFAbstractChosenOrder = (function() {
2862
2863 function CSFAbstractChosenOrder() {}
2864
2865 CSFAbstractChosenOrder.insertAt = function(node, index, parentNode) {
2866 return parentNode.insertBefore(node, parentNode.children[index].nextSibling);
2867 };
2868
2869 CSFAbstractChosenOrder.getFlattenedOptionsAndGroups = function(select) {
2870 var flattened_options, opt, options, sub_opt, sub_options, _i, _j, _len, _len1;
2871 options = Array.prototype.filter.call(select.childNodes, function(o) {
2872 var _ref;
2873 return (_ref = o.nodeName.toUpperCase()) === 'OPTION' || _ref === 'OPTGROUP';
2874 });
2875 flattened_options = [];
2876 for (_i = 0, _len = options.length; _i < _len; _i++) {
2877 opt = options[_i];
2878 flattened_options.push(opt);
2879 if (opt.nodeName.toUpperCase() === 'OPTGROUP') {
2880 sub_options = Array.prototype.filter.call(opt.childNodes, function(o) {
2881 return o.nodeName.toUpperCase() === 'OPTION';
2882 });
2883 for (_j = 0, _len1 = sub_options.length; _j < _len1; _j++) {
2884 sub_opt = sub_options[_j];
2885 flattened_options.push(sub_opt);
2886 }
2887 }
2888 }
2889 return flattened_options;
2890 };
2891
2892 CSFAbstractChosenOrder.isValidMultipleSelectElement = function(element) {
2893 return element !== null && typeof element !== "undefined" && element.nodeName === "SELECT" && element.multiple;
2894 };
2895
2896 CSFAbstractChosenOrder.getChosenUIContainer = function(select) {
2897 if (select.id !== "") {
2898 return document.getElementById(select.id.replace(/-/g, "_") + "_chosen");
2899 } else {
2900 return this.searchChosenUIContainer(select);
2901 }
2902 };
2903
2904 CSFAbstractChosenOrder.isChosenified = function(select) {
2905 return this.getChosenUIContainer(select) != null;
2906 };
2907
2908 CSFAbstractChosenOrder.forceSelection = function(select, selection) {
2909 var i, opt, options, _ref;
2910 options = this.getFlattenedOptionsAndGroups(select);
2911 i = 0;
2912 while (i < options.length) {
2913 opt = options[i];
2914 if (_ref = opt.getAttribute("value"), __indexOf.call(selection, _ref) >= 0) {
2915 opt.selected = true;
2916 opt.setAttribute("selected", "");
2917 } else {
2918 opt.selected = false;
2919 opt.removeAttribute("selected");
2920 }
2921 i++;
2922 }
2923 return this.triggerEvent(select, "chosen:updated");
2924 };
2925
2926 CSFAbstractChosenOrder.CSFChosenOrder = function(select, order, force) {
2927 var chosen_choices, chosen_options, chosen_ui, i, j, opt, opt_val, option, options, rel, relAttributeName, _i, _j, _len, _len1, _results;
2928 if (this.getDOMElement != null) {
2929 select = this.getDOMElement(select);
2930 }
2931 if (!this.isValidMultipleSelectElement(select)) {
2932 return;
2933 }
2934 chosen_ui = this.getChosenUIContainer(select);
2935 if (chosen_ui == null) {
2936 return;
2937 }
2938 if (order instanceof Array) {
2939 order = order.map(Function.prototype.call, String.prototype.trim);
2940 options = this.getFlattenedOptionsAndGroups(select);
2941 if ((force != null) && force === true) {
2942 this.forceSelection(select, order);
2943 }
2944 _results = [];
2945 for (i = _i = 0, _len = order.length; _i < _len; i = ++_i) {
2946 opt_val = order[i];
2947 rel = null;
2948 for (j = _j = 0, _len1 = options.length; _j < _len1; j = ++_j) {
2949 opt = options[j];
2950 if (opt.value === opt_val) {
2951 rel = j;
2952 }
2953 }
2954 chosen_options = chosen_ui.querySelectorAll('.search-choice');
2955 relAttributeName = this.relAttributeName;
2956 option = Array.prototype.filter.call(chosen_options, function(o) {
2957 return o.querySelector("a.search-choice-close[" + relAttributeName + "=\"" + rel + "\"]") != null;
2958 })[0];
2959 if (option == null) {
2960 continue;
2961 }
2962 chosen_choices = chosen_ui.querySelector("ul.chosen-choices");
2963 _results.push(this.insertAt(option, i, chosen_ui.querySelector('ul.chosen-choices')));
2964 }
2965 return _results;
2966 } else {
2967 return;
2968 }
2969 };
2970
2971 return CSFAbstractChosenOrder;
2972
2973 })();
2974
2975 $ = jQuery;
2976
2977 $.fn.extend({
2978 CSFChosenOrder: function(order, force) {
2979 return _CSFChosenOrder.CSFChosenOrder(this, order, force);
2980 }
2981 });
2982
2983 this._CSFChosenOrder = (function(_super) {
2984 __extends(_CSFChosenOrder, _super);
2985
2986 function _CSFChosenOrder() {
2987 _ref = _CSFChosenOrder.__super__.constructor.apply(this, arguments);
2988 return _ref;
2989 }
2990
2991 _CSFChosenOrder.relAttributeName = 'data-option-array-index';
2992
2993 _CSFChosenOrder.isjQueryObject = function(obj) {
2994 return (typeof jQuery !== "undefined" && jQuery !== null) && obj instanceof jQuery;
2995 };
2996
2997 _CSFChosenOrder.getDOMElement = function(element) {
2998 if (this.isjQueryObject(element)) {
2999 return element.get(0);
3000 } else {
3001 return element;
3002 }
3003 };
3004
3005 _CSFChosenOrder.searchChosenUIContainer = function(element) {
3006 if ($(element).data("chosen") != null) {
3007 return $(element).data("chosen").container[0];
3008 } else {
3009 return $(element).next(".chosen-container.chosen-container-multi").get(0);
3010 }
3011 };
3012
3013 _CSFChosenOrder.triggerEvent = function(target, event_name) {
3014 return $(target).trigger(event_name);
3015 };
3016
3017 return _CSFChosenOrder;
3018
3019 })(CSFAbstractChosenOrder);
3020
3021 }).call(this);
3022 ;(function() {
3023 var $, AbstractChosen, Chosen, SelectParser,
3024 bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
3025 extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
3026 hasProp = {}.hasOwnProperty;
3027
3028 SelectParser = (function() {
3029 function SelectParser() {
3030 this.options_index = 0;
3031 this.parsed = [];
3032 }
3033
3034 SelectParser.prototype.add_node = function(child) {
3035 if (child.nodeName.toUpperCase() === "OPTGROUP") {
3036 return this.add_group(child);
3037 } else {
3038 return this.add_option(child);
3039 }
3040 };
3041
3042 SelectParser.prototype.add_group = function(group) {
3043 var group_position, i, len, option, ref, results1;
3044 group_position = this.parsed.length;
3045 this.parsed.push({
3046 array_index: group_position,
3047 group: true,
3048 label: group.label,
3049 title: group.title ? group.title : void 0,
3050 children: 0,
3051 disabled: group.disabled,
3052 classes: group.className
3053 });
3054 ref = group.childNodes;
3055 results1 = [];
3056 for (i = 0, len = ref.length; i < len; i++) {
3057 option = ref[i];
3058 results1.push(this.add_option(option, group_position, group.disabled));
3059 }
3060 return results1;
3061 };
3062
3063 SelectParser.prototype.add_option = function(option, group_position, group_disabled) {
3064 if (option.nodeName.toUpperCase() === "OPTION") {
3065 if (option.text !== "") {
3066 if (group_position != null) {
3067 this.parsed[group_position].children += 1;
3068 }
3069 this.parsed.push({
3070 array_index: this.parsed.length,
3071 options_index: this.options_index,
3072 value: option.value,
3073 text: option.text,
3074 html: option.innerHTML,
3075 title: option.title ? option.title : void 0,
3076 selected: option.selected,
3077 disabled: group_disabled === true ? group_disabled : option.disabled,
3078 group_array_index: group_position,
3079 group_label: group_position != null ? this.parsed[group_position].label : null,
3080 classes: option.className,
3081 style: option.style.cssText
3082 });
3083 } else {
3084 this.parsed.push({
3085 array_index: this.parsed.length,
3086 options_index: this.options_index,
3087 empty: true
3088 });
3089 }
3090 return this.options_index += 1;
3091 }
3092 };
3093
3094 return SelectParser;
3095
3096 })();
3097
3098 SelectParser.select_to_array = function(select) {
3099 var child, i, len, parser, ref;
3100 parser = new SelectParser();
3101 ref = select.childNodes;
3102 for (i = 0, len = ref.length; i < len; i++) {
3103 child = ref[i];
3104 parser.add_node(child);
3105 }
3106 return parser.parsed;
3107 };
3108
3109 AbstractChosen = (function() {
3110 function AbstractChosen(form_field, options1) {
3111 this.form_field = form_field;
3112 this.options = options1 != null ? options1 : {};
3113 this.label_click_handler = bind(this.label_click_handler, this);
3114 if (!AbstractChosen.browser_is_supported()) {
3115 return;
3116 }
3117 this.is_multiple = this.form_field.multiple;
3118 this.set_default_text();
3119 this.set_default_values();
3120 this.setup();
3121 this.set_up_html();
3122 this.register_observers();
3123 this.on_ready();
3124 }
3125
3126 AbstractChosen.prototype.set_default_values = function() {
3127 this.click_test_action = (function(_this) {
3128 return function(evt) {
3129 return _this.test_active_click(evt);
3130 };
3131 })(this);
3132 this.activate_action = (function(_this) {
3133 return function(evt) {
3134 return _this.activate_field(evt);
3135 };
3136 })(this);
3137 this.active_field = false;
3138 this.mouse_on_container = false;
3139 this.results_showing = false;
3140 this.result_highlighted = null;
3141 this.is_rtl = this.options.rtl || /\bchosen-rtl\b/.test(this.form_field.className);
3142 this.allow_single_deselect = (this.options.allow_single_deselect != null) && (this.form_field.options[0] != null) && this.form_field.options[0].text === "" ? this.options.allow_single_deselect : false;
3143 this.disable_search_threshold = this.options.disable_search_threshold || 0;
3144 this.disable_search = this.options.disable_search || false;
3145 this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true;
3146 this.group_search = this.options.group_search != null ? this.options.group_search : true;
3147 this.search_contains = this.options.search_contains || false;
3148 this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true;
3149 this.max_selected_options = this.options.max_selected_options || Infinity;
3150 this.inherit_select_classes = this.options.inherit_select_classes || false;
3151 this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true;
3152 this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true;
3153 this.include_group_label_in_selected = this.options.include_group_label_in_selected || false;
3154 this.max_shown_results = this.options.max_shown_results || Number.POSITIVE_INFINITY;
3155 this.case_sensitive_search = this.options.case_sensitive_search || false;
3156 return this.hide_results_on_select = this.options.hide_results_on_select != null ? this.options.hide_results_on_select : true;
3157 };
3158
3159 AbstractChosen.prototype.set_default_text = function() {
3160 if (this.form_field.getAttribute("data-placeholder")) {
3161 this.default_text = this.form_field.getAttribute("data-placeholder");
3162 } else if (this.is_multiple) {
3163 this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text;
3164 } else {
3165 this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text;
3166 }
3167 this.default_text = this.escape_html(this.default_text);
3168 return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text;
3169 };
3170
3171 AbstractChosen.prototype.choice_label = function(item) {
3172 if (this.include_group_label_in_selected && (item.group_label != null)) {
3173 return "<b class='group-name'>" + (this.escape_html(item.group_label)) + "</b>" + item.html;
3174 } else {
3175 return item.html;
3176 }
3177 };
3178
3179 AbstractChosen.prototype.mouse_enter = function() {
3180 return this.mouse_on_container = true;
3181 };
3182
3183 AbstractChosen.prototype.mouse_leave = function() {
3184 return this.mouse_on_container = false;
3185 };
3186
3187 AbstractChosen.prototype.input_focus = function(evt) {
3188 if (this.is_multiple) {
3189 if (!this.active_field) {
3190 return setTimeout(((function(_this) {
3191 return function() {
3192 return _this.container_mousedown();
3193 };
3194 })(this)), 50);
3195 }
3196 } else {
3197 if (!this.active_field) {
3198 return this.activate_field();
3199 }
3200 }
3201 };
3202
3203 AbstractChosen.prototype.input_blur = function(evt) {
3204 if (!this.mouse_on_container) {
3205 this.active_field = false;
3206 return setTimeout(((function(_this) {
3207 return function() {
3208 return _this.blur_test();
3209 };
3210 })(this)), 100);
3211 }
3212 };
3213
3214 AbstractChosen.prototype.label_click_handler = function(evt) {
3215 if (this.is_multiple) {
3216 return this.container_mousedown(evt);
3217 } else {
3218 return this.activate_field();
3219 }
3220 };
3221
3222 AbstractChosen.prototype.results_option_build = function(options) {
3223 var content, data, data_content, i, len, ref, shown_results;
3224 content = '';
3225 shown_results = 0;
3226 ref = this.results_data;
3227 for (i = 0, len = ref.length; i < len; i++) {
3228 data = ref[i];
3229 data_content = '';
3230 if (data.group) {
3231 data_content = this.result_add_group(data);
3232 } else {
3233 data_content = this.result_add_option(data);
3234 }
3235 if (data_content !== '') {
3236 shown_results++;
3237 content += data_content;
3238 }
3239 if (options != null ? options.first : void 0) {
3240 if (data.selected && this.is_multiple) {
3241 this.choice_build(data);
3242 } else if (data.selected && !this.is_multiple) {
3243 this.single_set_selected_text(this.choice_label(data));
3244 }
3245 }
3246 if (shown_results >= this.max_shown_results) {
3247 break;
3248 }
3249 }
3250 return content;
3251 };
3252
3253 AbstractChosen.prototype.result_add_option = function(option) {
3254 var classes, option_el;
3255 if (!option.search_match) {
3256 return '';
3257 }
3258 if (!this.include_option_in_results(option)) {
3259 return '';
3260 }
3261 classes = [];
3262 if (!option.disabled && !(option.selected && this.is_multiple)) {
3263 classes.push("active-result");
3264 }
3265 if (option.disabled && !(option.selected && this.is_multiple)) {
3266 classes.push("disabled-result");
3267 }
3268 if (option.selected) {
3269 classes.push("result-selected");
3270 }
3271 if (option.group_array_index != null) {
3272 classes.push("group-option");
3273 }
3274 if (option.classes !== "") {
3275 classes.push(option.classes);
3276 }
3277 option_el = document.createElement("li");
3278 option_el.className = classes.join(" ");
3279 if (option.style) {
3280 option_el.style.cssText = option.style;
3281 }
3282 option_el.setAttribute("data-option-array-index", option.array_index);
3283 option_el.innerHTML = option.highlighted_html || option.html;
3284 if (option.title) {
3285 option_el.title = option.title;
3286 }
3287 return this.outerHTML(option_el);
3288 };
3289
3290 AbstractChosen.prototype.result_add_group = function(group) {
3291 var classes, group_el;
3292 if (!(group.search_match || group.group_match)) {
3293 return '';
3294 }
3295 if (!(group.active_options > 0)) {
3296 return '';
3297 }
3298 classes = [];
3299 classes.push("group-result");
3300 if (group.classes) {
3301 classes.push(group.classes);
3302 }
3303 group_el = document.createElement("li");
3304 group_el.className = classes.join(" ");
3305 group_el.innerHTML = group.highlighted_html || this.escape_html(group.label);
3306 if (group.title) {
3307 group_el.title = group.title;
3308 }
3309 return this.outerHTML(group_el);
3310 };
3311
3312 AbstractChosen.prototype.results_update_field = function() {
3313 this.set_default_text();
3314 if (!this.is_multiple) {
3315 this.results_reset_cleanup();
3316 }
3317 this.result_clear_highlight();
3318 this.results_build();
3319 if (this.results_showing) {
3320 return this.winnow_results();
3321 }
3322 };
3323
3324 AbstractChosen.prototype.reset_single_select_options = function() {
3325 var i, len, ref, result, results1;
3326 ref = this.results_data;
3327 results1 = [];
3328 for (i = 0, len = ref.length; i < len; i++) {
3329 result = ref[i];
3330 if (result.selected) {
3331 results1.push(result.selected = false);
3332 } else {
3333 results1.push(void 0);
3334 }
3335 }
3336 return results1;
3337 };
3338
3339 AbstractChosen.prototype.results_toggle = function() {
3340 if (this.results_showing) {
3341 return this.results_hide();
3342 } else {
3343 return this.results_show();
3344 }
3345 };
3346
3347 AbstractChosen.prototype.results_search = function(evt) {
3348 if (this.results_showing) {
3349 return this.winnow_results();
3350 } else {
3351 return this.results_show();
3352 }
3353 };
3354
3355 AbstractChosen.prototype.winnow_results = function(options) {
3356 var escapedQuery, fix, i, len, option, prefix, query, ref, regex, results, results_group, search_match, startpos, suffix, text;
3357 this.no_results_clear();
3358 results = 0;
3359 query = this.get_search_text();
3360 escapedQuery = query.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
3361 regex = this.get_search_regex(escapedQuery);
3362 ref = this.results_data;
3363 for (i = 0, len = ref.length; i < len; i++) {
3364 option = ref[i];
3365 option.search_match = false;
3366 results_group = null;
3367 search_match = null;
3368 option.highlighted_html = '';
3369 if (this.include_option_in_results(option)) {
3370 if (option.group) {
3371 option.group_match = false;
3372 option.active_options = 0;
3373 }
3374 if ((option.group_array_index != null) && this.results_data[option.group_array_index]) {
3375 results_group = this.results_data[option.group_array_index];
3376 if (results_group.active_options === 0 && results_group.search_match) {
3377 results += 1;
3378 }
3379 results_group.active_options += 1;
3380 }
3381 text = option.group ? option.label : option.text;
3382 if (!(option.group && !this.group_search)) {
3383 search_match = this.search_string_match(text, regex);
3384 option.search_match = search_match != null;
3385 if (option.search_match && !option.group) {
3386 results += 1;
3387 }
3388 if (option.search_match) {
3389 if (query.length) {
3390 startpos = search_match.index;
3391 prefix = text.slice(0, startpos);
3392 fix = text.slice(startpos, startpos + query.length);
3393 suffix = text.slice(startpos + query.length);
3394 option.highlighted_html = (this.escape_html(prefix)) + "<em>" + (this.escape_html(fix)) + "</em>" + (this.escape_html(suffix));
3395 }
3396 if (results_group != null) {
3397 results_group.group_match = true;
3398 }
3399 } else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) {
3400 option.search_match = true;
3401 }
3402 }
3403 }
3404 }
3405 this.result_clear_highlight();
3406 if (results < 1 && query.length) {
3407 this.update_results_content("");
3408 return this.no_results(query);
3409 } else {
3410 this.update_results_content(this.results_option_build());
3411 if (!(options != null ? options.skip_highlight : void 0)) {
3412 return this.winnow_results_set_highlight();
3413 }
3414 }
3415 };
3416
3417 AbstractChosen.prototype.get_search_regex = function(escaped_search_string) {
3418 var regex_flag, regex_string;
3419 regex_string = this.search_contains ? escaped_search_string : "(^|\\s|\\b)" + escaped_search_string + "[^\\s]*";
3420 if (!(this.enable_split_word_search || this.search_contains)) {
3421 regex_string = "^" + regex_string;
3422 }
3423 regex_flag = this.case_sensitive_search ? "" : "i";
3424 return new RegExp(regex_string, regex_flag);
3425 };
3426
3427 AbstractChosen.prototype.search_string_match = function(search_string, regex) {
3428 var match;
3429 match = regex.exec(search_string);
3430 if (!this.search_contains && (match != null ? match[1] : void 0)) {
3431 match.index += 1;
3432 }
3433 return match;
3434 };
3435
3436 AbstractChosen.prototype.choices_count = function() {
3437 var i, len, option, ref;
3438 if (this.selected_option_count != null) {
3439 return this.selected_option_count;
3440 }
3441 this.selected_option_count = 0;
3442 ref = this.form_field.options;
3443 for (i = 0, len = ref.length; i < len; i++) {
3444 option = ref[i];
3445 if (option.selected) {
3446 this.selected_option_count += 1;
3447 }
3448 }
3449 return this.selected_option_count;
3450 };
3451
3452 AbstractChosen.prototype.choices_click = function(evt) {
3453 evt.preventDefault();
3454 this.activate_field();
3455 if (!(this.results_showing || this.is_disabled)) {
3456 return this.results_show();
3457 }
3458 };
3459
3460 AbstractChosen.prototype.keydown_checker = function(evt) {
3461 var ref, stroke;
3462 stroke = (ref = evt.which) != null ? ref : evt.keyCode;
3463 this.search_field_scale();
3464 if (stroke !== 8 && this.pending_backstroke) {
3465 this.clear_backstroke();
3466 }
3467 switch (stroke) {
3468 case 8:
3469 this.backstroke_length = this.get_search_field_value().length;
3470 break;
3471 case 9:
3472 if (this.results_showing && !this.is_multiple) {
3473 this.result_select(evt);
3474 }
3475 this.mouse_on_container = false;
3476 break;
3477 case 13:
3478 if (this.results_showing) {
3479 evt.preventDefault();
3480 }
3481 break;
3482 case 27:
3483 if (this.results_showing) {
3484 evt.preventDefault();
3485 }
3486 break;
3487 case 32:
3488 if (this.disable_search) {
3489 evt.preventDefault();
3490 }
3491 break;
3492 case 38:
3493 evt.preventDefault();
3494 this.keyup_arrow();
3495 break;
3496 case 40:
3497 evt.preventDefault();
3498 this.keydown_arrow();
3499 break;
3500 }
3501 };
3502
3503 AbstractChosen.prototype.keyup_checker = function(evt) {
3504 var ref, stroke;
3505 stroke = (ref = evt.which) != null ? ref : evt.keyCode;
3506 this.search_field_scale();
3507 switch (stroke) {
3508 case 8:
3509 if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) {
3510 this.keydown_backstroke();
3511 } else if (!this.pending_backstroke) {
3512 this.result_clear_highlight();
3513 this.results_search();
3514 }
3515 break;
3516 case 13:
3517 evt.preventDefault();
3518 if (this.results_showing) {
3519 this.result_select(evt);
3520 }
3521 break;
3522 case 27:
3523 if (this.results_showing) {
3524 this.results_hide();
3525 }
3526 break;
3527 case 9:
3528 case 16:
3529 case 17:
3530 case 18:
3531 case 38:
3532 case 40:
3533 case 91:
3534 break;
3535 default:
3536 this.results_search();
3537 break;
3538 }
3539 };
3540
3541 AbstractChosen.prototype.clipboard_event_checker = function(evt) {
3542 if (this.is_disabled) {
3543 return;
3544 }
3545 return setTimeout(((function(_this) {
3546 return function() {
3547 return _this.results_search();
3548 };
3549 })(this)), 50);
3550 };
3551
3552 AbstractChosen.prototype.container_width = function() {
3553 if (this.options.width != null) {
3554 return this.options.width;
3555 } else {
3556 return this.form_field.offsetWidth + "px";
3557 }
3558 };
3559
3560 AbstractChosen.prototype.include_option_in_results = function(option) {
3561 if (this.is_multiple && (!this.display_selected_options && option.selected)) {
3562 return false;
3563 }
3564 if (!this.display_disabled_options && option.disabled) {
3565 return false;
3566 }
3567 if (option.empty) {
3568 return false;
3569 }
3570 return true;
3571 };
3572
3573 AbstractChosen.prototype.search_results_touchstart = function(evt) {
3574 this.touch_started = true;
3575 return this.search_results_mouseover(evt);
3576 };
3577
3578 AbstractChosen.prototype.search_results_touchmove = function(evt) {
3579 this.touch_started = false;
3580 return this.search_results_mouseout(evt);
3581 };
3582
3583 AbstractChosen.prototype.search_results_touchend = function(evt) {
3584 if (this.touch_started) {
3585 return this.search_results_mouseup(evt);
3586 }
3587 };
3588
3589 AbstractChosen.prototype.outerHTML = function(element) {
3590 var tmp;
3591 if (element.outerHTML) {
3592 return element.outerHTML;
3593 }
3594 tmp = document.createElement("div");
3595 tmp.appendChild(element);
3596 return tmp.innerHTML;
3597 };
3598
3599 AbstractChosen.prototype.get_single_html = function() {
3600 return "<a class=\"chosen-single chosen-default\">\n <span>" + this.default_text + "</span>\n <div><b></b></div>\n</a>\n<div class=\"chosen-drop\">\n <div class=\"chosen-search\">\n <input class=\"chosen-search-input\" type=\"text\" autocomplete=\"off\" />\n </div>\n <ul class=\"chosen-results\"></ul>\n</div>";
3601 };
3602
3603 AbstractChosen.prototype.get_multi_html = function() {
3604 return "<ul class=\"chosen-choices\">\n <li class=\"search-field\">\n <input class=\"chosen-search-input\" type=\"text\" autocomplete=\"off\" value=\"" + this.default_text + "\" />\n </li>\n</ul>\n<div class=\"chosen-drop\">\n <ul class=\"chosen-results\"></ul>\n</div>";
3605 };
3606
3607 AbstractChosen.prototype.get_no_results_html = function(terms) {
3608 return "<li class=\"no-results\">\n " + this.results_none_found + " <span>" + (this.escape_html(terms)) + "</span>\n</li>";
3609 };
3610
3611 AbstractChosen.browser_is_supported = function() {
3612 if ("Microsoft Internet Explorer" === window.navigator.appName) {
3613 return document.documentMode >= 8;
3614 }
3615 if (/iP(od|hone)/i.test(window.navigator.userAgent) || /IEMobile/i.test(window.navigator.userAgent) || /Windows Phone/i.test(window.navigator.userAgent) || /BlackBerry/i.test(window.navigator.userAgent) || /BB10/i.test(window.navigator.userAgent) || /Android.*Mobile/i.test(window.navigator.userAgent)) {
3616 return false;
3617 }
3618 return true;
3619 };
3620
3621 AbstractChosen.default_multiple_text = "Select Some Options";
3622
3623 AbstractChosen.default_single_text = "Select an Option";
3624
3625 AbstractChosen.default_no_result_text = "No results match";
3626
3627 return AbstractChosen;
3628
3629 })();
3630
3631 $ = jQuery;
3632
3633 $.fn.extend({
3634 chosen: function(options) {
3635 if (!AbstractChosen.browser_is_supported()) {
3636 return this;
3637 }
3638 return this.each(function(input_field) {
3639 var $this, chosen;
3640 $this = $(this);
3641 chosen = $this.data('chosen');
3642 if (options === 'destroy') {
3643 if (chosen instanceof Chosen) {
3644 chosen.destroy();
3645 }
3646 return;
3647 }
3648 if (!(chosen instanceof Chosen)) {
3649 $this.data('chosen', new Chosen(this, options));
3650 }
3651 });
3652 }
3653 });
3654
3655 Chosen = (function(superClass) {
3656 extend(Chosen, superClass);
3657
3658 function Chosen() {
3659 return Chosen.__super__.constructor.apply(this, arguments);
3660 }
3661
3662 Chosen.prototype.setup = function() {
3663 this.form_field_jq = $(this.form_field);
3664 return this.current_selectedIndex = this.form_field.selectedIndex;
3665 };
3666
3667 Chosen.prototype.set_up_html = function() {
3668 var container_classes, container_props;
3669 container_classes = ["chosen-container"];
3670 container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single"));
3671 if (this.inherit_select_classes && this.form_field.className) {
3672 container_classes.push(this.form_field.className);
3673 }
3674 if (this.is_rtl) {
3675 container_classes.push("chosen-rtl");
3676 }
3677 container_props = {
3678 'class': container_classes.join(' '),
3679 'title': this.form_field.title
3680 };
3681 if (this.form_field.id.length) {
3682 container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen";
3683 }
3684 this.container = $("<div />", container_props);
3685 this.container.width(this.container_width());
3686 if (this.is_multiple) {
3687 this.container.html(this.get_multi_html());
3688 } else {
3689 this.container.html(this.get_single_html());
3690 }
3691 this.form_field_jq.hide().after(this.container);
3692 this.dropdown = this.container.find('div.chosen-drop').first();
3693 this.search_field = this.container.find('input').first();
3694 this.search_results = this.container.find('ul.chosen-results').first();
3695 this.search_field_scale();
3696 this.search_no_results = this.container.find('li.no-results').first();
3697 if (this.is_multiple) {
3698 this.search_choices = this.container.find('ul.chosen-choices').first();
3699 this.search_container = this.container.find('li.search-field').first();
3700 } else {
3701 this.search_container = this.container.find('div.chosen-search').first();
3702 this.selected_item = this.container.find('.chosen-single').first();
3703 }
3704 this.results_build();
3705 this.set_tab_index();
3706 return this.set_label_behavior();
3707 };
3708
3709 Chosen.prototype.on_ready = function() {
3710 return this.form_field_jq.trigger("chosen:ready", {
3711 chosen: this
3712 });
3713 };
3714
3715 Chosen.prototype.register_observers = function() {
3716 this.container.on('touchstart.chosen', (function(_this) {
3717 return function(evt) {
3718 _this.container_mousedown(evt);
3719 };
3720 })(this));
3721 this.container.on('touchend.chosen', (function(_this) {
3722 return function(evt) {
3723 _this.container_mouseup(evt);
3724 };
3725 })(this));
3726 this.container.on('mousedown.chosen', (function(_this) {
3727 return function(evt) {
3728 _this.container_mousedown(evt);
3729 };
3730 })(this));
3731 this.container.on('mouseup.chosen', (function(_this) {
3732 return function(evt) {
3733 _this.container_mouseup(evt);
3734 };
3735 })(this));
3736 this.container.on('mouseenter.chosen', (function(_this) {
3737 return function(evt) {
3738 _this.mouse_enter(evt);
3739 };
3740 })(this));
3741 this.container.on('mouseleave.chosen', (function(_this) {
3742 return function(evt) {
3743 _this.mouse_leave(evt);
3744 };
3745 })(this));
3746 this.search_results.on('mouseup.chosen', (function(_this) {
3747 return function(evt) {
3748 _this.search_results_mouseup(evt);
3749 };
3750 })(this));
3751 this.search_results.on('mouseover.chosen', (function(_this) {
3752 return function(evt) {
3753 _this.search_results_mouseover(evt);
3754 };
3755 })(this));
3756 this.search_results.on('mouseout.chosen', (function(_this) {
3757 return function(evt) {
3758 _this.search_results_mouseout(evt);
3759 };
3760 })(this));
3761 this.search_results.on('mousewheel.chosen DOMMouseScroll.chosen', (function(_this) {
3762 return function(evt) {
3763 _this.search_results_mousewheel(evt);
3764 };
3765 })(this));
3766 this.search_results.on('touchstart.chosen', (function(_this) {
3767 return function(evt) {
3768 _this.search_results_touchstart(evt);
3769 };
3770 })(this));
3771 this.search_results.on('touchmove.chosen', (function(_this) {
3772 return function(evt) {
3773 _this.search_results_touchmove(evt);
3774 };
3775 })(this));
3776 this.search_results.on('touchend.chosen', (function(_this) {
3777 return function(evt) {
3778 _this.search_results_touchend(evt);
3779 };
3780 })(this));
3781 this.form_field_jq.on("chosen:updated.chosen", (function(_this) {
3782 return function(evt) {
3783 _this.results_update_field(evt);
3784 };
3785 })(this));
3786 this.form_field_jq.on("chosen:activate.chosen", (function(_this) {
3787 return function(evt) {
3788 _this.activate_field(evt);
3789 };
3790 })(this));
3791 this.form_field_jq.on("chosen:open.chosen", (function(_this) {
3792 return function(evt) {
3793 _this.container_mousedown(evt);
3794 };
3795 })(this));
3796 this.form_field_jq.on("chosen:close.chosen", (function(_this) {
3797 return function(evt) {
3798 _this.close_field(evt);
3799 };
3800 })(this));
3801 this.search_field.on('blur.chosen', (function(_this) {
3802 return function(evt) {
3803 _this.input_blur(evt);
3804 };
3805 })(this));
3806 this.search_field.on('keyup.chosen', (function(_this) {
3807 return function(evt) {
3808 _this.keyup_checker(evt);
3809 };
3810 })(this));
3811 this.search_field.on('keydown.chosen', (function(_this) {
3812 return function(evt) {
3813 _this.keydown_checker(evt);
3814 };
3815 })(this));
3816 this.search_field.on('focus.chosen', (function(_this) {
3817 return function(evt) {
3818 _this.input_focus(evt);
3819 };
3820 })(this));
3821 this.search_field.on('cut.chosen', (function(_this) {
3822 return function(evt) {
3823 _this.clipboard_event_checker(evt);
3824 };
3825 })(this));
3826 this.search_field.on('paste.chosen', (function(_this) {
3827 return function(evt) {
3828 _this.clipboard_event_checker(evt);
3829 };
3830 })(this));
3831 if (this.is_multiple) {
3832 return this.search_choices.on('click.chosen', (function(_this) {
3833 return function(evt) {
3834 _this.choices_click(evt);
3835 };
3836 })(this));
3837 } else {
3838 return this.container.on('click.chosen', function(evt) {
3839 evt.preventDefault();
3840 });
3841 }
3842 };
3843
3844 Chosen.prototype.destroy = function() {
3845 $(this.container[0].ownerDocument).off('click.chosen', this.click_test_action);
3846 if (this.form_field_label.length > 0) {
3847 this.form_field_label.off('click.chosen');
3848 }
3849 if (this.search_field[0].tabIndex) {
3850 this.form_field_jq[0].tabIndex = this.search_field[0].tabIndex;
3851 }
3852 this.container.remove();
3853 this.form_field_jq.removeData('chosen');
3854 return this.form_field_jq.show();
3855 };
3856
3857 Chosen.prototype.search_field_disabled = function() {
3858 this.is_disabled = this.form_field.disabled || this.form_field_jq.parents('fieldset').is(':disabled');
3859 this.container.toggleClass('chosen-disabled', this.is_disabled);
3860 this.search_field[0].disabled = this.is_disabled;
3861 if (!this.is_multiple) {
3862 this.selected_item.off('focus.chosen', this.activate_field);
3863 }
3864 if (this.is_disabled) {
3865 return this.close_field();
3866 } else if (!this.is_multiple) {
3867 return this.selected_item.on('focus.chosen', this.activate_field);
3868 }
3869 };
3870
3871 Chosen.prototype.container_mousedown = function(evt) {
3872 var ref;
3873 if (this.is_disabled) {
3874 return;
3875 }
3876 if (evt && ((ref = evt.type) === 'mousedown' || ref === 'touchstart') && !this.results_showing) {
3877 evt.preventDefault();
3878 }
3879 if (!((evt != null) && ($(evt.target)).hasClass("search-choice-close"))) {
3880 if (!this.active_field) {
3881 if (this.is_multiple) {
3882 this.search_field.val("");
3883 }
3884 $(this.container[0].ownerDocument).on('click.chosen', this.click_test_action);
3885 this.results_show();
3886 } else if (!this.is_multiple && evt && (($(evt.target)[0] === this.selected_item[0]) || $(evt.target).parents("a.chosen-single").length)) {
3887 evt.preventDefault();
3888 this.results_toggle();
3889 }
3890 return this.activate_field();
3891 }
3892 };
3893
3894 Chosen.prototype.container_mouseup = function(evt) {
3895 if (evt.target.nodeName === "ABBR" && !this.is_disabled) {
3896 return this.results_reset(evt);
3897 }
3898 };
3899
3900 Chosen.prototype.search_results_mousewheel = function(evt) {
3901 var delta;
3902 if (evt.originalEvent) {
3903 delta = evt.originalEvent.deltaY || -evt.originalEvent.wheelDelta || evt.originalEvent.detail;
3904 }
3905 if (delta != null) {
3906 evt.preventDefault();
3907 if (evt.type === 'DOMMouseScroll') {
3908 delta = delta * 40;
3909 }
3910 return this.search_results.scrollTop(delta + this.search_results.scrollTop());
3911 }
3912 };
3913
3914 Chosen.prototype.blur_test = function(evt) {
3915 if (!this.active_field && this.container.hasClass("chosen-container-active")) {
3916 return this.close_field();
3917 }
3918 };
3919
3920 Chosen.prototype.close_field = function() {
3921 $(this.container[0].ownerDocument).off("click.chosen", this.click_test_action);
3922 this.active_field = false;
3923 this.results_hide();
3924 this.container.removeClass("chosen-container-active");
3925 this.clear_backstroke();
3926 this.show_search_field_default();
3927 this.search_field_scale();
3928 return this.search_field.blur();
3929 };
3930
3931 Chosen.prototype.activate_field = function() {
3932 if (this.is_disabled) {
3933 return;
3934 }
3935 this.container.addClass("chosen-container-active");
3936 this.active_field = true;
3937 this.search_field.val(this.search_field.val());
3938 return this.search_field.focus();
3939 };
3940
3941 Chosen.prototype.test_active_click = function(evt) {
3942 var active_container;
3943 active_container = $(evt.target).closest('.chosen-container');
3944 if (active_container.length && this.container[0] === active_container[0]) {
3945 return this.active_field = true;
3946 } else {
3947 return this.close_field();
3948 }
3949 };
3950
3951 Chosen.prototype.results_build = function() {
3952 this.parsing = true;
3953 this.selected_option_count = null;
3954 this.results_data = SelectParser.select_to_array(this.form_field);
3955 if (this.is_multiple) {
3956 this.search_choices.find("li.search-choice").remove();
3957 } else {
3958 this.single_set_selected_text();
3959 if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) {
3960 this.search_field[0].readOnly = true;
3961 this.container.addClass("chosen-container-single-nosearch");
3962 } else {
3963 this.search_field[0].readOnly = false;
3964 this.container.removeClass("chosen-container-single-nosearch");
3965 }
3966 }
3967 this.update_results_content(this.results_option_build({
3968 first: true
3969 }));
3970 this.search_field_disabled();
3971 this.show_search_field_default();
3972 this.search_field_scale();
3973 return this.parsing = false;
3974 };
3975
3976 Chosen.prototype.result_do_highlight = function(el) {
3977 var high_bottom, high_top, maxHeight, visible_bottom, visible_top;
3978 if (el.length) {
3979 this.result_clear_highlight();
3980 this.result_highlight = el;
3981 this.result_highlight.addClass("highlighted");
3982 maxHeight = parseInt(this.search_results.css("maxHeight"), 10);
3983 visible_top = this.search_results.scrollTop();
3984 visible_bottom = maxHeight + visible_top;
3985 high_top = this.result_highlight.position().top + this.search_results.scrollTop();
3986 high_bottom = high_top + this.result_highlight.outerHeight();
3987 if (high_bottom >= visible_bottom) {
3988 return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0);
3989 } else if (high_top < visible_top) {
3990 return this.search_results.scrollTop(high_top);
3991 }
3992 }
3993 };
3994
3995 Chosen.prototype.result_clear_highlight = function() {
3996 if (this.result_highlight) {
3997 this.result_highlight.removeClass("highlighted");
3998 }
3999 return this.result_highlight = null;
4000 };
4001
4002 Chosen.prototype.results_show = function() {
4003 if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
4004 this.form_field_jq.trigger("chosen:maxselected", {
4005 chosen: this
4006 });
4007 return false;
4008 }
4009 this.container.addClass("chosen-with-drop");
4010 this.results_showing = true;
4011 this.search_field.focus();
4012 this.search_field.val(this.get_search_field_value());
4013 this.winnow_results();
4014 return this.form_field_jq.trigger("chosen:showing_dropdown", {
4015 chosen: this
4016 });
4017 };
4018
4019 Chosen.prototype.update_results_content = function(content) {
4020 return this.search_results.html(content);
4021 };
4022
4023 Chosen.prototype.results_hide = function() {
4024 if (this.results_showing) {
4025 this.result_clear_highlight();
4026 this.container.removeClass("chosen-with-drop");
4027 this.form_field_jq.trigger("chosen:hiding_dropdown", {
4028 chosen: this
4029 });
4030 }
4031 return this.results_showing = false;
4032 };
4033
4034 Chosen.prototype.set_tab_index = function(el) {
4035 var ti;
4036 if (this.form_field.tabIndex) {
4037 ti = this.form_field.tabIndex;
4038 this.form_field.tabIndex = -1;
4039 return this.search_field[0].tabIndex = ti;
4040 }
4041 };
4042
4043 Chosen.prototype.set_label_behavior = function() {
4044 this.form_field_label = this.form_field_jq.parents("label");
4045 if (!this.form_field_label.length && this.form_field.id.length) {
4046 this.form_field_label = $("label[for='" + this.form_field.id + "']");
4047 }
4048 if (this.form_field_label.length > 0) {
4049 return this.form_field_label.on('click.chosen', this.label_click_handler);
4050 }
4051 };
4052
4053 Chosen.prototype.show_search_field_default = function() {
4054 if (this.is_multiple && this.choices_count() < 1 && !this.active_field) {
4055 this.search_field.val(this.default_text);
4056 return this.search_field.addClass("default");
4057 } else {
4058 this.search_field.val("");
4059 return this.search_field.removeClass("default");
4060 }
4061 };
4062
4063 Chosen.prototype.search_results_mouseup = function(evt) {
4064 var target;
4065 target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
4066 if (target.length) {
4067 this.result_highlight = target;
4068 this.result_select(evt);
4069 return this.search_field.focus();
4070 }
4071 };
4072
4073 Chosen.prototype.search_results_mouseover = function(evt) {
4074 var target;
4075 target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
4076 if (target) {
4077 return this.result_do_highlight(target);
4078 }
4079 };
4080
4081 Chosen.prototype.search_results_mouseout = function(evt) {
4082 if ($(evt.target).hasClass("active-result") || $(evt.target).parents('.active-result').first()) {
4083 return this.result_clear_highlight();
4084 }
4085 };
4086
4087 Chosen.prototype.choice_build = function(item) {
4088 var choice, close_link;
4089 choice = $('<li />', {
4090 "class": "search-choice"
4091 }).html("<span>" + (this.choice_label(item)) + "</span>");
4092 if (item.disabled) {
4093 choice.addClass('search-choice-disabled');
4094 } else {
4095 close_link = $('<a />', {
4096 "class": 'search-choice-close',
4097 'data-option-array-index': item.array_index
4098 });
4099 close_link.on('click.chosen', (function(_this) {
4100 return function(evt) {
4101 return _this.choice_destroy_link_click(evt);
4102 };
4103 })(this));
4104 choice.append(close_link);
4105 }
4106 return this.search_container.before(choice);
4107 };
4108
4109 Chosen.prototype.choice_destroy_link_click = function(evt) {
4110 evt.preventDefault();
4111 evt.stopPropagation();
4112 if (!this.is_disabled) {
4113 return this.choice_destroy($(evt.target));
4114 }
4115 };
4116
4117 Chosen.prototype.choice_destroy = function(link) {
4118 if (this.result_deselect(link[0].getAttribute("data-option-array-index"))) {
4119 if (this.active_field) {
4120 this.search_field.focus();
4121 } else {
4122 this.show_search_field_default();
4123 }
4124 if (this.is_multiple && this.choices_count() > 0 && this.get_search_field_value().length < 1) {
4125 this.results_hide();
4126 }
4127 link.parents('li').first().remove();
4128 return this.search_field_scale();
4129 }
4130 };
4131
4132 Chosen.prototype.results_reset = function() {
4133 this.reset_single_select_options();
4134 this.form_field.options[0].selected = true;
4135 this.single_set_selected_text();
4136 this.show_search_field_default();
4137 this.results_reset_cleanup();
4138 this.trigger_form_field_change();
4139 if (this.active_field) {
4140 return this.results_hide();
4141 }
4142 };
4143
4144 Chosen.prototype.results_reset_cleanup = function() {
4145 this.current_selectedIndex = this.form_field.selectedIndex;
4146 return this.selected_item.find("abbr").remove();
4147 };
4148
4149 Chosen.prototype.result_select = function(evt) {
4150 var high, item;
4151 if (this.result_highlight) {
4152 high = this.result_highlight;
4153 this.result_clear_highlight();
4154 if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
4155 this.form_field_jq.trigger("chosen:maxselected", {
4156 chosen: this
4157 });
4158 return false;
4159 }
4160 if (this.is_multiple) {
4161 high.removeClass("active-result");
4162 } else {
4163 this.reset_single_select_options();
4164 }
4165 high.addClass("result-selected");
4166 item = this.results_data[high[0].getAttribute("data-option-array-index")];
4167 item.selected = true;
4168 this.form_field.options[item.options_index].selected = true;
4169 this.selected_option_count = null;
4170 if (this.is_multiple) {
4171 this.choice_build(item);
4172 } else {
4173 this.single_set_selected_text(this.choice_label(item));
4174 }
4175 if (this.is_multiple && (!this.hide_results_on_select || (evt.metaKey || evt.ctrlKey))) {
4176 if (evt.metaKey || evt.ctrlKey) {
4177 this.winnow_results({
4178 skip_highlight: true
4179 });
4180 } else {
4181 this.search_field.val("");
4182 this.winnow_results();
4183 }
4184 } else {
4185 this.results_hide();
4186 this.show_search_field_default();
4187 }
4188 if (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex) {
4189 this.trigger_form_field_change({
4190 selected: this.form_field.options[item.options_index].value
4191 });
4192 }
4193 this.current_selectedIndex = this.form_field.selectedIndex;
4194 evt.preventDefault();
4195 return this.search_field_scale();
4196 }
4197 };
4198
4199 Chosen.prototype.single_set_selected_text = function(text) {
4200 if (text == null) {
4201 text = this.default_text;
4202 }
4203 if (text === this.default_text) {
4204 this.selected_item.addClass("chosen-default");
4205 } else {
4206 this.single_deselect_control_build();
4207 this.selected_item.removeClass("chosen-default");
4208 }
4209 return this.selected_item.find("span").html(text);
4210 };
4211
4212 Chosen.prototype.result_deselect = function(pos) {
4213 var result_data;
4214 result_data = this.results_data[pos];
4215 if (!this.form_field.options[result_data.options_index].disabled) {
4216 result_data.selected = false;
4217 this.form_field.options[result_data.options_index].selected = false;
4218 this.selected_option_count = null;
4219 this.result_clear_highlight();
4220 if (this.results_showing) {
4221 this.winnow_results();
4222 }
4223 this.trigger_form_field_change({
4224 deselected: this.form_field.options[result_data.options_index].value
4225 });
4226 this.search_field_scale();
4227 return true;
4228 } else {
4229 return false;
4230 }
4231 };
4232
4233 Chosen.prototype.single_deselect_control_build = function() {
4234 if (!this.allow_single_deselect) {
4235 return;
4236 }
4237 if (!this.selected_item.find("abbr").length) {
4238 this.selected_item.find("span").first().after("<abbr class=\"search-choice-close\"></abbr>");
4239 }
4240 return this.selected_item.addClass("chosen-single-with-deselect");
4241 };
4242
4243 Chosen.prototype.get_search_field_value = function() {
4244 return this.search_field.val();
4245 };
4246
4247 Chosen.prototype.get_search_text = function() {
4248 return $.trim(this.get_search_field_value());
4249 };
4250
4251 Chosen.prototype.escape_html = function(text) {
4252 return $('<div/>').text(text).html();
4253 };
4254
4255 Chosen.prototype.winnow_results_set_highlight = function() {
4256 var do_high, selected_results;
4257 selected_results = !this.is_multiple ? this.search_results.find(".result-selected.active-result") : [];
4258 do_high = selected_results.length ? selected_results.first() : this.search_results.find(".active-result").first();
4259 if (do_high != null) {
4260 return this.result_do_highlight(do_high);
4261 }
4262 };
4263
4264 Chosen.prototype.no_results = function(terms) {
4265 var no_results_html;
4266 no_results_html = this.get_no_results_html(terms);
4267 this.search_results.append(no_results_html);
4268 return this.form_field_jq.trigger("chosen:no_results", {
4269 chosen: this
4270 });
4271 };
4272
4273 Chosen.prototype.no_results_clear = function() {
4274 return this.search_results.find(".no-results").remove();
4275 };
4276
4277 Chosen.prototype.keydown_arrow = function() {
4278 var next_sib;
4279 if (this.results_showing && this.result_highlight) {
4280 next_sib = this.result_highlight.nextAll("li.active-result").first();
4281 if (next_sib) {
4282 return this.result_do_highlight(next_sib);
4283 }
4284 } else {
4285 return this.results_show();
4286 }
4287 };
4288
4289 Chosen.prototype.keyup_arrow = function() {
4290 var prev_sibs;
4291 if (!this.results_showing && !this.is_multiple) {
4292 return this.results_show();
4293 } else if (this.result_highlight) {
4294 prev_sibs = this.result_highlight.prevAll("li.active-result");
4295 if (prev_sibs.length) {
4296 return this.result_do_highlight(prev_sibs.first());
4297 } else {
4298 if (this.choices_count() > 0) {
4299 this.results_hide();
4300 }
4301 return this.result_clear_highlight();
4302 }
4303 }
4304 };
4305
4306 Chosen.prototype.keydown_backstroke = function() {
4307 var next_available_destroy;
4308 if (this.pending_backstroke) {
4309 this.choice_destroy(this.pending_backstroke.find("a").first());
4310 return this.clear_backstroke();
4311 } else {
4312 next_available_destroy = this.search_container.siblings("li.search-choice").last();
4313 if (next_available_destroy.length && !next_available_destroy.hasClass("search-choice-disabled")) {
4314 this.pending_backstroke = next_available_destroy;
4315 if (this.single_backstroke_delete) {
4316 return this.keydown_backstroke();
4317 } else {
4318 return this.pending_backstroke.addClass("search-choice-focus");
4319 }
4320 }
4321 }
4322 };
4323
4324 Chosen.prototype.clear_backstroke = function() {
4325 if (this.pending_backstroke) {
4326 this.pending_backstroke.removeClass("search-choice-focus");
4327 }
4328 return this.pending_backstroke = null;
4329 };
4330
4331 Chosen.prototype.search_field_scale = function() {
4332 var div, i, len, style, style_block, styles, width;
4333 if (!this.is_multiple) {
4334 return;
4335 }
4336 style_block = {
4337 position: 'absolute',
4338 left: '-1000px',
4339 top: '-1000px',
4340 display: 'none',
4341 whiteSpace: 'pre'
4342 };
4343 styles = ['fontSize', 'fontStyle', 'fontWeight', 'fontFamily', 'lineHeight', 'textTransform', 'letterSpacing'];
4344 for (i = 0, len = styles.length; i < len; i++) {
4345 style = styles[i];
4346 style_block[style] = this.search_field.css(style);
4347 }
4348 div = $('<div />').css(style_block);
4349 div.text(this.get_search_field_value());
4350 $('body').append(div);
4351 width = div.width() + 25;
4352 div.remove();
4353 if (this.container.is(':visible')) {
4354 width = Math.min(this.container.outerWidth() - 10, width);
4355 }
4356 return this.search_field.width(width);
4357 };
4358
4359 Chosen.prototype.trigger_form_field_change = function(extra) {
4360 this.form_field_jq.trigger("input", extra);
4361 return this.form_field_jq.trigger("change", extra);
4362 };
4363
4364 return Chosen;
4365
4366 })(AbstractChosen);
4367
4368 }).call(this);
4369 ;/**
4370 *
4371 * jQuery Interdependencies library
4372 * https://github.com/miohtama/jquery-interdependencies
4373 * Copyright 2012-2013 Mikko Ohtamaa, others
4374 *
4375 * Customized by Codestar
4376 *
4377 */
4378 (function($) {
4379
4380 'use strict';
4381
4382 function Rule(controller, condition, value) {
4383 this.init(controller, condition, value);
4384 }
4385
4386 $.extend(Rule.prototype, {
4387
4388 init: function(controller, condition, value) {
4389
4390 this.controller = controller;
4391 this.condition = condition;
4392 this.value = value;
4393 this.rules = [];
4394 this.controls = [];
4395
4396 },
4397
4398 evalCondition: function(context, control, condition, val1, val2) {
4399
4400 if( condition == '==' ) {
4401
4402 return this.checkBoolean(val1) == this.checkBoolean(val2);
4403
4404 } else if( condition == '!=' ) {
4405
4406 return this.checkBoolean(val1) != this.checkBoolean(val2);
4407
4408 } else if( condition == '>=' ) {
4409
4410 return Number(val2) >= Number(val1);
4411
4412 } else if( condition == '<=' ) {
4413
4414 return Number(val2) <= Number(val1);
4415
4416 } else if( condition == '>' ) {
4417
4418 return Number(val2) > Number(val1);
4419
4420 } else if( condition == '<' ) {
4421
4422 return Number(val2) < Number(val1);
4423
4424 } else if( condition == '()' ) {
4425
4426 return window[val1](context, control, val2);
4427
4428 } else if( condition == 'any' ) {
4429
4430 if( $.isArray( val2 ) ) {
4431 for (var i = val2.length - 1; i >= 0; i--) {
4432 if( $.inArray( val2[i], val1.split(',') ) !== -1 ) {
4433 return true;
4434 }
4435 }
4436 } else {
4437 if( $.inArray( val2, val1.split(',') ) !== -1 ) {
4438 return true;
4439 }
4440 }
4441
4442 } else if( condition == 'not-any' ) {
4443
4444 if( $.isArray( val2 ) ) {
4445 for (var i = val2.length - 1; i >= 0; i--) {
4446 if( $.inArray( val2[i], val1.split(',') ) == -1 ) {
4447 return true;
4448 }
4449 }
4450 } else {
4451 if( $.inArray( val2, val1.split(',') ) == -1 ) {
4452 return true;
4453 }
4454 }
4455
4456 }
4457
4458 return false;
4459
4460 },
4461
4462 checkBoolean: function(value) {
4463
4464 switch( value ) {
4465
4466 case true:
4467 case 'true':
4468 case 1:
4469 case '1':
4470 value = true;
4471 break;
4472
4473 case null:
4474 case false:
4475 case 'false':
4476 case 0:
4477 case '0':
4478 value = false;
4479 break;
4480
4481 }
4482
4483 return value;
4484 },
4485
4486 checkCondition: function( context ) {
4487
4488 if( !this.condition ) {
4489 return true;
4490 }
4491 this.controller = this.controller.replace(/=""(.*?)""/g, '="$1"');
4492
4493 var control = context.find(this.controller);
4494
4495
4496
4497
4498 var control_value = this.getControlValue(context, control);
4499
4500 if( control_value === undefined ) {
4501 return false;
4502 }
4503
4504 control_value = this.normalizeValue(control, this.value, control_value);
4505
4506 return this.evalCondition(context, control, this.condition, this.value, control_value);
4507 },
4508
4509 normalizeValue: function( control, baseValue, control_value ) {
4510
4511 if( typeof baseValue == 'number' ) {
4512 return parseFloat( control_value );
4513 }
4514
4515 return control_value;
4516 },
4517
4518 getControlValue: function(context, control) {
4519
4520 if( control.length > 1 && ( control.attr('type') == 'radio' || control.attr('type') == 'checkbox' ) ) {
4521
4522 return control.filter(':checked').map(function() { return this.value; }).get();
4523
4524 } else if ( control.attr('type') == 'checkbox' || control.attr('type') == 'radio' ) {
4525
4526 return control.is(':checked');
4527
4528 }
4529
4530 return control.val();
4531
4532 },
4533
4534 createRule: function(controller, condition, value) {
4535 var rule = new Rule(controller, condition, value);
4536 this.rules.push(rule);
4537 return rule;
4538 },
4539
4540 include: function(input) {
4541 this.controls.push(input);
4542 },
4543
4544 applyRule: function(context, enforced) {
4545
4546 var result;
4547
4548 if( typeof( enforced ) == 'undefined' ) {
4549 result = this.checkCondition(context);
4550 } else {
4551 result = enforced;
4552 }
4553
4554 var controls = $.map(this.controls, function(elem, idx) {
4555 return context.find(elem);
4556 });
4557
4558 if( result ) {
4559
4560 $(controls).each(function() {
4561 $(this).removeClass('csf-depend-on');
4562 });
4563
4564 $(this.rules).each(function() {
4565 this.applyRule(context);
4566 });
4567
4568 } else {
4569
4570 $(controls).each(function() {
4571 $(this).addClass('csf-depend-on');
4572 });
4573
4574 $(this.rules).each(function() {
4575 this.applyRule(context, false);
4576 });
4577
4578 }
4579 }
4580 });
4581
4582 function Ruleset() {
4583 this.rules = [];
4584 };
4585
4586 $.extend(Ruleset.prototype, {
4587
4588 createRule: function(controller, condition, value) {
4589 var rule = new Rule(controller, condition, value);
4590 this.rules.push(rule);
4591 return rule;
4592 },
4593
4594 applyRules: function(context) {
4595 $(this.rules).each(function() {
4596 this.applyRule(context);
4597 });
4598 }
4599 });
4600
4601 $.eshb_deps = {
4602
4603 createRuleset: function() {
4604 return new Ruleset();
4605 },
4606
4607 enable: function(selection, ruleset, depends) {
4608
4609 selection.on('change keyup', function(elem) {
4610
4611 var depend_id = elem.target.getAttribute('data-depend-id') || elem.target.getAttribute('data-sub-depend-id');
4612
4613 if( depends.indexOf( depend_id ) !== -1 ) {
4614 ruleset.applyRules(selection);
4615 }
4616
4617 });
4618
4619 ruleset.applyRules(selection);
4620
4621 return true;
4622 }
4623 };
4624
4625 })(jQuery);
4626 ;/**
4627 *
4628 * jQuery serializeObject
4629 *
4630 * @copyright 2014, macek <paulmacek@gmail.com>
4631 * @link https://github.com/macek/jquery-serialize-object
4632 * @license BSD
4633 * @version 2.5.0
4634 *
4635 * Customized by Codestar
4636 *
4637 */
4638 (function(root, factory) {
4639
4640 // AMD
4641 if (typeof define === "function" && define.amd) {
4642 define(["exports", "jquery"], function(exports, $) {
4643 return factory(exports, $);
4644 });
4645 }
4646
4647 // CommonJS
4648 else if (typeof exports !== "undefined") {
4649 var $ = require("jquery");
4650 factory(exports, $);
4651 }
4652
4653 // Browser
4654 else {
4655 factory(root, (root.jQuery || root.Zepto || root.ender || root.$));
4656 }
4657
4658 }(this, function(exports, $) {
4659
4660 //
4661 // Codestar: Added custom patterns for spesific validate
4662 //
4663 var patterns = {
4664 validate: /^(?!(_nonce|_pseudo))[a-zA-Z0-9_-]*(?:\[(?:\d*|(?!(_nonce|_pseudo))[a-zA-Z0-9_-]+)\])*$/i,
4665 key: /[a-zA-Z0-9_-]+|(?=\[\])/g,
4666 named: /^[a-zA-Z0-9_-]+$/,
4667 push: /^$/,
4668 fixed: /^\d+$/
4669 };
4670
4671 function FormSerializer(helper, $form) {
4672
4673 // private variables
4674 var data = {},
4675 pushes = {};
4676
4677 // private API
4678 function build(base, key, value) {
4679 base[key] = value;
4680 return base;
4681 }
4682
4683 function makeObject(root, value) {
4684
4685 var keys = root.match(patterns.key), k;
4686
4687 // nest, nest, ..., nest
4688 while ((k = keys.pop()) !== undefined) {
4689 // foo[]
4690 if (patterns.push.test(k)) {
4691 var idx = incrementPush(root.replace(/\[\]$/, ''));
4692 value = build([], idx, value);
4693 }
4694
4695 // foo[n]
4696 else if (patterns.fixed.test(k)) {
4697 value = build([], k, value);
4698 }
4699
4700 // foo; foo[bar]
4701 else if (patterns.named.test(k)) {
4702 value = build({}, k, value);
4703 }
4704 }
4705
4706 return value;
4707 }
4708
4709 function incrementPush(key) {
4710 if (pushes[key] === undefined) {
4711 pushes[key] = 0;
4712 }
4713 return pushes[key]++;
4714 }
4715
4716 function addPair(pair) {
4717 if (!patterns.validate.test(pair.name)) return this;
4718 var obj = makeObject(pair.name, pair.value);
4719 data = helper.extend(true, data, obj);
4720 return this;
4721 }
4722
4723 function addPairs(pairs) {
4724 if (!helper.isArray(pairs)) {
4725 throw new Error("formSerializer.addPairs expects an Array");
4726 }
4727 for (var i=0, len=pairs.length; i<len; i++) {
4728 this.addPair(pairs[i]);
4729 }
4730 return this;
4731 }
4732
4733 function serialize() {
4734 return data;
4735 }
4736
4737 function serializeJSON() {
4738 return JSON.stringify(serialize());
4739 }
4740
4741 // public API
4742 this.addPair = addPair;
4743 this.addPairs = addPairs;
4744 this.serialize = serialize;
4745 this.serializeJSON = serializeJSON;
4746 }
4747
4748 FormSerializer.patterns = patterns;
4749
4750 FormSerializer.serializeObject = function serializeObject() {
4751 return new FormSerializer($, this).
4752 addPairs(this.serializeArray()).
4753 serialize();
4754 };
4755
4756 FormSerializer.serializeJSON = function serializeJSON() {
4757 return new FormSerializer($, this).
4758 addPairs(this.serializeArray()).
4759 serializeJSON();
4760 };
4761
4762 //
4763 // Codestar: Renamed function names for avoid conflicts
4764 //
4765
4766 if (typeof $.fn !== "undefined") {
4767 $.fn.serializeObjectCSF = FormSerializer.serializeObject;
4768 $.fn.serializeJSONCSF = FormSerializer.serializeJSON;
4769 }
4770
4771 exports.FormSerializer = FormSerializer;
4772
4773 return FormSerializer;
4774 }));
4775