PluginProbe
StreamCast – bring live radio to your site with a sleek player / 2.3.2
StreamCast – bring live radio to your site with a sleek player v2.3.2
2.4.5 2.4.4 trunk 1.0 1.1 2.0.0 2.1.10 2.1.2 2.1.4 2.1.5 2.1.8 2.2.1 2.2.3 2.2.4 2.2.5 2.3.0 2.3.1 2.3.2 2.3.3 2.3.4 2.3.5 2.3.6 2.3.7 2.3.8 2.3.9 All 29 releases
streamcast / admin / codestar-framework / assets / js / plugins.js

plugins.js in StreamCast – bring live radio to your site with a sleek player 2.3.2, at admin/codestar-framework/assets/js/plugins.js

4,766 lines 188.4 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('csf-chosen', _this.options.data).done( function( response ) {
2777 _this.show_results( response );
2778 }).fail( function( response ) {
2779 _this.container.find('.no-results').text(response.error);
2780 });
2781
2782 }, this.options.type_delay );
2783
2784 };
2785
2786 CSFAjaxChosen.prototype.show_results = function( items ) {
2787
2788 var _this = this;
2789
2790 if ( this.is_typing || items === null ) { return; }
2791
2792 if ( items.length === 0 ) {
2793 this.element.data().chosen.no_results_clear();
2794 this.element.data().chosen.no_results(this.search_field.val());
2795 return;
2796 }
2797
2798 var selected_values = [];
2799
2800 this.element.find('option').each(function() {
2801 if ( $(this).is(':selected') ) {
2802 selected_values.push( $(this).val() + "-" + $(this).text() );
2803 } else {
2804 if( $(this).attr('value').length ) {
2805 $(this).remove();
2806 }
2807 }
2808 });
2809
2810 $.each(items, function(i, item) {
2811 if ( $.inArray( item.value + "-" + item.text, selected_values ) === -1 ) {
2812 $('<option />').attr('value', item.value).html(item.text).appendTo(_this.element);
2813 }
2814 });
2815
2816 var value_before_trigger = this.search_field.val();
2817 var width_before_trigger = this.search_field.innerWidth();
2818
2819 this.element.trigger('chosen:updated');
2820
2821 if( this.is_multiple ) {
2822
2823 var $hidden_select = this.element.parent().find('.csf-hide-select');
2824 var $hidden_value = $hidden_select.val() || [];
2825
2826 this.element.CSFChosenOrder($hidden_value, true);
2827 this.search_field.css('width', width_before_trigger);
2828
2829 }
2830
2831 this.search_field.val(value_before_trigger);
2832
2833 if ( this.chosenXhr.done !== null ) {
2834 this.chosenXhr.done(items);
2835 }
2836
2837 };
2838
2839 $.fn.CSFAjaxChosen = function(chosenOptions) {
2840 return this.each(function() {
2841 new CSFAjaxChosen(this, chosenOptions);
2842 });
2843 };
2844
2845 })(jQuery);
2846 ;// Chosen Order v1.2.1
2847 // This plugin allows you to handle the order of the selection for Chosen multiple <select> dropdowns
2848 // Full source at https://github.com/tristanjahier/chosen-order
2849 // Copyright (c) 2013 - Tristan Jahier, http://tristan-jahier.fr
2850 (function() {
2851 var $, CSFAbstractChosenOrder, _ref,
2852 __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; },
2853 __hasProp = {}.hasOwnProperty,
2854 __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; };
2855
2856 CSFAbstractChosenOrder = (function() {
2857
2858 function CSFAbstractChosenOrder() {}
2859
2860 CSFAbstractChosenOrder.insertAt = function(node, index, parentNode) {
2861 return parentNode.insertBefore(node, parentNode.children[index].nextSibling);
2862 };
2863
2864 CSFAbstractChosenOrder.getFlattenedOptionsAndGroups = function(select) {
2865 var flattened_options, opt, options, sub_opt, sub_options, _i, _j, _len, _len1;
2866 options = Array.prototype.filter.call(select.childNodes, function(o) {
2867 var _ref;
2868 return (_ref = o.nodeName.toUpperCase()) === 'OPTION' || _ref === 'OPTGROUP';
2869 });
2870 flattened_options = [];
2871 for (_i = 0, _len = options.length; _i < _len; _i++) {
2872 opt = options[_i];
2873 flattened_options.push(opt);
2874 if (opt.nodeName.toUpperCase() === 'OPTGROUP') {
2875 sub_options = Array.prototype.filter.call(opt.childNodes, function(o) {
2876 return o.nodeName.toUpperCase() === 'OPTION';
2877 });
2878 for (_j = 0, _len1 = sub_options.length; _j < _len1; _j++) {
2879 sub_opt = sub_options[_j];
2880 flattened_options.push(sub_opt);
2881 }
2882 }
2883 }
2884 return flattened_options;
2885 };
2886
2887 CSFAbstractChosenOrder.isValidMultipleSelectElement = function(element) {
2888 return element !== null && typeof element !== "undefined" && element.nodeName === "SELECT" && element.multiple;
2889 };
2890
2891 CSFAbstractChosenOrder.getChosenUIContainer = function(select) {
2892 if (select.id !== "") {
2893 return document.getElementById(select.id.replace(/-/g, "_") + "_chosen");
2894 } else {
2895 return this.searchChosenUIContainer(select);
2896 }
2897 };
2898
2899 CSFAbstractChosenOrder.isChosenified = function(select) {
2900 return this.getChosenUIContainer(select) != null;
2901 };
2902
2903 CSFAbstractChosenOrder.forceSelection = function(select, selection) {
2904 var i, opt, options, _ref;
2905 options = this.getFlattenedOptionsAndGroups(select);
2906 i = 0;
2907 while (i < options.length) {
2908 opt = options[i];
2909 if (_ref = opt.getAttribute("value"), __indexOf.call(selection, _ref) >= 0) {
2910 opt.selected = true;
2911 opt.setAttribute("selected", "");
2912 } else {
2913 opt.selected = false;
2914 opt.removeAttribute("selected");
2915 }
2916 i++;
2917 }
2918 return this.triggerEvent(select, "chosen:updated");
2919 };
2920
2921 CSFAbstractChosenOrder.CSFChosenOrder = function(select, order, force) {
2922 var chosen_choices, chosen_options, chosen_ui, i, j, opt, opt_val, option, options, rel, relAttributeName, _i, _j, _len, _len1, _results;
2923 if (this.getDOMElement != null) {
2924 select = this.getDOMElement(select);
2925 }
2926 if (!this.isValidMultipleSelectElement(select)) {
2927 return;
2928 }
2929 chosen_ui = this.getChosenUIContainer(select);
2930 if (chosen_ui == null) {
2931 return;
2932 }
2933 if (order instanceof Array) {
2934 order = order.map(Function.prototype.call, String.prototype.trim);
2935 options = this.getFlattenedOptionsAndGroups(select);
2936 if ((force != null) && force === true) {
2937 this.forceSelection(select, order);
2938 }
2939 _results = [];
2940 for (i = _i = 0, _len = order.length; _i < _len; i = ++_i) {
2941 opt_val = order[i];
2942 rel = null;
2943 for (j = _j = 0, _len1 = options.length; _j < _len1; j = ++_j) {
2944 opt = options[j];
2945 if (opt.value === opt_val) {
2946 rel = j;
2947 }
2948 }
2949 chosen_options = chosen_ui.querySelectorAll('.search-choice');
2950 relAttributeName = this.relAttributeName;
2951 option = Array.prototype.filter.call(chosen_options, function(o) {
2952 return o.querySelector("a.search-choice-close[" + relAttributeName + "=\"" + rel + "\"]") != null;
2953 })[0];
2954 if (option == null) {
2955 continue;
2956 }
2957 chosen_choices = chosen_ui.querySelector("ul.chosen-choices");
2958 _results.push(this.insertAt(option, i, chosen_ui.querySelector('ul.chosen-choices')));
2959 }
2960 return _results;
2961 } else {
2962 return;
2963 }
2964 };
2965
2966 return CSFAbstractChosenOrder;
2967
2968 })();
2969
2970 $ = jQuery;
2971
2972 $.fn.extend({
2973 CSFChosenOrder: function(order, force) {
2974 return _CSFChosenOrder.CSFChosenOrder(this, order, force);
2975 }
2976 });
2977
2978 this._CSFChosenOrder = (function(_super) {
2979 __extends(_CSFChosenOrder, _super);
2980
2981 function _CSFChosenOrder() {
2982 _ref = _CSFChosenOrder.__super__.constructor.apply(this, arguments);
2983 return _ref;
2984 }
2985
2986 _CSFChosenOrder.relAttributeName = 'data-option-array-index';
2987
2988 _CSFChosenOrder.isjQueryObject = function(obj) {
2989 return (typeof jQuery !== "undefined" && jQuery !== null) && obj instanceof jQuery;
2990 };
2991
2992 _CSFChosenOrder.getDOMElement = function(element) {
2993 if (this.isjQueryObject(element)) {
2994 return element.get(0);
2995 } else {
2996 return element;
2997 }
2998 };
2999
3000 _CSFChosenOrder.searchChosenUIContainer = function(element) {
3001 if ($(element).data("chosen") != null) {
3002 return $(element).data("chosen").container[0];
3003 } else {
3004 return $(element).next(".chosen-container.chosen-container-multi").get(0);
3005 }
3006 };
3007
3008 _CSFChosenOrder.triggerEvent = function(target, event_name) {
3009 return $(target).trigger(event_name);
3010 };
3011
3012 return _CSFChosenOrder;
3013
3014 })(CSFAbstractChosenOrder);
3015
3016 }).call(this);
3017 ;(function() {
3018 var $, AbstractChosen, Chosen, SelectParser,
3019 bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
3020 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; },
3021 hasProp = {}.hasOwnProperty;
3022
3023 SelectParser = (function() {
3024 function SelectParser() {
3025 this.options_index = 0;
3026 this.parsed = [];
3027 }
3028
3029 SelectParser.prototype.add_node = function(child) {
3030 if (child.nodeName.toUpperCase() === "OPTGROUP") {
3031 return this.add_group(child);
3032 } else {
3033 return this.add_option(child);
3034 }
3035 };
3036
3037 SelectParser.prototype.add_group = function(group) {
3038 var group_position, i, len, option, ref, results1;
3039 group_position = this.parsed.length;
3040 this.parsed.push({
3041 array_index: group_position,
3042 group: true,
3043 label: group.label,
3044 title: group.title ? group.title : void 0,
3045 children: 0,
3046 disabled: group.disabled,
3047 classes: group.className
3048 });
3049 ref = group.childNodes;
3050 results1 = [];
3051 for (i = 0, len = ref.length; i < len; i++) {
3052 option = ref[i];
3053 results1.push(this.add_option(option, group_position, group.disabled));
3054 }
3055 return results1;
3056 };
3057
3058 SelectParser.prototype.add_option = function(option, group_position, group_disabled) {
3059 if (option.nodeName.toUpperCase() === "OPTION") {
3060 if (option.text !== "") {
3061 if (group_position != null) {
3062 this.parsed[group_position].children += 1;
3063 }
3064 this.parsed.push({
3065 array_index: this.parsed.length,
3066 options_index: this.options_index,
3067 value: option.value,
3068 text: option.text,
3069 html: option.innerHTML,
3070 title: option.title ? option.title : void 0,
3071 selected: option.selected,
3072 disabled: group_disabled === true ? group_disabled : option.disabled,
3073 group_array_index: group_position,
3074 group_label: group_position != null ? this.parsed[group_position].label : null,
3075 classes: option.className,
3076 style: option.style.cssText
3077 });
3078 } else {
3079 this.parsed.push({
3080 array_index: this.parsed.length,
3081 options_index: this.options_index,
3082 empty: true
3083 });
3084 }
3085 return this.options_index += 1;
3086 }
3087 };
3088
3089 return SelectParser;
3090
3091 })();
3092
3093 SelectParser.select_to_array = function(select) {
3094 var child, i, len, parser, ref;
3095 parser = new SelectParser();
3096 ref = select.childNodes;
3097 for (i = 0, len = ref.length; i < len; i++) {
3098 child = ref[i];
3099 parser.add_node(child);
3100 }
3101 return parser.parsed;
3102 };
3103
3104 AbstractChosen = (function() {
3105 function AbstractChosen(form_field, options1) {
3106 this.form_field = form_field;
3107 this.options = options1 != null ? options1 : {};
3108 this.label_click_handler = bind(this.label_click_handler, this);
3109 if (!AbstractChosen.browser_is_supported()) {
3110 return;
3111 }
3112 this.is_multiple = this.form_field.multiple;
3113 this.set_default_text();
3114 this.set_default_values();
3115 this.setup();
3116 this.set_up_html();
3117 this.register_observers();
3118 this.on_ready();
3119 }
3120
3121 AbstractChosen.prototype.set_default_values = function() {
3122 this.click_test_action = (function(_this) {
3123 return function(evt) {
3124 return _this.test_active_click(evt);
3125 };
3126 })(this);
3127 this.activate_action = (function(_this) {
3128 return function(evt) {
3129 return _this.activate_field(evt);
3130 };
3131 })(this);
3132 this.active_field = false;
3133 this.mouse_on_container = false;
3134 this.results_showing = false;
3135 this.result_highlighted = null;
3136 this.is_rtl = this.options.rtl || /\bchosen-rtl\b/.test(this.form_field.className);
3137 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;
3138 this.disable_search_threshold = this.options.disable_search_threshold || 0;
3139 this.disable_search = this.options.disable_search || false;
3140 this.enable_split_word_search = this.options.enable_split_word_search != null ? this.options.enable_split_word_search : true;
3141 this.group_search = this.options.group_search != null ? this.options.group_search : true;
3142 this.search_contains = this.options.search_contains || false;
3143 this.single_backstroke_delete = this.options.single_backstroke_delete != null ? this.options.single_backstroke_delete : true;
3144 this.max_selected_options = this.options.max_selected_options || Infinity;
3145 this.inherit_select_classes = this.options.inherit_select_classes || false;
3146 this.display_selected_options = this.options.display_selected_options != null ? this.options.display_selected_options : true;
3147 this.display_disabled_options = this.options.display_disabled_options != null ? this.options.display_disabled_options : true;
3148 this.include_group_label_in_selected = this.options.include_group_label_in_selected || false;
3149 this.max_shown_results = this.options.max_shown_results || Number.POSITIVE_INFINITY;
3150 this.case_sensitive_search = this.options.case_sensitive_search || false;
3151 return this.hide_results_on_select = this.options.hide_results_on_select != null ? this.options.hide_results_on_select : true;
3152 };
3153
3154 AbstractChosen.prototype.set_default_text = function() {
3155 if (this.form_field.getAttribute("data-placeholder")) {
3156 this.default_text = this.form_field.getAttribute("data-placeholder");
3157 } else if (this.is_multiple) {
3158 this.default_text = this.options.placeholder_text_multiple || this.options.placeholder_text || AbstractChosen.default_multiple_text;
3159 } else {
3160 this.default_text = this.options.placeholder_text_single || this.options.placeholder_text || AbstractChosen.default_single_text;
3161 }
3162 this.default_text = this.escape_html(this.default_text);
3163 return this.results_none_found = this.form_field.getAttribute("data-no_results_text") || this.options.no_results_text || AbstractChosen.default_no_result_text;
3164 };
3165
3166 AbstractChosen.prototype.choice_label = function(item) {
3167 if (this.include_group_label_in_selected && (item.group_label != null)) {
3168 return "<b class='group-name'>" + (this.escape_html(item.group_label)) + "</b>" + item.html;
3169 } else {
3170 return item.html;
3171 }
3172 };
3173
3174 AbstractChosen.prototype.mouse_enter = function() {
3175 return this.mouse_on_container = true;
3176 };
3177
3178 AbstractChosen.prototype.mouse_leave = function() {
3179 return this.mouse_on_container = false;
3180 };
3181
3182 AbstractChosen.prototype.input_focus = function(evt) {
3183 if (this.is_multiple) {
3184 if (!this.active_field) {
3185 return setTimeout(((function(_this) {
3186 return function() {
3187 return _this.container_mousedown();
3188 };
3189 })(this)), 50);
3190 }
3191 } else {
3192 if (!this.active_field) {
3193 return this.activate_field();
3194 }
3195 }
3196 };
3197
3198 AbstractChosen.prototype.input_blur = function(evt) {
3199 if (!this.mouse_on_container) {
3200 this.active_field = false;
3201 return setTimeout(((function(_this) {
3202 return function() {
3203 return _this.blur_test();
3204 };
3205 })(this)), 100);
3206 }
3207 };
3208
3209 AbstractChosen.prototype.label_click_handler = function(evt) {
3210 if (this.is_multiple) {
3211 return this.container_mousedown(evt);
3212 } else {
3213 return this.activate_field();
3214 }
3215 };
3216
3217 AbstractChosen.prototype.results_option_build = function(options) {
3218 var content, data, data_content, i, len, ref, shown_results;
3219 content = '';
3220 shown_results = 0;
3221 ref = this.results_data;
3222 for (i = 0, len = ref.length; i < len; i++) {
3223 data = ref[i];
3224 data_content = '';
3225 if (data.group) {
3226 data_content = this.result_add_group(data);
3227 } else {
3228 data_content = this.result_add_option(data);
3229 }
3230 if (data_content !== '') {
3231 shown_results++;
3232 content += data_content;
3233 }
3234 if (options != null ? options.first : void 0) {
3235 if (data.selected && this.is_multiple) {
3236 this.choice_build(data);
3237 } else if (data.selected && !this.is_multiple) {
3238 this.single_set_selected_text(this.choice_label(data));
3239 }
3240 }
3241 if (shown_results >= this.max_shown_results) {
3242 break;
3243 }
3244 }
3245 return content;
3246 };
3247
3248 AbstractChosen.prototype.result_add_option = function(option) {
3249 var classes, option_el;
3250 if (!option.search_match) {
3251 return '';
3252 }
3253 if (!this.include_option_in_results(option)) {
3254 return '';
3255 }
3256 classes = [];
3257 if (!option.disabled && !(option.selected && this.is_multiple)) {
3258 classes.push("active-result");
3259 }
3260 if (option.disabled && !(option.selected && this.is_multiple)) {
3261 classes.push("disabled-result");
3262 }
3263 if (option.selected) {
3264 classes.push("result-selected");
3265 }
3266 if (option.group_array_index != null) {
3267 classes.push("group-option");
3268 }
3269 if (option.classes !== "") {
3270 classes.push(option.classes);
3271 }
3272 option_el = document.createElement("li");
3273 option_el.className = classes.join(" ");
3274 if (option.style) {
3275 option_el.style.cssText = option.style;
3276 }
3277 option_el.setAttribute("data-option-array-index", option.array_index);
3278 option_el.innerHTML = option.highlighted_html || option.html;
3279 if (option.title) {
3280 option_el.title = option.title;
3281 }
3282 return this.outerHTML(option_el);
3283 };
3284
3285 AbstractChosen.prototype.result_add_group = function(group) {
3286 var classes, group_el;
3287 if (!(group.search_match || group.group_match)) {
3288 return '';
3289 }
3290 if (!(group.active_options > 0)) {
3291 return '';
3292 }
3293 classes = [];
3294 classes.push("group-result");
3295 if (group.classes) {
3296 classes.push(group.classes);
3297 }
3298 group_el = document.createElement("li");
3299 group_el.className = classes.join(" ");
3300 group_el.innerHTML = group.highlighted_html || this.escape_html(group.label);
3301 if (group.title) {
3302 group_el.title = group.title;
3303 }
3304 return this.outerHTML(group_el);
3305 };
3306
3307 AbstractChosen.prototype.results_update_field = function() {
3308 this.set_default_text();
3309 if (!this.is_multiple) {
3310 this.results_reset_cleanup();
3311 }
3312 this.result_clear_highlight();
3313 this.results_build();
3314 if (this.results_showing) {
3315 return this.winnow_results();
3316 }
3317 };
3318
3319 AbstractChosen.prototype.reset_single_select_options = function() {
3320 var i, len, ref, result, results1;
3321 ref = this.results_data;
3322 results1 = [];
3323 for (i = 0, len = ref.length; i < len; i++) {
3324 result = ref[i];
3325 if (result.selected) {
3326 results1.push(result.selected = false);
3327 } else {
3328 results1.push(void 0);
3329 }
3330 }
3331 return results1;
3332 };
3333
3334 AbstractChosen.prototype.results_toggle = function() {
3335 if (this.results_showing) {
3336 return this.results_hide();
3337 } else {
3338 return this.results_show();
3339 }
3340 };
3341
3342 AbstractChosen.prototype.results_search = function(evt) {
3343 if (this.results_showing) {
3344 return this.winnow_results();
3345 } else {
3346 return this.results_show();
3347 }
3348 };
3349
3350 AbstractChosen.prototype.winnow_results = function(options) {
3351 var escapedQuery, fix, i, len, option, prefix, query, ref, regex, results, results_group, search_match, startpos, suffix, text;
3352 this.no_results_clear();
3353 results = 0;
3354 query = this.get_search_text();
3355 escapedQuery = query.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
3356 regex = this.get_search_regex(escapedQuery);
3357 ref = this.results_data;
3358 for (i = 0, len = ref.length; i < len; i++) {
3359 option = ref[i];
3360 option.search_match = false;
3361 results_group = null;
3362 search_match = null;
3363 option.highlighted_html = '';
3364 if (this.include_option_in_results(option)) {
3365 if (option.group) {
3366 option.group_match = false;
3367 option.active_options = 0;
3368 }
3369 if ((option.group_array_index != null) && this.results_data[option.group_array_index]) {
3370 results_group = this.results_data[option.group_array_index];
3371 if (results_group.active_options === 0 && results_group.search_match) {
3372 results += 1;
3373 }
3374 results_group.active_options += 1;
3375 }
3376 text = option.group ? option.label : option.text;
3377 if (!(option.group && !this.group_search)) {
3378 search_match = this.search_string_match(text, regex);
3379 option.search_match = search_match != null;
3380 if (option.search_match && !option.group) {
3381 results += 1;
3382 }
3383 if (option.search_match) {
3384 if (query.length) {
3385 startpos = search_match.index;
3386 prefix = text.slice(0, startpos);
3387 fix = text.slice(startpos, startpos + query.length);
3388 suffix = text.slice(startpos + query.length);
3389 option.highlighted_html = (this.escape_html(prefix)) + "<em>" + (this.escape_html(fix)) + "</em>" + (this.escape_html(suffix));
3390 }
3391 if (results_group != null) {
3392 results_group.group_match = true;
3393 }
3394 } else if ((option.group_array_index != null) && this.results_data[option.group_array_index].search_match) {
3395 option.search_match = true;
3396 }
3397 }
3398 }
3399 }
3400 this.result_clear_highlight();
3401 if (results < 1 && query.length) {
3402 this.update_results_content("");
3403 return this.no_results(query);
3404 } else {
3405 this.update_results_content(this.results_option_build());
3406 if (!(options != null ? options.skip_highlight : void 0)) {
3407 return this.winnow_results_set_highlight();
3408 }
3409 }
3410 };
3411
3412 AbstractChosen.prototype.get_search_regex = function(escaped_search_string) {
3413 var regex_flag, regex_string;
3414 regex_string = this.search_contains ? escaped_search_string : "(^|\\s|\\b)" + escaped_search_string + "[^\\s]*";
3415 if (!(this.enable_split_word_search || this.search_contains)) {
3416 regex_string = "^" + regex_string;
3417 }
3418 regex_flag = this.case_sensitive_search ? "" : "i";
3419 return new RegExp(regex_string, regex_flag);
3420 };
3421
3422 AbstractChosen.prototype.search_string_match = function(search_string, regex) {
3423 var match;
3424 match = regex.exec(search_string);
3425 if (!this.search_contains && (match != null ? match[1] : void 0)) {
3426 match.index += 1;
3427 }
3428 return match;
3429 };
3430
3431 AbstractChosen.prototype.choices_count = function() {
3432 var i, len, option, ref;
3433 if (this.selected_option_count != null) {
3434 return this.selected_option_count;
3435 }
3436 this.selected_option_count = 0;
3437 ref = this.form_field.options;
3438 for (i = 0, len = ref.length; i < len; i++) {
3439 option = ref[i];
3440 if (option.selected) {
3441 this.selected_option_count += 1;
3442 }
3443 }
3444 return this.selected_option_count;
3445 };
3446
3447 AbstractChosen.prototype.choices_click = function(evt) {
3448 evt.preventDefault();
3449 this.activate_field();
3450 if (!(this.results_showing || this.is_disabled)) {
3451 return this.results_show();
3452 }
3453 };
3454
3455 AbstractChosen.prototype.keydown_checker = function(evt) {
3456 var ref, stroke;
3457 stroke = (ref = evt.which) != null ? ref : evt.keyCode;
3458 this.search_field_scale();
3459 if (stroke !== 8 && this.pending_backstroke) {
3460 this.clear_backstroke();
3461 }
3462 switch (stroke) {
3463 case 8:
3464 this.backstroke_length = this.get_search_field_value().length;
3465 break;
3466 case 9:
3467 if (this.results_showing && !this.is_multiple) {
3468 this.result_select(evt);
3469 }
3470 this.mouse_on_container = false;
3471 break;
3472 case 13:
3473 if (this.results_showing) {
3474 evt.preventDefault();
3475 }
3476 break;
3477 case 27:
3478 if (this.results_showing) {
3479 evt.preventDefault();
3480 }
3481 break;
3482 case 32:
3483 if (this.disable_search) {
3484 evt.preventDefault();
3485 }
3486 break;
3487 case 38:
3488 evt.preventDefault();
3489 this.keyup_arrow();
3490 break;
3491 case 40:
3492 evt.preventDefault();
3493 this.keydown_arrow();
3494 break;
3495 }
3496 };
3497
3498 AbstractChosen.prototype.keyup_checker = function(evt) {
3499 var ref, stroke;
3500 stroke = (ref = evt.which) != null ? ref : evt.keyCode;
3501 this.search_field_scale();
3502 switch (stroke) {
3503 case 8:
3504 if (this.is_multiple && this.backstroke_length < 1 && this.choices_count() > 0) {
3505 this.keydown_backstroke();
3506 } else if (!this.pending_backstroke) {
3507 this.result_clear_highlight();
3508 this.results_search();
3509 }
3510 break;
3511 case 13:
3512 evt.preventDefault();
3513 if (this.results_showing) {
3514 this.result_select(evt);
3515 }
3516 break;
3517 case 27:
3518 if (this.results_showing) {
3519 this.results_hide();
3520 }
3521 break;
3522 case 9:
3523 case 16:
3524 case 17:
3525 case 18:
3526 case 38:
3527 case 40:
3528 case 91:
3529 break;
3530 default:
3531 this.results_search();
3532 break;
3533 }
3534 };
3535
3536 AbstractChosen.prototype.clipboard_event_checker = function(evt) {
3537 if (this.is_disabled) {
3538 return;
3539 }
3540 return setTimeout(((function(_this) {
3541 return function() {
3542 return _this.results_search();
3543 };
3544 })(this)), 50);
3545 };
3546
3547 AbstractChosen.prototype.container_width = function() {
3548 if (this.options.width != null) {
3549 return this.options.width;
3550 } else {
3551 return this.form_field.offsetWidth + "px";
3552 }
3553 };
3554
3555 AbstractChosen.prototype.include_option_in_results = function(option) {
3556 if (this.is_multiple && (!this.display_selected_options && option.selected)) {
3557 return false;
3558 }
3559 if (!this.display_disabled_options && option.disabled) {
3560 return false;
3561 }
3562 if (option.empty) {
3563 return false;
3564 }
3565 return true;
3566 };
3567
3568 AbstractChosen.prototype.search_results_touchstart = function(evt) {
3569 this.touch_started = true;
3570 return this.search_results_mouseover(evt);
3571 };
3572
3573 AbstractChosen.prototype.search_results_touchmove = function(evt) {
3574 this.touch_started = false;
3575 return this.search_results_mouseout(evt);
3576 };
3577
3578 AbstractChosen.prototype.search_results_touchend = function(evt) {
3579 if (this.touch_started) {
3580 return this.search_results_mouseup(evt);
3581 }
3582 };
3583
3584 AbstractChosen.prototype.outerHTML = function(element) {
3585 var tmp;
3586 if (element.outerHTML) {
3587 return element.outerHTML;
3588 }
3589 tmp = document.createElement("div");
3590 tmp.appendChild(element);
3591 return tmp.innerHTML;
3592 };
3593
3594 AbstractChosen.prototype.get_single_html = function() {
3595 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>";
3596 };
3597
3598 AbstractChosen.prototype.get_multi_html = function() {
3599 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>";
3600 };
3601
3602 AbstractChosen.prototype.get_no_results_html = function(terms) {
3603 return "<li class=\"no-results\">\n " + this.results_none_found + " <span>" + (this.escape_html(terms)) + "</span>\n</li>";
3604 };
3605
3606 AbstractChosen.browser_is_supported = function() {
3607 if ("Microsoft Internet Explorer" === window.navigator.appName) {
3608 return document.documentMode >= 8;
3609 }
3610 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)) {
3611 return false;
3612 }
3613 return true;
3614 };
3615
3616 AbstractChosen.default_multiple_text = "Select Some Options";
3617
3618 AbstractChosen.default_single_text = "Select an Option";
3619
3620 AbstractChosen.default_no_result_text = "No results match";
3621
3622 return AbstractChosen;
3623
3624 })();
3625
3626 $ = jQuery;
3627
3628 $.fn.extend({
3629 chosen: function(options) {
3630 if (!AbstractChosen.browser_is_supported()) {
3631 return this;
3632 }
3633 return this.each(function(input_field) {
3634 var $this, chosen;
3635 $this = $(this);
3636 chosen = $this.data('chosen');
3637 if (options === 'destroy') {
3638 if (chosen instanceof Chosen) {
3639 chosen.destroy();
3640 }
3641 return;
3642 }
3643 if (!(chosen instanceof Chosen)) {
3644 $this.data('chosen', new Chosen(this, options));
3645 }
3646 });
3647 }
3648 });
3649
3650 Chosen = (function(superClass) {
3651 extend(Chosen, superClass);
3652
3653 function Chosen() {
3654 return Chosen.__super__.constructor.apply(this, arguments);
3655 }
3656
3657 Chosen.prototype.setup = function() {
3658 this.form_field_jq = $(this.form_field);
3659 return this.current_selectedIndex = this.form_field.selectedIndex;
3660 };
3661
3662 Chosen.prototype.set_up_html = function() {
3663 var container_classes, container_props;
3664 container_classes = ["chosen-container"];
3665 container_classes.push("chosen-container-" + (this.is_multiple ? "multi" : "single"));
3666 if (this.inherit_select_classes && this.form_field.className) {
3667 container_classes.push(this.form_field.className);
3668 }
3669 if (this.is_rtl) {
3670 container_classes.push("chosen-rtl");
3671 }
3672 container_props = {
3673 'class': container_classes.join(' '),
3674 'title': this.form_field.title
3675 };
3676 if (this.form_field.id.length) {
3677 container_props.id = this.form_field.id.replace(/[^\w]/g, '_') + "_chosen";
3678 }
3679 this.container = $("<div />", container_props);
3680 this.container.width(this.container_width());
3681 if (this.is_multiple) {
3682 this.container.html(this.get_multi_html());
3683 } else {
3684 this.container.html(this.get_single_html());
3685 }
3686 this.form_field_jq.hide().after(this.container);
3687 this.dropdown = this.container.find('div.chosen-drop').first();
3688 this.search_field = this.container.find('input').first();
3689 this.search_results = this.container.find('ul.chosen-results').first();
3690 this.search_field_scale();
3691 this.search_no_results = this.container.find('li.no-results').first();
3692 if (this.is_multiple) {
3693 this.search_choices = this.container.find('ul.chosen-choices').first();
3694 this.search_container = this.container.find('li.search-field').first();
3695 } else {
3696 this.search_container = this.container.find('div.chosen-search').first();
3697 this.selected_item = this.container.find('.chosen-single').first();
3698 }
3699 this.results_build();
3700 this.set_tab_index();
3701 return this.set_label_behavior();
3702 };
3703
3704 Chosen.prototype.on_ready = function() {
3705 return this.form_field_jq.trigger("chosen:ready", {
3706 chosen: this
3707 });
3708 };
3709
3710 Chosen.prototype.register_observers = function() {
3711 this.container.on('touchstart.chosen', (function(_this) {
3712 return function(evt) {
3713 _this.container_mousedown(evt);
3714 };
3715 })(this));
3716 this.container.on('touchend.chosen', (function(_this) {
3717 return function(evt) {
3718 _this.container_mouseup(evt);
3719 };
3720 })(this));
3721 this.container.on('mousedown.chosen', (function(_this) {
3722 return function(evt) {
3723 _this.container_mousedown(evt);
3724 };
3725 })(this));
3726 this.container.on('mouseup.chosen', (function(_this) {
3727 return function(evt) {
3728 _this.container_mouseup(evt);
3729 };
3730 })(this));
3731 this.container.on('mouseenter.chosen', (function(_this) {
3732 return function(evt) {
3733 _this.mouse_enter(evt);
3734 };
3735 })(this));
3736 this.container.on('mouseleave.chosen', (function(_this) {
3737 return function(evt) {
3738 _this.mouse_leave(evt);
3739 };
3740 })(this));
3741 this.search_results.on('mouseup.chosen', (function(_this) {
3742 return function(evt) {
3743 _this.search_results_mouseup(evt);
3744 };
3745 })(this));
3746 this.search_results.on('mouseover.chosen', (function(_this) {
3747 return function(evt) {
3748 _this.search_results_mouseover(evt);
3749 };
3750 })(this));
3751 this.search_results.on('mouseout.chosen', (function(_this) {
3752 return function(evt) {
3753 _this.search_results_mouseout(evt);
3754 };
3755 })(this));
3756 this.search_results.on('mousewheel.chosen DOMMouseScroll.chosen', (function(_this) {
3757 return function(evt) {
3758 _this.search_results_mousewheel(evt);
3759 };
3760 })(this));
3761 this.search_results.on('touchstart.chosen', (function(_this) {
3762 return function(evt) {
3763 _this.search_results_touchstart(evt);
3764 };
3765 })(this));
3766 this.search_results.on('touchmove.chosen', (function(_this) {
3767 return function(evt) {
3768 _this.search_results_touchmove(evt);
3769 };
3770 })(this));
3771 this.search_results.on('touchend.chosen', (function(_this) {
3772 return function(evt) {
3773 _this.search_results_touchend(evt);
3774 };
3775 })(this));
3776 this.form_field_jq.on("chosen:updated.chosen", (function(_this) {
3777 return function(evt) {
3778 _this.results_update_field(evt);
3779 };
3780 })(this));
3781 this.form_field_jq.on("chosen:activate.chosen", (function(_this) {
3782 return function(evt) {
3783 _this.activate_field(evt);
3784 };
3785 })(this));
3786 this.form_field_jq.on("chosen:open.chosen", (function(_this) {
3787 return function(evt) {
3788 _this.container_mousedown(evt);
3789 };
3790 })(this));
3791 this.form_field_jq.on("chosen:close.chosen", (function(_this) {
3792 return function(evt) {
3793 _this.close_field(evt);
3794 };
3795 })(this));
3796 this.search_field.on('blur.chosen', (function(_this) {
3797 return function(evt) {
3798 _this.input_blur(evt);
3799 };
3800 })(this));
3801 this.search_field.on('keyup.chosen', (function(_this) {
3802 return function(evt) {
3803 _this.keyup_checker(evt);
3804 };
3805 })(this));
3806 this.search_field.on('keydown.chosen', (function(_this) {
3807 return function(evt) {
3808 _this.keydown_checker(evt);
3809 };
3810 })(this));
3811 this.search_field.on('focus.chosen', (function(_this) {
3812 return function(evt) {
3813 _this.input_focus(evt);
3814 };
3815 })(this));
3816 this.search_field.on('cut.chosen', (function(_this) {
3817 return function(evt) {
3818 _this.clipboard_event_checker(evt);
3819 };
3820 })(this));
3821 this.search_field.on('paste.chosen', (function(_this) {
3822 return function(evt) {
3823 _this.clipboard_event_checker(evt);
3824 };
3825 })(this));
3826 if (this.is_multiple) {
3827 return this.search_choices.on('click.chosen', (function(_this) {
3828 return function(evt) {
3829 _this.choices_click(evt);
3830 };
3831 })(this));
3832 } else {
3833 return this.container.on('click.chosen', function(evt) {
3834 evt.preventDefault();
3835 });
3836 }
3837 };
3838
3839 Chosen.prototype.destroy = function() {
3840 $(this.container[0].ownerDocument).off('click.chosen', this.click_test_action);
3841 if (this.form_field_label.length > 0) {
3842 this.form_field_label.off('click.chosen');
3843 }
3844 if (this.search_field[0].tabIndex) {
3845 this.form_field_jq[0].tabIndex = this.search_field[0].tabIndex;
3846 }
3847 this.container.remove();
3848 this.form_field_jq.removeData('chosen');
3849 return this.form_field_jq.show();
3850 };
3851
3852 Chosen.prototype.search_field_disabled = function() {
3853 this.is_disabled = this.form_field.disabled || this.form_field_jq.parents('fieldset').is(':disabled');
3854 this.container.toggleClass('chosen-disabled', this.is_disabled);
3855 this.search_field[0].disabled = this.is_disabled;
3856 if (!this.is_multiple) {
3857 this.selected_item.off('focus.chosen', this.activate_field);
3858 }
3859 if (this.is_disabled) {
3860 return this.close_field();
3861 } else if (!this.is_multiple) {
3862 return this.selected_item.on('focus.chosen', this.activate_field);
3863 }
3864 };
3865
3866 Chosen.prototype.container_mousedown = function(evt) {
3867 var ref;
3868 if (this.is_disabled) {
3869 return;
3870 }
3871 if (evt && ((ref = evt.type) === 'mousedown' || ref === 'touchstart') && !this.results_showing) {
3872 evt.preventDefault();
3873 }
3874 if (!((evt != null) && ($(evt.target)).hasClass("search-choice-close"))) {
3875 if (!this.active_field) {
3876 if (this.is_multiple) {
3877 this.search_field.val("");
3878 }
3879 $(this.container[0].ownerDocument).on('click.chosen', this.click_test_action);
3880 this.results_show();
3881 } else if (!this.is_multiple && evt && (($(evt.target)[0] === this.selected_item[0]) || $(evt.target).parents("a.chosen-single").length)) {
3882 evt.preventDefault();
3883 this.results_toggle();
3884 }
3885 return this.activate_field();
3886 }
3887 };
3888
3889 Chosen.prototype.container_mouseup = function(evt) {
3890 if (evt.target.nodeName === "ABBR" && !this.is_disabled) {
3891 return this.results_reset(evt);
3892 }
3893 };
3894
3895 Chosen.prototype.search_results_mousewheel = function(evt) {
3896 var delta;
3897 if (evt.originalEvent) {
3898 delta = evt.originalEvent.deltaY || -evt.originalEvent.wheelDelta || evt.originalEvent.detail;
3899 }
3900 if (delta != null) {
3901 evt.preventDefault();
3902 if (evt.type === 'DOMMouseScroll') {
3903 delta = delta * 40;
3904 }
3905 return this.search_results.scrollTop(delta + this.search_results.scrollTop());
3906 }
3907 };
3908
3909 Chosen.prototype.blur_test = function(evt) {
3910 if (!this.active_field && this.container.hasClass("chosen-container-active")) {
3911 return this.close_field();
3912 }
3913 };
3914
3915 Chosen.prototype.close_field = function() {
3916 $(this.container[0].ownerDocument).off("click.chosen", this.click_test_action);
3917 this.active_field = false;
3918 this.results_hide();
3919 this.container.removeClass("chosen-container-active");
3920 this.clear_backstroke();
3921 this.show_search_field_default();
3922 this.search_field_scale();
3923 return this.search_field.blur();
3924 };
3925
3926 Chosen.prototype.activate_field = function() {
3927 if (this.is_disabled) {
3928 return;
3929 }
3930 this.container.addClass("chosen-container-active");
3931 this.active_field = true;
3932 this.search_field.val(this.search_field.val());
3933 return this.search_field.focus();
3934 };
3935
3936 Chosen.prototype.test_active_click = function(evt) {
3937 var active_container;
3938 active_container = $(evt.target).closest('.chosen-container');
3939 if (active_container.length && this.container[0] === active_container[0]) {
3940 return this.active_field = true;
3941 } else {
3942 return this.close_field();
3943 }
3944 };
3945
3946 Chosen.prototype.results_build = function() {
3947 this.parsing = true;
3948 this.selected_option_count = null;
3949 this.results_data = SelectParser.select_to_array(this.form_field);
3950 if (this.is_multiple) {
3951 this.search_choices.find("li.search-choice").remove();
3952 } else {
3953 this.single_set_selected_text();
3954 if (this.disable_search || this.form_field.options.length <= this.disable_search_threshold) {
3955 this.search_field[0].readOnly = true;
3956 this.container.addClass("chosen-container-single-nosearch");
3957 } else {
3958 this.search_field[0].readOnly = false;
3959 this.container.removeClass("chosen-container-single-nosearch");
3960 }
3961 }
3962 this.update_results_content(this.results_option_build({
3963 first: true
3964 }));
3965 this.search_field_disabled();
3966 this.show_search_field_default();
3967 this.search_field_scale();
3968 return this.parsing = false;
3969 };
3970
3971 Chosen.prototype.result_do_highlight = function(el) {
3972 var high_bottom, high_top, maxHeight, visible_bottom, visible_top;
3973 if (el.length) {
3974 this.result_clear_highlight();
3975 this.result_highlight = el;
3976 this.result_highlight.addClass("highlighted");
3977 maxHeight = parseInt(this.search_results.css("maxHeight"), 10);
3978 visible_top = this.search_results.scrollTop();
3979 visible_bottom = maxHeight + visible_top;
3980 high_top = this.result_highlight.position().top + this.search_results.scrollTop();
3981 high_bottom = high_top + this.result_highlight.outerHeight();
3982 if (high_bottom >= visible_bottom) {
3983 return this.search_results.scrollTop((high_bottom - maxHeight) > 0 ? high_bottom - maxHeight : 0);
3984 } else if (high_top < visible_top) {
3985 return this.search_results.scrollTop(high_top);
3986 }
3987 }
3988 };
3989
3990 Chosen.prototype.result_clear_highlight = function() {
3991 if (this.result_highlight) {
3992 this.result_highlight.removeClass("highlighted");
3993 }
3994 return this.result_highlight = null;
3995 };
3996
3997 Chosen.prototype.results_show = function() {
3998 if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
3999 this.form_field_jq.trigger("chosen:maxselected", {
4000 chosen: this
4001 });
4002 return false;
4003 }
4004 this.container.addClass("chosen-with-drop");
4005 this.results_showing = true;
4006 this.search_field.focus();
4007 this.search_field.val(this.get_search_field_value());
4008 this.winnow_results();
4009 return this.form_field_jq.trigger("chosen:showing_dropdown", {
4010 chosen: this
4011 });
4012 };
4013
4014 Chosen.prototype.update_results_content = function(content) {
4015 return this.search_results.html(content);
4016 };
4017
4018 Chosen.prototype.results_hide = function() {
4019 if (this.results_showing) {
4020 this.result_clear_highlight();
4021 this.container.removeClass("chosen-with-drop");
4022 this.form_field_jq.trigger("chosen:hiding_dropdown", {
4023 chosen: this
4024 });
4025 }
4026 return this.results_showing = false;
4027 };
4028
4029 Chosen.prototype.set_tab_index = function(el) {
4030 var ti;
4031 if (this.form_field.tabIndex) {
4032 ti = this.form_field.tabIndex;
4033 this.form_field.tabIndex = -1;
4034 return this.search_field[0].tabIndex = ti;
4035 }
4036 };
4037
4038 Chosen.prototype.set_label_behavior = function() {
4039 this.form_field_label = this.form_field_jq.parents("label");
4040 if (!this.form_field_label.length && this.form_field.id.length) {
4041 this.form_field_label = $("label[for='" + this.form_field.id + "']");
4042 }
4043 if (this.form_field_label.length > 0) {
4044 return this.form_field_label.on('click.chosen', this.label_click_handler);
4045 }
4046 };
4047
4048 Chosen.prototype.show_search_field_default = function() {
4049 if (this.is_multiple && this.choices_count() < 1 && !this.active_field) {
4050 this.search_field.val(this.default_text);
4051 return this.search_field.addClass("default");
4052 } else {
4053 this.search_field.val("");
4054 return this.search_field.removeClass("default");
4055 }
4056 };
4057
4058 Chosen.prototype.search_results_mouseup = function(evt) {
4059 var target;
4060 target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
4061 if (target.length) {
4062 this.result_highlight = target;
4063 this.result_select(evt);
4064 return this.search_field.focus();
4065 }
4066 };
4067
4068 Chosen.prototype.search_results_mouseover = function(evt) {
4069 var target;
4070 target = $(evt.target).hasClass("active-result") ? $(evt.target) : $(evt.target).parents(".active-result").first();
4071 if (target) {
4072 return this.result_do_highlight(target);
4073 }
4074 };
4075
4076 Chosen.prototype.search_results_mouseout = function(evt) {
4077 if ($(evt.target).hasClass("active-result") || $(evt.target).parents('.active-result').first()) {
4078 return this.result_clear_highlight();
4079 }
4080 };
4081
4082 Chosen.prototype.choice_build = function(item) {
4083 var choice, close_link;
4084 choice = $('<li />', {
4085 "class": "search-choice"
4086 }).html("<span>" + (this.choice_label(item)) + "</span>");
4087 if (item.disabled) {
4088 choice.addClass('search-choice-disabled');
4089 } else {
4090 close_link = $('<a />', {
4091 "class": 'search-choice-close',
4092 'data-option-array-index': item.array_index
4093 });
4094 close_link.on('click.chosen', (function(_this) {
4095 return function(evt) {
4096 return _this.choice_destroy_link_click(evt);
4097 };
4098 })(this));
4099 choice.append(close_link);
4100 }
4101 return this.search_container.before(choice);
4102 };
4103
4104 Chosen.prototype.choice_destroy_link_click = function(evt) {
4105 evt.preventDefault();
4106 evt.stopPropagation();
4107 if (!this.is_disabled) {
4108 return this.choice_destroy($(evt.target));
4109 }
4110 };
4111
4112 Chosen.prototype.choice_destroy = function(link) {
4113 if (this.result_deselect(link[0].getAttribute("data-option-array-index"))) {
4114 if (this.active_field) {
4115 this.search_field.focus();
4116 } else {
4117 this.show_search_field_default();
4118 }
4119 if (this.is_multiple && this.choices_count() > 0 && this.get_search_field_value().length < 1) {
4120 this.results_hide();
4121 }
4122 link.parents('li').first().remove();
4123 return this.search_field_scale();
4124 }
4125 };
4126
4127 Chosen.prototype.results_reset = function() {
4128 this.reset_single_select_options();
4129 this.form_field.options[0].selected = true;
4130 this.single_set_selected_text();
4131 this.show_search_field_default();
4132 this.results_reset_cleanup();
4133 this.trigger_form_field_change();
4134 if (this.active_field) {
4135 return this.results_hide();
4136 }
4137 };
4138
4139 Chosen.prototype.results_reset_cleanup = function() {
4140 this.current_selectedIndex = this.form_field.selectedIndex;
4141 return this.selected_item.find("abbr").remove();
4142 };
4143
4144 Chosen.prototype.result_select = function(evt) {
4145 var high, item;
4146 if (this.result_highlight) {
4147 high = this.result_highlight;
4148 this.result_clear_highlight();
4149 if (this.is_multiple && this.max_selected_options <= this.choices_count()) {
4150 this.form_field_jq.trigger("chosen:maxselected", {
4151 chosen: this
4152 });
4153 return false;
4154 }
4155 if (this.is_multiple) {
4156 high.removeClass("active-result");
4157 } else {
4158 this.reset_single_select_options();
4159 }
4160 high.addClass("result-selected");
4161 item = this.results_data[high[0].getAttribute("data-option-array-index")];
4162 item.selected = true;
4163 this.form_field.options[item.options_index].selected = true;
4164 this.selected_option_count = null;
4165 if (this.is_multiple) {
4166 this.choice_build(item);
4167 } else {
4168 this.single_set_selected_text(this.choice_label(item));
4169 }
4170 if (this.is_multiple && (!this.hide_results_on_select || (evt.metaKey || evt.ctrlKey))) {
4171 if (evt.metaKey || evt.ctrlKey) {
4172 this.winnow_results({
4173 skip_highlight: true
4174 });
4175 } else {
4176 this.search_field.val("");
4177 this.winnow_results();
4178 }
4179 } else {
4180 this.results_hide();
4181 this.show_search_field_default();
4182 }
4183 if (this.is_multiple || this.form_field.selectedIndex !== this.current_selectedIndex) {
4184 this.trigger_form_field_change({
4185 selected: this.form_field.options[item.options_index].value
4186 });
4187 }
4188 this.current_selectedIndex = this.form_field.selectedIndex;
4189 evt.preventDefault();
4190 return this.search_field_scale();
4191 }
4192 };
4193
4194 Chosen.prototype.single_set_selected_text = function(text) {
4195 if (text == null) {
4196 text = this.default_text;
4197 }
4198 if (text === this.default_text) {
4199 this.selected_item.addClass("chosen-default");
4200 } else {
4201 this.single_deselect_control_build();
4202 this.selected_item.removeClass("chosen-default");
4203 }
4204 return this.selected_item.find("span").html(text);
4205 };
4206
4207 Chosen.prototype.result_deselect = function(pos) {
4208 var result_data;
4209 result_data = this.results_data[pos];
4210 if (!this.form_field.options[result_data.options_index].disabled) {
4211 result_data.selected = false;
4212 this.form_field.options[result_data.options_index].selected = false;
4213 this.selected_option_count = null;
4214 this.result_clear_highlight();
4215 if (this.results_showing) {
4216 this.winnow_results();
4217 }
4218 this.trigger_form_field_change({
4219 deselected: this.form_field.options[result_data.options_index].value
4220 });
4221 this.search_field_scale();
4222 return true;
4223 } else {
4224 return false;
4225 }
4226 };
4227
4228 Chosen.prototype.single_deselect_control_build = function() {
4229 if (!this.allow_single_deselect) {
4230 return;
4231 }
4232 if (!this.selected_item.find("abbr").length) {
4233 this.selected_item.find("span").first().after("<abbr class=\"search-choice-close\"></abbr>");
4234 }
4235 return this.selected_item.addClass("chosen-single-with-deselect");
4236 };
4237
4238 Chosen.prototype.get_search_field_value = function() {
4239 return this.search_field.val();
4240 };
4241
4242 Chosen.prototype.get_search_text = function() {
4243 return $.trim(this.get_search_field_value());
4244 };
4245
4246 Chosen.prototype.escape_html = function(text) {
4247 return $('<div/>').text(text).html();
4248 };
4249
4250 Chosen.prototype.winnow_results_set_highlight = function() {
4251 var do_high, selected_results;
4252 selected_results = !this.is_multiple ? this.search_results.find(".result-selected.active-result") : [];
4253 do_high = selected_results.length ? selected_results.first() : this.search_results.find(".active-result").first();
4254 if (do_high != null) {
4255 return this.result_do_highlight(do_high);
4256 }
4257 };
4258
4259 Chosen.prototype.no_results = function(terms) {
4260 var no_results_html;
4261 no_results_html = this.get_no_results_html(terms);
4262 this.search_results.append(no_results_html);
4263 return this.form_field_jq.trigger("chosen:no_results", {
4264 chosen: this
4265 });
4266 };
4267
4268 Chosen.prototype.no_results_clear = function() {
4269 return this.search_results.find(".no-results").remove();
4270 };
4271
4272 Chosen.prototype.keydown_arrow = function() {
4273 var next_sib;
4274 if (this.results_showing && this.result_highlight) {
4275 next_sib = this.result_highlight.nextAll("li.active-result").first();
4276 if (next_sib) {
4277 return this.result_do_highlight(next_sib);
4278 }
4279 } else {
4280 return this.results_show();
4281 }
4282 };
4283
4284 Chosen.prototype.keyup_arrow = function() {
4285 var prev_sibs;
4286 if (!this.results_showing && !this.is_multiple) {
4287 return this.results_show();
4288 } else if (this.result_highlight) {
4289 prev_sibs = this.result_highlight.prevAll("li.active-result");
4290 if (prev_sibs.length) {
4291 return this.result_do_highlight(prev_sibs.first());
4292 } else {
4293 if (this.choices_count() > 0) {
4294 this.results_hide();
4295 }
4296 return this.result_clear_highlight();
4297 }
4298 }
4299 };
4300
4301 Chosen.prototype.keydown_backstroke = function() {
4302 var next_available_destroy;
4303 if (this.pending_backstroke) {
4304 this.choice_destroy(this.pending_backstroke.find("a").first());
4305 return this.clear_backstroke();
4306 } else {
4307 next_available_destroy = this.search_container.siblings("li.search-choice").last();
4308 if (next_available_destroy.length && !next_available_destroy.hasClass("search-choice-disabled")) {
4309 this.pending_backstroke = next_available_destroy;
4310 if (this.single_backstroke_delete) {
4311 return this.keydown_backstroke();
4312 } else {
4313 return this.pending_backstroke.addClass("search-choice-focus");
4314 }
4315 }
4316 }
4317 };
4318
4319 Chosen.prototype.clear_backstroke = function() {
4320 if (this.pending_backstroke) {
4321 this.pending_backstroke.removeClass("search-choice-focus");
4322 }
4323 return this.pending_backstroke = null;
4324 };
4325
4326 Chosen.prototype.search_field_scale = function() {
4327 var div, i, len, style, style_block, styles, width;
4328 if (!this.is_multiple) {
4329 return;
4330 }
4331 style_block = {
4332 position: 'absolute',
4333 left: '-1000px',
4334 top: '-1000px',
4335 display: 'none',
4336 whiteSpace: 'pre'
4337 };
4338 styles = ['fontSize', 'fontStyle', 'fontWeight', 'fontFamily', 'lineHeight', 'textTransform', 'letterSpacing'];
4339 for (i = 0, len = styles.length; i < len; i++) {
4340 style = styles[i];
4341 style_block[style] = this.search_field.css(style);
4342 }
4343 div = $('<div />').css(style_block);
4344 div.text(this.get_search_field_value());
4345 $('body').append(div);
4346 width = div.width() + 25;
4347 div.remove();
4348 if (this.container.is(':visible')) {
4349 width = Math.min(this.container.outerWidth() - 10, width);
4350 }
4351 return this.search_field.width(width);
4352 };
4353
4354 Chosen.prototype.trigger_form_field_change = function(extra) {
4355 this.form_field_jq.trigger("input", extra);
4356 return this.form_field_jq.trigger("change", extra);
4357 };
4358
4359 return Chosen;
4360
4361 })(AbstractChosen);
4362
4363 }).call(this);
4364 ;/**
4365 *
4366 * jQuery Interdependencies library
4367 * http://miohtama.github.com/jquery-interdependencies/
4368 * Copyright 2012-2013 Mikko Ohtamaa, others
4369 *
4370 * Customized by Codestar
4371 *
4372 */
4373 (function($) {
4374
4375 'use strict';
4376
4377 function Rule(controller, condition, value) {
4378 this.init(controller, condition, value);
4379 }
4380
4381 $.extend(Rule.prototype, {
4382
4383 init: function(controller, condition, value) {
4384
4385 this.controller = controller;
4386 this.condition = condition;
4387 this.value = value;
4388 this.rules = [];
4389 this.controls = [];
4390
4391 },
4392
4393 evalCondition: function(context, control, condition, val1, val2) {
4394
4395 if( condition == '==' ) {
4396
4397 return this.checkBoolean(val1) == this.checkBoolean(val2);
4398
4399 } else if( condition == '!=' ) {
4400
4401 return this.checkBoolean(val1) != this.checkBoolean(val2);
4402
4403 } else if( condition == '>=' ) {
4404
4405 return Number(val2) >= Number(val1);
4406
4407 } else if( condition == '<=' ) {
4408
4409 return Number(val2) <= Number(val1);
4410
4411 } else if( condition == '>' ) {
4412
4413 return Number(val2) > Number(val1);
4414
4415 } else if( condition == '<' ) {
4416
4417 return Number(val2) < Number(val1);
4418
4419 } else if( condition == '()' ) {
4420
4421 return window[val1](context, control, val2);
4422
4423 } else if( condition == 'any' ) {
4424
4425 if( $.isArray( val2 ) ) {
4426 for (var i = val2.length - 1; i >= 0; i--) {
4427 if( $.inArray( val2[i], val1.split(',') ) !== -1 ) {
4428 return true;
4429 }
4430 }
4431 } else {
4432 if( $.inArray( val2, val1.split(',') ) !== -1 ) {
4433 return true;
4434 }
4435 }
4436
4437 } else if( condition == 'not-any' ) {
4438
4439 if( $.isArray( val2 ) ) {
4440 for (var i = val2.length - 1; i >= 0; i--) {
4441 if( $.inArray( val2[i], val1.split(',') ) == -1 ) {
4442 return true;
4443 }
4444 }
4445 } else {
4446 if( $.inArray( val2, val1.split(',') ) == -1 ) {
4447 return true;
4448 }
4449 }
4450
4451 }
4452
4453 return false;
4454
4455 },
4456
4457 checkBoolean: function(value) {
4458
4459 switch( value ) {
4460
4461 case true:
4462 case 'true':
4463 case 1:
4464 case '1':
4465 value = true;
4466 break;
4467
4468 case null:
4469 case false:
4470 case 'false':
4471 case 0:
4472 case '0':
4473 value = false;
4474 break;
4475
4476 }
4477
4478 return value;
4479 },
4480
4481 checkCondition: function( context ) {
4482
4483 if( !this.condition ) {
4484 return true;
4485 }
4486
4487 var control = context.find(this.controller);
4488
4489 var control_value = this.getControlValue(context, control);
4490
4491 if( control_value === undefined ) {
4492 return false;
4493 }
4494
4495 control_value = this.normalizeValue(control, this.value, control_value);
4496
4497 return this.evalCondition(context, control, this.condition, this.value, control_value);
4498 },
4499
4500 normalizeValue: function( control, baseValue, control_value ) {
4501
4502 if( typeof baseValue == 'number' ) {
4503 return parseFloat( control_value );
4504 }
4505
4506 return control_value;
4507 },
4508
4509 getControlValue: function(context, control) {
4510
4511 if( control.length > 1 && ( control.attr('type') == 'radio' || control.attr('type') == 'checkbox' ) ) {
4512
4513 return control.filter(':checked').map(function() { return this.value; }).get();
4514
4515 } else if ( control.attr('type') == 'checkbox' || control.attr('type') == 'radio' ) {
4516
4517 return control.is(':checked');
4518
4519 }
4520
4521 return control.val();
4522
4523 },
4524
4525 createRule: function(controller, condition, value) {
4526 var rule = new Rule(controller, condition, value);
4527 this.rules.push(rule);
4528 return rule;
4529 },
4530
4531 include: function(input) {
4532 this.controls.push(input);
4533 },
4534
4535 applyRule: function(context, enforced) {
4536
4537 var result;
4538
4539 if( typeof( enforced ) == 'undefined' ) {
4540 result = this.checkCondition(context);
4541 } else {
4542 result = enforced;
4543 }
4544
4545 var controls = $.map(this.controls, function(elem, idx) {
4546 return context.find(elem);
4547 });
4548
4549 if( result ) {
4550
4551 $(controls).each(function() {
4552 $(this).removeClass('csf-depend-on');
4553 });
4554
4555 $(this.rules).each(function() {
4556 this.applyRule(context);
4557 });
4558
4559 } else {
4560
4561 $(controls).each(function() {
4562 $(this).addClass('csf-depend-on');
4563 });
4564
4565 $(this.rules).each(function() {
4566 this.applyRule(context, false);
4567 });
4568
4569 }
4570 }
4571 });
4572
4573 function Ruleset() {
4574 this.rules = [];
4575 };
4576
4577 $.extend(Ruleset.prototype, {
4578
4579 createRule: function(controller, condition, value) {
4580 var rule = new Rule(controller, condition, value);
4581 this.rules.push(rule);
4582 return rule;
4583 },
4584
4585 applyRules: function(context) {
4586 $(this.rules).each(function() {
4587 this.applyRule(context);
4588 });
4589 }
4590 });
4591
4592 $.csf_deps = {
4593
4594 createRuleset: function() {
4595 return new Ruleset();
4596 },
4597
4598 enable: function(selection, ruleset, depends) {
4599
4600 selection.on('change keyup', function(elem) {
4601
4602 var depend_id = elem.target.getAttribute('data-depend-id') || elem.target.getAttribute('data-sub-depend-id');
4603
4604 if( depends.indexOf( depend_id ) !== -1 ) {
4605 ruleset.applyRules(selection);
4606 }
4607
4608 });
4609
4610 ruleset.applyRules(selection);
4611
4612 return true;
4613 }
4614 };
4615
4616 })(jQuery);
4617 ;/**
4618 *
4619 * jQuery serializeObject
4620 *
4621 * @copyright 2014, macek <paulmacek@gmail.com>
4622 * @link https://github.com/macek/jquery-serialize-object
4623 * @license BSD
4624 * @version 2.5.0
4625 *
4626 * Customized by Codestar
4627 *
4628 */
4629 (function(root, factory) {
4630
4631 // AMD
4632 if (typeof define === "function" && define.amd) {
4633 define(["exports", "jquery"], function(exports, $) {
4634 return factory(exports, $);
4635 });
4636 }
4637
4638 // CommonJS
4639 else if (typeof exports !== "undefined") {
4640 var $ = require("jquery");
4641 factory(exports, $);
4642 }
4643
4644 // Browser
4645 else {
4646 factory(root, (root.jQuery || root.Zepto || root.ender || root.$));
4647 }
4648
4649 }(this, function(exports, $) {
4650
4651 //
4652 // Codestar: Added custom patterns for spesific validate
4653 //
4654 var patterns = {
4655 validate: /^(?!(_nonce|_pseudo))[a-zA-Z0-9_-]*(?:\[(?:\d*|(?!(_nonce|_pseudo))[a-zA-Z0-9_-]+)\])*$/i,
4656 key: /[a-zA-Z0-9_-]+|(?=\[\])/g,
4657 named: /^[a-zA-Z0-9_-]+$/,
4658 push: /^$/,
4659 fixed: /^\d+$/
4660 };
4661
4662 function FormSerializer(helper, $form) {
4663
4664 // private variables
4665 var data = {},
4666 pushes = {};
4667
4668 // private API
4669 function build(base, key, value) {
4670 base[key] = value;
4671 return base;
4672 }
4673
4674 function makeObject(root, value) {
4675
4676 var keys = root.match(patterns.key), k;
4677
4678 // nest, nest, ..., nest
4679 while ((k = keys.pop()) !== undefined) {
4680 // foo[]
4681 if (patterns.push.test(k)) {
4682 var idx = incrementPush(root.replace(/\[\]$/, ''));
4683 value = build([], idx, value);
4684 }
4685
4686 // foo[n]
4687 else if (patterns.fixed.test(k)) {
4688 value = build([], k, value);
4689 }
4690
4691 // foo; foo[bar]
4692 else if (patterns.named.test(k)) {
4693 value = build({}, k, value);
4694 }
4695 }
4696
4697 return value;
4698 }
4699
4700 function incrementPush(key) {
4701 if (pushes[key] === undefined) {
4702 pushes[key] = 0;
4703 }
4704 return pushes[key]++;
4705 }
4706
4707 function addPair(pair) {
4708 if (!patterns.validate.test(pair.name)) return this;
4709 var obj = makeObject(pair.name, pair.value);
4710 data = helper.extend(true, data, obj);
4711 return this;
4712 }
4713
4714 function addPairs(pairs) {
4715 if (!helper.isArray(pairs)) {
4716 throw new Error("formSerializer.addPairs expects an Array");
4717 }
4718 for (var i=0, len=pairs.length; i<len; i++) {
4719 this.addPair(pairs[i]);
4720 }
4721 return this;
4722 }
4723
4724 function serialize() {
4725 return data;
4726 }
4727
4728 function serializeJSON() {
4729 return JSON.stringify(serialize());
4730 }
4731
4732 // public API
4733 this.addPair = addPair;
4734 this.addPairs = addPairs;
4735 this.serialize = serialize;
4736 this.serializeJSON = serializeJSON;
4737 }
4738
4739 FormSerializer.patterns = patterns;
4740
4741 FormSerializer.serializeObject = function serializeObject() {
4742 return new FormSerializer($, this).
4743 addPairs(this.serializeArray()).
4744 serialize();
4745 };
4746
4747 FormSerializer.serializeJSON = function serializeJSON() {
4748 return new FormSerializer($, this).
4749 addPairs(this.serializeArray()).
4750 serializeJSON();
4751 };
4752
4753 //
4754 // Codestar: Renamed function names for avoid conflicts
4755 //
4756
4757 if (typeof $.fn !== "undefined") {
4758 $.fn.serializeObjectCSF = FormSerializer.serializeObject;
4759 $.fn.serializeJSONCSF = FormSerializer.serializeJSON;
4760 }
4761
4762 exports.FormSerializer = FormSerializer;
4763
4764 return FormSerializer;
4765 }));
4766