window.kentico = window.kentico || {};
window.kentico._forms = window.kentico._forms || {};
window.kentico._forms.formFileUploaderComponent = (function (document) {

    function disableElements(form) {
        form.fileUploaderDisabledElements = [];
        var elements = form.elements;
        for (var i = 0; i < elements.length; i++) {
            var element = elements[i];
            if (!element.disabled) {
                form.fileUploaderDisabledElements.push(i);
                element.disabled = true;
            }
        }
    }

    function enableElements(form) {
        form.fileUploaderDisabledElements.forEach(function (disabledElement) {
            form.elements[disabledElement].disabled = false;
        });
    }

    function clearTempFile(fileInput, inputReplacementFilename, inputPlaceholder, tempFileIdentifierInput, tempFileOriginalNameInput, inputTextButton, inputIconButton) {
        fileInput.value = null;
        fileInput.removeAttribute("hidden");
        inputReplacementFilename.setAttribute("hidden", "hidden");

        inputPlaceholder.innerText = inputPlaceholder.originalText;
        tempFileIdentifierInput.value = "";
        tempFileOriginalNameInput.value = "";

        inputTextButton.setAttribute("hidden", "hidden");
        inputIconButton.setAttribute("data-icon", "select");
        inputIconButton.removeAttribute("title");
    }

    function attachScript(config) {
        var fileInput = document.getElementById(config.fileInputId);
        var inputPlaceholder = document.getElementById(config.fileInputId + "-placeholder");
        var inputReplacementFilename = document.getElementById(config.fileInputId + "-replacement");
        var inputTextButton = document.getElementById(config.fileInputId + "-button");
        var inputIconButton = document.getElementById(config.fileInputId + "-icon");

        var tempFileIdentifierInput = document.getElementById(config.tempFileIdentifierInputId);
        var tempFileOriginalNameInput = document.getElementById(config.tempFileOriginalNameInputId);
        var systemFileNameInput = document.getElementById(config.systemFileNameInputId);
        var originalFileNameInput = document.getElementById(config.originalFileNameInputId);
        var deletePersistentFileInput = document.getElementById(config.deletePersistentFileInputId);

        var deleteFileIconButtonTitle = config.deleteFileIconButtonTitle;

        inputPlaceholder.originalText = inputPlaceholder.innerText;
        inputTextButton.originalText = inputTextButton.innerText;

        // If a file is selected, set text of the label and file input replacement to its filename.
        if (tempFileOriginalNameInput.value || (originalFileNameInput.value && deletePersistentFileInput.value.toUpperCase() === "FALSE")) {
            inputPlaceholder.innerText = tempFileOriginalNameInput.value || config.originalFileNamePlain;

            inputTextButton.removeAttribute("hidden");
            inputIconButton.setAttribute("data-icon", "remove");
            inputIconButton.setAttribute("title", deleteFileIconButtonTitle);

            inputReplacementFilename.removeAttribute("hidden");
            fileInput.setAttribute("hidden", "hidden");
        }

        // If file has not yet been persisted, send a request to delete it.
        var deleteTempFile = function () {
            if (tempFileIdentifierInput.value) {
                var deleteRequest = new XMLHttpRequest();

                deleteRequest.open("POST", config.deleteEndpoint + "&tempFileIdentifier=" + tempFileIdentifierInput.value);
                deleteRequest.send();
            }
        };
        // Deletes both permanent and temp files.
        var deleteFile = function () {
            if (systemFileNameInput.value) {
                deletePersistentFileInput.value = true;
            }

            deleteTempFile();

            clearTempFile(fileInput, inputReplacementFilename, inputPlaceholder, tempFileIdentifierInput, tempFileOriginalNameInput, inputTextButton, inputIconButton);
        };
        // Wrapper for the deleteFile function used when the icon button is clicked.
        var deleteFileIcon = function (event) {
            if (inputIconButton.getAttribute("data-icon") === "remove") {
                event.preventDefault();
                deleteFile();
            }
        };

        inputTextButton.addEventListener("click", deleteFile);
        inputIconButton.addEventListener("click", deleteFileIcon);

        fileInput.addEventListener("change", function () {
            // In IE11 change fires also when setting fileInput value to null.
            if (!fileInput.value) {
                return;
            }

            inputTextButton.removeAttribute("hidden");
            inputIconButton.setAttribute("data-icon", "loading");
            disableElements(fileInput.form);

            // Validate file size.
            var file = fileInput.files[0];
            if (file !== undefined) {
                if (file.size > config.maxFileSize * 1024) {

                    fileInput.value = null;
                    tempFileIdentifierInput.value = "";
                    originalFileNameInput = "";

                    window.alert(config.maxFileSizeExceededErrorMessage);
                    enableElements(fileInput.form);
                    inputIconButton.setAttribute("data-icon", "select");

                    return;
                }
            }

            var data = new FormData();
            var submitRequest = new XMLHttpRequest();
            submitRequest.contentType = "multipart/form-data";

            data.append("file", file);

            submitRequest.addEventListener("load", function (e) {
                if (submitRequest.readyState === 4) {
                    if (submitRequest.status === 200) {
                        var result = submitRequest.response;
                        // IE11 and Edge do not support response type 'json'
                        if (typeof result === "string") {
                            result = JSON.parse(result);
                        }

                        if (result.errorMessage) {
                            fileInput.value = null;
                            alert(result.errorMessage);

                            inputIconButton.setAttribute("data-icon", "select");
                            inputTextButton.setAttribute("hidden", "hidden");
                        } else {
                            if (systemFileNameInput.value) {
                                deletePersistentFileInput.value = true;
                            }
                            deleteTempFile();

                            var filename = fileInput.files[0].name;

                            tempFileIdentifierInput.value = result.fileIdentifier;
                            tempFileOriginalNameInput.value = filename;

                            inputPlaceholder.innerText = filename;
                            inputTextButton.removeAttribute("hidden");
                            inputIconButton.setAttribute("data-icon", "remove");
                            inputIconButton.setAttribute("title", deleteFileIconButtonTitle);

                            inputReplacementFilename.innerText = filename;
                            inputReplacementFilename.removeAttribute("hidden");
                            fileInput.setAttribute("hidden", "hidden");
                        }
                    } else {
                        alert("Error sending file: " + submitRequest.statusText);

                        inputIconButton.setAttribute("data-icon", "select");
                        inputTextButton.setAttribute("hidden", "hidden");
                    }

                    inputTextButton.innerHTML = inputTextButton.originalText;
                    enableElements(fileInput.form);
                }
            });

            submitRequest.upload.addEventListener("progress", function (event) {
                inputTextButton.innerText = parseInt(event.loaded / event.total * 100) + "%";
            });

            submitRequest.open("POST", config.submitEndpoint);
            submitRequest.responseType = "json";
            submitRequest.send(data);
        });
    }

    return {
        attachScript: attachScript
    };
}(document));

/*!
* dependencyLibs/inputmask.dependencyLib.js
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2019 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 4.0.9
*/

(function(factory) {
    if (typeof define === "function" && define.amd) {
        define([ "../global/window" ], factory);
    } else if (typeof exports === "object") {
        module.exports = factory(require("../global/window"));
    } else {
        window.dependencyLib = factory(window);
    }
})(function(window) {
    var document = window.document;
    function indexOf(list, elem) {
        var i = 0, len = list.length;
        for (;i < len; i++) {
            if (list[i] === elem) {
                return i;
            }
        }
        return -1;
    }
    function isWindow(obj) {
        return obj != null && obj === obj.window;
    }
    function isArraylike(obj) {
        var length = "length" in obj && obj.length, ltype = typeof obj;
        if (ltype === "function" || isWindow(obj)) {
            return false;
        }
        if (obj.nodeType === 1 && length) {
            return true;
        }
        return ltype === "array" || length === 0 || typeof length === "number" && length > 0 && length - 1 in obj;
    }
    function isValidElement(elem) {
        return elem instanceof Element;
    }
    function DependencyLib(elem) {
        if (elem instanceof DependencyLib) {
            return elem;
        }
        if (!(this instanceof DependencyLib)) {
            return new DependencyLib(elem);
        }
        if (elem !== undefined && elem !== null && elem !== window) {
            this[0] = elem.nodeName ? elem : elem[0] !== undefined && elem[0].nodeName ? elem[0] : document.querySelector(elem);
            if (this[0] !== undefined && this[0] !== null) {
                this[0].eventRegistry = this[0].eventRegistry || {};
            }
        }
    }
    function getWindow(elem) {
        return isWindow(elem) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false;
    }
    DependencyLib.prototype = {
        on: function(events, handler) {
            if (isValidElement(this[0])) {
                var eventRegistry = this[0].eventRegistry, elem = this[0];
                var addEvent = function(ev, namespace) {
                    if (elem.addEventListener) {
                        elem.addEventListener(ev, handler, false);
                    } else if (elem.attachEvent) {
                        elem.attachEvent("on" + ev, handler);
                    }
                    eventRegistry[ev] = eventRegistry[ev] || {};
                    eventRegistry[ev][namespace] = eventRegistry[ev][namespace] || [];
                    eventRegistry[ev][namespace].push(handler);
                };
                var _events = events.split(" ");
                for (var endx = 0; endx < _events.length; endx++) {
                    var nsEvent = _events[endx].split("."), ev = nsEvent[0], namespace = nsEvent[1] || "global";
                    addEvent(ev, namespace);
                }
            }
            return this;
        },
        off: function(events, handler) {
            if (isValidElement(this[0])) {
                var eventRegistry = this[0].eventRegistry, elem = this[0];
                var removeEvent = function(ev, namespace, handler) {
                    if (ev in eventRegistry === true) {
                        if (elem.removeEventListener) {
                            elem.removeEventListener(ev, handler, false);
                        } else if (elem.detachEvent) {
                            elem.detachEvent("on" + ev, handler);
                        }
                        if (namespace === "global") {
                            for (var nmsp in eventRegistry[ev]) {
                                eventRegistry[ev][nmsp].splice(eventRegistry[ev][nmsp].indexOf(handler), 1);
                            }
                        } else {
                            eventRegistry[ev][namespace].splice(eventRegistry[ev][namespace].indexOf(handler), 1);
                        }
                    }
                };
                var resolveNamespace = function(ev, namespace) {
                    var evts = [], hndx, hndL;
                    if (ev.length > 0) {
                        if (handler === undefined) {
                            for (hndx = 0, hndL = eventRegistry[ev][namespace].length; hndx < hndL; hndx++) {
                                evts.push({
                                    ev: ev,
                                    namespace: namespace && namespace.length > 0 ? namespace : "global",
                                    handler: eventRegistry[ev][namespace][hndx]
                                });
                            }
                        } else {
                            evts.push({
                                ev: ev,
                                namespace: namespace && namespace.length > 0 ? namespace : "global",
                                handler: handler
                            });
                        }
                    } else if (namespace.length > 0) {
                        for (var evNdx in eventRegistry) {
                            for (var nmsp in eventRegistry[evNdx]) {
                                if (nmsp === namespace) {
                                    if (handler === undefined) {
                                        for (hndx = 0, hndL = eventRegistry[evNdx][nmsp].length; hndx < hndL; hndx++) {
                                            evts.push({
                                                ev: evNdx,
                                                namespace: nmsp,
                                                handler: eventRegistry[evNdx][nmsp][hndx]
                                            });
                                        }
                                    } else {
                                        evts.push({
                                            ev: evNdx,
                                            namespace: nmsp,
                                            handler: handler
                                        });
                                    }
                                }
                            }
                        }
                    }
                    return evts;
                };
                var _events = events.split(" ");
                for (var endx = 0; endx < _events.length; endx++) {
                    var nsEvent = _events[endx].split("."), offEvents = resolveNamespace(nsEvent[0], nsEvent[1]);
                    for (var i = 0, offEventsL = offEvents.length; i < offEventsL; i++) {
                        removeEvent(offEvents[i].ev, offEvents[i].namespace, offEvents[i].handler);
                    }
                }
            }
            return this;
        },
        trigger: function(events) {
            if (isValidElement(this[0])) {
                var eventRegistry = this[0].eventRegistry, elem = this[0];
                var _events = typeof events === "string" ? events.split(" ") : [ events.type ];
                for (var endx = 0; endx < _events.length; endx++) {
                    var nsEvent = _events[endx].split("."), ev = nsEvent[0], namespace = nsEvent[1] || "global";
                    if (document !== undefined && namespace === "global") {
                        var evnt, i, params = {
                            bubbles: true,
                            cancelable: true,
                            detail: arguments[1]
                        };
                        if (document.createEvent) {
                            try {
                                evnt = new CustomEvent(ev, params);
                            } catch (e) {
                                evnt = document.createEvent("CustomEvent");
                                evnt.initCustomEvent(ev, params.bubbles, params.cancelable, params.detail);
                            }
                            if (events.type) DependencyLib.extend(evnt, events);
                            elem.dispatchEvent(evnt);
                        } else {
                            evnt = document.createEventObject();
                            evnt.eventType = ev;
                            evnt.detail = arguments[1];
                            if (events.type) DependencyLib.extend(evnt, events);
                            elem.fireEvent("on" + evnt.eventType, evnt);
                        }
                    } else if (eventRegistry[ev] !== undefined) {
                        arguments[0] = arguments[0].type ? arguments[0] : DependencyLib.Event(arguments[0]);
                        if (namespace === "global") {
                            for (var nmsp in eventRegistry[ev]) {
                                for (i = 0; i < eventRegistry[ev][nmsp].length; i++) {
                                    eventRegistry[ev][nmsp][i].apply(elem, arguments);
                                }
                            }
                        } else {
                            for (i = 0; i < eventRegistry[ev][namespace].length; i++) {
                                eventRegistry[ev][namespace][i].apply(elem, arguments);
                            }
                        }
                    }
                }
            }
            return this;
        }
    };
    DependencyLib.isFunction = function(obj) {
        return typeof obj === "function";
    };
    DependencyLib.noop = function() {};
    DependencyLib.isArray = Array.isArray;
    DependencyLib.inArray = function(elem, arr, i) {
        return arr == null ? -1 : indexOf(arr, elem, i);
    };
    DependencyLib.valHooks = undefined;
    DependencyLib.isPlainObject = function(obj) {
        if (typeof obj !== "object" || obj.nodeType || isWindow(obj)) {
            return false;
        }
        if (obj.constructor && !Object.hasOwnProperty.call(obj.constructor.prototype, "isPrototypeOf")) {
            return false;
        }
        return true;
    };
    DependencyLib.extend = function() {
        var options, name, src, copy, copyIsArray, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false;
        if (typeof target === "boolean") {
            deep = target;
            target = arguments[i] || {};
            i++;
        }
        if (typeof target !== "object" && !DependencyLib.isFunction(target)) {
            target = {};
        }
        if (i === length) {
            target = this;
            i--;
        }
        for (;i < length; i++) {
            if ((options = arguments[i]) != null) {
                for (name in options) {
                    src = target[name];
                    copy = options[name];
                    if (target === copy) {
                        continue;
                    }
                    if (deep && copy && (DependencyLib.isPlainObject(copy) || (copyIsArray = DependencyLib.isArray(copy)))) {
                        if (copyIsArray) {
                            copyIsArray = false;
                            clone = src && DependencyLib.isArray(src) ? src : [];
                        } else {
                            clone = src && DependencyLib.isPlainObject(src) ? src : {};
                        }
                        target[name] = DependencyLib.extend(deep, clone, copy);
                    } else if (copy !== undefined) {
                        target[name] = copy;
                    }
                }
            }
        }
        return target;
    };
    DependencyLib.each = function(obj, callback) {
        var value, i = 0;
        if (isArraylike(obj)) {
            for (var length = obj.length; i < length; i++) {
                value = callback.call(obj[i], i, obj[i]);
                if (value === false) {
                    break;
                }
            }
        } else {
            for (i in obj) {
                value = callback.call(obj[i], i, obj[i]);
                if (value === false) {
                    break;
                }
            }
        }
        return obj;
    };
    DependencyLib.data = function(owner, key, value) {
        if (value === undefined) {
            return owner.__data ? owner.__data[key] : null;
        } else {
            owner.__data = owner.__data || {};
            owner.__data[key] = value;
        }
    };
    if (typeof window.CustomEvent === "function") {
        DependencyLib.Event = window.CustomEvent;
    } else {
        DependencyLib.Event = function(event, params) {
            params = params || {
                bubbles: false,
                cancelable: false,
                detail: undefined
            };
            var evt = document.createEvent("CustomEvent");
            evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
            return evt;
        };
        DependencyLib.Event.prototype = window.Event.prototype;
    }
    return DependencyLib;
});
/*!
* inputmask.js
* https://github.com/RobinHerbots/Inputmask
* Copyright (c) 2010 - 2019 Robin Herbots
* Licensed under the MIT license (http://www.opensource.org/licenses/mit-license.php)
* Version: 4.0.9
*/

(function(factory) {
    if (typeof define === "function" && define.amd) {
        define([ "./dependencyLibs/inputmask.dependencyLib", "./global/window" ], factory);
    } else if (typeof exports === "object") {
        module.exports = factory(require("./dependencyLibs/inputmask.dependencyLib"), require("./global/window"));
    } else {
        window.Inputmask = factory(window.dependencyLib || jQuery, window);
    }
})(function($, window, undefined) {
    var document = window.document, ua = navigator.userAgent, ie = ua.indexOf("MSIE ") > 0 || ua.indexOf("Trident/") > 0, mobile = isInputEventSupported("touchstart"), iemobile = /iemobile/i.test(ua), iphone = /iphone/i.test(ua) && !iemobile;
    function Inputmask(alias, options, internal) {
        if (!(this instanceof Inputmask)) {
            return new Inputmask(alias, options, internal);
        }
        this.el = undefined;
        this.events = {};
        this.maskset = undefined;
        this.refreshValue = false;
        if (internal !== true) {
            if ($.isPlainObject(alias)) {
                options = alias;
            } else {
                options = options || {};
                if (alias) options.alias = alias;
            }
            this.opts = $.extend(true, {}, this.defaults, options);
            this.noMasksCache = options && options.definitions !== undefined;
            this.userOptions = options || {};
            this.isRTL = this.opts.numericInput;
            resolveAlias(this.opts.alias, options, this.opts);
        }
    }
    Inputmask.prototype = {
        dataAttribute: "data-inputmask",
        defaults: {
            placeholder: "_",
            optionalmarker: [ "[", "]" ],
            quantifiermarker: [ "{", "}" ],
            groupmarker: [ "(", ")" ],
            alternatormarker: "|",
            escapeChar: "\\",
            mask: null,
            regex: null,
            oncomplete: $.noop,
            onincomplete: $.noop,
            oncleared: $.noop,
            repeat: 0,
            greedy: false,
            autoUnmask: false,
            removeMaskOnSubmit: false,
            clearMaskOnLostFocus: true,
            insertMode: true,
            clearIncomplete: false,
            alias: null,
            onKeyDown: $.noop,
            onBeforeMask: null,
            onBeforePaste: function(pastedValue, opts) {
                return $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(this, pastedValue, opts) : pastedValue;
            },
            onBeforeWrite: null,
            onUnMask: null,
            showMaskOnFocus: true,
            showMaskOnHover: true,
            onKeyValidation: $.noop,
            skipOptionalPartCharacter: " ",
            numericInput: false,
            rightAlign: false,
            undoOnEscape: true,
            radixPoint: "",
            _radixDance: false,
            groupSeparator: "",
            keepStatic: null,
            positionCaretOnTab: true,
            tabThrough: false,
            supportsInputType: [ "text", "tel", "url", "password", "search" ],
            ignorables: [ 8, 9, 13, 19, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46, 93, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 0, 229 ],
            isComplete: null,
            preValidation: null,
            postValidation: null,
            staticDefinitionSymbol: undefined,
            jitMasking: false,
            nullable: true,
            inputEventOnly: false,
            noValuePatching: false,
            positionCaretOnClick: "lvp",
            casing: null,
            inputmode: "verbatim",
            colorMask: false,
            disablePredictiveText: false,
            importDataAttributes: true,
            shiftPositions: true
        },
        definitions: {
            9: {
                validator: "[0-9\uff11-\uff19]",
                definitionSymbol: "*"
            },
            a: {
                validator: "[A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]",
                definitionSymbol: "*"
            },
            "*": {
                validator: "[0-9\uff11-\uff19A-Za-z\u0410-\u044f\u0401\u0451\xc0-\xff\xb5]"
            }
        },
        aliases: {},
        masksCache: {},
        mask: function(elems) {
            var that = this;
            function importAttributeOptions(npt, opts, userOptions, dataAttribute) {
                if (opts.importDataAttributes === true) {
                    var attrOptions = npt.getAttribute(dataAttribute), option, dataoptions, optionData, p;
                    var importOption = function(option, optionData) {
                        optionData = optionData !== undefined ? optionData : npt.getAttribute(dataAttribute + "-" + option);
                        if (optionData !== null) {
                            if (typeof optionData === "string") {
                                if (option.indexOf("on") === 0) optionData = window[optionData]; else if (optionData === "false") optionData = false; else if (optionData === "true") optionData = true;
                            }
                            userOptions[option] = optionData;
                        }
                    };
                    if (attrOptions && attrOptions !== "") {
                        attrOptions = attrOptions.replace(/'/g, '"');
                        dataoptions = JSON.parse("{" + attrOptions + "}");
                    }
                    if (dataoptions) {
                        optionData = undefined;
                        for (p in dataoptions) {
                            if (p.toLowerCase() === "alias") {
                                optionData = dataoptions[p];
                                break;
                            }
                        }
                    }
                    importOption("alias", optionData);
                    if (userOptions.alias) {
                        resolveAlias(userOptions.alias, userOptions, opts);
                    }
                    for (option in opts) {
                        if (dataoptions) {
                            optionData = undefined;
                            for (p in dataoptions) {
                                if (p.toLowerCase() === option.toLowerCase()) {
                                    optionData = dataoptions[p];
                                    break;
                                }
                            }
                        }
                        importOption(option, optionData);
                    }
                }
                $.extend(true, opts, userOptions);
                if (npt.dir === "rtl" || opts.rightAlign) {
                    npt.style.textAlign = "right";
                }
                if (npt.dir === "rtl" || opts.numericInput) {
                    npt.dir = "ltr";
                    npt.removeAttribute("dir");
                    opts.isRTL = true;
                }
                return Object.keys(userOptions).length;
            }
            if (typeof elems === "string") {
                elems = document.getElementById(elems) || document.querySelectorAll(elems);
            }
            elems = elems.nodeName ? [ elems ] : elems;
            $.each(elems, function(ndx, el) {
                var scopedOpts = $.extend(true, {}, that.opts);
                if (importAttributeOptions(el, scopedOpts, $.extend(true, {}, that.userOptions), that.dataAttribute)) {
                    var maskset = generateMaskSet(scopedOpts, that.noMasksCache);
                    if (maskset !== undefined) {
                        if (el.inputmask !== undefined) {
                            el.inputmask.opts.autoUnmask = true;
                            el.inputmask.remove();
                        }
                        el.inputmask = new Inputmask(undefined, undefined, true);
                        el.inputmask.opts = scopedOpts;
                        el.inputmask.noMasksCache = that.noMasksCache;
                        el.inputmask.userOptions = $.extend(true, {}, that.userOptions);
                        el.inputmask.isRTL = scopedOpts.isRTL || scopedOpts.numericInput;
                        el.inputmask.el = el;
                        el.inputmask.maskset = maskset;
                        $.data(el, "_inputmask_opts", scopedOpts);
                        maskScope.call(el.inputmask, {
                            action: "mask"
                        });
                    }
                }
            });
            return elems && elems[0] ? elems[0].inputmask || this : this;
        },
        option: function(options, noremask) {
            if (typeof options === "string") {
                return this.opts[options];
            } else if (typeof options === "object") {
                $.extend(this.userOptions, options);
                if (this.el && noremask !== true) {
                    this.mask(this.el);
                }
                return this;
            }
        },
        unmaskedvalue: function(value) {
            this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
            return maskScope.call(this, {
                action: "unmaskedvalue",
                value: value
            });
        },
        remove: function() {
            return maskScope.call(this, {
                action: "remove"
            });
        },
        getemptymask: function() {
            this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
            return maskScope.call(this, {
                action: "getemptymask"
            });
        },
        hasMaskedValue: function() {
            return !this.opts.autoUnmask;
        },
        isComplete: function() {
            this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
            return maskScope.call(this, {
                action: "isComplete"
            });
        },
        getmetadata: function() {
            this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
            return maskScope.call(this, {
                action: "getmetadata"
            });
        },
        isValid: function(value) {
            this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
            return maskScope.call(this, {
                action: "isValid",
                value: value
            });
        },
        format: function(value, metadata) {
            this.maskset = this.maskset || generateMaskSet(this.opts, this.noMasksCache);
            return maskScope.call(this, {
                action: "format",
                value: value,
                metadata: metadata
            });
        },
        setValue: function(value) {
            if (this.el) {
                $(this.el).trigger("setvalue", [ value ]);
            }
        },
        analyseMask: function(mask, regexMask, opts) {
            var tokenizer = /(?:[?*+]|\{[0-9\+\*]+(?:,[0-9\+\*]*)?(?:\|[0-9\+\*]*)?\})|[^.?*+^${[]()|\\]+|./g, regexTokenizer = /\[\^?]?(?:[^\\\]]+|\\[\S\s]?)*]?|\\(?:0(?:[0-3][0-7]{0,2}|[4-7][0-7]?)?|[1-9][0-9]*|x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|c[A-Za-z]|[\S\s]?)|\((?:\?[:=!]?)?|(?:[?*+]|\{[0-9]+(?:,[0-9]*)?\})\??|[^.?*+^${[()|\\]+|./g, escaped = false, currentToken = new MaskToken(), match, m, openenings = [], maskTokens = [], openingToken, currentOpeningToken, alternator, lastMatch, groupToken;
            function MaskToken(isGroup, isOptional, isQuantifier, isAlternator) {
                this.matches = [];
                this.openGroup = isGroup || false;
                this.alternatorGroup = false;
                this.isGroup = isGroup || false;
                this.isOptional = isOptional || false;
                this.isQuantifier = isQuantifier || false;
                this.isAlternator = isAlternator || false;
                this.quantifier = {
                    min: 1,
                    max: 1
                };
            }
            function insertTestDefinition(mtoken, element, position) {
                position = position !== undefined ? position : mtoken.matches.length;
                var prevMatch = mtoken.matches[position - 1];
                if (regexMask) {
                    if (element.indexOf("[") === 0 || escaped && /\\d|\\s|\\w]/i.test(element) || element === ".") {
                        mtoken.matches.splice(position++, 0, {
                            fn: new RegExp(element, opts.casing ? "i" : ""),
                            optionality: false,
                            newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== element,
                            casing: null,
                            def: element,
                            placeholder: undefined,
                            nativeDef: element
                        });
                    } else {
                        if (escaped) element = element[element.length - 1];
                        $.each(element.split(""), function(ndx, lmnt) {
                            prevMatch = mtoken.matches[position - 1];
                            mtoken.matches.splice(position++, 0, {
                                fn: null,
                                optionality: false,
                                newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== lmnt && prevMatch.fn !== null,
                                casing: null,
                                def: opts.staticDefinitionSymbol || lmnt,
                                placeholder: opts.staticDefinitionSymbol !== undefined ? lmnt : undefined,
                                nativeDef: (escaped ? "'" : "") + lmnt
                            });
                        });
                    }
                    escaped = false;
                } else {
                    var maskdef = (opts.definitions ? opts.definitions[element] : undefined) || Inputmask.prototype.definitions[element];
                    if (maskdef && !escaped) {
                        mtoken.matches.splice(position++, 0, {
                            fn: maskdef.validator ? typeof maskdef.validator == "string" ? new RegExp(maskdef.validator, opts.casing ? "i" : "") : new function() {
                                this.test = maskdef.validator;
                            }() : new RegExp("."),
                            optionality: false,
                            newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== (maskdef.definitionSymbol || element),
                            casing: maskdef.casing,
                            def: maskdef.definitionSymbol || element,
                            placeholder: maskdef.placeholder,
                            nativeDef: element
                        });
                    } else {
                        mtoken.matches.splice(position++, 0, {
                            fn: null,
                            optionality: false,
                            newBlockMarker: prevMatch === undefined ? "master" : prevMatch.def !== element && prevMatch.fn !== null,
                            casing: null,
                            def: opts.staticDefinitionSymbol || element,
                            placeholder: opts.staticDefinitionSymbol !== undefined ? element : undefined,
                            nativeDef: (escaped ? "'" : "") + element
                        });
                        escaped = false;
                    }
                }
            }
            function verifyGroupMarker(maskToken) {
                if (maskToken && maskToken.matches) {
                    $.each(maskToken.matches, function(ndx, token) {
                        var nextToken = maskToken.matches[ndx + 1];
                        if ((nextToken === undefined || (nextToken.matches === undefined || nextToken.isQuantifier === false)) && token && token.isGroup) {
                            token.isGroup = false;
                            if (!regexMask) {
                                insertTestDefinition(token, opts.groupmarker[0], 0);
                                if (token.openGroup !== true) {
                                    insertTestDefinition(token, opts.groupmarker[1]);
                                }
                            }
                        }
                        verifyGroupMarker(token);
                    });
                }
            }
            function defaultCase() {
                if (openenings.length > 0) {
                    currentOpeningToken = openenings[openenings.length - 1];
                    insertTestDefinition(currentOpeningToken, m);
                    if (currentOpeningToken.isAlternator) {
                        alternator = openenings.pop();
                        for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
                            if (alternator.matches[mndx].isGroup) alternator.matches[mndx].isGroup = false;
                        }
                        if (openenings.length > 0) {
                            currentOpeningToken = openenings[openenings.length - 1];
                            currentOpeningToken.matches.push(alternator);
                        } else {
                            currentToken.matches.push(alternator);
                        }
                    }
                } else {
                    insertTestDefinition(currentToken, m);
                }
            }
            function reverseTokens(maskToken) {
                function reverseStatic(st) {
                    if (st === opts.optionalmarker[0]) st = opts.optionalmarker[1]; else if (st === opts.optionalmarker[1]) st = opts.optionalmarker[0]; else if (st === opts.groupmarker[0]) st = opts.groupmarker[1]; else if (st === opts.groupmarker[1]) st = opts.groupmarker[0];
                    return st;
                }
                maskToken.matches = maskToken.matches.reverse();
                for (var match in maskToken.matches) {
                    if (maskToken.matches.hasOwnProperty(match)) {
                        var intMatch = parseInt(match);
                        if (maskToken.matches[match].isQuantifier && maskToken.matches[intMatch + 1] && maskToken.matches[intMatch + 1].isGroup) {
                            var qt = maskToken.matches[match];
                            maskToken.matches.splice(match, 1);
                            maskToken.matches.splice(intMatch + 1, 0, qt);
                        }
                        if (maskToken.matches[match].matches !== undefined) {
                            maskToken.matches[match] = reverseTokens(maskToken.matches[match]);
                        } else {
                            maskToken.matches[match] = reverseStatic(maskToken.matches[match]);
                        }
                    }
                }
                return maskToken;
            }
            function groupify(matches) {
                var groupToken = new MaskToken(true);
                groupToken.openGroup = false;
                groupToken.matches = matches;
                return groupToken;
            }
            if (regexMask) {
                opts.optionalmarker[0] = undefined;
                opts.optionalmarker[1] = undefined;
            }
            while (match = regexMask ? regexTokenizer.exec(mask) : tokenizer.exec(mask)) {
                m = match[0];
                if (regexMask) {
                    switch (m.charAt(0)) {
                      case "?":
                        m = "{0,1}";
                        break;

                      case "+":
                      case "*":
                        m = "{" + m + "}";
                        break;
                    }
                }
                if (escaped) {
                    defaultCase();
                    continue;
                }
                switch (m.charAt(0)) {
                  case "(?=":
                    break;

                  case "(?!":
                    break;

                  case "(?<=":
                    break;

                  case "(?<!":
                    break;

                  case opts.escapeChar:
                    escaped = true;
                    if (regexMask) {
                        defaultCase();
                    }
                    break;

                  case opts.optionalmarker[1]:
                  case opts.groupmarker[1]:
                    openingToken = openenings.pop();
                    openingToken.openGroup = false;
                    if (openingToken !== undefined) {
                        if (openenings.length > 0) {
                            currentOpeningToken = openenings[openenings.length - 1];
                            currentOpeningToken.matches.push(openingToken);
                            if (currentOpeningToken.isAlternator) {
                                alternator = openenings.pop();
                                for (var mndx = 0; mndx < alternator.matches.length; mndx++) {
                                    alternator.matches[mndx].isGroup = false;
                                    alternator.matches[mndx].alternatorGroup = false;
                                }
                                if (openenings.length > 0) {
                                    currentOpeningToken = openenings[openenings.length - 1];
                                    currentOpeningToken.matches.push(alternator);
                                } else {
                                    currentToken.matches.push(alternator);
                                }
                            }
                        } else {
                            currentToken.matches.push(openingToken);
                        }
                    } else defaultCase();
                    break;

                  case opts.optionalmarker[0]:
                    openenings.push(new MaskToken(false, true));
                    break;

                  case opts.groupmarker[0]:
                    openenings.push(new MaskToken(true));
                    break;

                  case opts.quantifiermarker[0]:
                    var quantifier = new MaskToken(false, false, true);
                    m = m.replace(/[{}]/g, "");
                    var mqj = m.split("|"), mq = mqj[0].split(","), mq0 = isNaN(mq[0]) ? mq[0] : parseInt(mq[0]), mq1 = mq.length === 1 ? mq0 : isNaN(mq[1]) ? mq[1] : parseInt(mq[1]);
                    if (mq0 === "*" || mq0 === "+") {
                        mq0 = mq1 === "*" ? 0 : 1;
                    }
                    quantifier.quantifier = {
                        min: mq0,
                        max: mq1,
                        jit: mqj[1]
                    };
                    var matches = openenings.length > 0 ? openenings[openenings.length - 1].matches : currentToken.matches;
                    match = matches.pop();
                    if (match.isAlternator) {
                        matches.push(match);
                        matches = match.matches;
                        var groupToken = new MaskToken(true);
                        var tmpMatch = matches.pop();
                        matches.push(groupToken);
                        matches = groupToken.matches;
                        match = tmpMatch;
                    }
                    if (!match.isGroup) {
                        match = groupify([ match ]);
                    }
                    matches.push(match);
                    matches.push(quantifier);
                    break;

                  case opts.alternatormarker:
                    var groupQuantifier = function(matches) {
                        var lastMatch = matches.pop();
                        if (lastMatch.isQuantifier) {
                            lastMatch = groupify([ matches.pop(), lastMatch ]);
                        }
                        return lastMatch;
                    };
                    if (openenings.length > 0) {
                        currentOpeningToken = openenings[openenings.length - 1];
                        var subToken = currentOpeningToken.matches[currentOpeningToken.matches.length - 1];
                        if (currentOpeningToken.openGroup && (subToken.matches === undefined || subToken.isGroup === false && subToken.isAlternator === false)) {
                            lastMatch = openenings.pop();
                        } else {
                            lastMatch = groupQuantifier(currentOpeningToken.matches);
                        }
                    } else {
                        lastMatch = groupQuantifier(currentToken.matches);
                    }
                    if (lastMatch.isAlternator) {
                        openenings.push(lastMatch);
                    } else {
                        if (lastMatch.alternatorGroup) {
                            alternator = openenings.pop();
                            lastMatch.alternatorGroup = false;
                        } else {
                            alternator = new MaskToken(false, false, false, true);
                        }
                        alternator.matches.push(lastMatch);
                        openenings.push(alternator);
                        if (lastMatch.openGroup) {
                            lastMatch.openGroup = false;
                            var alternatorGroup = new MaskToken(true);
                            alternatorGroup.alternatorGroup = true;
                            openenings.push(alternatorGroup);
                        }
                    }
                    break;

                  default:
                    defaultCase();
                }
            }
            while (openenings.length > 0) {
                openingToken = openenings.pop();
                currentToken.matches.push(openingToken);
            }
            if (currentToken.matches.length > 0) {
                verifyGroupMarker(currentToken);
                maskTokens.push(currentToken);
            }
            if (opts.numericInput || opts.isRTL) {
                reverseTokens(maskTokens[0]);
            }
            return maskTokens;
        },
        positionColorMask: function(input, template) {
            input.style.left = template.offsetLeft + "px";
        }
    };
    Inputmask.extendDefaults = function(options) {
        $.extend(true, Inputmask.prototype.defaults, options);
    };
    Inputmask.extendDefinitions = function(definition) {
        $.extend(true, Inputmask.prototype.definitions, definition);
    };
    Inputmask.extendAliases = function(alias) {
        $.extend(true, Inputmask.prototype.aliases, alias);
    };
    Inputmask.format = function(value, options, metadata) {
        return Inputmask(options).format(value, metadata);
    };
    Inputmask.unmask = function(value, options) {
        return Inputmask(options).unmaskedvalue(value);
    };
    Inputmask.isValid = function(value, options) {
        return Inputmask(options).isValid(value);
    };
    Inputmask.remove = function(elems) {
        if (typeof elems === "string") {
            elems = document.getElementById(elems) || document.querySelectorAll(elems);
        }
        elems = elems.nodeName ? [ elems ] : elems;
        $.each(elems, function(ndx, el) {
            if (el.inputmask) el.inputmask.remove();
        });
    };
    Inputmask.setValue = function(elems, value) {
        if (typeof elems === "string") {
            elems = document.getElementById(elems) || document.querySelectorAll(elems);
        }
        elems = elems.nodeName ? [ elems ] : elems;
        $.each(elems, function(ndx, el) {
            if (el.inputmask) el.inputmask.setValue(value); else $(el).trigger("setvalue", [ value ]);
        });
    };
    Inputmask.escapeRegex = function(str) {
        var specials = [ "/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\", "$", "^" ];
        return str.replace(new RegExp("(\\" + specials.join("|\\") + ")", "gim"), "\\$1");
    };
    Inputmask.keyCode = {
        BACKSPACE: 8,
        BACKSPACE_SAFARI: 127,
        DELETE: 46,
        DOWN: 40,
        END: 35,
        ENTER: 13,
        ESCAPE: 27,
        HOME: 36,
        INSERT: 45,
        LEFT: 37,
        PAGE_DOWN: 34,
        PAGE_UP: 33,
        RIGHT: 39,
        SPACE: 32,
        TAB: 9,
        UP: 38,
        X: 88,
        CONTROL: 17
    };
    Inputmask.dependencyLib = $;
    function resolveAlias(aliasStr, options, opts) {
        var aliasDefinition = Inputmask.prototype.aliases[aliasStr];
        if (aliasDefinition) {
            if (aliasDefinition.alias) resolveAlias(aliasDefinition.alias, undefined, opts);
            $.extend(true, opts, aliasDefinition);
            $.extend(true, opts, options);
            return true;
        } else if (opts.mask === null) {
            opts.mask = aliasStr;
        }
        return false;
    }
    function generateMaskSet(opts, nocache) {
        function generateMask(mask, metadata, opts) {
            var regexMask = false;
            if (mask === null || mask === "") {
                regexMask = opts.regex !== null;
                if (regexMask) {
                    mask = opts.regex;
                    mask = mask.replace(/^(\^)(.*)(\$)$/, "$2");
                } else {
                    regexMask = true;
                    mask = ".*";
                }
            }
            if (mask.length === 1 && opts.greedy === false && opts.repeat !== 0) {
                opts.placeholder = "";
            }
            if (opts.repeat > 0 || opts.repeat === "*" || opts.repeat === "+") {
                var repeatStart = opts.repeat === "*" ? 0 : opts.repeat === "+" ? 1 : opts.repeat;
                mask = opts.groupmarker[0] + mask + opts.groupmarker[1] + opts.quantifiermarker[0] + repeatStart + "," + opts.repeat + opts.quantifiermarker[1];
            }
            var masksetDefinition, maskdefKey = regexMask ? "regex_" + opts.regex : opts.numericInput ? mask.split("").reverse().join("") : mask;
            if (Inputmask.prototype.masksCache[maskdefKey] === undefined || nocache === true) {
                masksetDefinition = {
                    mask: mask,
                    maskToken: Inputmask.prototype.analyseMask(mask, regexMask, opts),
                    validPositions: {},
                    _buffer: undefined,
                    buffer: undefined,
                    tests: {},
                    excludes: {},
                    metadata: metadata,
                    maskLength: undefined,
                    jitOffset: {}
                };
                if (nocache !== true) {
                    Inputmask.prototype.masksCache[maskdefKey] = masksetDefinition;
                    masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]);
                }
            } else masksetDefinition = $.extend(true, {}, Inputmask.prototype.masksCache[maskdefKey]);
            return masksetDefinition;
        }
        var ms;
        if ($.isFunction(opts.mask)) {
            opts.mask = opts.mask(opts);
        }
        if ($.isArray(opts.mask)) {
            if (opts.mask.length > 1) {
                if (opts.keepStatic === null) {
                    opts.keepStatic = "auto";
                    for (var i = 0; i < opts.mask.length; i++) {
                        if (opts.mask[i].charAt(0) !== opts.mask[0].charAt(0)) {
                            opts.keepStatic = true;
                            break;
                        }
                    }
                }
                var altMask = opts.groupmarker[0];
                $.each(opts.isRTL ? opts.mask.reverse() : opts.mask, function(ndx, msk) {
                    if (altMask.length > 1) {
                        altMask += opts.groupmarker[1] + opts.alternatormarker + opts.groupmarker[0];
                    }
                    if (msk.mask !== undefined && !$.isFunction(msk.mask)) {
                        altMask += msk.mask;
                    } else {
                        altMask += msk;
                    }
                });
                altMask += opts.groupmarker[1];
                return generateMask(altMask, opts.mask, opts);
            } else opts.mask = opts.mask.pop();
        }
        if (opts.mask && opts.mask.mask !== undefined && !$.isFunction(opts.mask.mask)) {
            ms = generateMask(opts.mask.mask, opts.mask, opts);
        } else {
            ms = generateMask(opts.mask, opts.mask, opts);
        }
        return ms;
    }
    function isInputEventSupported(eventName) {
        var el = document.createElement("input"), evName = "on" + eventName, isSupported = evName in el;
        if (!isSupported) {
            el.setAttribute(evName, "return;");
            isSupported = typeof el[evName] === "function";
        }
        el = null;
        return isSupported;
    }
    function maskScope(actionObj, maskset, opts) {
        maskset = maskset || this.maskset;
        opts = opts || this.opts;
        var inputmask = this, el = this.el, isRTL = this.isRTL, undoValue, $el, skipKeyPressEvent = false, skipInputEvent = false, ignorable = false, maxLength, mouseEnter = false, colorMask, originalPlaceholder;
        var getMaskTemplate = function(baseOnInput, minimalPos, includeMode, noJit, clearOptionalTail) {
            var greedy = opts.greedy;
            if (clearOptionalTail) opts.greedy = false;
            minimalPos = minimalPos || 0;
            var maskTemplate = [], ndxIntlzr, pos = 0, test, testPos, lvp = getLastValidPosition();
            do {
                if (baseOnInput === true && getMaskSet().validPositions[pos]) {
                    testPos = clearOptionalTail && getMaskSet().validPositions[pos].match.optionality === true && getMaskSet().validPositions[pos + 1] === undefined && (getMaskSet().validPositions[pos].generatedInput === true || getMaskSet().validPositions[pos].input == opts.skipOptionalPartCharacter && pos > 0) ? determineTestTemplate(pos, getTests(pos, ndxIntlzr, pos - 1)) : getMaskSet().validPositions[pos];
                    test = testPos.match;
                    ndxIntlzr = testPos.locator.slice();
                    maskTemplate.push(includeMode === true ? testPos.input : includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
                } else {
                    testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
                    test = testPos.match;
                    ndxIntlzr = testPos.locator.slice();
                    var jitMasking = noJit === true ? false : opts.jitMasking !== false ? opts.jitMasking : test.jit;
                    if (jitMasking === false || jitMasking === undefined || typeof jitMasking === "number" && isFinite(jitMasking) && jitMasking > pos) {
                        maskTemplate.push(includeMode === false ? test.nativeDef : getPlaceholder(pos, test));
                    }
                }
                if (opts.keepStatic === "auto") {
                    if (test.newBlockMarker && test.fn !== null) {
                        opts.keepStatic = pos - 1;
                    }
                }
                pos++;
            } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || minimalPos > pos);
            if (maskTemplate[maskTemplate.length - 1] === "") {
                maskTemplate.pop();
            }
            if (includeMode !== false || getMaskSet().maskLength === undefined) getMaskSet().maskLength = pos - 1;
            opts.greedy = greedy;
            return maskTemplate;
        };
        function getMaskSet() {
            return maskset;
        }
        function resetMaskSet(soft) {
            var maskset = getMaskSet();
            maskset.buffer = undefined;
            if (soft !== true) {
                maskset.validPositions = {};
                maskset.p = 0;
            }
        }
        function getLastValidPosition(closestTo, strict, validPositions) {
            var before = -1, after = -1, valids = validPositions || getMaskSet().validPositions;
            if (closestTo === undefined) closestTo = -1;
            for (var posNdx in valids) {
                var psNdx = parseInt(posNdx);
                if (valids[psNdx] && (strict || valids[psNdx].generatedInput !== true)) {
                    if (psNdx <= closestTo) before = psNdx;
                    if (psNdx >= closestTo) after = psNdx;
                }
            }
            return before === -1 || before == closestTo ? after : after == -1 ? before : closestTo - before < after - closestTo ? before : after;
        }
        function getDecisionTaker(tst) {
            var decisionTaker = tst.locator[tst.alternation];
            if (typeof decisionTaker == "string" && decisionTaker.length > 0) {
                decisionTaker = decisionTaker.split(",")[0];
            }
            return decisionTaker !== undefined ? decisionTaker.toString() : "";
        }
        function getLocator(tst, align) {
            var locator = (tst.alternation != undefined ? tst.mloc[getDecisionTaker(tst)] : tst.locator).join("");
            if (locator !== "") while (locator.length < align) locator += "0";
            return locator;
        }
        function determineTestTemplate(pos, tests) {
            pos = pos > 0 ? pos - 1 : 0;
            var altTest = getTest(pos), targetLocator = getLocator(altTest), tstLocator, closest, bestMatch;
            for (var ndx = 0; ndx < tests.length; ndx++) {
                var tst = tests[ndx];
                tstLocator = getLocator(tst, targetLocator.length);
                var distance = Math.abs(tstLocator - targetLocator);
                if (closest === undefined || tstLocator !== "" && distance < closest || bestMatch && !opts.greedy && bestMatch.match.optionality && bestMatch.match.newBlockMarker === "master" && (!tst.match.optionality || !tst.match.newBlockMarker) || bestMatch && bestMatch.match.optionalQuantifier && !tst.match.optionalQuantifier) {
                    closest = distance;
                    bestMatch = tst;
                }
            }
            return bestMatch;
        }
        function getTestTemplate(pos, ndxIntlzr, tstPs) {
            return getMaskSet().validPositions[pos] || determineTestTemplate(pos, getTests(pos, ndxIntlzr ? ndxIntlzr.slice() : ndxIntlzr, tstPs));
        }
        function getTest(pos, tests) {
            if (getMaskSet().validPositions[pos]) {
                return getMaskSet().validPositions[pos];
            }
            return (tests || getTests(pos))[0];
        }
        function positionCanMatchDefinition(pos, def) {
            var valid = false, tests = getTests(pos);
            for (var tndx = 0; tndx < tests.length; tndx++) {
                if (tests[tndx].match && tests[tndx].match.def === def) {
                    valid = true;
                    break;
                }
            }
            return valid;
        }
        function getTests(pos, ndxIntlzr, tstPs) {
            var maskTokens = getMaskSet().maskToken, testPos = ndxIntlzr ? tstPs : 0, ndxInitializer = ndxIntlzr ? ndxIntlzr.slice() : [ 0 ], matches = [], insertStop = false, latestMatch, cacheDependency = ndxIntlzr ? ndxIntlzr.join("") : "";
            function resolveTestFromToken(maskToken, ndxInitializer, loopNdx, quantifierRecurse) {
                function handleMatch(match, loopNdx, quantifierRecurse) {
                    function isFirstMatch(latestMatch, tokenGroup) {
                        var firstMatch = $.inArray(latestMatch, tokenGroup.matches) === 0;
                        if (!firstMatch) {
                            $.each(tokenGroup.matches, function(ndx, match) {
                                if (match.isQuantifier === true) firstMatch = isFirstMatch(latestMatch, tokenGroup.matches[ndx - 1]); else if (match.hasOwnProperty("matches")) firstMatch = isFirstMatch(latestMatch, match);
                                if (firstMatch) return false;
                            });
                        }
                        return firstMatch;
                    }
                    function resolveNdxInitializer(pos, alternateNdx, targetAlternation) {
                        var bestMatch, indexPos;
                        if (getMaskSet().tests[pos] || getMaskSet().validPositions[pos]) {
                            $.each(getMaskSet().tests[pos] || [ getMaskSet().validPositions[pos] ], function(ndx, lmnt) {
                                if (lmnt.mloc[alternateNdx]) {
                                    bestMatch = lmnt;
                                    return false;
                                }
                                var alternation = targetAlternation !== undefined ? targetAlternation : lmnt.alternation, ndxPos = lmnt.locator[alternation] !== undefined ? lmnt.locator[alternation].toString().indexOf(alternateNdx) : -1;
                                if ((indexPos === undefined || ndxPos < indexPos) && ndxPos !== -1) {
                                    bestMatch = lmnt;
                                    indexPos = ndxPos;
                                }
                            });
                        }
                        if (bestMatch) {
                            var bestMatchAltIndex = bestMatch.locator[bestMatch.alternation];
                            var locator = bestMatch.mloc[alternateNdx] || bestMatch.mloc[bestMatchAltIndex] || bestMatch.locator;
                            return locator.slice((targetAlternation !== undefined ? targetAlternation : bestMatch.alternation) + 1);
                        } else {
                            return targetAlternation !== undefined ? resolveNdxInitializer(pos, alternateNdx) : undefined;
                        }
                    }
                    function isSubsetOf(source, target) {
                        function expand(pattern) {
                            var expanded = [], start, end;
                            for (var i = 0, l = pattern.length; i < l; i++) {
                                if (pattern.charAt(i) === "-") {
                                    end = pattern.charCodeAt(i + 1);
                                    while (++start < end) expanded.push(String.fromCharCode(start));
                                } else {
                                    start = pattern.charCodeAt(i);
                                    expanded.push(pattern.charAt(i));
                                }
                            }
                            return expanded.join("");
                        }
                        if (opts.regex && source.match.fn !== null && target.match.fn !== null) {
                            return expand(target.match.def.replace(/[\[\]]/g, "")).indexOf(expand(source.match.def.replace(/[\[\]]/g, ""))) !== -1;
                        }
                        return source.match.def === target.match.nativeDef;
                    }
                    function staticCanMatchDefinition(source, target) {
                        var sloc = source.locator.slice(source.alternation).join(""), tloc = target.locator.slice(target.alternation).join(""), canMatch = sloc == tloc;
                        canMatch = canMatch && source.match.fn === null && target.match.fn !== null ? target.match.fn.test(source.match.def, getMaskSet(), pos, false, opts, false) : false;
                        return canMatch;
                    }
                    function setMergeLocators(targetMatch, altMatch) {
                        if (altMatch === undefined || targetMatch.alternation === altMatch.alternation && targetMatch.locator[targetMatch.alternation].toString().indexOf(altMatch.locator[altMatch.alternation]) === -1) {
                            targetMatch.mloc = targetMatch.mloc || {};
                            var locNdx = targetMatch.locator[targetMatch.alternation];
                            if (locNdx === undefined) targetMatch.alternation = undefined; else {
                                if (typeof locNdx === "string") locNdx = locNdx.split(",")[0];
                                if (targetMatch.mloc[locNdx] === undefined) targetMatch.mloc[locNdx] = targetMatch.locator.slice();
                                if (altMatch !== undefined) {
                                    for (var ndx in altMatch.mloc) {
                                        if (typeof ndx === "string") ndx = ndx.split(",")[0];
                                        if (targetMatch.mloc[ndx] === undefined) targetMatch.mloc[ndx] = altMatch.mloc[ndx];
                                    }
                                    targetMatch.locator[targetMatch.alternation] = Object.keys(targetMatch.mloc).join(",");
                                }
                                return true;
                            }
                        }
                        return false;
                    }
                    if (testPos > 500 && quantifierRecurse !== undefined) {
                        throw "Inputmask: There is probably an error in your mask definition or in the code. Create an issue on github with an example of the mask you are using. " + getMaskSet().mask;
                    }
                    if (testPos === pos && match.matches === undefined) {
                        matches.push({
                            match: match,
                            locator: loopNdx.reverse(),
                            cd: cacheDependency,
                            mloc: {}
                        });
                        return true;
                    } else if (match.matches !== undefined) {
                        if (match.isGroup && quantifierRecurse !== match) {
                            match = handleMatch(maskToken.matches[$.inArray(match, maskToken.matches) + 1], loopNdx, quantifierRecurse);
                            if (match) return true;
                        } else if (match.isOptional) {
                            var optionalToken = match;
                            match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
                            if (match) {
                                $.each(matches, function(ndx, mtch) {
                                    mtch.match.optionality = true;
                                });
                                latestMatch = matches[matches.length - 1].match;
                                if (quantifierRecurse === undefined && isFirstMatch(latestMatch, optionalToken)) {
                                    insertStop = true;
                                    testPos = pos;
                                } else return true;
                            }
                        } else if (match.isAlternator) {
                            var alternateToken = match, malternateMatches = [], maltMatches, currentMatches = matches.slice(), loopNdxCnt = loopNdx.length;
                            var altIndex = ndxInitializer.length > 0 ? ndxInitializer.shift() : -1;
                            if (altIndex === -1 || typeof altIndex === "string") {
                                var currentPos = testPos, ndxInitializerClone = ndxInitializer.slice(), altIndexArr = [], amndx;
                                if (typeof altIndex == "string") {
                                    altIndexArr = altIndex.split(",");
                                } else {
                                    for (amndx = 0; amndx < alternateToken.matches.length; amndx++) {
                                        altIndexArr.push(amndx.toString());
                                    }
                                }
                                if (getMaskSet().excludes[pos]) {
                                    var altIndexArrClone = altIndexArr.slice();
                                    for (var i = 0, el = getMaskSet().excludes[pos].length; i < el; i++) {
                                        altIndexArr.splice(altIndexArr.indexOf(getMaskSet().excludes[pos][i].toString()), 1);
                                    }
                                    if (altIndexArr.length === 0) {
                                        getMaskSet().excludes[pos] = undefined;
                                        altIndexArr = altIndexArrClone;
                                    }
                                }
                                if (opts.keepStatic === true || isFinite(parseInt(opts.keepStatic)) && currentPos >= opts.keepStatic) altIndexArr = altIndexArr.slice(0, 1);
                                var unMatchedAlternation = false;
                                for (var ndx = 0; ndx < altIndexArr.length; ndx++) {
                                    amndx = parseInt(altIndexArr[ndx]);
                                    matches = [];
                                    ndxInitializer = typeof altIndex === "string" ? resolveNdxInitializer(testPos, amndx, loopNdxCnt) || ndxInitializerClone.slice() : ndxInitializerClone.slice();
                                    if (alternateToken.matches[amndx] && handleMatch(alternateToken.matches[amndx], [ amndx ].concat(loopNdx), quantifierRecurse)) match = true; else if (ndx === 0) {
                                        unMatchedAlternation = true;
                                    }
                                    maltMatches = matches.slice();
                                    testPos = currentPos;
                                    matches = [];
                                    for (var ndx1 = 0; ndx1 < maltMatches.length; ndx1++) {
                                        var altMatch = maltMatches[ndx1], dropMatch = false;
                                        altMatch.match.jit = altMatch.match.jit || unMatchedAlternation;
                                        altMatch.alternation = altMatch.alternation || loopNdxCnt;
                                        setMergeLocators(altMatch);
                                        for (var ndx2 = 0; ndx2 < malternateMatches.length; ndx2++) {
                                            var altMatch2 = malternateMatches[ndx2];
                                            if (typeof altIndex !== "string" || altMatch.alternation !== undefined && $.inArray(altMatch.locator[altMatch.alternation].toString(), altIndexArr) !== -1) {
                                                if (altMatch.match.nativeDef === altMatch2.match.nativeDef) {
                                                    dropMatch = true;
                                                    setMergeLocators(altMatch2, altMatch);
                                                    break;
                                                } else if (isSubsetOf(altMatch, altMatch2)) {
                                                    if (setMergeLocators(altMatch, altMatch2)) {
                                                        dropMatch = true;
                                                        malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch);
                                                    }
                                                    break;
                                                } else if (isSubsetOf(altMatch2, altMatch)) {
                                                    setMergeLocators(altMatch2, altMatch);
                                                    break;
                                                } else if (staticCanMatchDefinition(altMatch, altMatch2)) {
                                                    if (setMergeLocators(altMatch, altMatch2)) {
                                                        dropMatch = true;
                                                        malternateMatches.splice(malternateMatches.indexOf(altMatch2), 0, altMatch);
                                                    }
                                                    break;
                                                }
                                            }
                                        }
                                        if (!dropMatch) {
                                            malternateMatches.push(altMatch);
                                        }
                                    }
                                }
                                matches = currentMatches.concat(malternateMatches);
                                testPos = pos;
                                insertStop = matches.length > 0;
                                match = malternateMatches.length > 0;
                                ndxInitializer = ndxInitializerClone.slice();
                            } else match = handleMatch(alternateToken.matches[altIndex] || maskToken.matches[altIndex], [ altIndex ].concat(loopNdx), quantifierRecurse);
                            if (match) return true;
                        } else if (match.isQuantifier && quantifierRecurse !== maskToken.matches[$.inArray(match, maskToken.matches) - 1]) {
                            var qt = match;
                            for (var qndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; qndx < (isNaN(qt.quantifier.max) ? qndx + 1 : qt.quantifier.max) && testPos <= pos; qndx++) {
                                var tokenGroup = maskToken.matches[$.inArray(qt, maskToken.matches) - 1];
                                match = handleMatch(tokenGroup, [ qndx ].concat(loopNdx), tokenGroup);
                                if (match) {
                                    latestMatch = matches[matches.length - 1].match;
                                    latestMatch.optionalQuantifier = qndx >= qt.quantifier.min;
                                    latestMatch.jit = (qndx || 1) * tokenGroup.matches.indexOf(latestMatch) >= qt.quantifier.jit;
                                    if (latestMatch.optionalQuantifier && isFirstMatch(latestMatch, tokenGroup)) {
                                        insertStop = true;
                                        testPos = pos;
                                        break;
                                    }
                                    if (latestMatch.jit) {
                                        getMaskSet().jitOffset[pos] = tokenGroup.matches.indexOf(latestMatch);
                                    }
                                    return true;
                                }
                            }
                        } else {
                            match = resolveTestFromToken(match, ndxInitializer, loopNdx, quantifierRecurse);
                            if (match) return true;
                        }
                    } else {
                        testPos++;
                    }
                }
                for (var tndx = ndxInitializer.length > 0 ? ndxInitializer.shift() : 0; tndx < maskToken.matches.length; tndx++) {
                    if (maskToken.matches[tndx].isQuantifier !== true) {
                        var match = handleMatch(maskToken.matches[tndx], [ tndx ].concat(loopNdx), quantifierRecurse);
                        if (match && testPos === pos) {
                            return match;
                        } else if (testPos > pos) {
                            break;
                        }
                    }
                }
            }
            function mergeLocators(pos, tests) {
                var locator = [];
                if (!$.isArray(tests)) tests = [ tests ];
                if (tests.length > 0) {
                    if (tests[0].alternation === undefined) {
                        locator = determineTestTemplate(pos, tests.slice()).locator.slice();
                        if (locator.length === 0) locator = tests[0].locator.slice();
                    } else {
                        $.each(tests, function(ndx, tst) {
                            if (tst.def !== "") {
                                if (locator.length === 0) locator = tst.locator.slice(); else {
                                    for (var i = 0; i < locator.length; i++) {
                                        if (tst.locator[i] && locator[i].toString().indexOf(tst.locator[i]) === -1) {
                                            locator[i] += "," + tst.locator[i];
                                        }
                                    }
                                }
                            }
                        });
                    }
                }
                return locator;
            }
            if (pos > -1) {
                if (ndxIntlzr === undefined) {
                    var previousPos = pos - 1, test;
                    while ((test = getMaskSet().validPositions[previousPos] || getMaskSet().tests[previousPos]) === undefined && previousPos > -1) {
                        previousPos--;
                    }
                    if (test !== undefined && previousPos > -1) {
                        ndxInitializer = mergeLocators(previousPos, test);
                        cacheDependency = ndxInitializer.join("");
                        testPos = previousPos;
                    }
                }
                if (getMaskSet().tests[pos] && getMaskSet().tests[pos][0].cd === cacheDependency) {
                    return getMaskSet().tests[pos];
                }
                for (var mtndx = ndxInitializer.shift(); mtndx < maskTokens.length; mtndx++) {
                    var match = resolveTestFromToken(maskTokens[mtndx], ndxInitializer, [ mtndx ]);
                    if (match && testPos === pos || testPos > pos) {
                        break;
                    }
                }
            }
            if (matches.length === 0 || insertStop) {
                matches.push({
                    match: {
                        fn: null,
                        optionality: false,
                        casing: null,
                        def: "",
                        placeholder: ""
                    },
                    locator: [],
                    mloc: {},
                    cd: cacheDependency
                });
            }
            if (ndxIntlzr !== undefined && getMaskSet().tests[pos]) {
                return $.extend(true, [], matches);
            }
            getMaskSet().tests[pos] = $.extend(true, [], matches);
            return getMaskSet().tests[pos];
        }
        function getBufferTemplate() {
            if (getMaskSet()._buffer === undefined) {
                getMaskSet()._buffer = getMaskTemplate(false, 1);
                if (getMaskSet().buffer === undefined) getMaskSet().buffer = getMaskSet()._buffer.slice();
            }
            return getMaskSet()._buffer;
        }
        function getBuffer(noCache) {
            if (getMaskSet().buffer === undefined || noCache === true) {
                getMaskSet().buffer = getMaskTemplate(true, getLastValidPosition(), true);
                if (getMaskSet()._buffer === undefined) getMaskSet()._buffer = getMaskSet().buffer.slice();
            }
            return getMaskSet().buffer;
        }
        function refreshFromBuffer(start, end, buffer) {
            var i, p;
            if (start === true) {
                resetMaskSet();
                start = 0;
                end = buffer.length;
            } else {
                for (i = start; i < end; i++) {
                    delete getMaskSet().validPositions[i];
                }
            }
            p = start;
            for (i = start; i < end; i++) {
                resetMaskSet(true);
                if (buffer[i] !== opts.skipOptionalPartCharacter) {
                    var valResult = isValid(p, buffer[i], true, true);
                    if (valResult !== false) {
                        resetMaskSet(true);
                        p = valResult.caret !== undefined ? valResult.caret : valResult.pos + 1;
                    }
                }
            }
        }
        function casing(elem, test, pos) {
            switch (opts.casing || test.casing) {
              case "upper":
                elem = elem.toUpperCase();
                break;

              case "lower":
                elem = elem.toLowerCase();
                break;

              case "title":
                var posBefore = getMaskSet().validPositions[pos - 1];
                if (pos === 0 || posBefore && posBefore.input === String.fromCharCode(Inputmask.keyCode.SPACE)) {
                    elem = elem.toUpperCase();
                } else {
                    elem = elem.toLowerCase();
                }
                break;

              default:
                if ($.isFunction(opts.casing)) {
                    var args = Array.prototype.slice.call(arguments);
                    args.push(getMaskSet().validPositions);
                    elem = opts.casing.apply(this, args);
                }
            }
            return elem;
        }
        function checkAlternationMatch(altArr1, altArr2, na) {
            var altArrC = opts.greedy ? altArr2 : altArr2.slice(0, 1), isMatch = false, naArr = na !== undefined ? na.split(",") : [], naNdx;
            for (var i = 0; i < naArr.length; i++) {
                if ((naNdx = altArr1.indexOf(naArr[i])) !== -1) {
                    altArr1.splice(naNdx, 1);
                }
            }
            for (var alndx = 0; alndx < altArr1.length; alndx++) {
                if ($.inArray(altArr1[alndx], altArrC) !== -1) {
                    isMatch = true;
                    break;
                }
            }
            return isMatch;
        }
        function alternate(pos, c, strict, fromSetValid, rAltPos) {
            var validPsClone = $.extend(true, {}, getMaskSet().validPositions), lastAlt, alternation, isValidRslt = false, altPos, prevAltPos, i, validPos, decisionPos, lAltPos = rAltPos !== undefined ? rAltPos : getLastValidPosition();
            if (lAltPos === -1 && rAltPos === undefined) {
                lastAlt = 0;
                prevAltPos = getTest(lastAlt);
                alternation = prevAltPos.alternation;
            } else {
                for (;lAltPos >= 0; lAltPos--) {
                    altPos = getMaskSet().validPositions[lAltPos];
                    if (altPos && altPos.alternation !== undefined) {
                        if (prevAltPos && prevAltPos.locator[altPos.alternation] !== altPos.locator[altPos.alternation]) {
                            break;
                        }
                        lastAlt = lAltPos;
                        alternation = getMaskSet().validPositions[lastAlt].alternation;
                        prevAltPos = altPos;
                    }
                }
            }
            if (alternation !== undefined) {
                decisionPos = parseInt(lastAlt);
                getMaskSet().excludes[decisionPos] = getMaskSet().excludes[decisionPos] || [];
                if (pos !== true) {
                    getMaskSet().excludes[decisionPos].push(getDecisionTaker(prevAltPos));
                }
                var validInputsClone = [], staticInputsBeforePos = 0;
                for (i = decisionPos; i < getLastValidPosition(undefined, true) + 1; i++) {
                    validPos = getMaskSet().validPositions[i];
                    if (validPos && validPos.generatedInput !== true) {
                        validInputsClone.push(validPos.input);
                    } else if (i < pos) staticInputsBeforePos++;
                    delete getMaskSet().validPositions[i];
                }
                while (getMaskSet().excludes[decisionPos] && getMaskSet().excludes[decisionPos].length < 10) {
                    var posOffset = staticInputsBeforePos * -1, validInputs = validInputsClone.slice();
                    getMaskSet().tests[decisionPos] = undefined;
                    resetMaskSet(true);
                    isValidRslt = true;
                    while (validInputs.length > 0) {
                        var input = validInputs.shift();
                        if (!(isValidRslt = isValid(getLastValidPosition(undefined, true) + 1, input, false, fromSetValid, true))) {
                            break;
                        }
                    }
                    if (isValidRslt && c !== undefined) {
                        var targetLvp = getLastValidPosition(pos) + 1;
                        for (i = decisionPos; i < getLastValidPosition() + 1; i++) {
                            validPos = getMaskSet().validPositions[i];
                            if ((validPos === undefined || validPos.match.fn == null) && i < pos + posOffset) {
                                posOffset++;
                            }
                        }
                        pos = pos + posOffset;
                        isValidRslt = isValid(pos > targetLvp ? targetLvp : pos, c, strict, fromSetValid, true);
                    }
                    if (!isValidRslt) {
                        resetMaskSet();
                        prevAltPos = getTest(decisionPos);
                        getMaskSet().validPositions = $.extend(true, {}, validPsClone);
                        if (getMaskSet().excludes[decisionPos]) {
                            var decisionTaker = getDecisionTaker(prevAltPos);
                            if (getMaskSet().excludes[decisionPos].indexOf(decisionTaker) !== -1) {
                                isValidRslt = alternate(pos, c, strict, fromSetValid, decisionPos - 1);
                                break;
                            }
                            getMaskSet().excludes[decisionPos].push(decisionTaker);
                            for (i = decisionPos; i < getLastValidPosition(undefined, true) + 1; i++) delete getMaskSet().validPositions[i];
                        } else {
                            isValidRslt = alternate(pos, c, strict, fromSetValid, decisionPos - 1);
                            break;
                        }
                    } else break;
                }
            }
            getMaskSet().excludes[decisionPos] = undefined;
            return isValidRslt;
        }
        function isValid(pos, c, strict, fromSetValid, fromAlternate, validateOnly) {
            function isSelection(posObj) {
                return isRTL ? posObj.begin - posObj.end > 1 || posObj.begin - posObj.end === 1 : posObj.end - posObj.begin > 1 || posObj.end - posObj.begin === 1;
            }
            strict = strict === true;
            var maskPos = pos;
            if (pos.begin !== undefined) {
                maskPos = isRTL ? pos.end : pos.begin;
            }
            function _isValid(position, c, strict) {
                var rslt = false;
                $.each(getTests(position), function(ndx, tst) {
                    var test = tst.match;
                    getBuffer(true);
                    rslt = test.fn != null ? test.fn.test(c, getMaskSet(), position, strict, opts, isSelection(pos)) : (c === test.def || c === opts.skipOptionalPartCharacter) && test.def !== "" ? {
                        c: getPlaceholder(position, test, true) || test.def,
                        pos: position
                    } : false;
                    if (rslt !== false) {
                        var elem = rslt.c !== undefined ? rslt.c : c, validatedPos = position;
                        elem = elem === opts.skipOptionalPartCharacter && test.fn === null ? getPlaceholder(position, test, true) || test.def : elem;
                        if (rslt.remove !== undefined) {
                            if (!$.isArray(rslt.remove)) rslt.remove = [ rslt.remove ];
                            $.each(rslt.remove.sort(function(a, b) {
                                return b - a;
                            }), function(ndx, lmnt) {
                                revalidateMask({
                                    begin: lmnt,
                                    end: lmnt + 1
                                });
                            });
                        }
                        if (rslt.insert !== undefined) {
                            if (!$.isArray(rslt.insert)) rslt.insert = [ rslt.insert ];
                            $.each(rslt.insert.sort(function(a, b) {
                                return a - b;
                            }), function(ndx, lmnt) {
                                isValid(lmnt.pos, lmnt.c, true, fromSetValid);
                            });
                        }
                        if (rslt !== true && rslt.pos !== undefined && rslt.pos !== position) {
                            validatedPos = rslt.pos;
                        }
                        if (rslt !== true && rslt.pos === undefined && rslt.c === undefined) {
                            return false;
                        }
                        if (!revalidateMask(pos, $.extend({}, tst, {
                            input: casing(elem, test, validatedPos)
                        }), fromSetValid, validatedPos)) {
                            rslt = false;
                        }
                        return false;
                    }
                });
                return rslt;
            }
            var result = true, positionsClone = $.extend(true, {}, getMaskSet().validPositions);
            if ($.isFunction(opts.preValidation) && !strict && fromSetValid !== true && validateOnly !== true) {
                result = opts.preValidation(getBuffer(), maskPos, c, isSelection(pos), opts, getMaskSet());
            }
            if (result === true) {
                trackbackPositions(undefined, maskPos, true);
                if (maxLength === undefined || maskPos < maxLength) {
                    result = _isValid(maskPos, c, strict);
                    if ((!strict || fromSetValid === true) && result === false && validateOnly !== true) {
                        var currentPosValid = getMaskSet().validPositions[maskPos];
                        if (currentPosValid && currentPosValid.match.fn === null && (currentPosValid.match.def === c || c === opts.skipOptionalPartCharacter)) {
                            result = {
                                caret: seekNext(maskPos)
                            };
                        } else {
                            if ((opts.insertMode || getMaskSet().validPositions[seekNext(maskPos)] === undefined) && (!isMask(maskPos, true) || getMaskSet().jitOffset[maskPos])) {
                                if (getMaskSet().jitOffset[maskPos] && getMaskSet().validPositions[seekNext(maskPos)] === undefined) {
                                    result = isValid(maskPos + getMaskSet().jitOffset[maskPos], c, strict);
                                    if (result !== false) result.caret = maskPos;
                                } else for (var nPos = maskPos + 1, snPos = seekNext(maskPos); nPos <= snPos; nPos++) {
                                    result = _isValid(nPos, c, strict);
                                    if (result !== false) {
                                        result = trackbackPositions(maskPos, result.pos !== undefined ? result.pos : nPos) || result;
                                        maskPos = nPos;
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
                if (result === false && opts.keepStatic !== false && (opts.regex == null || isComplete(getBuffer())) && !strict && fromAlternate !== true) {
                    result = alternate(maskPos, c, strict, fromSetValid);
                }
                if (result === true) {
                    result = {
                        pos: maskPos
                    };
                }
            }
            if ($.isFunction(opts.postValidation) && result !== false && !strict && fromSetValid !== true && validateOnly !== true) {
                var postResult = opts.postValidation(getBuffer(true), pos.begin !== undefined ? isRTL ? pos.end : pos.begin : pos, result, opts);
                if (postResult !== undefined) {
                    if (postResult.refreshFromBuffer && postResult.buffer) {
                        var refresh = postResult.refreshFromBuffer;
                        refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, postResult.buffer);
                    }
                    result = postResult === true ? result : postResult;
                }
            }
            if (result && result.pos === undefined) {
                result.pos = maskPos;
            }
            if (result === false || validateOnly === true) {
                resetMaskSet(true);
                getMaskSet().validPositions = $.extend(true, {}, positionsClone);
            }
            return result;
        }
        function trackbackPositions(originalPos, newPos, fillOnly) {
            var result;
            if (originalPos === undefined) {
                for (originalPos = newPos - 1; originalPos > 0; originalPos--) {
                    if (getMaskSet().validPositions[originalPos]) break;
                }
            }
            for (var ps = originalPos; ps < newPos; ps++) {
                if (getMaskSet().validPositions[ps] === undefined && !isMask(ps, true)) {
                    var vp = ps == 0 ? getTest(ps) : getMaskSet().validPositions[ps - 1];
                    if (vp) {
                        var tests = getTests(ps).slice();
                        if (tests[tests.length - 1].match.def === "") tests.pop();
                        var bestMatch = determineTestTemplate(ps, tests);
                        bestMatch = $.extend({}, bestMatch, {
                            input: getPlaceholder(ps, bestMatch.match, true) || bestMatch.match.def
                        });
                        bestMatch.generatedInput = true;
                        revalidateMask(ps, bestMatch, true);
                        if (fillOnly !== true) {
                            var cvpInput = getMaskSet().validPositions[newPos].input;
                            getMaskSet().validPositions[newPos] = undefined;
                            result = isValid(newPos, cvpInput, true, true);
                        }
                    }
                }
            }
            return result;
        }
        function revalidateMask(pos, validTest, fromSetValid, validatedPos) {
            function IsEnclosedStatic(pos, valids, selection) {
                var posMatch = valids[pos];
                if (posMatch !== undefined && (posMatch.match.fn === null && posMatch.match.optionality !== true || posMatch.input === opts.radixPoint)) {
                    var prevMatch = selection.begin <= pos - 1 ? valids[pos - 1] && valids[pos - 1].match.fn === null && valids[pos - 1] : valids[pos - 1], nextMatch = selection.end > pos + 1 ? valids[pos + 1] && valids[pos + 1].match.fn === null && valids[pos + 1] : valids[pos + 1];
                    return prevMatch && nextMatch;
                }
                return false;
            }
            var begin = pos.begin !== undefined ? pos.begin : pos, end = pos.end !== undefined ? pos.end : pos;
            if (pos.begin > pos.end) {
                begin = pos.end;
                end = pos.begin;
            }
            validatedPos = validatedPos !== undefined ? validatedPos : begin;
            if (begin !== end || opts.insertMode && getMaskSet().validPositions[validatedPos] !== undefined && fromSetValid === undefined) {
                var positionsClone = $.extend(true, {}, getMaskSet().validPositions), lvp = getLastValidPosition(undefined, true), i;
                getMaskSet().p = begin;
                for (i = lvp; i >= begin; i--) {
                    if (getMaskSet().validPositions[i] && getMaskSet().validPositions[i].match.nativeDef === "+") {
                        opts.isNegative = false;
                    }
                    delete getMaskSet().validPositions[i];
                }
                var valid = true, j = validatedPos, vps = getMaskSet().validPositions, needsValidation = false, posMatch = j, i = j;
                if (validTest) {
                    getMaskSet().validPositions[validatedPos] = $.extend(true, {}, validTest);
                    posMatch++;
                    j++;
                    if (begin < end) i++;
                }
                for (;i <= lvp; i++) {
                    var t = positionsClone[i];
                    if (t !== undefined && (i >= end || i >= begin && t.generatedInput !== true && IsEnclosedStatic(i, positionsClone, {
                        begin: begin,
                        end: end
                    }))) {
                        while (getTest(posMatch).match.def !== "") {
                            if (needsValidation === false && positionsClone[posMatch] && positionsClone[posMatch].match.nativeDef === t.match.nativeDef) {
                                getMaskSet().validPositions[posMatch] = $.extend(true, {}, positionsClone[posMatch]);
                                getMaskSet().validPositions[posMatch].input = t.input;
                                trackbackPositions(undefined, posMatch, true);
                                j = posMatch + 1;
                                valid = true;
                            } else if (opts.shiftPositions && positionCanMatchDefinition(posMatch, t.match.def)) {
                                var result = isValid(posMatch, t.input, true, true);
                                valid = result !== false;
                                j = result.caret || result.insert ? getLastValidPosition() : posMatch + 1;
                                needsValidation = true;
                            } else {
                                valid = t.generatedInput === true || t.input === opts.radixPoint && opts.numericInput === true;
                            }
                            if (valid) break;
                            if (!valid && posMatch > end && isMask(posMatch, true) && (t.match.fn !== null || posMatch > getMaskSet().maskLength)) {
                                break;
                            }
                            posMatch++;
                        }
                        if (getTest(posMatch).match.def == "") valid = false;
                        posMatch = j;
                    }
                    if (!valid) break;
                }
                if (!valid) {
                    getMaskSet().validPositions = $.extend(true, {}, positionsClone);
                    resetMaskSet(true);
                    return false;
                }
            } else if (validTest) {
                getMaskSet().validPositions[validatedPos] = $.extend(true, {}, validTest);
            }
            resetMaskSet(true);
            return true;
        }
        function isMask(pos, strict) {
            var test = getTestTemplate(pos).match;
            if (test.def === "") test = getTest(pos).match;
            if (test.fn != null) {
                return test.fn;
            }
            if (strict !== true && pos > -1) {
                var tests = getTests(pos);
                return tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0);
            }
            return false;
        }
        function seekNext(pos, newBlock) {
            var position = pos + 1;
            while (getTest(position).match.def !== "" && (newBlock === true && (getTest(position).match.newBlockMarker !== true || !isMask(position)) || newBlock !== true && !isMask(position))) {
                position++;
            }
            return position;
        }
        function seekPrevious(pos, newBlock) {
            var position = pos, tests;
            if (position <= 0) return 0;
            while (--position > 0 && (newBlock === true && getTest(position).match.newBlockMarker !== true || newBlock !== true && !isMask(position) && (tests = getTests(position), 
            tests.length < 2 || tests.length === 2 && tests[1].match.def === ""))) {}
            return position;
        }
        function writeBuffer(input, buffer, caretPos, event, triggerEvents) {
            if (event && $.isFunction(opts.onBeforeWrite)) {
                var result = opts.onBeforeWrite.call(inputmask, event, buffer, caretPos, opts);
                if (result) {
                    if (result.refreshFromBuffer) {
                        var refresh = result.refreshFromBuffer;
                        refreshFromBuffer(refresh === true ? refresh : refresh.start, refresh.end, result.buffer || buffer);
                        buffer = getBuffer(true);
                    }
                    if (caretPos !== undefined) caretPos = result.caret !== undefined ? result.caret : caretPos;
                }
            }
            if (input !== undefined) {
                input.inputmask._valueSet(buffer.join(""));
                if (caretPos !== undefined && (event === undefined || event.type !== "blur")) {
                    caret(input, caretPos);
                } else renderColorMask(input, caretPos, buffer.length === 0);
                if (triggerEvents === true) {
                    var $input = $(input), nptVal = input.inputmask._valueGet();
                    skipInputEvent = true;
                    $input.trigger("input");
                    setTimeout(function() {
                        if (nptVal === getBufferTemplate().join("")) {
                            $input.trigger("cleared");
                        } else if (isComplete(buffer) === true) {
                            $input.trigger("complete");
                        }
                    }, 0);
                }
            }
        }
        function getPlaceholder(pos, test, returnPL) {
            test = test || getTest(pos).match;
            if (test.placeholder !== undefined || returnPL === true) {
                return $.isFunction(test.placeholder) ? test.placeholder(opts) : test.placeholder;
            } else if (test.fn === null) {
                if (pos > -1 && getMaskSet().validPositions[pos] === undefined) {
                    var tests = getTests(pos), staticAlternations = [], prevTest;
                    if (tests.length > 1 + (tests[tests.length - 1].match.def === "" ? 1 : 0)) {
                        for (var i = 0; i < tests.length; i++) {
                            if (tests[i].match.optionality !== true && tests[i].match.optionalQuantifier !== true && (tests[i].match.fn === null || (prevTest === undefined || tests[i].match.fn.test(prevTest.match.def, getMaskSet(), pos, true, opts) !== false))) {
                                staticAlternations.push(tests[i]);
                                if (tests[i].match.fn === null) prevTest = tests[i];
                                if (staticAlternations.length > 1) {
                                    if (/[0-9a-bA-Z]/.test(staticAlternations[0].match.def)) {
                                        return opts.placeholder.charAt(pos % opts.placeholder.length);
                                    }
                                }
                            }
                        }
                    }
                }
                return test.def;
            }
            return opts.placeholder.charAt(pos % opts.placeholder.length);
        }
        function HandleNativePlaceholder(npt, value) {
            if (ie) {
                if (npt.inputmask._valueGet() !== value && (npt.placeholder !== value || npt.placeholder === "")) {
                    var buffer = getBuffer().slice(), nptValue = npt.inputmask._valueGet();
                    if (nptValue !== value) {
                        var lvp = getLastValidPosition();
                        if (lvp === -1 && nptValue === getBufferTemplate().join("")) {
                            buffer = [];
                        } else if (lvp !== -1) {
                            clearOptionalTail(buffer);
                        }
                        writeBuffer(npt, buffer);
                    }
                }
            } else if (npt.placeholder !== value) {
                npt.placeholder = value;
                if (npt.placeholder === "") npt.removeAttribute("placeholder");
            }
        }
        var EventRuler = {
            on: function(input, eventName, eventHandler) {
                var ev = function(e) {
                    var that = this;
                    if (that.inputmask === undefined && this.nodeName !== "FORM") {
                        var imOpts = $.data(that, "_inputmask_opts");
                        if (imOpts) new Inputmask(imOpts).mask(that); else EventRuler.off(that);
                    } else if (e.type !== "setvalue" && this.nodeName !== "FORM" && (that.disabled || that.readOnly && !(e.type === "keydown" && (e.ctrlKey && e.keyCode === 67) || opts.tabThrough === false && e.keyCode === Inputmask.keyCode.TAB))) {
                        e.preventDefault();
                    } else {
                        switch (e.type) {
                          case "input":
                            if (skipInputEvent === true) {
                                skipInputEvent = false;
                                return e.preventDefault();
                            }
                            if (mobile) {
                                var args = arguments;
                                setTimeout(function() {
                                    eventHandler.apply(that, args);
                                    caret(that, that.inputmask.caretPos, undefined, true);
                                }, 0);
                                return false;
                            }
                            break;

                          case "keydown":
                            skipKeyPressEvent = false;
                            skipInputEvent = false;
                            break;

                          case "keypress":
                            if (skipKeyPressEvent === true) {
                                return e.preventDefault();
                            }
                            skipKeyPressEvent = true;
                            break;

                          case "click":
                            if (iemobile || iphone) {
                                var args = arguments;
                                setTimeout(function() {
                                    eventHandler.apply(that, args);
                                }, 0);
                                return false;
                            }
                            break;
                        }
                        var returnVal = eventHandler.apply(that, arguments);
                        if (returnVal === false) {
                            e.preventDefault();
                            e.stopPropagation();
                        }
                        return returnVal;
                    }
                };
                input.inputmask.events[eventName] = input.inputmask.events[eventName] || [];
                input.inputmask.events[eventName].push(ev);
                if ($.inArray(eventName, [ "submit", "reset" ]) !== -1) {
                    if (input.form !== null) $(input.form).on(eventName, ev);
                } else {
                    $(input).on(eventName, ev);
                }
            },
            off: function(input, event) {
                if (input.inputmask && input.inputmask.events) {
                    var events;
                    if (event) {
                        events = [];
                        events[event] = input.inputmask.events[event];
                    } else {
                        events = input.inputmask.events;
                    }
                    $.each(events, function(eventName, evArr) {
                        while (evArr.length > 0) {
                            var ev = evArr.pop();
                            if ($.inArray(eventName, [ "submit", "reset" ]) !== -1) {
                                if (input.form !== null) $(input.form).off(eventName, ev);
                            } else {
                                $(input).off(eventName, ev);
                            }
                        }
                        delete input.inputmask.events[eventName];
                    });
                }
            }
        };
        var EventHandlers = {
            keydownEvent: function(e) {
                var input = this, $input = $(input), k = e.keyCode, pos = caret(input);
                if (k === Inputmask.keyCode.BACKSPACE || k === Inputmask.keyCode.DELETE || iphone && k === Inputmask.keyCode.BACKSPACE_SAFARI || e.ctrlKey && k === Inputmask.keyCode.X && !isInputEventSupported("cut")) {
                    e.preventDefault();
                    handleRemove(input, k, pos);
                    writeBuffer(input, getBuffer(true), getMaskSet().p, e, input.inputmask._valueGet() !== getBuffer().join(""));
                } else if (k === Inputmask.keyCode.END || k === Inputmask.keyCode.PAGE_DOWN) {
                    e.preventDefault();
                    var caretPos = seekNext(getLastValidPosition());
                    caret(input, e.shiftKey ? pos.begin : caretPos, caretPos, true);
                } else if (k === Inputmask.keyCode.HOME && !e.shiftKey || k === Inputmask.keyCode.PAGE_UP) {
                    e.preventDefault();
                    caret(input, 0, e.shiftKey ? pos.begin : 0, true);
                } else if ((opts.undoOnEscape && k === Inputmask.keyCode.ESCAPE || k === 90 && e.ctrlKey) && e.altKey !== true) {
                    checkVal(input, true, false, undoValue.split(""));
                    $input.trigger("click");
                } else if (k === Inputmask.keyCode.INSERT && !(e.shiftKey || e.ctrlKey)) {
                    opts.insertMode = !opts.insertMode;
                    input.setAttribute("im-insert", opts.insertMode);
                } else if (opts.tabThrough === true && k === Inputmask.keyCode.TAB) {
                    if (e.shiftKey === true) {
                        if (getTest(pos.begin).match.fn === null) {
                            pos.begin = seekNext(pos.begin);
                        }
                        pos.end = seekPrevious(pos.begin, true);
                        pos.begin = seekPrevious(pos.end, true);
                    } else {
                        pos.begin = seekNext(pos.begin, true);
                        pos.end = seekNext(pos.begin, true);
                        if (pos.end < getMaskSet().maskLength) pos.end--;
                    }
                    if (pos.begin < getMaskSet().maskLength) {
                        e.preventDefault();
                        caret(input, pos.begin, pos.end);
                    }
                }
                opts.onKeyDown.call(this, e, getBuffer(), caret(input).begin, opts);
                ignorable = $.inArray(k, opts.ignorables) !== -1;
            },
            keypressEvent: function(e, checkval, writeOut, strict, ndx) {
                var input = this, $input = $(input), k = e.which || e.charCode || e.keyCode;
                if (checkval !== true && (!(e.ctrlKey && e.altKey) && (e.ctrlKey || e.metaKey || ignorable))) {
                    if (k === Inputmask.keyCode.ENTER && undoValue !== getBuffer().join("")) {
                        undoValue = getBuffer().join("");
                        setTimeout(function() {
                            $input.trigger("change");
                        }, 0);
                    }
                    return true;
                } else {
                    if (k) {
                        if (k === 46 && e.shiftKey === false && opts.radixPoint !== "") k = opts.radixPoint.charCodeAt(0);
                        var pos = checkval ? {
                            begin: ndx,
                            end: ndx
                        } : caret(input), forwardPosition, c = String.fromCharCode(k), offset = 0;
                        if (opts._radixDance && opts.numericInput) {
                            var caretPos = getBuffer().indexOf(opts.radixPoint.charAt(0)) + 1;
                            if (pos.begin <= caretPos) {
                                if (k === opts.radixPoint.charCodeAt(0)) offset = 1;
                                pos.begin -= 1;
                                pos.end -= 1;
                            }
                        }
                        getMaskSet().writeOutBuffer = true;
                        var valResult = isValid(pos, c, strict);
                        if (valResult !== false) {
                            resetMaskSet(true);
                            forwardPosition = valResult.caret !== undefined ? valResult.caret : seekNext(valResult.pos.begin ? valResult.pos.begin : valResult.pos);
                            getMaskSet().p = forwardPosition;
                        }
                        forwardPosition = (opts.numericInput && valResult.caret === undefined ? seekPrevious(forwardPosition) : forwardPosition) + offset;
                        if (writeOut !== false) {
                            setTimeout(function() {
                                opts.onKeyValidation.call(input, k, valResult, opts);
                            }, 0);
                            if (getMaskSet().writeOutBuffer && valResult !== false) {
                                var buffer = getBuffer();
                                writeBuffer(input, buffer, forwardPosition, e, checkval !== true);
                            }
                        }
                        e.preventDefault();
                        if (checkval) {
                            if (valResult !== false) valResult.forwardPosition = forwardPosition;
                            return valResult;
                        }
                    }
                }
            },
            pasteEvent: function(e) {
                var input = this, ev = e.originalEvent || e, $input = $(input), inputValue = input.inputmask._valueGet(true), caretPos = caret(input), tempValue;
                if (isRTL) {
                    tempValue = caretPos.end;
                    caretPos.end = caretPos.begin;
                    caretPos.begin = tempValue;
                }
                var valueBeforeCaret = inputValue.substr(0, caretPos.begin), valueAfterCaret = inputValue.substr(caretPos.end, inputValue.length);
                if (valueBeforeCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(0, caretPos.begin).join("")) valueBeforeCaret = "";
                if (valueAfterCaret === (isRTL ? getBufferTemplate().reverse() : getBufferTemplate()).slice(caretPos.end).join("")) valueAfterCaret = "";
                if (window.clipboardData && window.clipboardData.getData) {
                    inputValue = valueBeforeCaret + window.clipboardData.getData("Text") + valueAfterCaret;
                } else if (ev.clipboardData && ev.clipboardData.getData) {
                    inputValue = valueBeforeCaret + ev.clipboardData.getData("text/plain") + valueAfterCaret;
                } else return true;
                var pasteValue = inputValue;
                if ($.isFunction(opts.onBeforePaste)) {
                    pasteValue = opts.onBeforePaste.call(inputmask, inputValue, opts);
                    if (pasteValue === false) {
                        return e.preventDefault();
                    }
                    if (!pasteValue) {
                        pasteValue = inputValue;
                    }
                }
                checkVal(input, false, false, pasteValue.toString().split(""));
                writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()), e, undoValue !== getBuffer().join(""));
                return e.preventDefault();
            },
            inputFallBackEvent: function(e) {
                function radixPointHandler(input, inputValue, caretPos) {
                    if (inputValue.charAt(caretPos.begin - 1) === "." && opts.radixPoint !== "") {
                        inputValue = inputValue.split("");
                        inputValue[caretPos.begin - 1] = opts.radixPoint.charAt(0);
                        inputValue = inputValue.join("");
                    }
                    return inputValue;
                }
                function ieMobileHandler(input, inputValue, caretPos) {
                    if (iemobile) {
                        var inputChar = inputValue.replace(getBuffer().join(""), "");
                        if (inputChar.length === 1) {
                            var iv = inputValue.split("");
                            iv.splice(caretPos.begin, 0, inputChar);
                            inputValue = iv.join("");
                        }
                    }
                    return inputValue;
                }
                var input = this, inputValue = input.inputmask._valueGet();
                if (getBuffer().join("") !== inputValue) {
                    var caretPos = caret(input);
                    inputValue = radixPointHandler(input, inputValue, caretPos);
                    inputValue = ieMobileHandler(input, inputValue, caretPos);
                    if (getBuffer().join("") !== inputValue) {
                        var buffer = getBuffer().join(""), offset = !opts.numericInput && inputValue.length > buffer.length ? -1 : 0, frontPart = inputValue.substr(0, caretPos.begin), backPart = inputValue.substr(caretPos.begin), frontBufferPart = buffer.substr(0, caretPos.begin + offset), backBufferPart = buffer.substr(caretPos.begin + offset);
                        var selection = caretPos, entries = "", isEntry = false;
                        if (frontPart !== frontBufferPart) {
                            var fpl = (isEntry = frontPart.length >= frontBufferPart.length) ? frontPart.length : frontBufferPart.length, i;
                            for (i = 0; frontPart.charAt(i) === frontBufferPart.charAt(i) && i < fpl; i++) ;
                            if (isEntry) {
                                selection.begin = i - offset;
                                entries += frontPart.slice(i, selection.end);
                            }
                        }
                        if (backPart !== backBufferPart) {
                            if (backPart.length > backBufferPart.length) {
                                entries += backPart.slice(0, 1);
                            } else {
                                if (backPart.length < backBufferPart.length) {
                                    selection.end += backBufferPart.length - backPart.length;
                                    if (!isEntry && opts.radixPoint !== "" && backPart === "" && frontPart.charAt(selection.begin + offset - 1) === opts.radixPoint) {
                                        selection.begin--;
                                        entries = opts.radixPoint;
                                    }
                                }
                            }
                        }
                        writeBuffer(input, getBuffer(), {
                            begin: selection.begin + offset,
                            end: selection.end + offset
                        });
                        if (entries.length > 0) {
                            $.each(entries.split(""), function(ndx, entry) {
                                var keypress = new $.Event("keypress");
                                keypress.which = entry.charCodeAt(0);
                                ignorable = false;
                                EventHandlers.keypressEvent.call(input, keypress);
                            });
                        } else {
                            if (selection.begin === selection.end - 1) {
                                selection.begin = seekPrevious(selection.begin + 1);
                                if (selection.begin === selection.end - 1) {
                                    caret(input, selection.begin);
                                } else {
                                    caret(input, selection.begin, selection.end);
                                }
                            }
                            var keydown = new $.Event("keydown");
                            keydown.keyCode = opts.numericInput ? Inputmask.keyCode.BACKSPACE : Inputmask.keyCode.DELETE;
                            EventHandlers.keydownEvent.call(input, keydown);
                        }
                        e.preventDefault();
                    }
                }
            },
            beforeInputEvent: function(e) {
                if (e.cancelable) {
                    var input = this;
                    switch (e.inputType) {
                      case "insertText":
                        $.each(e.data.split(""), function(ndx, entry) {
                            var keypress = new $.Event("keypress");
                            keypress.which = entry.charCodeAt(0);
                            ignorable = false;
                            EventHandlers.keypressEvent.call(input, keypress);
                        });
                        return e.preventDefault();

                      case "deleteContentBackward":
                        var keydown = new $.Event("keydown");
                        keydown.keyCode = Inputmask.keyCode.BACKSPACE;
                        EventHandlers.keydownEvent.call(input, keydown);
                        return e.preventDefault();

                      case "deleteContentForward":
                        var keydown = new $.Event("keydown");
                        keydown.keyCode = Inputmask.keyCode.DELETE;
                        EventHandlers.keydownEvent.call(input, keydown);
                        return e.preventDefault();
                    }
                }
            },
            setValueEvent: function(e) {
                this.inputmask.refreshValue = false;
                var input = this, value = e && e.detail ? e.detail[0] : arguments[1], value = value || input.inputmask._valueGet(true);
                if ($.isFunction(opts.onBeforeMask)) value = opts.onBeforeMask.call(inputmask, value, opts) || value;
                value = value.toString().split("");
                checkVal(input, true, false, value);
                undoValue = getBuffer().join("");
                if ((opts.clearMaskOnLostFocus || opts.clearIncomplete) && input.inputmask._valueGet() === getBufferTemplate().join("")) {
                    input.inputmask._valueSet("");
                }
            },
            focusEvent: function(e) {
                var input = this, nptValue = input.inputmask._valueGet();
                if (opts.showMaskOnFocus) {
                    if (nptValue !== getBuffer().join("")) {
                        writeBuffer(input, getBuffer(), seekNext(getLastValidPosition()));
                    } else if (mouseEnter === false) {
                        caret(input, seekNext(getLastValidPosition()));
                    }
                }
                if (opts.positionCaretOnTab === true && mouseEnter === false) {
                    EventHandlers.clickEvent.apply(input, [ e, true ]);
                }
                undoValue = getBuffer().join("");
            },
            mouseleaveEvent: function(e) {
                var input = this;
                mouseEnter = false;
                if (opts.clearMaskOnLostFocus && document.activeElement !== input) {
                    HandleNativePlaceholder(input, originalPlaceholder);
                }
            },
            clickEvent: function(e, tabbed) {
                function doRadixFocus(clickPos) {
                    if (opts.radixPoint !== "") {
                        var vps = getMaskSet().validPositions;
                        if (vps[clickPos] === undefined || vps[clickPos].input === getPlaceholder(clickPos)) {
                            if (clickPos < seekNext(-1)) return true;
                            var radixPos = $.inArray(opts.radixPoint, getBuffer());
                            if (radixPos !== -1) {
                                for (var vp in vps) {
                                    if (radixPos < vp && vps[vp].input !== getPlaceholder(vp)) {
                                        return false;
                                    }
                                }
                                return true;
                            }
                        }
                    }
                    return false;
                }
                var input = this;
                setTimeout(function() {
                    if (document.activeElement === input) {
                        var selectedCaret = caret(input);
                        if (tabbed) {
                            if (isRTL) {
                                selectedCaret.end = selectedCaret.begin;
                            } else {
                                selectedCaret.begin = selectedCaret.end;
                            }
                        }
                        if (selectedCaret.begin === selectedCaret.end) {
                            switch (opts.positionCaretOnClick) {
                              case "none":
                                break;

                              case "select":
                                caret(input, 0, getBuffer().length);
                                break;

                              case "ignore":
                                caret(input, seekNext(getLastValidPosition()));
                                break;

                              case "radixFocus":
                                if (doRadixFocus(selectedCaret.begin)) {
                                    var radixPos = getBuffer().join("").indexOf(opts.radixPoint);
                                    caret(input, opts.numericInput ? seekNext(radixPos) : radixPos);
                                    break;
                                }

                              default:
                                var clickPosition = selectedCaret.begin, lvclickPosition = getLastValidPosition(clickPosition, true), lastPosition = seekNext(lvclickPosition);
                                if (clickPosition < lastPosition) {
                                    caret(input, !isMask(clickPosition, true) && !isMask(clickPosition - 1, true) ? seekNext(clickPosition) : clickPosition);
                                } else {
                                    var lvp = getMaskSet().validPositions[lvclickPosition], tt = getTestTemplate(lastPosition, lvp ? lvp.match.locator : undefined, lvp), placeholder = getPlaceholder(lastPosition, tt.match);
                                    if (placeholder !== "" && getBuffer()[lastPosition] !== placeholder && tt.match.optionalQuantifier !== true && tt.match.newBlockMarker !== true || !isMask(lastPosition, opts.keepStatic) && tt.match.def === placeholder) {
                                        var newPos = seekNext(lastPosition);
                                        if (clickPosition >= newPos || clickPosition === lastPosition) {
                                            lastPosition = newPos;
                                        }
                                    }
                                    caret(input, lastPosition);
                                }
                                break;
                            }
                        }
                    }
                }, 0);
            },
            cutEvent: function(e) {
                var input = this, $input = $(input), pos = caret(input), ev = e.originalEvent || e;
                var clipboardData = window.clipboardData || ev.clipboardData, clipData = isRTL ? getBuffer().slice(pos.end, pos.begin) : getBuffer().slice(pos.begin, pos.end);
                clipboardData.setData("text", isRTL ? clipData.reverse().join("") : clipData.join(""));
                if (document.execCommand) document.execCommand("copy");
                handleRemove(input, Inputmask.keyCode.DELETE, pos);
                writeBuffer(input, getBuffer(), getMaskSet().p, e, undoValue !== getBuffer().join(""));
            },
            blurEvent: function(e) {
                var $input = $(this), input = this;
                if (input.inputmask) {
                    HandleNativePlaceholder(input, originalPlaceholder);
                    var nptValue = input.inputmask._valueGet(), buffer = getBuffer().slice();
                    if (nptValue !== "" || colorMask !== undefined) {
                        if (opts.clearMaskOnLostFocus) {
                            if (getLastValidPosition() === -1 && nptValue === getBufferTemplate().join("")) {
                                buffer = [];
                            } else {
                                clearOptionalTail(buffer);
                            }
                        }
                        if (isComplete(buffer) === false) {
                            setTimeout(function() {
                                $input.trigger("incomplete");
                            }, 0);
                            if (opts.clearIncomplete) {
                                resetMaskSet();
                                if (opts.clearMaskOnLostFocus) {
                                    buffer = [];
                                } else {
                                    buffer = getBufferTemplate().slice();
                                }
                            }
                        }
                        writeBuffer(input, buffer, undefined, e);
                    }
                    if (undoValue !== getBuffer().join("")) {
                        undoValue = buffer.join("");
                        $input.trigger("change");
                    }
                }
            },
            mouseenterEvent: function(e) {
                var input = this;
                mouseEnter = true;
                if (document.activeElement !== input && opts.showMaskOnHover) {
                    HandleNativePlaceholder(input, (isRTL ? getBuffer().slice().reverse() : getBuffer()).join(""));
                }
            },
            submitEvent: function(e) {
                if (undoValue !== getBuffer().join("")) {
                    $el.trigger("change");
                }
                if (opts.clearMaskOnLostFocus && getLastValidPosition() === -1 && el.inputmask._valueGet && el.inputmask._valueGet() === getBufferTemplate().join("")) {
                    el.inputmask._valueSet("");
                }
                if (opts.clearIncomplete && isComplete(getBuffer()) === false) {
                    el.inputmask._valueSet("");
                }
                if (opts.removeMaskOnSubmit) {
                    el.inputmask._valueSet(el.inputmask.unmaskedvalue(), true);
                    setTimeout(function() {
                        writeBuffer(el, getBuffer());
                    }, 0);
                }
            },
            resetEvent: function(e) {
                el.inputmask.refreshValue = true;
                setTimeout(function() {
                    $el.trigger("setvalue");
                }, 0);
            }
        };
        function checkVal(input, writeOut, strict, nptvl, initiatingEvent) {
            var inputmask = this || input.inputmask, inputValue = nptvl.slice(), charCodes = "", initialNdx = -1, result = undefined;
            function isTemplateMatch(ndx, charCodes) {
                var charCodeNdx = getMaskTemplate(true, 0, false).slice(ndx, seekNext(ndx)).join("").replace(/'/g, "").indexOf(charCodes);
                return charCodeNdx !== -1 && !isMask(ndx) && (getTest(ndx).match.nativeDef === charCodes.charAt(0) || getTest(ndx).match.fn === null && getTest(ndx).match.nativeDef === "'" + charCodes.charAt(0) || getTest(ndx).match.nativeDef === " " && (getTest(ndx + 1).match.nativeDef === charCodes.charAt(0) || getTest(ndx + 1).match.fn === null && getTest(ndx + 1).match.nativeDef === "'" + charCodes.charAt(0)));
            }
            resetMaskSet();
            if (!strict && opts.autoUnmask !== true) {
                var staticInput = getBufferTemplate().slice(0, seekNext(-1)).join(""), matches = inputValue.join("").match(new RegExp("^" + Inputmask.escapeRegex(staticInput), "g"));
                if (matches && matches.length > 0) {
                    inputValue.splice(0, matches.length * staticInput.length);
                    initialNdx = seekNext(initialNdx);
                }
            } else {
                initialNdx = seekNext(initialNdx);
            }
            if (initialNdx === -1) {
                getMaskSet().p = seekNext(initialNdx);
                initialNdx = 0;
            } else getMaskSet().p = initialNdx;
            inputmask.caretPos = {
                begin: initialNdx
            };
            $.each(inputValue, function(ndx, charCode) {
                if (charCode !== undefined) {
                    if (getMaskSet().validPositions[ndx] === undefined && inputValue[ndx] === getPlaceholder(ndx) && isMask(ndx, true) && isValid(ndx, inputValue[ndx], true, undefined, undefined, true) === false) {
                        getMaskSet().p++;
                    } else {
                        var keypress = new $.Event("_checkval");
                        keypress.which = charCode.charCodeAt(0);
                        charCodes += charCode;
                        var lvp = getLastValidPosition(undefined, true);
                        if (!isTemplateMatch(initialNdx, charCodes)) {
                            result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, inputmask.caretPos.begin);
                            if (result) {
                                initialNdx = inputmask.caretPos.begin + 1;
                                charCodes = "";
                            }
                        } else {
                            result = EventHandlers.keypressEvent.call(input, keypress, true, false, strict, lvp + 1);
                        }
                        if (result) {
                            writeBuffer(undefined, getBuffer(), result.forwardPosition, keypress, false);
                            inputmask.caretPos = {
                                begin: result.forwardPosition,
                                end: result.forwardPosition
                            };
                        }
                    }
                }
            });
            if (writeOut) writeBuffer(input, getBuffer(), result ? result.forwardPosition : undefined, initiatingEvent || new $.Event("checkval"), initiatingEvent && initiatingEvent.type === "input");
        }
        function unmaskedvalue(input) {
            if (input) {
                if (input.inputmask === undefined) {
                    return input.value;
                }
                if (input.inputmask && input.inputmask.refreshValue) {
                    EventHandlers.setValueEvent.call(input);
                }
            }
            var umValue = [], vps = getMaskSet().validPositions;
            for (var pndx in vps) {
                if (vps[pndx].match && vps[pndx].match.fn != null) {
                    umValue.push(vps[pndx].input);
                }
            }
            var unmaskedValue = umValue.length === 0 ? "" : (isRTL ? umValue.reverse() : umValue).join("");
            if ($.isFunction(opts.onUnMask)) {
                var bufferValue = (isRTL ? getBuffer().slice().reverse() : getBuffer()).join("");
                unmaskedValue = opts.onUnMask.call(inputmask, bufferValue, unmaskedValue, opts);
            }
            return unmaskedValue;
        }
        function caret(input, begin, end, notranslate) {
            function translatePosition(pos) {
                if (isRTL && typeof pos === "number" && (!opts.greedy || opts.placeholder !== "") && el) {
                    pos = el.inputmask._valueGet().length - pos;
                }
                return pos;
            }
            var range;
            if (begin !== undefined) {
                if ($.isArray(begin)) {
                    end = isRTL ? begin[0] : begin[1];
                    begin = isRTL ? begin[1] : begin[0];
                }
                if (begin.begin !== undefined) {
                    end = isRTL ? begin.begin : begin.end;
                    begin = isRTL ? begin.end : begin.begin;
                }
                if (typeof begin === "number") {
                    begin = notranslate ? begin : translatePosition(begin);
                    end = notranslate ? end : translatePosition(end);
                    end = typeof end == "number" ? end : begin;
                    var scrollCalc = parseInt(((input.ownerDocument.defaultView || window).getComputedStyle ? (input.ownerDocument.defaultView || window).getComputedStyle(input, null) : input.currentStyle).fontSize) * end;
                    input.scrollLeft = scrollCalc > input.scrollWidth ? scrollCalc : 0;
                    input.inputmask.caretPos = {
                        begin: begin,
                        end: end
                    };
                    if (input === document.activeElement) {
                        if ("selectionStart" in input) {
                            input.selectionStart = begin;
                            input.selectionEnd = end;
                        } else if (window.getSelection) {
                            range = document.createRange();
                            if (input.firstChild === undefined || input.firstChild === null) {
                                var textNode = document.createTextNode("");
                                input.appendChild(textNode);
                            }
                            range.setStart(input.firstChild, begin < input.inputmask._valueGet().length ? begin : input.inputmask._valueGet().length);
                            range.setEnd(input.firstChild, end < input.inputmask._valueGet().length ? end : input.inputmask._valueGet().length);
                            range.collapse(true);
                            var sel = window.getSelection();
                            sel.removeAllRanges();
                            sel.addRange(range);
                        } else if (input.createTextRange) {
                            range = input.createTextRange();
                            range.collapse(true);
                            range.moveEnd("character", end);
                            range.moveStart("character", begin);
                            range.select();
                        }
                        renderColorMask(input, {
                            begin: begin,
                            end: end
                        });
                    }
                }
            } else {
                if ("selectionStart" in input) {
                    begin = input.selectionStart;
                    end = input.selectionEnd;
                } else if (window.getSelection) {
                    range = window.getSelection().getRangeAt(0);
                    if (range.commonAncestorContainer.parentNode === input || range.commonAncestorContainer === input) {
                        begin = range.startOffset;
                        end = range.endOffset;
                    }
                } else if (document.selection && document.selection.createRange) {
                    range = document.selection.createRange();
                    begin = 0 - range.duplicate().moveStart("character", -input.inputmask._valueGet().length);
                    end = begin + range.text.length;
                }
                return {
                    begin: notranslate ? begin : translatePosition(begin),
                    end: notranslate ? end : translatePosition(end)
                };
            }
        }
        function determineLastRequiredPosition(returnDefinition) {
            var buffer = getMaskTemplate(true, getLastValidPosition(), true, true), bl = buffer.length, pos, lvp = getLastValidPosition(), positions = {}, lvTest = getMaskSet().validPositions[lvp], ndxIntlzr = lvTest !== undefined ? lvTest.locator.slice() : undefined, testPos;
            for (pos = lvp + 1; pos < buffer.length; pos++) {
                testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
                ndxIntlzr = testPos.locator.slice();
                positions[pos] = $.extend(true, {}, testPos);
            }
            var lvTestAlt = lvTest && lvTest.alternation !== undefined ? lvTest.locator[lvTest.alternation] : undefined;
            for (pos = bl - 1; pos > lvp; pos--) {
                testPos = positions[pos];
                if ((testPos.match.optionality || testPos.match.optionalQuantifier && testPos.match.newBlockMarker || lvTestAlt && (lvTestAlt !== positions[pos].locator[lvTest.alternation] && testPos.match.fn != null || testPos.match.fn === null && testPos.locator[lvTest.alternation] && checkAlternationMatch(testPos.locator[lvTest.alternation].toString().split(","), lvTestAlt.toString().split(",")) && getTests(pos)[0].def !== "")) && buffer[pos] === getPlaceholder(pos, testPos.match)) {
                    bl--;
                } else break;
            }
            return returnDefinition ? {
                l: bl,
                def: positions[bl] ? positions[bl].match : undefined
            } : bl;
        }
        function clearOptionalTail(buffer) {
            buffer.length = 0;
            var template = getMaskTemplate(true, 0, true, undefined, true), lmnt, validPos;
            while (lmnt = template.shift(), lmnt !== undefined) buffer.push(lmnt);
            return buffer;
        }
        function isComplete(buffer) {
            if ($.isFunction(opts.isComplete)) return opts.isComplete(buffer, opts);
            if (opts.repeat === "*") return undefined;
            var complete = false, lrp = determineLastRequiredPosition(true), aml = seekPrevious(lrp.l);
            if (lrp.def === undefined || lrp.def.newBlockMarker || lrp.def.optionality || lrp.def.optionalQuantifier) {
                complete = true;
                for (var i = 0; i <= aml; i++) {
                    var test = getTestTemplate(i).match;
                    if (test.fn !== null && getMaskSet().validPositions[i] === undefined && test.optionality !== true && test.optionalQuantifier !== true || test.fn === null && buffer[i] !== getPlaceholder(i, test)) {
                        complete = false;
                        break;
                    }
                }
            }
            return complete;
        }
        function handleRemove(input, k, pos, strict, fromIsValid) {
            if (opts.numericInput || isRTL) {
                if (k === Inputmask.keyCode.BACKSPACE) {
                    k = Inputmask.keyCode.DELETE;
                } else if (k === Inputmask.keyCode.DELETE) {
                    k = Inputmask.keyCode.BACKSPACE;
                }
                if (isRTL) {
                    var pend = pos.end;
                    pos.end = pos.begin;
                    pos.begin = pend;
                }
            }
            if (k === Inputmask.keyCode.BACKSPACE && pos.end - pos.begin < 1) {
                pos.begin = seekPrevious(pos.begin);
                if (getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator) {
                    pos.begin--;
                }
            } else if (k === Inputmask.keyCode.DELETE && pos.begin === pos.end) {
                pos.end = isMask(pos.end, true) && (getMaskSet().validPositions[pos.end] && getMaskSet().validPositions[pos.end].input !== opts.radixPoint) ? pos.end + 1 : seekNext(pos.end) + 1;
                if (getMaskSet().validPositions[pos.begin] !== undefined && getMaskSet().validPositions[pos.begin].input === opts.groupSeparator) {
                    pos.end++;
                }
            }
            revalidateMask(pos);
            if (strict !== true && opts.keepStatic !== false || opts.regex !== null) {
                var result = alternate(true);
                if (result) {
                    var newPos = result.caret !== undefined ? result.caret : result.pos ? seekNext(result.pos.begin ? result.pos.begin : result.pos) : getLastValidPosition(-1, true);
                    if (k !== Inputmask.keyCode.DELETE || pos.begin > newPos) {
                        pos.begin == newPos;
                    }
                }
            }
            var lvp = getLastValidPosition(pos.begin, true);
            if (lvp < pos.begin || pos.begin === -1) {
                getMaskSet().p = seekNext(lvp);
            } else if (strict !== true) {
                getMaskSet().p = pos.begin;
                if (fromIsValid !== true) {
                    while (getMaskSet().p < lvp && getMaskSet().validPositions[getMaskSet().p] === undefined) {
                        getMaskSet().p++;
                    }
                }
            }
        }
        function initializeColorMask(input) {
            var computedStyle = (input.ownerDocument.defaultView || window).getComputedStyle(input, null);
            function findCaretPos(clientx) {
                var e = document.createElement("span"), caretPos;
                for (var style in computedStyle) {
                    if (isNaN(style) && style.indexOf("font") !== -1) {
                        e.style[style] = computedStyle[style];
                    }
                }
                e.style.textTransform = computedStyle.textTransform;
                e.style.letterSpacing = computedStyle.letterSpacing;
                e.style.position = "absolute";
                e.style.height = "auto";
                e.style.width = "auto";
                e.style.visibility = "hidden";
                e.style.whiteSpace = "nowrap";
                document.body.appendChild(e);
                var inputText = input.inputmask._valueGet(), previousWidth = 0, itl;
                for (caretPos = 0, itl = inputText.length; caretPos <= itl; caretPos++) {
                    e.innerHTML += inputText.charAt(caretPos) || "_";
                    if (e.offsetWidth >= clientx) {
                        var offset1 = clientx - previousWidth;
                        var offset2 = e.offsetWidth - clientx;
                        e.innerHTML = inputText.charAt(caretPos);
                        offset1 -= e.offsetWidth / 3;
                        caretPos = offset1 < offset2 ? caretPos - 1 : caretPos;
                        break;
                    }
                    previousWidth = e.offsetWidth;
                }
                document.body.removeChild(e);
                return caretPos;
            }
            var template = document.createElement("div");
            template.style.width = computedStyle.width;
            template.style.textAlign = computedStyle.textAlign;
            colorMask = document.createElement("div");
            input.inputmask.colorMask = colorMask;
            colorMask.className = "im-colormask";
            input.parentNode.insertBefore(colorMask, input);
            input.parentNode.removeChild(input);
            colorMask.appendChild(input);
            colorMask.appendChild(template);
            input.style.left = template.offsetLeft + "px";
            $(colorMask).on("mouseleave", function(e) {
                return EventHandlers.mouseleaveEvent.call(input, [ e ]);
            });
            $(colorMask).on("mouseenter", function(e) {
                return EventHandlers.mouseenterEvent.call(input, [ e ]);
            });
            $(colorMask).on("click", function(e) {
                caret(input, findCaretPos(e.clientX));
                return EventHandlers.clickEvent.call(input, [ e ]);
            });
        }
        function renderColorMask(input, caretPos, clear) {
            var maskTemplate = [], isStatic = false, test, testPos, ndxIntlzr, pos = 0;
            function setEntry(entry) {
                if (entry === undefined) entry = "";
                if (!isStatic && (test.fn === null || testPos.input === undefined)) {
                    isStatic = true;
                    maskTemplate.push("<span class='im-static'>" + entry);
                } else if (isStatic && (test.fn !== null && testPos.input !== undefined || test.def === "")) {
                    isStatic = false;
                    var mtl = maskTemplate.length;
                    maskTemplate[mtl - 1] = maskTemplate[mtl - 1] + "</span>";
                    maskTemplate.push(entry);
                } else maskTemplate.push(entry);
            }
            function setCaret() {
                if (document.activeElement === input) {
                    maskTemplate.splice(caretPos.begin, 0, caretPos.begin === caretPos.end || caretPos.end > getMaskSet().maskLength ? '<mark class="im-caret" style="border-right-width: 1px;border-right-style: solid;">' : '<mark class="im-caret-select">');
                    maskTemplate.splice(caretPos.end + 1, 0, "</mark>");
                }
            }
            if (colorMask !== undefined) {
                var buffer = getBuffer();
                if (caretPos === undefined) {
                    caretPos = caret(input);
                } else if (caretPos.begin === undefined) {
                    caretPos = {
                        begin: caretPos,
                        end: caretPos
                    };
                }
                if (clear !== true) {
                    var lvp = getLastValidPosition();
                    do {
                        if (getMaskSet().validPositions[pos]) {
                            testPos = getMaskSet().validPositions[pos];
                            test = testPos.match;
                            ndxIntlzr = testPos.locator.slice();
                            setEntry(buffer[pos]);
                        } else {
                            testPos = getTestTemplate(pos, ndxIntlzr, pos - 1);
                            test = testPos.match;
                            ndxIntlzr = testPos.locator.slice();
                            if (opts.jitMasking === false || pos < lvp || typeof opts.jitMasking === "number" && isFinite(opts.jitMasking) && opts.jitMasking > pos) {
                                setEntry(getPlaceholder(pos, test));
                            } else isStatic = false;
                        }
                        pos++;
                    } while ((maxLength === undefined || pos < maxLength) && (test.fn !== null || test.def !== "") || lvp > pos || isStatic);
                    if (isStatic) setEntry();
                    setCaret();
                }
                var template = colorMask.getElementsByTagName("div")[0];
                template.innerHTML = maskTemplate.join("");
                input.inputmask.positionColorMask(input, template);
            }
        }
        function mask(elem) {
            function isElementTypeSupported(input, opts) {
                function patchValueProperty(npt) {
                    var valueGet;
                    var valueSet;
                    function patchValhook(type) {
                        if ($.valHooks && ($.valHooks[type] === undefined || $.valHooks[type].inputmaskpatch !== true)) {
                            var valhookGet = $.valHooks[type] && $.valHooks[type].get ? $.valHooks[type].get : function(elem) {
                                return elem.value;
                            };
                            var valhookSet = $.valHooks[type] && $.valHooks[type].set ? $.valHooks[type].set : function(elem, value) {
                                elem.value = value;
                                return elem;
                            };
                            $.valHooks[type] = {
                                get: function(elem) {
                                    if (elem.inputmask) {
                                        if (elem.inputmask.opts.autoUnmask) {
                                            return elem.inputmask.unmaskedvalue();
                                        } else {
                                            var result = valhookGet(elem);
                                            return getLastValidPosition(undefined, undefined, elem.inputmask.maskset.validPositions) !== -1 || opts.nullable !== true ? result : "";
                                        }
                                    } else return valhookGet(elem);
                                },
                                set: function(elem, value) {
                                    var $elem = $(elem), result;
                                    result = valhookSet(elem, value);
                                    if (elem.inputmask) {
                                        $elem.trigger("setvalue", [ value ]);
                                    }
                                    return result;
                                },
                                inputmaskpatch: true
                            };
                        }
                    }
                    function getter() {
                        if (this.inputmask) {
                            return this.inputmask.opts.autoUnmask ? this.inputmask.unmaskedvalue() : getLastValidPosition() !== -1 || opts.nullable !== true ? document.activeElement === this && opts.clearMaskOnLostFocus ? (isRTL ? clearOptionalTail(getBuffer().slice()).reverse() : clearOptionalTail(getBuffer().slice())).join("") : valueGet.call(this) : "";
                        } else return valueGet.call(this);
                    }
                    function setter(value) {
                        valueSet.call(this, value);
                        if (this.inputmask) {
                            $(this).trigger("setvalue", [ value ]);
                        }
                    }
                    function installNativeValueSetFallback(npt) {
                        EventRuler.on(npt, "mouseenter", function(event) {
                            var $input = $(this), input = this, value = input.inputmask._valueGet();
                            if (value !== getBuffer().join("")) {
                                $input.trigger("setvalue");
                            }
                        });
                    }
                    if (!npt.inputmask.__valueGet) {
                        if (opts.noValuePatching !== true) {
                            if (Object.getOwnPropertyDescriptor) {
                                if (typeof Object.getPrototypeOf !== "function") {
                                    Object.getPrototypeOf = typeof "test".__proto__ === "object" ? function(object) {
                                        return object.__proto__;
                                    } : function(object) {
                                        return object.constructor.prototype;
                                    };
                                }
                                var valueProperty = Object.getPrototypeOf ? Object.getOwnPropertyDescriptor(Object.getPrototypeOf(npt), "value") : undefined;
                                if (valueProperty && valueProperty.get && valueProperty.set) {
                                    valueGet = valueProperty.get;
                                    valueSet = valueProperty.set;
                                    Object.defineProperty(npt, "value", {
                                        get: getter,
                                        set: setter,
                                        configurable: true
                                    });
                                } else if (npt.tagName !== "INPUT") {
                                    valueGet = function() {
                                        return this.textContent;
                                    };
                                    valueSet = function(value) {
                                        this.textContent = value;
                                    };
                                    Object.defineProperty(npt, "value", {
                                        get: getter,
                                        set: setter,
                                        configurable: true
                                    });
                                }
                            } else if (document.__lookupGetter__ && npt.__lookupGetter__("value")) {
                                valueGet = npt.__lookupGetter__("value");
                                valueSet = npt.__lookupSetter__("value");
                                npt.__defineGetter__("value", getter);
                                npt.__defineSetter__("value", setter);
                            }
                            npt.inputmask.__valueGet = valueGet;
                            npt.inputmask.__valueSet = valueSet;
                        }
                        npt.inputmask._valueGet = function(overruleRTL) {
                            return isRTL && overruleRTL !== true ? valueGet.call(this.el).split("").reverse().join("") : valueGet.call(this.el);
                        };
                        npt.inputmask._valueSet = function(value, overruleRTL) {
                            valueSet.call(this.el, value === null || value === undefined ? "" : overruleRTL !== true && isRTL ? value.split("").reverse().join("") : value);
                        };
                        if (valueGet === undefined) {
                            valueGet = function() {
                                return this.value;
                            };
                            valueSet = function(value) {
                                this.value = value;
                            };
                            patchValhook(npt.type);
                            installNativeValueSetFallback(npt);
                        }
                    }
                }
                var elementType = input.getAttribute("type");
                var isSupported = input.tagName === "INPUT" && $.inArray(elementType, opts.supportsInputType) !== -1 || input.isContentEditable || input.tagName === "TEXTAREA";
                if (!isSupported) {
                    if (input.tagName === "INPUT") {
                        var el = document.createElement("input");
                        el.setAttribute("type", elementType);
                        isSupported = el.type === "text";
                        el = null;
                    } else isSupported = "partial";
                }
                if (isSupported !== false) {
                    patchValueProperty(input);
                } else input.inputmask = undefined;
                return isSupported;
            }
            EventRuler.off(elem);
            var isSupported = isElementTypeSupported(elem, opts);
            if (isSupported !== false) {
                el = elem;
                $el = $(el);
                originalPlaceholder = el.placeholder;
                maxLength = el !== undefined ? el.maxLength : undefined;
                if (maxLength === -1) maxLength = undefined;
                if (opts.colorMask === true) {
                    initializeColorMask(el);
                }
                if (mobile) {
                    if ("inputMode" in el) {
                        el.inputmode = opts.inputmode;
                        el.setAttribute("inputmode", opts.inputmode);
                    }
                    if (opts.disablePredictiveText === true) {
                        if ("autocorrect" in el) {
                            el.autocorrect = false;
                        } else {
                            if (opts.colorMask !== true) {
                                initializeColorMask(el);
                            }
                            el.type = "password";
                        }
                    }
                }
                if (isSupported === true) {
                    el.setAttribute("im-insert", opts.insertMode);
                    EventRuler.on(el, "submit", EventHandlers.submitEvent);
                    EventRuler.on(el, "reset", EventHandlers.resetEvent);
                    EventRuler.on(el, "blur", EventHandlers.blurEvent);
                    EventRuler.on(el, "focus", EventHandlers.focusEvent);
                    if (opts.colorMask !== true) {
                        EventRuler.on(el, "click", EventHandlers.clickEvent);
                        EventRuler.on(el, "mouseleave", EventHandlers.mouseleaveEvent);
                        EventRuler.on(el, "mouseenter", EventHandlers.mouseenterEvent);
                    }
                    EventRuler.on(el, "paste", EventHandlers.pasteEvent);
                    EventRuler.on(el, "cut", EventHandlers.cutEvent);
                    EventRuler.on(el, "complete", opts.oncomplete);
                    EventRuler.on(el, "incomplete", opts.onincomplete);
                    EventRuler.on(el, "cleared", opts.oncleared);
                    if (!mobile && opts.inputEventOnly !== true) {
                        EventRuler.on(el, "keydown", EventHandlers.keydownEvent);
                        EventRuler.on(el, "keypress", EventHandlers.keypressEvent);
                    } else {
                        el.removeAttribute("maxLength");
                    }
                    EventRuler.on(el, "input", EventHandlers.inputFallBackEvent);
                    EventRuler.on(el, "beforeinput", EventHandlers.beforeInputEvent);
                }
                EventRuler.on(el, "setvalue", EventHandlers.setValueEvent);
                undoValue = getBufferTemplate().join("");
                if (el.inputmask._valueGet(true) !== "" || opts.clearMaskOnLostFocus === false || document.activeElement === el) {
                    var initialValue = $.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(inputmask, el.inputmask._valueGet(true), opts) || el.inputmask._valueGet(true) : el.inputmask._valueGet(true);
                    if (initialValue !== "") checkVal(el, true, false, initialValue.split(""));
                    var buffer = getBuffer().slice();
                    undoValue = buffer.join("");
                    if (isComplete(buffer) === false) {
                        if (opts.clearIncomplete) {
                            resetMaskSet();
                        }
                    }
                    if (opts.clearMaskOnLostFocus && document.activeElement !== el) {
                        if (getLastValidPosition() === -1) {
                            buffer = [];
                        } else {
                            clearOptionalTail(buffer);
                        }
                    }
                    if (opts.clearMaskOnLostFocus === false || opts.showMaskOnFocus && document.activeElement === el || el.inputmask._valueGet(true) !== "") writeBuffer(el, buffer);
                    if (document.activeElement === el) {
                        caret(el, seekNext(getLastValidPosition()));
                    }
                }
            }
        }
        var valueBuffer;
        if (actionObj !== undefined) {
            switch (actionObj.action) {
              case "isComplete":
                el = actionObj.el;
                return isComplete(getBuffer());

              case "unmaskedvalue":
                if (el === undefined || actionObj.value !== undefined) {
                    valueBuffer = actionObj.value;
                    valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(inputmask, valueBuffer, opts) || valueBuffer : valueBuffer).split("");
                    checkVal.call(this, undefined, false, false, valueBuffer);
                    if ($.isFunction(opts.onBeforeWrite)) opts.onBeforeWrite.call(inputmask, undefined, getBuffer(), 0, opts);
                }
                return unmaskedvalue(el);

              case "mask":
                mask(el);
                break;

              case "format":
                valueBuffer = ($.isFunction(opts.onBeforeMask) ? opts.onBeforeMask.call(inputmask, actionObj.value, opts) || actionObj.value : actionObj.value).split("");
                checkVal.call(this, undefined, true, false, valueBuffer);
                if (actionObj.metadata) {
                    return {
                        value: isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join(""),
                        metadata: maskScope.call(this, {
                            action: "getmetadata"
                        }, maskset, opts)
                    };
                }
                return isRTL ? getBuffer().slice().reverse().join("") : getBuffer().join("");

              case "isValid":
                if (actionObj.value) {
                    valueBuffer = actionObj.value.split("");
                    checkVal.call(this, undefined, true, true, valueBuffer);
                } else {
                    actionObj.value = getBuffer().join("");
                }
                var buffer = getBuffer();
                var rl = determineLastRequiredPosition(), lmib = buffer.length - 1;
                for (;lmib > rl; lmib--) {
                    if (isMask(lmib)) break;
                }
                buffer.splice(rl, lmib + 1 - rl);
                return isComplete(buffer) && actionObj.value === getBuffer().join("");

              case "getemptymask":
                return getBufferTemplate().join("");

              case "remove":
                if (el && el.inputmask) {
                    $.data(el, "_inputmask_opts", null);
                    $el = $(el);
                    el.inputmask._valueSet(opts.autoUnmask ? unmaskedvalue(el) : el.inputmask._valueGet(true));
                    EventRuler.off(el);
                    if (el.inputmask.colorMask) {
                        colorMask = el.inputmask.colorMask;
                        colorMask.removeChild(el);
                        colorMask.parentNode.insertBefore(el, colorMask);
                        colorMask.parentNode.removeChild(colorMask);
                    }
                    var valueProperty;
                    if (Object.getOwnPropertyDescriptor && Object.getPrototypeOf) {
                        valueProperty = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value");
                        if (valueProperty) {
                            if (el.inputmask.__valueGet) {
                                Object.defineProperty(el, "value", {
                                    get: el.inputmask.__valueGet,
                                    set: el.inputmask.__valueSet,
                                    configurable: true
                                });
                            }
                        }
                    } else if (document.__lookupGetter__ && el.__lookupGetter__("value")) {
                        if (el.inputmask.__valueGet) {
                            el.__defineGetter__("value", el.inputmask.__valueGet);
                            el.__defineSetter__("value", el.inputmask.__valueSet);
                        }
                    }
                    el.inputmask = undefined;
                }
                return el;
                break;

              case "getmetadata":
                if ($.isArray(maskset.metadata)) {
                    var maskTarget = getMaskTemplate(true, 0, false).join("");
                    $.each(maskset.metadata, function(ndx, mtdt) {
                        if (mtdt.mask === maskTarget) {
                            maskTarget = mtdt;
                            return false;
                        }
                    });
                    return maskTarget;
                }
                return maskset.metadata;
            }
        }
    }
    return Inputmask;
});
window.kentico = window.kentico || {};

/**
 * Media file selector module.
 * @param {object} namespace Namespace under which this module operates.
 */
(function (namespace) {
    // Register the initialization function only in page builder
    if (!namespace.pageBuilder) {
        return;
    }

    var init = function (id, filesData) {
        var component = document.getElementById(id);
        component.getString = window.kentico.localization.getString;
        component.selectedData = filesData;
    };

    const modalDialogInternal = namespace._modalDialog = namespace._modalDialog || {};
    const mediaFilesSelector = modalDialogInternal.mediaFilesSelector = modalDialogInternal.mediaFilesSelector || {};
    mediaFilesSelector.init = init;
})(window.kentico);
window.kentico = window.kentico || {};

/**
 * Page selector module.
 * @param {object} namespace Namespace under which this module operates.
 */
(function (namespace) {
    // Register the initialization function only in page builder
    if (!namespace.pageBuilder) {
        return;
    }

    var init = function (id, selectedPageData) {
        var component = document.getElementById(id);
        component.getString = window.kentico.localization.getString;
        component.selectedPageData = selectedPageData;
    };

    const modalDialogInternal = namespace._modalDialog = namespace._modalDialog || {};
    const pageSelector = modalDialogInternal.pageSelector = modalDialogInternal.pageSelector || {};
    pageSelector.init = init;
})(window.kentico);
window.kentico = window.kentico || {};

/**
 * Page selector module.
 * @param {object} namespace Namespace under which this module operates.
 */
(function (namespace) {
    // Register the initialization function only in page builder
    if (!namespace.pageBuilder) {
        return;
    }

    var init = function (id, selectedPageData) {
        var component = document.getElementById(id);
        component.getString = window.kentico.localization.getString;
        component.selectedPageData = selectedPageData;
    };

    const modalDialogInternal = namespace._modalDialog = namespace._modalDialog || {};
    const pathSelector = modalDialogInternal.pathSelector = modalDialogInternal.pathSelector || {};
    pathSelector.init = init;
})(window.kentico);
function createColorPickerFormComponent(formControl, defaultColor) {
    var htmlContentInput = document.querySelector("[name='" + formControl + "'");

    if (htmlContentInput.value !== null) {
        defaultColor = htmlContentInput.value;
    }

    // Simple example, see optional options for more configuration.
    var pickr = Pickr.create({
        el: 'div[data-picker=color]',
        theme: 'nano', // or 'monolith', or 'nano'
        default: defaultColor,
        defaultRepresentation: 'HEX',
        swatches: [
            'rgba(244, 67, 54, 1)',
            'rgba(233, 30, 99, 1)',
            'rgba(156, 39, 176, 1)',
            'rgba(103, 58, 183, 1)',
            'rgba(63, 81, 181, 1)',
            'rgba(33, 150, 243, 1)',
            'rgba(3, 169, 244, 1)',
            'rgba(0, 188, 212, 1)',
            'rgba(0, 150, 136, 1)',
            'rgba(76, 175, 80, 1)',
            'rgba(139, 195, 74, 1)',
            'rgba(205, 220, 57, 1)',
            'rgba(255, 235, 59, 1)',
            'rgba(255, 193, 7, 1)'
        ],
        components: {
            // Main components
            preview: true,
            opacity: true,
            hue: true,
            // Input / output Options
            interaction: {
                hex: true,
                rgba: true,
                hsla: true,
                hsva: true,
                cmyk: true,
                input: true,
                cancel: true,
                clear: true,
                save: true
            }
        }
    });

    if (htmlContentInput.value === null) {
        defaultColor = pickr.getColor().toRGBA().toString(0);
    }

    pickr.on('save', function(color, instance) {
        var rgba = instance.getColor().toHEXA().toString(0);
        htmlContentInput.value = rgba;
    }).on('clear', function(instance) {
        htmlContentInput.value = "";
    });
}

/*! Pickr 1.8.1 MIT | https://github.com/Simonwep/pickr */
!function(t,e){"object"==typeof exports&&"object"==typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):"object"==typeof exports?exports.Pickr=e():t.Pickr=e()}(window,(function(){return function(t){var e={};function r(n){if(e[n])return e[n].exports;var o=e[n]={i:n,l:!1,exports:{}};return t[n].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=t,r.c=e,r.d=function(t,e,n){r.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:n})},r.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},r.t=function(t,e){if(1&e&&(t=r(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var n=Object.create(null);if(r.r(n),Object.defineProperty(n,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var o in t)r.d(n,o,function(e){return t[e]}.bind(null,o));return n},r.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return r.d(e,"a",e),e},r.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},r.p="",r(r.s=140)}([function(t,e,r){var n=r(3),o=r(14).f,i=r(13),a=r(16),c=r(44),u=r(77),s=r(82);t.exports=function(t,e){var r,l,f,p,v,h=t.target,d=t.global,g=t.stat;if(r=d?n:g?n[h]||c(h,{}):(n[h]||{}).prototype)for(l in e){if(p=e[l],f=t.noTargetGet?(v=o(r,l))&&v.value:r[l],!s(d?l:h+(g?".":"#")+l,t.forced)&&void 0!==f){if(typeof p==typeof f)continue;u(p,f)}(t.sham||f&&f.sham)&&i(p,"sham",!0),a(r,l,p,t)}}},function(t,e){t.exports=function(t){try{return!!t()}catch(t){return!0}}},function(t,e,r){var n=r(3),o=r(31),i=r(5),a=r(46),c=r(51),u=r(84),s=o("wks"),l=n.Symbol,f=u?l:l&&l.withoutSetter||a;t.exports=function(t){return i(s,t)&&(c||"string"==typeof s[t])||(c&&i(l,t)?s[t]=l[t]:s[t]=f("Symbol."+t)),s[t]}},function(t,e,r){(function(e){var r=function(t){return t&&t.Math==Math&&t};t.exports=r("object"==typeof globalThis&&globalThis)||r("object"==typeof window&&window)||r("object"==typeof self&&self)||r("object"==typeof e&&e)||function(){return this}()||Function("return this")()}).call(this,r(108))},function(t,e,r){var n=r(7);t.exports=function(t){if(!n(t))throw TypeError(String(t)+" is not an object");return t}},function(t,e,r){var n=r(12),o={}.hasOwnProperty;t.exports=function(t,e){return o.call(n(t),e)}},function(t,e,r){var n=r(1);t.exports=!n((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]}))},function(t,e){t.exports=function(t){return"object"==typeof t?null!==t:"function"==typeof t}},function(t,e,r){var n=r(6),o=r(74),i=r(4),a=r(19),c=Object.defineProperty;e.f=n?c:function(t,e,r){if(i(t),e=a(e,!0),i(r),o)try{return c(t,e,r)}catch(t){}if("get"in r||"set"in r)throw TypeError("Accessors not supported");return"value"in r&&(t[e]=r.value),t}},function(t,e,r){var n=r(17),o=Math.min;t.exports=function(t){return t>0?o(n(t),9007199254740991):0}},function(t,e,r){var n=r(28),o=r(11);t.exports=function(t){return n(o(t))}},function(t,e){t.exports=function(t){if(null==t)throw TypeError("Can't call method on "+t);return t}},function(t,e,r){var n=r(11);t.exports=function(t){return Object(n(t))}},function(t,e,r){var n=r(6),o=r(8),i=r(18);t.exports=n?function(t,e,r){return o.f(t,e,i(1,r))}:function(t,e,r){return t[e]=r,t}},function(t,e,r){var n=r(6),o=r(43),i=r(18),a=r(10),c=r(19),u=r(5),s=r(74),l=Object.getOwnPropertyDescriptor;e.f=n?l:function(t,e){if(t=a(t),e=c(e,!0),s)try{return l(t,e)}catch(t){}if(u(t,e))return i(!o.f.call(t,e),t[e])}},function(t,e){var r={}.toString;t.exports=function(t){return r.call(t).slice(8,-1)}},function(t,e,r){var n=r(3),o=r(13),i=r(5),a=r(44),c=r(76),u=r(29),s=u.get,l=u.enforce,f=String(String).split("String");(t.exports=function(t,e,r,c){var u,s=!!c&&!!c.unsafe,p=!!c&&!!c.enumerable,v=!!c&&!!c.noTargetGet;"function"==typeof r&&("string"!=typeof e||i(r,"name")||o(r,"name",e),(u=l(r)).source||(u.source=f.join("string"==typeof e?e:""))),t!==n?(s?!v&&t[e]&&(p=!0):delete t[e],p?t[e]=r:o(t,e,r)):p?t[e]=r:a(e,r)})(Function.prototype,"toString",(function(){return"function"==typeof this&&s(this).source||c(this)}))},function(t,e){var r=Math.ceil,n=Math.floor;t.exports=function(t){return isNaN(t=+t)?0:(t>0?n:r)(t)}},function(t,e){t.exports=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}}},function(t,e,r){var n=r(7);t.exports=function(t,e){if(!n(t))return t;var r,o;if(e&&"function"==typeof(r=t.toString)&&!n(o=r.call(t)))return o;if("function"==typeof(r=t.valueOf)&&!n(o=r.call(t)))return o;if(!e&&"function"==typeof(r=t.toString)&&!n(o=r.call(t)))return o;throw TypeError("Can't convert object to primitive value")}},function(t,e){t.exports=!1},function(t,e,r){var n=r(86),o=r(28),i=r(12),a=r(9),c=r(53),u=[].push,s=function(t){var e=1==t,r=2==t,s=3==t,l=4==t,f=6==t,p=7==t,v=5==t||f;return function(h,d,g,y){for(var b,m,w=i(h),x=o(w),S=n(d,g,3),_=a(x.length),O=0,A=y||c,E=e?A(h,_):r||p?A(h,0):void 0;_>O;O++)if((v||O in x)&&(m=S(b=x[O],O,w),t))if(e)E[O]=m;else if(m)switch(t){case 3:return!0;case 5:return b;case 6:return O;case 2:u.call(E,b)}else switch(t){case 4:return!1;case 7:u.call(E,b)}return f?-1:s||l?l:E}};t.exports={forEach:s(0),map:s(1),filter:s(2),some:s(3),every:s(4),find:s(5),findIndex:s(6),filterOut:s(7)}},function(t,e,r){"use strict";var n=r(0),o=r(39);n({target:"RegExp",proto:!0,forced:/./.exec!==o},{exec:o})},function(t,e,r){var n=r(58),o=r(16),i=r(116);n||o(Object.prototype,"toString",i,{unsafe:!0})},function(t,e,r){"use strict";var n=r(19),o=r(8),i=r(18);t.exports=function(t,e,r){var a=n(e);a in t?o.f(t,a,i(0,r)):t[a]=r}},function(t,e,r){var n=r(1),o=r(2),i=r(52),a=o("species");t.exports=function(t){return i>=51||!n((function(){var e=[];return(e.constructor={})[a]=function(){return{foo:1}},1!==e[t](Boolean).foo}))}},function(t,e){t.exports={}},function(t,e,r){var n=r(0),o=r(110);n({target:"Object",stat:!0,forced:Object.assign!==o},{assign:o})},function(t,e,r){var n=r(1),o=r(15),i="".split;t.exports=n((function(){return!Object("z").propertyIsEnumerable(0)}))?function(t){return"String"==o(t)?i.call(t,""):Object(t)}:Object},function(t,e,r){var n,o,i,a=r(109),c=r(3),u=r(7),s=r(13),l=r(5),f=r(45),p=r(30),v=r(32),h=c.WeakMap;if(a||f.state){var d=f.state||(f.state=new h),g=d.get,y=d.has,b=d.set;n=function(t,e){if(y.call(d,t))throw new TypeError("Object already initialized");return e.facade=t,b.call(d,t,e),e},o=function(t){return g.call(d,t)||{}},i=function(t){return y.call(d,t)}}else{var m=p("state");v[m]=!0,n=function(t,e){if(l(t,m))throw new TypeError("Object already initialized");return e.facade=t,s(t,m,e),e},o=function(t){return l(t,m)?t[m]:{}},i=function(t){return l(t,m)}}t.exports={set:n,get:o,has:i,enforce:function(t){return i(t)?o(t):n(t,{})},getterFor:function(t){return function(e){var r;if(!u(e)||(r=o(e)).type!==t)throw TypeError("Incompatible receiver, "+t+" required");return r}}}},function(t,e,r){var n=r(31),o=r(46),i=n("keys");t.exports=function(t){return i[t]||(i[t]=o(t))}},function(t,e,r){var n=r(20),o=r(45);(t.exports=function(t,e){return o[t]||(o[t]=void 0!==e?e:{})})("versions",[]).push({version:"3.12.1",mode:n?"pure":"global",copyright:"© 2021 Denis Pushkarev (zloirock.ru)"})},function(t,e){t.exports={}},function(t,e,r){var n=r(79),o=r(3),i=function(t){return"function"==typeof t?t:void 0};t.exports=function(t,e){return arguments.length<2?i(n[t])||i(o[t]):n[t]&&n[t][e]||o[t]&&o[t][e]}},function(t,e,r){var n=r(80),o=r(48).concat("length","prototype");e.f=Object.getOwnPropertyNames||function(t){return n(t,o)}},function(t,e,r){var n=r(80),o=r(48);t.exports=Object.keys||function(t){return n(t,o)}},function(t,e,r){var n,o=r(4),i=r(112),a=r(48),c=r(32),u=r(113),s=r(75),l=r(30),f=l("IE_PROTO"),p=function(){},v=function(t){return"<script>"+t+"<\/script>"},h=function(){try{n=document.domain&&new ActiveXObject("htmlfile")}catch(t){}var t,e;h=n?function(t){t.write(v("")),t.close();var e=t.parentWindow.Object;return t=null,e}(n):((e=s("iframe")).style.display="none",u.appendChild(e),e.src=String("javascript:"),(t=e.contentWindow.document).open(),t.write(v("document.F=Object")),t.close(),t.F);for(var r=a.length;r--;)delete h.prototype[a[r]];return h()};c[f]=!0,t.exports=Object.create||function(t,e){var r;return null!==t?(p.prototype=o(t),r=new p,p.prototype=null,r[f]=t):r=h(),void 0===e?r:i(r,e)}},function(t,e,r){var n=r(3),o=r(85),i=r(114),a=r(13);for(var c in o){var u=n[c],s=u&&u.prototype;if(s&&s.forEach!==i)try{a(s,"forEach",i)}catch(t){s.forEach=i}}},function(t,e,r){var n=r(15);t.exports=Array.isArray||function(t){return"Array"==n(t)}},function(t,e,r){"use strict";var n,o,i=r(89),a=r(90),c=r(31),u=RegExp.prototype.exec,s=c("native-string-replace",String.prototype.replace),l=u,f=(n=/a/,o=/b*/g,u.call(n,"a"),u.call(o,"a"),0!==n.lastIndex||0!==o.lastIndex),p=a.UNSUPPORTED_Y||a.BROKEN_CARET,v=void 0!==/()??/.exec("")[1];(f||v||p)&&(l=function(t){var e,r,n,o,a=this,c=p&&a.sticky,l=i.call(a),h=a.source,d=0,g=t;return c&&(-1===(l=l.replace("y","")).indexOf("g")&&(l+="g"),g=String(t).slice(a.lastIndex),a.lastIndex>0&&(!a.multiline||a.multiline&&"\n"!==t[a.lastIndex-1])&&(h="(?: "+h+")",g=" "+g,d++),r=new RegExp("^(?:"+h+")",l)),v&&(r=new RegExp("^"+h+"$(?!\\s)",l)),f&&(e=a.lastIndex),n=u.call(c?r:a,g),c?n?(n.input=n.input.slice(d),n[0]=n[0].slice(d),n.index=a.lastIndex,a.lastIndex+=n[0].length):a.lastIndex=0:f&&n&&(a.lastIndex=a.global?n.index+n[0].length:e),v&&n&&n.length>1&&s.call(n[0],r,(function(){for(o=1;o<arguments.length-2;o++)void 0===arguments[o]&&(n[o]=void 0)})),n}),t.exports=l},function(t,e,r){"use strict";var n=r(6),o=r(3),i=r(82),a=r(16),c=r(5),u=r(15),s=r(117),l=r(19),f=r(1),p=r(36),v=r(34).f,h=r(14).f,d=r(8).f,g=r(95).trim,y=o.Number,b=y.prototype,m="Number"==u(p(b)),w=function(t){var e,r,n,o,i,a,c,u,s=l(t,!1);if("string"==typeof s&&s.length>2)if(43===(e=(s=g(s)).charCodeAt(0))||45===e){if(88===(r=s.charCodeAt(2))||120===r)return NaN}else if(48===e){switch(s.charCodeAt(1)){case 66:case 98:n=2,o=49;break;case 79:case 111:n=8,o=55;break;default:return+s}for(a=(i=s.slice(2)).length,c=0;c<a;c++)if((u=i.charCodeAt(c))<48||u>o)return NaN;return parseInt(i,n)}return+s};if(i("Number",!y(" 0o1")||!y("0b1")||y("+0x1"))){for(var x,S=function(t){var e=arguments.length<1?0:t,r=this;return r instanceof S&&(m?f((function(){b.valueOf.call(r)})):"Number"!=u(r))?s(new y(w(e)),r,S):w(e)},_=n?v(y):"MAX_VALUE,MIN_VALUE,NaN,NEGATIVE_INFINITY,POSITIVE_INFINITY,EPSILON,isFinite,isInteger,isNaN,isSafeInteger,MAX_SAFE_INTEGER,MIN_SAFE_INTEGER,parseFloat,parseInt,isInteger,fromString,range".split(","),O=0;_.length>O;O++)c(y,x=_[O])&&!c(S,x)&&d(S,x,h(y,x));S.prototype=b,b.constructor=S,a(o,"Number",S)}},function(t,e,r){"use strict";var n=r(10),o=r(50),i=r(26),a=r(29),c=r(97),u=a.set,s=a.getterFor("Array Iterator");t.exports=c(Array,"Array",(function(t,e){u(this,{type:"Array Iterator",target:n(t),index:0,kind:e})}),(function(){var t=s(this),e=t.target,r=t.kind,n=t.index++;return!e||n>=e.length?(t.target=void 0,{value:void 0,done:!0}):"keys"==r?{value:n,done:!1}:"values"==r?{value:e[n],done:!1}:{value:[n,e[n]],done:!1}}),"values"),i.Arguments=i.Array,o("keys"),o("values"),o("entries")},function(t,e,r){var n=r(0),o=r(12),i=r(35);n({target:"Object",stat:!0,forced:r(1)((function(){i(1)}))},{keys:function(t){return i(o(t))}})},function(t,e,r){"use strict";var n={}.propertyIsEnumerable,o=Object.getOwnPropertyDescriptor,i=o&&!n.call({1:2},1);e.f=i?function(t){var e=o(this,t);return!!e&&e.enumerable}:n},function(t,e,r){var n=r(3),o=r(13);t.exports=function(t,e){try{o(n,t,e)}catch(r){n[t]=e}return e}},function(t,e,r){var n=r(3),o=r(44),i=n["__core-js_shared__"]||o("__core-js_shared__",{});t.exports=i},function(t,e){var r=0,n=Math.random();t.exports=function(t){return"Symbol("+String(void 0===t?"":t)+")_"+(++r+n).toString(36)}},function(t,e,r){var n=r(17),o=Math.max,i=Math.min;t.exports=function(t,e){var r=n(t);return r<0?o(r+e,0):i(r,e)}},function(t,e){t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},function(t,e){e.f=Object.getOwnPropertySymbols},function(t,e,r){var n=r(2),o=r(36),i=r(8),a=n("unscopables"),c=Array.prototype;null==c[a]&&i.f(c,a,{configurable:!0,value:o(null)}),t.exports=function(t){c[a][t]=!0}},function(t,e,r){var n=r(52),o=r(1);t.exports=!!Object.getOwnPropertySymbols&&!o((function(){return!String(Symbol())||!Symbol.sham&&n&&n<41}))},function(t,e,r){var n,o,i=r(3),a=r(83),c=i.process,u=c&&c.versions,s=u&&u.v8;s?o=(n=s.split("."))[0]<4?1:n[0]+n[1]:a&&(!(n=a.match(/Edge\/(\d+)/))||n[1]>=74)&&(n=a.match(/Chrome\/(\d+)/))&&(o=n[1]),t.exports=o&&+o},function(t,e,r){var n=r(7),o=r(38),i=r(2)("species");t.exports=function(t,e){var r;return o(t)&&("function"!=typeof(r=t.constructor)||r!==Array&&!o(r.prototype)?n(r)&&null===(r=r[i])&&(r=void 0):r=void 0),new(void 0===r?Array:r)(0===e?0:e)}},function(t,e,r){"use strict";var n=r(17),o=r(11);t.exports=function(t){var e=String(o(this)),r="",i=n(t);if(i<0||i==1/0)throw RangeError("Wrong number of repetitions");for(;i>0;(i>>>=1)&&(e+=e))1&i&&(r+=e);return r}},function(t,e,r){"use strict";r(22);var n=r(16),o=r(39),i=r(1),a=r(2),c=r(13),u=a("species"),s=RegExp.prototype,l=!i((function(){var t=/./;return t.exec=function(){var t=[];return t.groups={a:"7"},t},"7"!=="".replace(t,"$<a>")})),f="$0"==="a".replace(/./,"$0"),p=a("replace"),v=!!/./[p]&&""===/./[p]("a","$0"),h=!i((function(){var t=/(?:)/,e=t.exec;t.exec=function(){return e.apply(this,arguments)};var r="ab".split(t);return 2!==r.length||"a"!==r[0]||"b"!==r[1]}));t.exports=function(t,e,r,p){var d=a(t),g=!i((function(){var e={};return e[d]=function(){return 7},7!=""[t](e)})),y=g&&!i((function(){var e=!1,r=/a/;return"split"===t&&((r={}).constructor={},r.constructor[u]=function(){return r},r.flags="",r[d]=/./[d]),r.exec=function(){return e=!0,null},r[d](""),!e}));if(!g||!y||"replace"===t&&(!l||!f||v)||"split"===t&&!h){var b=/./[d],m=r(d,""[t],(function(t,e,r,n,i){var a=e.exec;return a===o||a===s.exec?g&&!i?{done:!0,value:b.call(e,r,n)}:{done:!0,value:t.call(r,e,n)}:{done:!1}}),{REPLACE_KEEPS_$0:f,REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE:v}),w=m[0],x=m[1];n(String.prototype,t,w),n(s,d,2==e?function(t,e){return x.call(t,this,e)}:function(t){return x.call(t,this)})}p&&c(s[d],"sham",!0)}},function(t,e,r){"use strict";var n=r(92).charAt;t.exports=function(t,e,r){return e+(r?n(t,e).length:1)}},function(t,e,r){var n=r(15),o=r(39);t.exports=function(t,e){var r=t.exec;if("function"==typeof r){var i=r.call(t,e);if("object"!=typeof i)throw TypeError("RegExp exec method returned something other than an Object or null");return i}if("RegExp"!==n(t))throw TypeError("RegExp#exec called on incompatible receiver");return o.call(t,e)}},function(t,e,r){var n={};n[r(2)("toStringTag")]="z",t.exports="[object z]"===String(n)},function(t,e,r){"use strict";var n=r(16),o=r(4),i=r(1),a=r(89),c=RegExp.prototype,u=c.toString,s=i((function(){return"/a/b"!=u.call({source:"a",flags:"b"})})),l="toString"!=u.name;(s||l)&&n(RegExp.prototype,"toString",(function(){var t=o(this),e=String(t.source),r=t.flags;return"/"+e+"/"+String(void 0===r&&t instanceof RegExp&&!("flags"in c)?a.call(t):r)}),{unsafe:!0})},function(t,e,r){"use strict";var n=r(0),o=r(1),i=r(38),a=r(7),c=r(12),u=r(9),s=r(24),l=r(53),f=r(25),p=r(2),v=r(52),h=p("isConcatSpreadable"),d=v>=51||!o((function(){var t=[];return t[h]=!1,t.concat()[0]!==t})),g=f("concat"),y=function(t){if(!a(t))return!1;var e=t[h];return void 0!==e?!!e:i(t)};n({target:"Array",proto:!0,forced:!d||!g},{concat:function(t){var e,r,n,o,i,a=c(this),f=l(a,0),p=0;for(e=-1,n=arguments.length;e<n;e++)if(y(i=-1===e?a:arguments[e])){if(p+(o=u(i.length))>9007199254740991)throw TypeError("Maximum allowed index exceeded");for(r=0;r<o;r++,p++)r in i&&s(f,p,i[r])}else{if(p>=9007199254740991)throw TypeError("Maximum allowed index exceeded");s(f,p++,i)}return f.length=p,f}})},function(t,e,r){var n=r(8).f,o=r(5),i=r(2)("toStringTag");t.exports=function(t,e,r){t&&!o(t=r?t:t.prototype,i)&&n(t,i,{configurable:!0,value:e})}},function(t,e,r){var n=r(3),o=r(85),i=r(41),a=r(13),c=r(2),u=c("iterator"),s=c("toStringTag"),l=i.values;for(var f in o){var p=n[f],v=p&&p.prototype;if(v){if(v[u]!==l)try{a(v,u,l)}catch(t){v[u]=l}if(v[s]||a(v,s,f),o[f])for(var h in i)if(v[h]!==i[h])try{a(v,h,i[h])}catch(t){v[h]=i[h]}}}},function(t,e,r){"use strict";var n=r(0),o=r(3),i=r(33),a=r(20),c=r(6),u=r(51),s=r(84),l=r(1),f=r(5),p=r(38),v=r(7),h=r(4),d=r(12),g=r(10),y=r(19),b=r(18),m=r(36),w=r(35),x=r(34),S=r(124),_=r(49),O=r(14),A=r(8),E=r(43),j=r(13),P=r(16),C=r(31),k=r(30),I=r(32),T=r(46),R=r(2),L=r(103),N=r(104),M=r(61),D=r(29),F=r(21).forEach,B=k("hidden"),U=R("toPrimitive"),H=D.set,$=D.getterFor("Symbol"),G=Object.prototype,V=o.Symbol,W=i("JSON","stringify"),z=O.f,Y=A.f,X=S.f,K=E.f,q=C("symbols"),J=C("op-symbols"),Q=C("string-to-symbol-registry"),Z=C("symbol-to-string-registry"),tt=C("wks"),et=o.QObject,rt=!et||!et.prototype||!et.prototype.findChild,nt=c&&l((function(){return 7!=m(Y({},"a",{get:function(){return Y(this,"a",{value:7}).a}})).a}))?function(t,e,r){var n=z(G,e);n&&delete G[e],Y(t,e,r),n&&t!==G&&Y(G,e,n)}:Y,ot=function(t,e){var r=q[t]=m(V.prototype);return H(r,{type:"Symbol",tag:t,description:e}),c||(r.description=e),r},it=s?function(t){return"symbol"==typeof t}:function(t){return Object(t)instanceof V},at=function(t,e,r){t===G&&at(J,e,r),h(t);var n=y(e,!0);return h(r),f(q,n)?(r.enumerable?(f(t,B)&&t[B][n]&&(t[B][n]=!1),r=m(r,{enumerable:b(0,!1)})):(f(t,B)||Y(t,B,b(1,{})),t[B][n]=!0),nt(t,n,r)):Y(t,n,r)},ct=function(t,e){h(t);var r=g(e),n=w(r).concat(ft(r));return F(n,(function(e){c&&!ut.call(r,e)||at(t,e,r[e])})),t},ut=function(t){var e=y(t,!0),r=K.call(this,e);return!(this===G&&f(q,e)&&!f(J,e))&&(!(r||!f(this,e)||!f(q,e)||f(this,B)&&this[B][e])||r)},st=function(t,e){var r=g(t),n=y(e,!0);if(r!==G||!f(q,n)||f(J,n)){var o=z(r,n);return!o||!f(q,n)||f(r,B)&&r[B][n]||(o.enumerable=!0),o}},lt=function(t){var e=X(g(t)),r=[];return F(e,(function(t){f(q,t)||f(I,t)||r.push(t)})),r},ft=function(t){var e=t===G,r=X(e?J:g(t)),n=[];return F(r,(function(t){!f(q,t)||e&&!f(G,t)||n.push(q[t])})),n};(u||(P((V=function(){if(this instanceof V)throw TypeError("Symbol is not a constructor");var t=arguments.length&&void 0!==arguments[0]?String(arguments[0]):void 0,e=T(t),r=function(t){this===G&&r.call(J,t),f(this,B)&&f(this[B],e)&&(this[B][e]=!1),nt(this,e,b(1,t))};return c&&rt&&nt(G,e,{configurable:!0,set:r}),ot(e,t)}).prototype,"toString",(function(){return $(this).tag})),P(V,"withoutSetter",(function(t){return ot(T(t),t)})),E.f=ut,A.f=at,O.f=st,x.f=S.f=lt,_.f=ft,L.f=function(t){return ot(R(t),t)},c&&(Y(V.prototype,"description",{configurable:!0,get:function(){return $(this).description}}),a||P(G,"propertyIsEnumerable",ut,{unsafe:!0}))),n({global:!0,wrap:!0,forced:!u,sham:!u},{Symbol:V}),F(w(tt),(function(t){N(t)})),n({target:"Symbol",stat:!0,forced:!u},{for:function(t){var e=String(t);if(f(Q,e))return Q[e];var r=V(e);return Q[e]=r,Z[r]=e,r},keyFor:function(t){if(!it(t))throw TypeError(t+" is not a symbol");if(f(Z,t))return Z[t]},useSetter:function(){rt=!0},useSimple:function(){rt=!1}}),n({target:"Object",stat:!0,forced:!u,sham:!c},{create:function(t,e){return void 0===e?m(t):ct(m(t),e)},defineProperty:at,defineProperties:ct,getOwnPropertyDescriptor:st}),n({target:"Object",stat:!0,forced:!u},{getOwnPropertyNames:lt,getOwnPropertySymbols:ft}),n({target:"Object",stat:!0,forced:l((function(){_.f(1)}))},{getOwnPropertySymbols:function(t){return _.f(d(t))}}),W)&&n({target:"JSON",stat:!0,forced:!u||l((function(){var t=V();return"[null]"!=W([t])||"{}"!=W({a:t})||"{}"!=W(Object(t))}))},{stringify:function(t,e,r){for(var n,o=[t],i=1;arguments.length>i;)o.push(arguments[i++]);if(n=e,(v(e)||void 0!==t)&&!it(t))return p(e)||(e=function(t,e){if("function"==typeof n&&(e=n.call(this,t,e)),!it(e))return e}),o[1]=e,W.apply(null,o)}});V.prototype[U]||j(V.prototype,U,V.prototype.valueOf),M(V,"Symbol"),I[B]=!0},function(t,e,r){"use strict";var n=r(0),o=r(21).filter;n({target:"Array",proto:!0,forced:!r(25)("filter")},{filter:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,r){var n=r(0),o=r(1),i=r(10),a=r(14).f,c=r(6),u=o((function(){a(1)}));n({target:"Object",stat:!0,forced:!c||u,sham:!c},{getOwnPropertyDescriptor:function(t,e){return a(i(t),e)}})},function(t,e,r){var n=r(0),o=r(6),i=r(78),a=r(10),c=r(14),u=r(24);n({target:"Object",stat:!0,sham:!o},{getOwnPropertyDescriptors:function(t){for(var e,r,n=a(t),o=c.f,s=i(n),l={},f=0;s.length>f;)void 0!==(r=o(n,e=s[f++]))&&u(l,e,r);return l}})},function(t,e,r){"use strict";var n=r(0),o=r(7),i=r(38),a=r(47),c=r(9),u=r(10),s=r(24),l=r(2),f=r(25)("slice"),p=l("species"),v=[].slice,h=Math.max;n({target:"Array",proto:!0,forced:!f},{slice:function(t,e){var r,n,l,f=u(this),d=c(f.length),g=a(t,d),y=a(void 0===e?d:e,d);if(i(f)&&("function"!=typeof(r=f.constructor)||r!==Array&&!i(r.prototype)?o(r)&&null===(r=r[p])&&(r=void 0):r=void 0,r===Array||void 0===r))return v.call(f,g,y);for(n=new(void 0===r?Array:r)(h(y-g,0)),l=0;g<y;g++,l++)g in f&&s(n,l,f[g]);return n.length=l,n}})},function(t,e,r){var n=r(6),o=r(8).f,i=Function.prototype,a=i.toString,c=/^\s*function ([^ (]*)/;n&&!("name"in i)&&o(i,"name",{configurable:!0,get:function(){try{return a.call(this).match(c)[1]}catch(t){return""}}})},function(t,e,r){var n=r(0),o=r(125);n({target:"Array",stat:!0,forced:!r(130)((function(t){Array.from(t)}))},{from:o})},function(t,e,r){"use strict";var n=r(92).charAt,o=r(29),i=r(97),a=o.set,c=o.getterFor("String Iterator");i(String,"String",(function(t){a(this,{type:"String Iterator",string:String(t),index:0})}),(function(){var t,e=c(this),r=e.string,o=e.index;return o>=r.length?{value:void 0,done:!0}:(t=n(r,o),e.index+=t.length,{value:t,done:!1})}))},function(t,e,r){"use strict";var n=r(0),o=r(6),i=r(3),a=r(5),c=r(7),u=r(8).f,s=r(77),l=i.Symbol;if(o&&"function"==typeof l&&(!("description"in l.prototype)||void 0!==l().description)){var f={},p=function(){var t=arguments.length<1||void 0===arguments[0]?void 0:String(arguments[0]),e=this instanceof p?new l(t):void 0===t?l():l(t);return""===t&&(f[e]=!0),e};s(p,l);var v=p.prototype=l.prototype;v.constructor=p;var h=v.toString,d="Symbol(test)"==String(l("test")),g=/^Symbol\((.*)\)[^)]+$/;u(v,"description",{configurable:!0,get:function(){var t=c(this)?this.valueOf():this,e=h.call(t);if(a(f,t))return"";var r=d?e.slice(7,-1):e.replace(g,"$1");return""===r?void 0:r}}),n({global:!0,forced:!0},{Symbol:p})}},function(t,e,r){r(104)("iterator")},function(t,e,r){"use strict";var n=r(55),o=r(102),i=r(4),a=r(11),c=r(133),u=r(56),s=r(9),l=r(57),f=r(39),p=r(90).UNSUPPORTED_Y,v=[].push,h=Math.min;n("split",2,(function(t,e,r){var n;return n="c"=="abbc".split(/(b)*/)[1]||4!="test".split(/(?:)/,-1).length||2!="ab".split(/(?:ab)*/).length||4!=".".split(/(.?)(.?)/).length||".".split(/()()/).length>1||"".split(/.?/).length?function(t,r){var n=String(a(this)),i=void 0===r?4294967295:r>>>0;if(0===i)return[];if(void 0===t)return[n];if(!o(t))return e.call(n,t,i);for(var c,u,s,l=[],p=(t.ignoreCase?"i":"")+(t.multiline?"m":"")+(t.unicode?"u":"")+(t.sticky?"y":""),h=0,d=new RegExp(t.source,p+"g");(c=f.call(d,n))&&!((u=d.lastIndex)>h&&(l.push(n.slice(h,c.index)),c.length>1&&c.index<n.length&&v.apply(l,c.slice(1)),s=c[0].length,h=u,l.length>=i));)d.lastIndex===c.index&&d.lastIndex++;return h===n.length?!s&&d.test("")||l.push(""):l.push(n.slice(h)),l.length>i?l.slice(0,i):l}:"0".split(void 0,0).length?function(t,r){return void 0===t&&0===r?[]:e.call(this,t,r)}:e,[function(e,r){var o=a(this),i=null==e?void 0:e[t];return void 0!==i?i.call(e,o,r):n.call(String(o),e,r)},function(t,o){var a=r(n,t,this,o,n!==e);if(a.done)return a.value;var f=i(t),v=String(this),d=c(f,RegExp),g=f.unicode,y=(f.ignoreCase?"i":"")+(f.multiline?"m":"")+(f.unicode?"u":"")+(p?"g":"y"),b=new d(p?"^(?:"+f.source+")":f,y),m=void 0===o?4294967295:o>>>0;if(0===m)return[];if(0===v.length)return null===l(b,v)?[v]:[];for(var w=0,x=0,S=[];x<v.length;){b.lastIndex=p?0:x;var _,O=l(b,p?v.slice(x):v);if(null===O||(_=h(s(b.lastIndex+(p?x:0)),v.length))===w)x=u(v,x,g);else{if(S.push(v.slice(w,x)),S.length===m)return S;for(var A=1;A<=O.length-1;A++)if(S.push(O[A]),S.length===m)return S;x=w=_}}return S.push(v.slice(w)),S}]}),p)},function(t,e,r){var n=r(6),o=r(1),i=r(75);t.exports=!n&&!o((function(){return 7!=Object.defineProperty(i("div"),"a",{get:function(){return 7}}).a}))},function(t,e,r){var n=r(3),o=r(7),i=n.document,a=o(i)&&o(i.createElement);t.exports=function(t){return a?i.createElement(t):{}}},function(t,e,r){var n=r(45),o=Function.toString;"function"!=typeof n.inspectSource&&(n.inspectSource=function(t){return o.call(t)}),t.exports=n.inspectSource},function(t,e,r){var n=r(5),o=r(78),i=r(14),a=r(8);t.exports=function(t,e){for(var r=o(e),c=a.f,u=i.f,s=0;s<r.length;s++){var l=r[s];n(t,l)||c(t,l,u(e,l))}}},function(t,e,r){var n=r(33),o=r(34),i=r(49),a=r(4);t.exports=n("Reflect","ownKeys")||function(t){var e=o.f(a(t)),r=i.f;return r?e.concat(r(t)):e}},function(t,e,r){var n=r(3);t.exports=n},function(t,e,r){var n=r(5),o=r(10),i=r(81).indexOf,a=r(32);t.exports=function(t,e){var r,c=o(t),u=0,s=[];for(r in c)!n(a,r)&&n(c,r)&&s.push(r);for(;e.length>u;)n(c,r=e[u++])&&(~i(s,r)||s.push(r));return s}},function(t,e,r){var n=r(10),o=r(9),i=r(47),a=function(t){return function(e,r,a){var c,u=n(e),s=o(u.length),l=i(a,s);if(t&&r!=r){for(;s>l;)if((c=u[l++])!=c)return!0}else for(;s>l;l++)if((t||l in u)&&u[l]===r)return t||l||0;return!t&&-1}};t.exports={includes:a(!0),indexOf:a(!1)}},function(t,e,r){var n=r(1),o=/#|\.prototype\./,i=function(t,e){var r=c[a(t)];return r==s||r!=u&&("function"==typeof e?n(e):!!e)},a=i.normalize=function(t){return String(t).replace(o,".").toLowerCase()},c=i.data={},u=i.NATIVE="N",s=i.POLYFILL="P";t.exports=i},function(t,e,r){var n=r(33);t.exports=n("navigator","userAgent")||""},function(t,e,r){var n=r(51);t.exports=n&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},function(t,e){t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},function(t,e,r){var n=r(87);t.exports=function(t,e,r){if(n(t),void 0===e)return t;switch(r){case 0:return function(){return t.call(e)};case 1:return function(r){return t.call(e,r)};case 2:return function(r,n){return t.call(e,r,n)};case 3:return function(r,n,o){return t.call(e,r,n,o)}}return function(){return t.apply(e,arguments)}}},function(t,e){t.exports=function(t){if("function"!=typeof t)throw TypeError(String(t)+" is not a function");return t}},function(t,e,r){"use strict";var n=r(1);t.exports=function(t,e){var r=[][t];return!!r&&n((function(){r.call(null,e||function(){throw 1},1)}))}},function(t,e,r){"use strict";var n=r(4);t.exports=function(){var t=n(this),e="";return t.global&&(e+="g"),t.ignoreCase&&(e+="i"),t.multiline&&(e+="m"),t.dotAll&&(e+="s"),t.unicode&&(e+="u"),t.sticky&&(e+="y"),e}},function(t,e,r){"use strict";var n=r(1);function o(t,e){return RegExp(t,e)}e.UNSUPPORTED_Y=n((function(){var t=o("a","y");return t.lastIndex=2,null!=t.exec("abcd")})),e.BROKEN_CARET=n((function(){var t=o("^r","gy");return t.lastIndex=2,null!=t.exec("str")}))},function(t,e,r){"use strict";var n=r(55),o=r(4),i=r(9),a=r(11),c=r(56),u=r(57);n("match",1,(function(t,e,r){return[function(e){var r=a(this),n=null==e?void 0:e[t];return void 0!==n?n.call(e,r):new RegExp(e)[t](String(r))},function(t){var n=r(e,t,this);if(n.done)return n.value;var a=o(t),s=String(this);if(!a.global)return u(a,s);var l=a.unicode;a.lastIndex=0;for(var f,p=[],v=0;null!==(f=u(a,s));){var h=String(f[0]);p[v]=h,""===h&&(a.lastIndex=c(s,i(a.lastIndex),l)),v++}return 0===v?null:p}]}))},function(t,e,r){var n=r(17),o=r(11),i=function(t){return function(e,r){var i,a,c=String(o(e)),u=n(r),s=c.length;return u<0||u>=s?t?"":void 0:(i=c.charCodeAt(u))<55296||i>56319||u+1===s||(a=c.charCodeAt(u+1))<56320||a>57343?t?c.charAt(u):i:t?c.slice(u,u+2):a-56320+(i-55296<<10)+65536}};t.exports={codeAt:i(!1),charAt:i(!0)}},function(t,e,r){var n=r(58),o=r(15),i=r(2)("toStringTag"),a="Arguments"==o(function(){return arguments}());t.exports=n?o:function(t){var e,r,n;return void 0===t?"Undefined":null===t?"Null":"string"==typeof(r=function(t,e){try{return t[e]}catch(t){}}(e=Object(t),i))?r:a?o(e):"Object"==(n=o(e))&&"function"==typeof e.callee?"Arguments":n}},function(t,e,r){var n=r(4),o=r(118);t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var t,e=!1,r={};try{(t=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(r,[]),e=r instanceof Array}catch(t){}return function(r,i){return n(r),o(i),e?t.call(r,i):r.__proto__=i,r}}():void 0)},function(t,e,r){var n=r(11),o="["+r(96)+"]",i=RegExp("^"+o+o+"*"),a=RegExp(o+o+"*$"),c=function(t){return function(e){var r=String(n(e));return 1&t&&(r=r.replace(i,"")),2&t&&(r=r.replace(a,"")),r}};t.exports={start:c(1),end:c(2),trim:c(3)}},function(t,e){t.exports="\t\n\v\f\r                　\u2028\u2029\ufeff"},function(t,e,r){"use strict";var n=r(0),o=r(119),i=r(99),a=r(94),c=r(61),u=r(13),s=r(16),l=r(2),f=r(20),p=r(26),v=r(98),h=v.IteratorPrototype,d=v.BUGGY_SAFARI_ITERATORS,g=l("iterator"),y=function(){return this};t.exports=function(t,e,r,l,v,b,m){o(r,e,l);var w,x,S,_=function(t){if(t===v&&P)return P;if(!d&&t in E)return E[t];switch(t){case"keys":case"values":case"entries":return function(){return new r(this,t)}}return function(){return new r(this)}},O=e+" Iterator",A=!1,E=t.prototype,j=E[g]||E["@@iterator"]||v&&E[v],P=!d&&j||_(v),C="Array"==e&&E.entries||j;if(C&&(w=i(C.call(new t)),h!==Object.prototype&&w.next&&(f||i(w)===h||(a?a(w,h):"function"!=typeof w[g]&&u(w,g,y)),c(w,O,!0,!0),f&&(p[O]=y))),"values"==v&&j&&"values"!==j.name&&(A=!0,P=function(){return j.call(this)}),f&&!m||E[g]===P||u(E,g,P),p[e]=P,v)if(x={values:_("values"),keys:b?P:_("keys"),entries:_("entries")},m)for(S in x)(d||A||!(S in E))&&s(E,S,x[S]);else n({target:e,proto:!0,forced:d||A},x);return x}},function(t,e,r){"use strict";var n,o,i,a=r(1),c=r(99),u=r(13),s=r(5),l=r(2),f=r(20),p=l("iterator"),v=!1;[].keys&&("next"in(i=[].keys())?(o=c(c(i)))!==Object.prototype&&(n=o):v=!0);var h=null==n||a((function(){var t={};return n[p].call(t)!==t}));h&&(n={}),f&&!h||s(n,p)||u(n,p,(function(){return this})),t.exports={IteratorPrototype:n,BUGGY_SAFARI_ITERATORS:v}},function(t,e,r){var n=r(5),o=r(12),i=r(30),a=r(120),c=i("IE_PROTO"),u=Object.prototype;t.exports=a?Object.getPrototypeOf:function(t){return t=o(t),n(t,c)?t[c]:"function"==typeof t.constructor&&t instanceof t.constructor?t.constructor.prototype:t instanceof Object?u:null}},function(t,e,r){"use strict";var n=r(0),o=r(21).find,i=r(50),a=!0;"find"in[]&&Array(1).find((function(){a=!1})),n({target:"Array",proto:!0,forced:a},{find:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i("find")},function(t,e,r){"use strict";var n,o=r(0),i=r(14).f,a=r(9),c=r(122),u=r(11),s=r(123),l=r(20),f="".startsWith,p=Math.min,v=s("startsWith");o({target:"String",proto:!0,forced:!!(l||v||(n=i(String.prototype,"startsWith"),!n||n.writable))&&!v},{startsWith:function(t){var e=String(u(this));c(t);var r=a(p(arguments.length>1?arguments[1]:void 0,e.length)),n=String(t);return f?f.call(e,n,r):e.slice(r,r+n.length)===n}})},function(t,e,r){var n=r(7),o=r(15),i=r(2)("match");t.exports=function(t){var e;return n(t)&&(void 0!==(e=t[i])?!!e:"RegExp"==o(t))}},function(t,e,r){var n=r(2);e.f=n},function(t,e,r){var n=r(79),o=r(5),i=r(103),a=r(8).f;t.exports=function(t){var e=n.Symbol||(n.Symbol={});o(e,t)||a(e,t,{value:i.f(t)})}},function(t,e,r){"use strict";var n=r(0),o=r(21).map;n({target:"Array",proto:!0,forced:!r(25)("map")},{map:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,r){"use strict";var n=r(0),o=r(136).start;n({target:"String",proto:!0,forced:r(137)},{padStart:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}})},function(t,e,r){"use strict";var n=r(0),o=r(28),i=r(10),a=r(88),c=[].join,u=o!=Object,s=a("join",",");n({target:"Array",proto:!0,forced:u||!s},{join:function(t){return c.call(i(this),void 0===t?",":t)}})},function(t,e){var r;r=function(){return this}();try{r=r||new Function("return this")()}catch(t){"object"==typeof window&&(r=window)}t.exports=r},function(t,e,r){var n=r(3),o=r(76),i=n.WeakMap;t.exports="function"==typeof i&&/native code/.test(o(i))},function(t,e,r){"use strict";var n=r(6),o=r(1),i=r(35),a=r(49),c=r(43),u=r(12),s=r(28),l=Object.assign,f=Object.defineProperty;t.exports=!l||o((function(){if(n&&1!==l({b:1},l(f({},"a",{enumerable:!0,get:function(){f(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var t={},e={},r=Symbol();return t[r]=7,"abcdefghijklmnopqrst".split("").forEach((function(t){e[t]=t})),7!=l({},t)[r]||"abcdefghijklmnopqrst"!=i(l({},e)).join("")}))?function(t,e){for(var r=u(t),o=arguments.length,l=1,f=a.f,p=c.f;o>l;)for(var v,h=s(arguments[l++]),d=f?i(h).concat(f(h)):i(h),g=d.length,y=0;g>y;)v=d[y++],n&&!p.call(h,v)||(r[v]=h[v]);return r}:l},function(t,e,r){"use strict";var n=r(0),o=r(81).includes,i=r(50);n({target:"Array",proto:!0},{includes:function(t){return o(this,t,arguments.length>1?arguments[1]:void 0)}}),i("includes")},function(t,e,r){var n=r(6),o=r(8),i=r(4),a=r(35);t.exports=n?Object.defineProperties:function(t,e){i(t);for(var r,n=a(e),c=n.length,u=0;c>u;)o.f(t,r=n[u++],e[r]);return t}},function(t,e,r){var n=r(33);t.exports=n("document","documentElement")},function(t,e,r){"use strict";var n=r(21).forEach,o=r(88)("forEach");t.exports=o?[].forEach:function(t){return n(this,t,arguments.length>1?arguments[1]:void 0)}},function(t,e,r){r(0)({target:"String",proto:!0},{repeat:r(54)})},function(t,e,r){"use strict";var n=r(58),o=r(93);t.exports=n?{}.toString:function(){return"[object "+o(this)+"]"}},function(t,e,r){var n=r(7),o=r(94);t.exports=function(t,e,r){var i,a;return o&&"function"==typeof(i=e.constructor)&&i!==r&&n(a=i.prototype)&&a!==r.prototype&&o(t,a),t}},function(t,e,r){var n=r(7);t.exports=function(t){if(!n(t)&&null!==t)throw TypeError("Can't set "+String(t)+" as a prototype");return t}},function(t,e,r){"use strict";var n=r(98).IteratorPrototype,o=r(36),i=r(18),a=r(61),c=r(26),u=function(){return this};t.exports=function(t,e,r){var s=e+" Iterator";return t.prototype=o(n,{next:i(1,r)}),a(t,s,!1,!0),c[s]=u,t}},function(t,e,r){var n=r(1);t.exports=!n((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype}))},function(t,e,r){"use strict";var n=r(0),o=r(47),i=r(17),a=r(9),c=r(12),u=r(53),s=r(24),l=r(25)("splice"),f=Math.max,p=Math.min;n({target:"Array",proto:!0,forced:!l},{splice:function(t,e){var r,n,l,v,h,d,g=c(this),y=a(g.length),b=o(t,y),m=arguments.length;if(0===m?r=n=0:1===m?(r=0,n=y-b):(r=m-2,n=p(f(i(e),0),y-b)),y+r-n>9007199254740991)throw TypeError("Maximum allowed length exceeded");for(l=u(g,n),v=0;v<n;v++)(h=b+v)in g&&s(l,v,g[h]);if(l.length=n,r<n){for(v=b;v<y-n;v++)d=v+r,(h=v+n)in g?g[d]=g[h]:delete g[d];for(v=y;v>y-n+r;v--)delete g[v-1]}else if(r>n)for(v=y-n;v>b;v--)d=v+r-1,(h=v+n-1)in g?g[d]=g[h]:delete g[d];for(v=0;v<r;v++)g[v+b]=arguments[v+2];return g.length=y-n+r,l}})},function(t,e,r){var n=r(102);t.exports=function(t){if(n(t))throw TypeError("The method doesn't accept regular expressions");return t}},function(t,e,r){var n=r(2)("match");t.exports=function(t){var e=/./;try{"/./"[t](e)}catch(r){try{return e[n]=!1,"/./"[t](e)}catch(t){}}return!1}},function(t,e,r){var n=r(10),o=r(34).f,i={}.toString,a="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(t){return a&&"[object Window]"==i.call(t)?function(t){try{return o(t)}catch(t){return a.slice()}}(t):o(n(t))}},function(t,e,r){"use strict";var n=r(86),o=r(12),i=r(126),a=r(128),c=r(9),u=r(24),s=r(129);t.exports=function(t){var e,r,l,f,p,v,h=o(t),d="function"==typeof this?this:Array,g=arguments.length,y=g>1?arguments[1]:void 0,b=void 0!==y,m=s(h),w=0;if(b&&(y=n(y,g>2?arguments[2]:void 0,2)),null==m||d==Array&&a(m))for(r=new d(e=c(h.length));e>w;w++)v=b?y(h[w],w):h[w],u(r,w,v);else for(p=(f=m.call(h)).next,r=new d;!(l=p.call(f)).done;w++)v=b?i(f,y,[l.value,w],!0):l.value,u(r,w,v);return r.length=w,r}},function(t,e,r){var n=r(4),o=r(127);t.exports=function(t,e,r,i){try{return i?e(n(r)[0],r[1]):e(r)}catch(e){throw o(t),e}}},function(t,e,r){var n=r(4);t.exports=function(t){var e=t.return;if(void 0!==e)return n(e.call(t)).value}},function(t,e,r){var n=r(2),o=r(26),i=n("iterator"),a=Array.prototype;t.exports=function(t){return void 0!==t&&(o.Array===t||a[i]===t)}},function(t,e,r){var n=r(93),o=r(26),i=r(2)("iterator");t.exports=function(t){if(null!=t)return t[i]||t["@@iterator"]||o[n(t)]}},function(t,e,r){var n=r(2)("iterator"),o=!1;try{var i=0,a={next:function(){return{done:!!i++}},return:function(){o=!0}};a[n]=function(){return this},Array.from(a,(function(){throw 2}))}catch(t){}t.exports=function(t,e){if(!e&&!o)return!1;var r=!1;try{var i={};i[n]=function(){return{next:function(){return{done:r=!0}}}},t(i)}catch(t){}return r}},function(t,e,r){"use strict";var n=r(0),o=r(95).trim;n({target:"String",proto:!0,forced:r(132)("trim")},{trim:function(){return o(this)}})},function(t,e,r){var n=r(1),o=r(96);t.exports=function(t){return n((function(){return!!o[t]()||"​᠎"!="​᠎"[t]()||o[t].name!==t}))}},function(t,e,r){var n=r(4),o=r(87),i=r(2)("species");t.exports=function(t,e){var r,a=n(t).constructor;return void 0===a||null==(r=n(a)[i])?e:o(r)}},function(t,e,r){"use strict";var n=r(55),o=r(4),i=r(9),a=r(17),c=r(11),u=r(56),s=r(135),l=r(57),f=Math.max,p=Math.min;n("replace",2,(function(t,e,r,n){var v=n.REGEXP_REPLACE_SUBSTITUTES_UNDEFINED_CAPTURE,h=n.REPLACE_KEEPS_$0,d=v?"$":"$0";return[function(r,n){var o=c(this),i=null==r?void 0:r[t];return void 0!==i?i.call(r,o,n):e.call(String(o),r,n)},function(t,n){if(!v&&h||"string"==typeof n&&-1===n.indexOf(d)){var c=r(e,t,this,n);if(c.done)return c.value}var g=o(t),y=String(this),b="function"==typeof n;b||(n=String(n));var m=g.global;if(m){var w=g.unicode;g.lastIndex=0}for(var x=[];;){var S=l(g,y);if(null===S)break;if(x.push(S),!m)break;""===String(S[0])&&(g.lastIndex=u(y,i(g.lastIndex),w))}for(var _,O="",A=0,E=0;E<x.length;E++){S=x[E];for(var j=String(S[0]),P=f(p(a(S.index),y.length),0),C=[],k=1;k<S.length;k++)C.push(void 0===(_=S[k])?_:String(_));var I=S.groups;if(b){var T=[j].concat(C,P,y);void 0!==I&&T.push(I);var R=String(n.apply(void 0,T))}else R=s(j,y,P,C,I,n);P>=A&&(O+=y.slice(A,P)+R,A=P+j.length)}return O+y.slice(A)}]}))},function(t,e,r){var n=r(12),o=Math.floor,i="".replace,a=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,c=/\$([$&'`]|\d{1,2})/g;t.exports=function(t,e,r,u,s,l){var f=r+t.length,p=u.length,v=c;return void 0!==s&&(s=n(s),v=a),i.call(l,v,(function(n,i){var a;switch(i.charAt(0)){case"$":return"$";case"&":return t;case"`":return e.slice(0,r);case"'":return e.slice(f);case"<":a=s[i.slice(1,-1)];break;default:var c=+i;if(0===c)return n;if(c>p){var l=o(c/10);return 0===l?n:l<=p?void 0===u[l-1]?i.charAt(1):u[l-1]+i.charAt(1):n}a=u[c-1]}return void 0===a?"":a}))}},function(t,e,r){var n=r(9),o=r(54),i=r(11),a=Math.ceil,c=function(t){return function(e,r,c){var u,s,l=String(i(e)),f=l.length,p=void 0===c?" ":String(c),v=n(r);return v<=f||""==p?l:(u=v-f,(s=o.call(p,a(u/p.length))).length>u&&(s=s.slice(0,u)),t?l+s:s+l)}};t.exports={start:c(!1),end:c(!0)}},function(t,e,r){var n=r(83);t.exports=/Version\/10(?:\.\d+){1,2}(?: [\w./]+)?(?: Mobile\/\w+)? Safari\//.test(n)},function(t,e,r){"use strict";var n=r(0),o=r(17),i=r(139),a=r(54),c=r(1),u=1..toFixed,s=Math.floor,l=function(t,e,r){return 0===e?r:e%2==1?l(t,e-1,r*t):l(t*t,e/2,r)},f=function(t,e,r){for(var n=-1,o=r;++n<6;)o+=e*t[n],t[n]=o%1e7,o=s(o/1e7)},p=function(t,e){for(var r=6,n=0;--r>=0;)n+=t[r],t[r]=s(n/e),n=n%e*1e7},v=function(t){for(var e=6,r="";--e>=0;)if(""!==r||0===e||0!==t[e]){var n=String(t[e]);r=""===r?n:r+a.call("0",7-n.length)+n}return r};n({target:"Number",proto:!0,forced:u&&("0.000"!==8e-5.toFixed(3)||"1"!==.9.toFixed(0)||"1.25"!==1.255.toFixed(2)||"1000000000000000128"!==(0xde0b6b3a7640080).toFixed(0))||!c((function(){u.call({})}))},{toFixed:function(t){var e,r,n,c,u=i(this),s=o(t),h=[0,0,0,0,0,0],d="",g="0";if(s<0||s>20)throw RangeError("Incorrect fraction digits");if(u!=u)return"NaN";if(u<=-1e21||u>=1e21)return String(u);if(u<0&&(d="-",u=-u),u>1e-21)if(r=(e=function(t){for(var e=0,r=t;r>=4096;)e+=12,r/=4096;for(;r>=2;)e+=1,r/=2;return e}(u*l(2,69,1))-69)<0?u*l(2,-e,1):u/l(2,e,1),r*=4503599627370496,(e=52-e)>0){for(f(h,0,r),n=s;n>=7;)f(h,1e7,0),n-=7;for(f(h,l(10,n,1),0),n=e-1;n>=23;)p(h,1<<23),n-=23;p(h,1<<n),f(h,1,1),p(h,2),g=v(h)}else f(h,0,r),f(h,1<<-e,0),g=v(h)+a.call("0",s);return g=s>0?d+((c=g.length)<=s?"0."+a.call("0",s-c)+g:g.slice(0,c-s)+"."+g.slice(c-s)):d+g}})},function(t,e,r){var n=r(15);t.exports=function(t){if("number"!=typeof t&&"Number"!=n(t))throw TypeError("Incorrect invocation");return+t}},function(t,e,r){"use strict";r.r(e);var n={};r.r(n),r.d(n,"on",(function(){return l})),r.d(n,"off",(function(){return f})),r.d(n,"createElementFromString",(function(){return p})),r.d(n,"createFromTemplate",(function(){return v})),r.d(n,"eventPath",(function(){return h})),r.d(n,"resolveElement",(function(){return d})),r.d(n,"adjustableInputNumbers",(function(){return g}));r(27),r(111),r(37),r(115),r(22),r(91),r(23),r(59),r(60),r(40),r(41),r(62),r(121),r(42),r(100),r(101),r(63),r(64),r(65),r(66),r(67),r(68),r(69),r(70),r(71),r(72),r(131),r(73),r(134);function o(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function i(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?o(Object(r),!0).forEach((function(e){a(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):o(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function a(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function c(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return u(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return u(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function u(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function s(t,e,r,n){var o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:{};e instanceof HTMLCollection||e instanceof NodeList?e=Array.from(e):Array.isArray(e)||(e=[e]),Array.isArray(r)||(r=[r]);for(var a,u=c(e);!(a=u()).done;)for(var s,l=a.value,f=c(r);!(s=f()).done;){var p=s.value;l[t](p,n,i({capture:!1},o))}return Array.prototype.slice.call(arguments,1)}var l=s.bind(null,"addEventListener"),f=s.bind(null,"removeEventListener");function p(t){var e=document.createElement("div");return e.innerHTML=t.trim(),e.firstElementChild}function v(t){var e=function(t,e){var r=t.getAttribute(e);return t.removeAttribute(e),r};return function t(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=e(r,":obj"),i=e(r,":ref"),a=o?n[o]={}:n;i&&(n[i]=r);for(var c=0,u=Array.from(r.children);c<u.length;c++){var s=u[c],l=e(s,":arr"),f=t(s,l?{}:a);l&&(a[l]||(a[l]=[])).push(Object.keys(f).length?f:s)}return n}(p(t))}function h(t){var e=t.path||t.composedPath&&t.composedPath();if(e)return e;var r=t.target.parentElement;for(e=[t.target,r];r=r.parentElement;)e.push(r);return e.push(document,window),e}function d(t){return t instanceof Element?t:"string"==typeof t?t.split(/>>/g).reduce((function(t,e,r,n){return t=t.querySelector(e),r<n.length-1?t.shadowRoot:t}),document):null}function g(t){var e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:function(t){return t};function r(r){var n=[.001,.01,.1][Number(r.shiftKey||2*r.ctrlKey)]*(r.deltaY<0?1:-1),o=0,i=t.selectionStart;t.value=t.value.replace(/[\d.]+/g,(function(t,r){return r<=i&&r+t.length>=i?(i=r,e(Number(t),n,o)):(o++,t)})),t.focus(),t.setSelectionRange(i,i),r.preventDefault(),t.dispatchEvent(new Event("input"))}l(t,"focus",(function(){return l(window,"wheel",r,{passive:!1})})),l(t,"blur",(function(){return f(window,"wheel",r)}))}r(105),r(106),r(107);var y=Math.min,b=Math.max,m=Math.floor,w=Math.round;function x(t,e,r){e/=100,r/=100;var n=m(t=t/360*6),o=t-n,i=r*(1-e),a=r*(1-o*e),c=r*(1-(1-o)*e),u=n%6;return[255*[r,a,i,i,c,r][u],255*[c,r,r,a,i,i][u],255*[i,i,c,r,r,a][u]]}function S(t,e,r){return x(t,e,r).map((function(t){return w(t).toString(16).padStart(2,"0")}))}function _(t,e,r){var n=x(t,e,r),o=n[0]/255,i=n[1]/255,a=n[2]/255,c=y(1-o,1-i,1-a);return[100*(1===c?0:(1-o-c)/(1-c)),100*(1===c?0:(1-i-c)/(1-c)),100*(1===c?0:(1-a-c)/(1-c)),100*c]}function O(t,e,r){var n=(2-(e/=100))*(r/=100)/2;return 0!==n&&(e=1===n?0:n<.5?e*r/(2*n):e*r/(2-2*n)),[t,100*e,100*n]}function A(t,e,r){var n,o,i=y(t/=255,e/=255,r/=255),a=b(t,e,r),c=a-i;if(0===c)n=o=0;else{o=c/a;var u=((a-t)/6+c/2)/c,s=((a-e)/6+c/2)/c,l=((a-r)/6+c/2)/c;t===a?n=l-s:e===a?n=1/3+u-l:r===a&&(n=2/3+s-u),n<0?n+=1:n>1&&(n-=1)}return[360*n,100*o,100*a]}function E(t,e,r,n){e/=100,r/=100;var o=255*(1-y(1,(t/=100)*(1-(n/=100))+n)),i=255*(1-y(1,e*(1-n)+n)),a=255*(1-y(1,r*(1-n)+n));return[].concat(A(o,i,a))}function j(t,e,r){e/=100;var n=2*(e*=(r/=100)<.5?r:1-r)/(r+e)*100,o=100*(r+e);return[t,isNaN(n)?0:n,o]}function P(t){return A.apply(void 0,t.match(/.{2}/g).map((function(t){return parseInt(t,16)})))}function C(t){t=t.match(/^[a-zA-Z]+$/)?function(t){if("black"===t.toLowerCase())return"#000";var e=document.createElement("canvas").getContext("2d");return e.fillStyle=t,"#000"===e.fillStyle?null:e.fillStyle}(t):t;var e,r={cmyk:/^cmyk[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)/i,rgba:/^((rgba)|rgb)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hsla:/^((hsla)|hsl)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hsva:/^((hsva)|hsv)[\D]+([\d.]+)[\D]+([\d.]+)[\D]+([\d.]+)[\D]*?([\d.]+|$)/i,hexa:/^#?(([\dA-Fa-f]{3,4})|([\dA-Fa-f]{6})|([\dA-Fa-f]{8}))$/i},n=function(t){return t.map((function(t){return/^(|\d+)\.\d+|\d+$/.test(t)?Number(t):void 0}))};t:for(var o in r)if(e=r[o].exec(t)){var i=function(t){return!!e[2]==("number"==typeof t)};switch(o){case"cmyk":var a=n(e),c=a[1],u=a[2],s=a[3],l=a[4];if(c>100||u>100||s>100||l>100)break t;return{values:E(c,u,s,l),type:o};case"rgba":var f=n(e),p=f[3],v=f[4],h=f[5],d=f[6];if(p>255||v>255||h>255||d<0||d>1||!i(d))break t;return{values:[].concat(A(p,v,h),[d]),a:d,type:o};case"hexa":var g=e[1];4!==g.length&&3!==g.length||(g=g.split("").map((function(t){return t+t})).join(""));var y=g.substring(0,6),b=g.substring(6);return b=b?parseInt(b,16)/255:void 0,{values:[].concat(P(y),[b]),a:b,type:o};case"hsla":var m=n(e),w=m[3],x=m[4],S=m[5],_=m[6];if(w>360||x>100||S>100||_<0||_>1||!i(_))break t;return{values:[].concat(j(w,x,S),[_]),a:_,type:o};case"hsva":var O=n(e),C=O[3],k=O[4],I=O[5],T=O[6];if(C>360||k>100||I>100||T<0||T>1||!i(T))break t;return{values:[C,k,I,T],a:T,type:o}}}return{values:null,type:null}}r(138);function k(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,o=function(t,e){return function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:-1;return e(~r?t.map((function(t){return Number(t.toFixed(r))})):t)}},i={h:t,s:e,v:r,a:n,toHSVA:function(){var t=[i.h,i.s,i.v,i.a];return t.toString=o(t,(function(t){return"hsva("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+i.a+")"})),t},toHSLA:function(){var t=[].concat(O(i.h,i.s,i.v),[i.a]);return t.toString=o(t,(function(t){return"hsla("+t[0]+", "+t[1]+"%, "+t[2]+"%, "+i.a+")"})),t},toRGBA:function(){var t=[].concat(x(i.h,i.s,i.v),[i.a]);return t.toString=o(t,(function(t){return"rgba("+t[0]+", "+t[1]+", "+t[2]+", "+i.a+")"})),t},toCMYK:function(){var t=_(i.h,i.s,i.v);return t.toString=o(t,(function(t){return"cmyk("+t[0]+"%, "+t[1]+"%, "+t[2]+"%, "+t[3]+"%)"})),t},toHEXA:function(){var t=S(i.h,i.s,i.v),e=i.a>=1?"":Number((255*i.a).toFixed(0)).toString(16).toUpperCase().padStart(2,"0");return e&&t.push(e),t.toString=function(){return"#"+t.join("").toUpperCase()},t},clone:function(){return k(i.h,i.s,i.v,i.a)}};return i}var I=function(t){return Math.max(Math.min(t,1),0)};function T(t){var e={options:Object.assign({lock:null,onchange:function(){return 0},onstop:function(){return 0}},t),_keyboard:function(t){var r=e.options,n=t.type,o=t.key;if(document.activeElement===r.wrapper){var i=e.options.lock,a="ArrowUp"===o,c="ArrowRight"===o,u="ArrowDown"===o,s="ArrowLeft"===o;if("keydown"===n&&(a||c||u||s)){var l=0,f=0;"v"===i?l=a||c?1:-1:"h"===i?l=a||c?-1:1:(f=a?-1:u?1:0,l=s?-1:c?1:0),e.update(I(e.cache.x+.01*l),I(e.cache.y+.01*f)),t.preventDefault()}else o.startsWith("Arrow")&&(e.options.onstop(),t.preventDefault())}},_tapstart:function(t){l(document,["mouseup","touchend","touchcancel"],e._tapstop),l(document,["mousemove","touchmove"],e._tapmove),t.cancelable&&t.preventDefault(),e._tapmove(t)},_tapmove:function(t){var r=e.options,n=e.cache,o=r.lock,i=r.element,a=r.wrapper.getBoundingClientRect(),c=0,u=0;if(t){var s=t&&t.touches&&t.touches[0];c=t?(s||t).clientX:0,u=t?(s||t).clientY:0,c<a.left?c=a.left:c>a.left+a.width&&(c=a.left+a.width),u<a.top?u=a.top:u>a.top+a.height&&(u=a.top+a.height),c-=a.left,u-=a.top}else n&&(c=n.x*a.width,u=n.y*a.height);"h"!==o&&(i.style.left="calc("+c/a.width*100+"% - "+i.offsetWidth/2+"px)"),"v"!==o&&(i.style.top="calc("+u/a.height*100+"% - "+i.offsetHeight/2+"px)"),e.cache={x:c/a.width,y:u/a.height};var l=I(c/a.width),f=I(u/a.height);switch(o){case"v":return r.onchange(l);case"h":return r.onchange(f);default:return r.onchange(l,f)}},_tapstop:function(){e.options.onstop(),f(document,["mouseup","touchend","touchcancel"],e._tapstop),f(document,["mousemove","touchmove"],e._tapmove)},trigger:function(){e._tapmove()},update:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=e.options.wrapper.getBoundingClientRect(),o=n.left,i=n.top,a=n.width,c=n.height;"h"===e.options.lock&&(r=t),e._tapmove({clientX:o+a*t,clientY:i+c*r})},destroy:function(){var t=e.options,r=e._tapstart,n=e._keyboard;f(document,["keydown","keyup"],n),f([t.wrapper,t.element],"mousedown",r),f([t.wrapper,t.element],"touchstart",r,{passive:!1})}},r=e.options,n=e._tapstart,o=e._keyboard;return l([r.wrapper,r.element],"mousedown",n),l([r.wrapper,r.element],"touchstart",n,{passive:!1}),l(document,["keydown","keyup"],o),e}function R(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};t=Object.assign({onchange:function(){return 0},className:"",elements:[]},t);var e=l(t.elements,"click",(function(e){t.elements.forEach((function(r){return r.classList[e.target===r?"add":"remove"](t.className)})),t.onchange(e),e.stopPropagation()}));return{destroy:function(){return f.apply(n,e)}}}function L(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return N(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return N(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function N(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function M(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function D(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?M(Object(r),!0).forEach((function(e){F(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):M(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function F(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}
/*! NanoPop 2.1.0 MIT | https://github.com/Simonwep/nanopop */var B={variantFlipOrder:{start:"sme",middle:"mse",end:"ems"},positionFlipOrder:{top:"tbrl",right:"rltb",bottom:"btrl",left:"lrbt"},position:"bottom",margin:8},U=function(t,e,r){var n=D(D({container:document.documentElement.getBoundingClientRect()},B),r),o=n.container,i=n.margin,a=n.position,c=n.variantFlipOrder,u=n.positionFlipOrder,s=e.style,l=s.left,f=s.top;e.style.left="0",e.style.top="0";for(var p,v=t.getBoundingClientRect(),h=e.getBoundingClientRect(),d={t:v.top-h.height-i,b:v.bottom+i,r:v.right+i,l:v.left-h.width-i},g={vs:v.left,vm:v.left+v.width/2+-h.width/2,ve:v.left+v.width-h.width,hs:v.top,hm:v.bottom-v.height/2-h.height/2,he:v.bottom-h.height},y=a.split("-"),b=y[0],m=y[1],w=void 0===m?"middle":m,x=u[b],S=c[w],_=o.top,O=o.left,A=o.bottom,E=o.right,j=L(x);!(p=j()).done;){var P=p.value,C="t"===P||"b"===P,k=d[P],I=C?["top","left"]:["left","top"],T=I[0],R=I[1],N=C?[h.height,h.width]:[h.width,h.height],M=N[1],F=C?[A,E]:[E,A],U=F[1],H=C?[_,O]:[O,_],$=H[1];if(!(k<H[0]||k+N[0]>F[0]))for(var G,V=L(S);!(G=V()).done;){var W=G.value,z=g[(C?"v":"h")+W];if(!(z<$||z+M>U))return e.style[R]=z-h[R]+"px",e.style[T]=k-h[T]+"px",P+W}}return e.style.left=l,e.style.top=f,null};function H(t,e){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return $(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return $(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var n=0;return function(){return n>=t.length?{done:!0}:{done:!1,value:t[n++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function $(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}function G(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function V(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}var W=function(){function t(e){var r=this;V(this,"_initializingActive",!0),V(this,"_recalc",!0),V(this,"_nanopop",null),V(this,"_root",null),V(this,"_color",k()),V(this,"_lastColor",k()),V(this,"_swatchColors",[]),V(this,"_setupAnimationFrame",null),V(this,"_eventListener",{init:[],save:[],hide:[],show:[],clear:[],change:[],changestop:[],cancel:[],swatchselect:[]}),this.options=e=Object.assign(function(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?G(Object(r),!0).forEach((function(e){V(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):G(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}({},t.DEFAULT_OPTIONS),e);var n=e,o=n.swatches,i=n.components,a=n.theme,c=n.sliders,u=n.lockOpacity,s=n.padding;["nano","monolith"].includes(a)&&!c&&(e.sliders="h"),i.interaction||(i.interaction={});var l=i.preview,f=i.opacity,p=i.hue,v=i.palette;i.opacity=!u&&f,i.palette=v||l||f||p,this._preBuild(),this._buildComponents(),this._bindEvents(),this._finalBuild(),o&&o.length&&o.forEach((function(t){return r.addSwatch(t)}));var h,d,g,y,b=this._root,m=b.button,w=b.app;this._nanopop=(d=w,g={margin:s},y="object"!=typeof(h=m)||h instanceof HTMLElement?D({reference:h,popper:d},g):h,{update:function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:y,e=Object.assign(y,t),r=e.reference,n=e.popper;if(!n||!r)throw new Error("Popper- or reference-element missing.");return U(r,n,y)}}),m.setAttribute("role","button"),m.setAttribute("aria-label",this._t("btn:toggle"));var x=this;this._setupAnimationFrame=requestAnimationFrame((function t(){if(!w.offsetWidth)return requestAnimationFrame(t);x.setColor(e.default),x._rePositioningPicker(),e.defaultRepresentation&&(x._representation=e.defaultRepresentation,x.setColorRepresentation(x._representation)),e.showAlways&&x.show(),x._initializingActive=!1,x._emit("init")}))}var e=t.prototype;return e._preBuild=function(){for(var t,e,r,n,o,i,a,c,u,s,l,f,p=this.options,h=0,g=["el","container"];h<g.length;h++){var y=g[h];p[y]=d(p[y])}this._root=(e=(t=this).options,r=e.components,n=e.useAsButton,o=e.inline,i=e.appClass,a=e.theme,c=e.lockOpacity,u=function(t){return t?"":'style="display:none" hidden'},l=v('\n      <div :ref="root" class="pickr">\n\n        '+(n?"":'<button type="button" :ref="button" class="pcr-button"></button>')+'\n\n        <div :ref="app" class="pcr-app '+(i||"")+'" data-theme="'+a+'" '+(o?'style="position: unset"':"")+' aria-label="'+(s=function(e){return t._t(e)})("ui:dialog")+'" role="window">\n          <div class="pcr-selection" '+u(r.palette)+'>\n            <div :obj="preview" class="pcr-color-preview" '+u(r.preview)+'>\n              <button type="button" :ref="lastColor" class="pcr-last-color" aria-label="'+s("btn:last-color")+'"></button>\n              <div :ref="currentColor" class="pcr-current-color"></div>\n            </div>\n\n            <div :obj="palette" class="pcr-color-palette">\n              <div :ref="picker" class="pcr-picker"></div>\n              <div :ref="palette" class="pcr-palette" tabindex="0" aria-label="'+s("aria:palette")+'" role="listbox"></div>\n            </div>\n\n            <div :obj="hue" class="pcr-color-chooser" '+u(r.hue)+'>\n              <div :ref="picker" class="pcr-picker"></div>\n              <div :ref="slider" class="pcr-hue pcr-slider" tabindex="0" aria-label="'+s("aria:hue")+'" role="slider"></div>\n            </div>\n\n            <div :obj="opacity" class="pcr-color-opacity" '+u(r.opacity)+'>\n              <div :ref="picker" class="pcr-picker"></div>\n              <div :ref="slider" class="pcr-opacity pcr-slider" tabindex="0" aria-label="'+s("aria:opacity")+'" role="slider"></div>\n            </div>\n          </div>\n\n          <div class="pcr-swatches '+(r.palette?"":"pcr-last")+'" :ref="swatches"></div>\n\n          <div :obj="interaction" class="pcr-interaction" '+u(Object.keys(r.interaction).length)+'>\n            <input :ref="result" class="pcr-result" type="text" spellcheck="false" '+u(r.interaction.input)+' aria-label="'+s("aria:input")+'">\n\n            <input :arr="options" class="pcr-type" data-type="HEXA" value="'+(c?"HEX":"HEXA")+'" type="button" '+u(r.interaction.hex)+'>\n            <input :arr="options" class="pcr-type" data-type="RGBA" value="'+(c?"RGB":"RGBA")+'" type="button" '+u(r.interaction.rgba)+'>\n            <input :arr="options" class="pcr-type" data-type="HSLA" value="'+(c?"HSL":"HSLA")+'" type="button" '+u(r.interaction.hsla)+'>\n            <input :arr="options" class="pcr-type" data-type="HSVA" value="'+(c?"HSV":"HSVA")+'" type="button" '+u(r.interaction.hsva)+'>\n            <input :arr="options" class="pcr-type" data-type="CMYK" value="CMYK" type="button" '+u(r.interaction.cmyk)+'>\n\n            <input :ref="save" class="pcr-save" value="'+s("btn:save")+'" type="button" '+u(r.interaction.save)+' aria-label="'+s("aria:btn:save")+'">\n            <input :ref="cancel" class="pcr-cancel" value="'+s("btn:cancel")+'" type="button" '+u(r.interaction.cancel)+' aria-label="'+s("aria:btn:cancel")+'">\n            <input :ref="clear" class="pcr-clear" value="'+s("btn:clear")+'" type="button" '+u(r.interaction.clear)+' aria-label="'+s("aria:btn:clear")+'">\n          </div>\n        </div>\n      </div>\n    '),(f=l.interaction).options.find((function(t){return!t.hidden&&!t.classList.add("active")})),f.type=function(){return f.options.find((function(t){return t.classList.contains("active")}))},l),p.useAsButton&&(this._root.button=p.el),p.container.appendChild(this._root.root)},e._finalBuild=function(){var t=this.options,e=this._root;if(t.container.removeChild(e.root),t.inline){var r=t.el.parentElement;t.el.nextSibling?r.insertBefore(e.app,t.el.nextSibling):r.appendChild(e.app)}else t.container.appendChild(e.app);t.useAsButton?t.inline&&t.el.remove():t.el.parentNode.replaceChild(e.root,t.el),t.disabled&&this.disable(),t.comparison||(e.button.style.transition="none",t.useAsButton||(e.preview.lastColor.style.transition="none")),this.hide()},e._buildComponents=function(){var t=this,e=this,r=this.options.components,n=(e.options.sliders||"v").repeat(2),o=n.match(/^[vh]+$/g)?n:[],i=o[0],a=o[1],c=function(){return t._color||(t._color=t._lastColor.clone())},u={palette:T({element:e._root.palette.picker,wrapper:e._root.palette.palette,onstop:function(){return e._emit("changestop","slider",e)},onchange:function(t,n){if(r.palette){var o=c(),i=e._root,a=e.options,u=i.preview,s=u.lastColor,l=u.currentColor;e._recalc&&(o.s=100*t,o.v=100-100*n,o.v<0&&(o.v=0),e._updateOutput("slider"));var f=o.toRGBA().toString(0);this.element.style.background=f,this.wrapper.style.background="\n                        linear-gradient(to top, rgba(0, 0, 0, "+o.a+"), transparent),\n                        linear-gradient(to left, hsla("+o.h+", 100%, 50%, "+o.a+"), rgba(255, 255, 255, "+o.a+"))\n                    ",a.comparison?a.useAsButton||e._lastColor||s.style.setProperty("--pcr-color",f):(i.button.style.color=f,i.button.classList.remove("clear"));for(var p,v=o.toHEXA().toString(),h=H(e._swatchColors);!(p=h()).done;){var d=p.value,g=d.el,y=d.color;g.classList[v===y.toHEXA().toString()?"add":"remove"]("pcr-active")}l.style.setProperty("--pcr-color",f)}}}),hue:T({lock:"v"===a?"h":"v",element:e._root.hue.picker,wrapper:e._root.hue.slider,onstop:function(){return e._emit("changestop","slider",e)},onchange:function(t){if(r.hue&&r.palette){var n=c();e._recalc&&(n.h=360*t),this.element.style.backgroundColor="hsl("+n.h+", 100%, 50%)",u.palette.trigger()}}}),opacity:T({lock:"v"===i?"h":"v",element:e._root.opacity.picker,wrapper:e._root.opacity.slider,onstop:function(){return e._emit("changestop","slider",e)},onchange:function(t){if(r.opacity&&r.palette){var n=c();e._recalc&&(n.a=Math.round(100*t)/100),this.element.style.background="rgba(0, 0, 0, "+n.a+")",u.palette.trigger()}}}),selectable:R({elements:e._root.interaction.options,className:"active",onchange:function(t){e._representation=t.target.getAttribute("data-type").toUpperCase(),e._recalc&&e._updateOutput("swatch")}})};this._components=u},e._bindEvents=function(){var t=this,e=this._root,r=this.options,n=[l(e.interaction.clear,"click",(function(){return t._clearColor()})),l([e.interaction.cancel,e.preview.lastColor],"click",(function(){t.setHSVA.apply(t,(t._lastColor||t._color).toHSVA().concat([!0])),t._emit("cancel")})),l(e.interaction.save,"click",(function(){!t.applyColor()&&!r.showAlways&&t.hide()})),l(e.interaction.result,["keyup","input"],(function(e){t.setColor(e.target.value,!0)&&!t._initializingActive&&(t._emit("change",t._color,"input",t),t._emit("changestop","input",t)),e.stopImmediatePropagation()})),l(e.interaction.result,["focus","blur"],(function(e){t._recalc="blur"===e.type,t._recalc&&t._updateOutput(null)})),l([e.palette.palette,e.palette.picker,e.hue.slider,e.hue.picker,e.opacity.slider,e.opacity.picker],["mousedown","touchstart"],(function(){return t._recalc=!0}),{passive:!0})];if(!r.showAlways){var o=r.closeWithKey;n.push(l(e.button,"click",(function(){return t.isOpen()?t.hide():t.show()})),l(document,"keyup",(function(e){return t.isOpen()&&(e.key===o||e.code===o)&&t.hide()})),l(document,["touchstart","mousedown"],(function(r){t.isOpen()&&!h(r).some((function(t){return t===e.app||t===e.button}))&&t.hide()}),{capture:!0}))}if(r.adjustableNumbers){var i={rgba:[255,255,255,1],hsva:[360,100,100,1],hsla:[360,100,100,1],cmyk:[100,100,100,100]};g(e.interaction.result,(function(e,r,n){var o=i[t.getColorRepresentation().toLowerCase()];if(o){var a=o[n],c=e+(a>=100?1e3*r:r);return c<=0?0:Number((c<a?c:a).toPrecision(3))}return e}))}if(r.autoReposition&&!r.inline){var a=null,c=this;n.push(l(window,["scroll","resize"],(function(){c.isOpen()&&(r.closeOnScroll&&c.hide(),null===a?(a=setTimeout((function(){return a=null}),100),requestAnimationFrame((function t(){c._rePositioningPicker(),null!==a&&requestAnimationFrame(t)}))):(clearTimeout(a),a=setTimeout((function(){return a=null}),100)))}),{capture:!0}))}this._eventBindings=n},e._rePositioningPicker=function(){var t=this.options;if(!t.inline&&!this._nanopop.update({container:document.body.getBoundingClientRect(),position:t.position})){var e=this._root.app,r=e.getBoundingClientRect();e.style.top=(window.innerHeight-r.height)/2+"px",e.style.left=(window.innerWidth-r.width)/2+"px"}},e._updateOutput=function(t){var e=this._root,r=this._color,n=this.options;if(e.interaction.type()){var o="to"+e.interaction.type().getAttribute("data-type");e.interaction.result.value="function"==typeof r[o]?r[o]().toString(n.outputPrecision):""}!this._initializingActive&&this._recalc&&this._emit("change",r,t,this)},e._clearColor=function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=this._root,r=this.options;r.useAsButton||(e.button.style.color="rgba(0, 0, 0, 0.15)"),e.button.classList.add("clear"),r.showAlways||this.hide(),this._lastColor=null,this._initializingActive||t||(this._emit("save",null),this._emit("clear"))},e._parseLocalColor=function(t){var e=C(t),r=e.values,n=e.type,o=e.a,i=this.options.lockOpacity,a=void 0!==o&&1!==o;return r&&3===r.length&&(r[3]=void 0),{values:!r||i&&a?null:r,type:n}},e._t=function(e){return this.options.i18n[e]||t.I18N_DEFAULTS[e]},e._emit=function(t){for(var e=this,r=arguments.length,n=new Array(r>1?r-1:0),o=1;o<r;o++)n[o-1]=arguments[o];this._eventListener[t].forEach((function(t){return t.apply(void 0,n.concat([e]))}))},e.on=function(t,e){return this._eventListener[t].push(e),this},e.off=function(t,e){var r=this._eventListener[t]||[],n=r.indexOf(e);return~n&&r.splice(n,1),this},e.addSwatch=function(t){var e=this,r=this._parseLocalColor(t).values;if(r){var n=this._swatchColors,o=this._root,i=k.apply(void 0,r),a=p('<button type="button" style="--pcr-color: '+i.toRGBA().toString(0)+'" aria-label="'+this._t("btn:swatch")+'"/>');return o.swatches.appendChild(a),n.push({el:a,color:i}),this._eventBindings.push(l(a,"click",(function(){e.setHSVA.apply(e,i.toHSVA().concat([!0])),e._emit("swatchselect",i),e._emit("change",i,"swatch",e)}))),!0}return!1},e.removeSwatch=function(t){var e=this._swatchColors[t];if(e){var r=e.el;return this._root.swatches.removeChild(r),this._swatchColors.splice(t,1),!0}return!1},e.applyColor=function(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0],e=this._root,r=e.preview,n=e.button,o=this._color.toRGBA().toString(0);return r.lastColor.style.setProperty("--pcr-color",o),this.options.useAsButton||n.style.setProperty("--pcr-color",o),n.classList.remove("clear"),this._lastColor=this._color.clone(),this._initializingActive||t||this._emit("save",this._color),this},e.destroy=function(){var t=this;cancelAnimationFrame(this._setupAnimationFrame),this._eventBindings.forEach((function(t){return f.apply(n,t)})),Object.keys(this._components).forEach((function(e){return t._components[e].destroy()}))},e.destroyAndRemove=function(){var t=this;this.destroy();var e=this._root,r=e.root,n=e.app;r.parentElement&&r.parentElement.removeChild(r),n.parentElement.removeChild(n),Object.keys(this).forEach((function(e){return t[e]=null}))},e.hide=function(){return!!this.isOpen()&&(this._root.app.classList.remove("visible"),this._emit("hide"),!0)},e.show=function(){return!this.options.disabled&&!this.isOpen()&&(this._root.app.classList.add("visible"),this._rePositioningPicker(),this._emit("show",this._color),this)},e.isOpen=function(){return this._root.app.classList.contains("visible")},e.setHSVA=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:360,e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1,o=arguments.length>4&&void 0!==arguments[4]&&arguments[4],i=this._recalc;if(this._recalc=!1,t<0||t>360||e<0||e>100||r<0||r>100||n<0||n>1)return!1;this._color=k(t,e,r,n);var a=this._components,c=a.hue,u=a.opacity,s=a.palette;return c.update(t/360),u.update(n),s.update(e/100,1-r/100),o||this.applyColor(),i&&this._updateOutput(),this._recalc=i,!0},e.setColor=function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(null===t)return this._clearColor(e),!0;var r=this._parseLocalColor(t),n=r.values,o=r.type;if(n){var i=o.toUpperCase(),a=this._root.interaction.options,c=a.find((function(t){return t.getAttribute("data-type")===i}));if(c&&!c.hidden)for(var u,s=H(a);!(u=s()).done;){var l=u.value;l.classList[l===c?"add":"remove"]("active")}return!!this.setHSVA.apply(this,n.concat([e]))&&this.setColorRepresentation(i)}return!1},e.setColorRepresentation=function(t){return t=t.toUpperCase(),!!this._root.interaction.options.find((function(e){return e.getAttribute("data-type").startsWith(t)&&!e.click()}))},e.getColorRepresentation=function(){return this._representation},e.getColor=function(){return this._color},e.getSelectedColor=function(){return this._lastColor},e.getRoot=function(){return this._root},e.disable=function(){return this.hide(),this.options.disabled=!0,this._root.button.classList.add("disabled"),this},e.enable=function(){return this.options.disabled=!1,this._root.button.classList.remove("disabled"),this},t}();V(W,"utils",n),V(W,"version","1.8.1"),V(W,"I18N_DEFAULTS",{"ui:dialog":"color picker dialog","btn:toggle":"toggle color picker dialog","btn:swatch":"color swatch","btn:last-color":"use previous color","btn:save":"Save","btn:cancel":"Cancel","btn:clear":"Clear","aria:btn:save":"save and close","aria:btn:cancel":"cancel and close","aria:btn:clear":"clear and close","aria:input":"color input field","aria:palette":"color selection area","aria:hue":"hue selection slider","aria:opacity":"selection slider"}),V(W,"DEFAULT_OPTIONS",{appClass:null,theme:"classic",useAsButton:!1,padding:8,disabled:!1,comparison:!0,closeOnScroll:!1,outputPrecision:0,lockOpacity:!1,autoReposition:!0,container:"body",components:{interaction:{}},i18n:{},swatches:null,inline:!1,sliders:null,default:"#42445a",defaultRepresentation:null,position:"bottom-middle",adjustableNumbers:!0,showAlways:!1,closeWithKey:"Escape"}),V(W,"create",(function(t){return new W(t)}));e.default=W}]).default}));
//# sourceMappingURL=pickr.es5.min.js.map
function createDatePickerFormComponent(formControl, showTime) {
    var htmlContentInput = document.querySelector("[name='" + formControl + "'");
    showTime = showTime || false;

    // Check for jQuery
    if (window.jQuery) {
        // Check for the datepicker.  If not found load manually.
        if (window.jQuery.datetimepicker) {
            $(htmlContentInput).datetimepicker({ timepicker: showTime, format: 'm/d/y' });
        } else {
            $.ajaxSetup({
                cache: true
            });
            $.getScript("/Content/FormComponents/DatePickerComponent/datetimepicker/jquery.datetimepicker.js").done(function (script, textStatus) {
                $(htmlContentInput).datetimepicker({ timepicker: showTime, format: 'm/d/y'});
            });
        }
    } else {
        console.log("jQuery not found. Waiting for load 2 seconds.");
        setTimeout(2000, createDatePickerFormComponent(formControl));
    }
}
var DateFormatter; !function () { "use strict"; var D, s, r, a, n; D = function (e, t) { return "string" == typeof e && "string" == typeof t && e.toLowerCase() === t.toLowerCase() }, s = function (e, t, a) { var n = a || "0", r = e.toString(); return r.length < t ? s(n + r, t) : r }, r = function (e) { var t, a; for (e = e || {}, t = 1; t < arguments.length; t++)if (a = arguments[t]) for (var n in a) a.hasOwnProperty(n) && ("object" == typeof a[n] ? r(e[n], a[n]) : e[n] = a[n]); return e }, a = function (e, t) { for (var a = 0; a < t.length; a++)if (t[a].toLowerCase() === e.toLowerCase()) return a; return -1 }, n = { dateSettings: { days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], meridiem: ["AM", "PM"], ordinal: function (e) { var t = e % 10, a = { 1: "st", 2: "nd", 3: "rd" }; return 1 !== Math.floor(e % 100 / 10) && a[t] ? a[t] : "th" } }, separators: /[ \-+\/\.T:@]/g, validParts: /[dDjlNSwzWFmMntLoYyaABgGhHisueTIOPZcrU]/g, intParts: /[djwNzmnyYhHgGis]/g, tzParts: /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g, tzClip: /[^-+\dA-Z]/g }, (DateFormatter = function (e) { var t = this, a = r(n, e); t.dateSettings = a.dateSettings, t.separators = a.separators, t.validParts = a.validParts, t.intParts = a.intParts, t.tzParts = a.tzParts, t.tzClip = a.tzClip }).prototype = { constructor: DateFormatter, getMonth: function (e) { var t; return 0 === (t = a(e, this.dateSettings.monthsShort) + 1) && (t = a(e, this.dateSettings.months) + 1), t }, parseDate: function (e, t) { var a, n, r, o, i, s, d, u, l, f, c = this, m = !1, h = !1, g = c.dateSettings, p = { date: null, year: null, month: null, day: null, hour: 0, min: 0, sec: 0 }; if (!e) return null; if (e instanceof Date) return e; if ("U" === t) return (r = parseInt(e)) ? new Date(1e3 * r) : e; switch (typeof e) { case "number": return new Date(e); case "string": break; default: return null }if (!(a = t.match(c.validParts)) || 0 === a.length) throw new Error("Invalid date format definition."); for (n = e.replace(c.separators, "\0").split("\0"), r = 0; r < n.length; r++)switch (o = n[r], i = parseInt(o), a[r]) { case "y": case "Y": if (!i) return null; l = o.length, p.year = 2 === l ? parseInt((i < 70 ? "20" : "19") + o) : i, m = !0; break; case "m": case "n": case "M": case "F": if (isNaN(i)) { if (!(0 < (s = c.getMonth(o)))) return null; p.month = s } else { if (!(1 <= i && i <= 12)) return null; p.month = i } m = !0; break; case "d": case "j": if (!(1 <= i && i <= 31)) return null; p.day = i, m = !0; break; case "g": case "h": if (f = n[d = -1 < a.indexOf("a") ? a.indexOf("a") : -1 < a.indexOf("A") ? a.indexOf("A") : -1], -1 < d) u = D(f, g.meridiem[0]) ? 0 : D(f, g.meridiem[1]) ? 12 : -1, 1 <= i && i <= 12 && -1 < u ? p.hour = i + u - 1 : 0 <= i && i <= 23 && (p.hour = i); else { if (!(0 <= i && i <= 23)) return null; p.hour = i } h = !0; break; case "G": case "H": if (!(0 <= i && i <= 23)) return null; p.hour = i, h = !0; break; case "i": if (!(0 <= i && i <= 59)) return null; p.min = i, h = !0; break; case "s": if (!(0 <= i && i <= 59)) return null; p.sec = i, h = !0 }if (!0 === m && p.year && p.month && p.day) p.date = new Date(p.year, p.month - 1, p.day, p.hour, p.min, p.sec, 0); else { if (!0 !== h) return null; p.date = new Date(0, 0, 0, p.hour, p.min, p.sec, 0) } return p.date }, guessDate: function (e, t) { if ("string" != typeof e) return e; var a, n, r, o, i, s, d = e.replace(this.separators, "\0").split("\0"), u = t.match(this.validParts), l = new Date, f = 0; if (!/^[djmn]/g.test(u[0])) return e; for (r = 0; r < d.length; r++) { if (f = 2, i = d[r], s = parseInt(i.substr(0, 2)), isNaN(s)) return null; switch (r) { case 0: "m" === u[0] || "n" === u[0] ? l.setMonth(s - 1) : l.setDate(s); break; case 1: "m" === u[0] || "n" === u[0] ? l.setDate(s) : l.setMonth(s - 1); break; case 2: if (n = l.getFullYear(), f = (a = i.length) < 4 ? a : 4, !(n = parseInt(a < 4 ? n.toString().substr(0, 4 - a) + i : i.substr(0, 4)))) return null; l.setFullYear(n); break; case 3: l.setHours(s); break; case 4: l.setMinutes(s); break; case 5: l.setSeconds(s) }0 < (o = i.substr(f)).length && d.splice(r + 1, 0, o) } return l }, parseFormat: function (e, n) { var a, t = this, r = t.dateSettings, o = /\\?(.?)/gi, i = function (e, t) { return a[e] ? a[e]() : t }; return a = { d: function () { return s(a.j(), 2) }, D: function () { return r.daysShort[a.w()] }, j: function () { return n.getDate() }, l: function () { return r.days[a.w()] }, N: function () { return a.w() || 7 }, w: function () { return n.getDay() }, z: function () { var e = new Date(a.Y(), a.n() - 1, a.j()), t = new Date(a.Y(), 0, 1); return Math.round((e - t) / 864e5) }, W: function () { var e = new Date(a.Y(), a.n() - 1, a.j() - a.N() + 3), t = new Date(e.getFullYear(), 0, 4); return s(1 + Math.round((e - t) / 864e5 / 7), 2) }, F: function () { return r.months[n.getMonth()] }, m: function () { return s(a.n(), 2) }, M: function () { return r.monthsShort[n.getMonth()] }, n: function () { return n.getMonth() + 1 }, t: function () { return new Date(a.Y(), a.n(), 0).getDate() }, L: function () { var e = a.Y(); return e % 4 == 0 && e % 100 != 0 || e % 400 == 0 ? 1 : 0 }, o: function () { var e = a.n(), t = a.W(); return a.Y() + (12 === e && t < 9 ? 1 : 1 === e && 9 < t ? -1 : 0) }, Y: function () { return n.getFullYear() }, y: function () { return a.Y().toString().slice(-2) }, a: function () { return a.A().toLowerCase() }, A: function () { var e = a.G() < 12 ? 0 : 1; return r.meridiem[e] }, B: function () { var e = 3600 * n.getUTCHours(), t = 60 * n.getUTCMinutes(), a = n.getUTCSeconds(); return s(Math.floor((e + t + a + 3600) / 86.4) % 1e3, 3) }, g: function () { return a.G() % 12 || 12 }, G: function () { return n.getHours() }, h: function () { return s(a.g(), 2) }, H: function () { return s(a.G(), 2) }, i: function () { return s(n.getMinutes(), 2) }, s: function () { return s(n.getSeconds(), 2) }, u: function () { return s(1e3 * n.getMilliseconds(), 6) }, e: function () { return /\((.*)\)/.exec(String(n))[1] || "Coordinated Universal Time" }, I: function () { return new Date(a.Y(), 0) - Date.UTC(a.Y(), 0) != new Date(a.Y(), 6) - Date.UTC(a.Y(), 6) ? 1 : 0 }, O: function () { var e = n.getTimezoneOffset(), t = Math.abs(e); return (0 < e ? "-" : "+") + s(100 * Math.floor(t / 60) + t % 60, 4) }, P: function () { var e = a.O(); return e.substr(0, 3) + ":" + e.substr(3, 2) }, T: function () { return (String(n).match(t.tzParts) || [""]).pop().replace(t.tzClip, "") || "UTC" }, Z: function () { return 60 * -n.getTimezoneOffset() }, c: function () { return "Y-m-d\\TH:i:sP".replace(o, i) }, r: function () { return "D, d M Y H:i:s O".replace(o, i) }, U: function () { return n.getTime() / 1e3 || 0 } }, i(e, e) }, formatDate: function (e, t) { var a, n, r, o, i, s = ""; if ("string" == typeof e && !(e = this.parseDate(e, t))) return null; if (e instanceof Date) { for (r = t.length, a = 0; a < r; a++)"S" !== (i = t.charAt(a)) && "\\" !== i && (0 < a && "\\" === t.charAt(a - 1) ? s += i : (o = this.parseFormat(i, e), a !== r - 1 && this.intParts.test(i) && "S" === t.charAt(a + 1) && (n = parseInt(o) || 0, o += this.dateSettings.ordinal(n)), s += o)); return s } return "" } } }(); var datetimepickerFactory = function (L) { "use strict"; var s = { i18n: { ar: { months: ["كانون الثاني", "شباط", "آذار", "نيسان", "مايو", "حزيران", "تموز", "آب", "أيلول", "تشرين الأول", "تشرين الثاني", "كانون الأول"], dayOfWeekShort: ["ن", "ث", "ع", "خ", "ج", "س", "ح"], dayOfWeek: ["الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", "الأحد"] }, ro: { months: ["Ianuarie", "Februarie", "Martie", "Aprilie", "Mai", "Iunie", "Iulie", "August", "Septembrie", "Octombrie", "Noiembrie", "Decembrie"], dayOfWeekShort: ["Du", "Lu", "Ma", "Mi", "Jo", "Vi", "Sâ"], dayOfWeek: ["Duminică", "Luni", "Marţi", "Miercuri", "Joi", "Vineri", "Sâmbătă"] }, id: { months: ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"], dayOfWeekShort: ["Min", "Sen", "Sel", "Rab", "Kam", "Jum", "Sab"], dayOfWeek: ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"] }, is: { months: ["Janúar", "Febrúar", "Mars", "Apríl", "Maí", "Júní", "Júlí", "Ágúst", "September", "Október", "Nóvember", "Desember"], dayOfWeekShort: ["Sun", "Mán", "Þrið", "Mið", "Fim", "Fös", "Lau"], dayOfWeek: ["Sunnudagur", "Mánudagur", "Þriðjudagur", "Miðvikudagur", "Fimmtudagur", "Föstudagur", "Laugardagur"] }, bg: { months: ["Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"], dayOfWeekShort: ["Нд", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"], dayOfWeek: ["Неделя", "Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота"] }, fa: { months: ["فروردین", "اردیبهشت", "خرداد", "تیر", "مرداد", "شهریور", "مهر", "آبان", "آذر", "دی", "بهمن", "اسفند"], dayOfWeekShort: ["یکشنبه", "دوشنبه", "سه شنبه", "چهارشنبه", "پنجشنبه", "جمعه", "شنبه"], dayOfWeek: ["یک‌شنبه", "دوشنبه", "سه‌شنبه", "چهارشنبه", "پنج‌شنبه", "جمعه", "شنبه", "یک‌شنبه"] }, ru: { months: ["Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"], dayOfWeekShort: ["Вс", "Пн", "Вт", "Ср", "Чт", "Пт", "Сб"], dayOfWeek: ["Воскресенье", "Понедельник", "Вторник", "Среда", "Четверг", "Пятница", "Суббота"] }, uk: { months: ["Січень", "Лютий", "Березень", "Квітень", "Травень", "Червень", "Липень", "Серпень", "Вересень", "Жовтень", "Листопад", "Грудень"], dayOfWeekShort: ["Ндл", "Пнд", "Втр", "Срд", "Чтв", "Птн", "Сбт"], dayOfWeek: ["Неділя", "Понеділок", "Вівторок", "Середа", "Четвер", "П'ятниця", "Субота"] }, en: { months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], dayOfWeekShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] }, el: { months: ["Ιανουάριος", "Φεβρουάριος", "Μάρτιος", "Απρίλιος", "Μάιος", "Ιούνιος", "Ιούλιος", "Αύγουστος", "Σεπτέμβριος", "Οκτώβριος", "Νοέμβριος", "Δεκέμβριος"], dayOfWeekShort: ["Κυρ", "Δευ", "Τρι", "Τετ", "Πεμ", "Παρ", "Σαβ"], dayOfWeek: ["Κυριακή", "Δευτέρα", "Τρίτη", "Τετάρτη", "Πέμπτη", "Παρασκευή", "Σάββατο"] }, de: { months: ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], dayOfWeekShort: ["So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"], dayOfWeek: ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"] }, nl: { months: ["januari", "februari", "maart", "april", "mei", "juni", "juli", "augustus", "september", "oktober", "november", "december"], dayOfWeekShort: ["zo", "ma", "di", "wo", "do", "vr", "za"], dayOfWeek: ["zondag", "maandag", "dinsdag", "woensdag", "donderdag", "vrijdag", "zaterdag"] }, tr: { months: ["Ocak", "Şubat", "Mart", "Nisan", "Mayıs", "Haziran", "Temmuz", "Ağustos", "Eylül", "Ekim", "Kasım", "Aralık"], dayOfWeekShort: ["Paz", "Pts", "Sal", "Çar", "Per", "Cum", "Cts"], dayOfWeek: ["Pazar", "Pazartesi", "Salı", "Çarşamba", "Perşembe", "Cuma", "Cumartesi"] }, fr: { months: ["Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"], dayOfWeekShort: ["Dim", "Lun", "Mar", "Mer", "Jeu", "Ven", "Sam"], dayOfWeek: ["dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi"] }, es: { months: ["Enero", "Febrero", "Marzo", "Abril", "Mayo", "Junio", "Julio", "Agosto", "Septiembre", "Octubre", "Noviembre", "Diciembre"], dayOfWeekShort: ["Dom", "Lun", "Mar", "Mié", "Jue", "Vie", "Sáb"], dayOfWeek: ["Domingo", "Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado"] }, th: { months: ["มกราคม", "กุมภาพันธ์", "มีนาคม", "เมษายน", "พฤษภาคม", "มิถุนายน", "กรกฎาคม", "สิงหาคม", "กันยายน", "ตุลาคม", "พฤศจิกายน", "ธันวาคม"], dayOfWeekShort: ["อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส."], dayOfWeek: ["อาทิตย์", "จันทร์", "อังคาร", "พุธ", "พฤหัส", "ศุกร์", "เสาร์", "อาทิตย์"] }, pl: { months: ["styczeń", "luty", "marzec", "kwiecień", "maj", "czerwiec", "lipiec", "sierpień", "wrzesień", "październik", "listopad", "grudzień"], dayOfWeekShort: ["nd", "pn", "wt", "śr", "cz", "pt", "sb"], dayOfWeek: ["niedziela", "poniedziałek", "wtorek", "środa", "czwartek", "piątek", "sobota"] }, pt: { months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"], dayOfWeekShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sab"], dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"] }, ch: { months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], dayOfWeekShort: ["日", "一", "二", "三", "四", "五", "六"] }, se: { months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"], dayOfWeekShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"] }, km: { months: ["មករា​", "កុម្ភៈ", "មិនា​", "មេសា​", "ឧសភា​", "មិថុនា​", "កក្កដា​", "សីហា​", "កញ្ញា​", "តុលា​", "វិច្ឆិកា", "ធ្នូ​"], dayOfWeekShort: ["អាទិ​", "ច័ន្ទ​", "អង្គារ​", "ពុធ​", "ព្រហ​​", "សុក្រ​", "សៅរ៍"], dayOfWeek: ["អាទិត្យ​", "ច័ន្ទ​", "អង្គារ​", "ពុធ​", "ព្រហស្បតិ៍​", "សុក្រ​", "សៅរ៍"] }, kr: { months: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"], dayOfWeekShort: ["일", "월", "화", "수", "목", "금", "토"], dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"] }, it: { months: ["Gennaio", "Febbraio", "Marzo", "Aprile", "Maggio", "Giugno", "Luglio", "Agosto", "Settembre", "Ottobre", "Novembre", "Dicembre"], dayOfWeekShort: ["Dom", "Lun", "Mar", "Mer", "Gio", "Ven", "Sab"], dayOfWeek: ["Domenica", "Lunedì", "Martedì", "Mercoledì", "Giovedì", "Venerdì", "Sabato"] }, da: { months: ["Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December"], dayOfWeekShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"], dayOfWeek: ["søndag", "mandag", "tirsdag", "onsdag", "torsdag", "fredag", "lørdag"] }, no: { months: ["Januar", "Februar", "Mars", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Desember"], dayOfWeekShort: ["Søn", "Man", "Tir", "Ons", "Tor", "Fre", "Lør"], dayOfWeek: ["Søndag", "Mandag", "Tirsdag", "Onsdag", "Torsdag", "Fredag", "Lørdag"] }, ja: { months: ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"], dayOfWeekShort: ["日", "月", "火", "水", "木", "金", "土"], dayOfWeek: ["日曜", "月曜", "火曜", "水曜", "木曜", "金曜", "土曜"] }, vi: { months: ["Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"], dayOfWeekShort: ["CN", "T2", "T3", "T4", "T5", "T6", "T7"], dayOfWeek: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"] }, sl: { months: ["Januar", "Februar", "Marec", "April", "Maj", "Junij", "Julij", "Avgust", "September", "Oktober", "November", "December"], dayOfWeekShort: ["Ned", "Pon", "Tor", "Sre", "Čet", "Pet", "Sob"], dayOfWeek: ["Nedelja", "Ponedeljek", "Torek", "Sreda", "Četrtek", "Petek", "Sobota"] }, cs: { months: ["Leden", "Únor", "Březen", "Duben", "Květen", "Červen", "Červenec", "Srpen", "Září", "Říjen", "Listopad", "Prosinec"], dayOfWeekShort: ["Ne", "Po", "Út", "St", "Čt", "Pá", "So"] }, hu: { months: ["Január", "Február", "Március", "Április", "Május", "Június", "Július", "Augusztus", "Szeptember", "Október", "November", "December"], dayOfWeekShort: ["Va", "Hé", "Ke", "Sze", "Cs", "Pé", "Szo"], dayOfWeek: ["vasárnap", "hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat"] }, az: { months: ["Yanvar", "Fevral", "Mart", "Aprel", "May", "Iyun", "Iyul", "Avqust", "Sentyabr", "Oktyabr", "Noyabr", "Dekabr"], dayOfWeekShort: ["B", "Be", "Ça", "Ç", "Ca", "C", "Ş"], dayOfWeek: ["Bazar", "Bazar ertəsi", "Çərşənbə axşamı", "Çərşənbə", "Cümə axşamı", "Cümə", "Şənbə"] }, bs: { months: ["Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"], dayOfWeekShort: ["Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"], dayOfWeek: ["Nedjelja", "Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"] }, ca: { months: ["Gener", "Febrer", "Març", "Abril", "Maig", "Juny", "Juliol", "Agost", "Setembre", "Octubre", "Novembre", "Desembre"], dayOfWeekShort: ["Dg", "Dl", "Dt", "Dc", "Dj", "Dv", "Ds"], dayOfWeek: ["Diumenge", "Dilluns", "Dimarts", "Dimecres", "Dijous", "Divendres", "Dissabte"] }, "en-GB": { months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], dayOfWeekShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], dayOfWeek: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"] }, et: { months: ["Jaanuar", "Veebruar", "Märts", "Aprill", "Mai", "Juuni", "Juuli", "August", "September", "Oktoober", "November", "Detsember"], dayOfWeekShort: ["P", "E", "T", "K", "N", "R", "L"], dayOfWeek: ["Pühapäev", "Esmaspäev", "Teisipäev", "Kolmapäev", "Neljapäev", "Reede", "Laupäev"] }, eu: { months: ["Urtarrila", "Otsaila", "Martxoa", "Apirila", "Maiatza", "Ekaina", "Uztaila", "Abuztua", "Iraila", "Urria", "Azaroa", "Abendua"], dayOfWeekShort: ["Ig.", "Al.", "Ar.", "Az.", "Og.", "Or.", "La."], dayOfWeek: ["Igandea", "Astelehena", "Asteartea", "Asteazkena", "Osteguna", "Ostirala", "Larunbata"] }, fi: { months: ["Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu"], dayOfWeekShort: ["Su", "Ma", "Ti", "Ke", "To", "Pe", "La"], dayOfWeek: ["sunnuntai", "maanantai", "tiistai", "keskiviikko", "torstai", "perjantai", "lauantai"] }, gl: { months: ["Xan", "Feb", "Maz", "Abr", "Mai", "Xun", "Xul", "Ago", "Set", "Out", "Nov", "Dec"], dayOfWeekShort: ["Dom", "Lun", "Mar", "Mer", "Xov", "Ven", "Sab"], dayOfWeek: ["Domingo", "Luns", "Martes", "Mércores", "Xoves", "Venres", "Sábado"] }, hr: { months: ["Siječanj", "Veljača", "Ožujak", "Travanj", "Svibanj", "Lipanj", "Srpanj", "Kolovoz", "Rujan", "Listopad", "Studeni", "Prosinac"], dayOfWeekShort: ["Ned", "Pon", "Uto", "Sri", "Čet", "Pet", "Sub"], dayOfWeek: ["Nedjelja", "Ponedjeljak", "Utorak", "Srijeda", "Četvrtak", "Petak", "Subota"] }, ko: { months: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"], dayOfWeekShort: ["일", "월", "화", "수", "목", "금", "토"], dayOfWeek: ["일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일"] }, lt: { months: ["Sausio", "Vasario", "Kovo", "Balandžio", "Gegužės", "Birželio", "Liepos", "Rugpjūčio", "Rugsėjo", "Spalio", "Lapkričio", "Gruodžio"], dayOfWeekShort: ["Sek", "Pir", "Ant", "Tre", "Ket", "Pen", "Šeš"], dayOfWeek: ["Sekmadienis", "Pirmadienis", "Antradienis", "Trečiadienis", "Ketvirtadienis", "Penktadienis", "Šeštadienis"] }, lv: { months: ["Janvāris", "Februāris", "Marts", "Aprīlis ", "Maijs", "Jūnijs", "Jūlijs", "Augusts", "Septembris", "Oktobris", "Novembris", "Decembris"], dayOfWeekShort: ["Sv", "Pr", "Ot", "Tr", "Ct", "Pk", "St"], dayOfWeek: ["Svētdiena", "Pirmdiena", "Otrdiena", "Trešdiena", "Ceturtdiena", "Piektdiena", "Sestdiena"] }, mk: { months: ["јануари", "февруари", "март", "април", "мај", "јуни", "јули", "август", "септември", "октомври", "ноември", "декември"], dayOfWeekShort: ["нед", "пон", "вто", "сре", "чет", "пет", "саб"], dayOfWeek: ["Недела", "Понеделник", "Вторник", "Среда", "Четврток", "Петок", "Сабота"] }, mn: { months: ["1-р сар", "2-р сар", "3-р сар", "4-р сар", "5-р сар", "6-р сар", "7-р сар", "8-р сар", "9-р сар", "10-р сар", "11-р сар", "12-р сар"], dayOfWeekShort: ["Дав", "Мяг", "Лха", "Пүр", "Бсн", "Бям", "Ням"], dayOfWeek: ["Даваа", "Мягмар", "Лхагва", "Пүрэв", "Баасан", "Бямба", "Ням"] }, "pt-BR": { months: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"], dayOfWeekShort: ["Dom", "Seg", "Ter", "Qua", "Qui", "Sex", "Sáb"], dayOfWeek: ["Domingo", "Segunda", "Terça", "Quarta", "Quinta", "Sexta", "Sábado"] }, sk: { months: ["Január", "Február", "Marec", "Apríl", "Máj", "Jún", "Júl", "August", "September", "Október", "November", "December"], dayOfWeekShort: ["Ne", "Po", "Ut", "St", "Št", "Pi", "So"], dayOfWeek: ["Nedeľa", "Pondelok", "Utorok", "Streda", "Štvrtok", "Piatok", "Sobota"] }, sq: { months: ["Janar", "Shkurt", "Mars", "Prill", "Maj", "Qershor", "Korrik", "Gusht", "Shtator", "Tetor", "Nëntor", "Dhjetor"], dayOfWeekShort: ["Die", "Hën", "Mar", "Mër", "Enj", "Pre", "Shtu"], dayOfWeek: ["E Diel", "E Hënë", "E Martē", "E Mërkurë", "E Enjte", "E Premte", "E Shtunë"] }, "sr-YU": { months: ["Januar", "Februar", "Mart", "April", "Maj", "Jun", "Jul", "Avgust", "Septembar", "Oktobar", "Novembar", "Decembar"], dayOfWeekShort: ["Ned", "Pon", "Uto", "Sre", "čet", "Pet", "Sub"], dayOfWeek: ["Nedelja", "Ponedeljak", "Utorak", "Sreda", "Četvrtak", "Petak", "Subota"] }, sr: { months: ["јануар", "фебруар", "март", "април", "мај", "јун", "јул", "август", "септембар", "октобар", "новембар", "децембар"], dayOfWeekShort: ["нед", "пон", "уто", "сре", "чет", "пет", "суб"], dayOfWeek: ["Недеља", "Понедељак", "Уторак", "Среда", "Четвртак", "Петак", "Субота"] }, sv: { months: ["Januari", "Februari", "Mars", "April", "Maj", "Juni", "Juli", "Augusti", "September", "Oktober", "November", "December"], dayOfWeekShort: ["Sön", "Mån", "Tis", "Ons", "Tor", "Fre", "Lör"], dayOfWeek: ["Söndag", "Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag", "Lördag"] }, "zh-TW": { months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], dayOfWeekShort: ["日", "一", "二", "三", "四", "五", "六"], dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] }, zh: { months: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"], dayOfWeekShort: ["日", "一", "二", "三", "四", "五", "六"], dayOfWeek: ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"] }, ug: { months: ["1-ئاي", "2-ئاي", "3-ئاي", "4-ئاي", "5-ئاي", "6-ئاي", "7-ئاي", "8-ئاي", "9-ئاي", "10-ئاي", "11-ئاي", "12-ئاي"], dayOfWeek: ["يەكشەنبە", "دۈشەنبە", "سەيشەنبە", "چارشەنبە", "پەيشەنبە", "جۈمە", "شەنبە"] }, he: { months: ["ינואר", "פברואר", "מרץ", "אפריל", "מאי", "יוני", "יולי", "אוגוסט", "ספטמבר", "אוקטובר", "נובמבר", "דצמבר"], dayOfWeekShort: ["א'", "ב'", "ג'", "ד'", "ה'", "ו'", "שבת"], dayOfWeek: ["ראשון", "שני", "שלישי", "רביעי", "חמישי", "שישי", "שבת", "ראשון"] }, hy: { months: ["Հունվար", "Փետրվար", "Մարտ", "Ապրիլ", "Մայիս", "Հունիս", "Հուլիս", "Օգոստոս", "Սեպտեմբեր", "Հոկտեմբեր", "Նոյեմբեր", "Դեկտեմբեր"], dayOfWeekShort: ["Կի", "Երկ", "Երք", "Չոր", "Հնգ", "Ուրբ", "Շբթ"], dayOfWeek: ["Կիրակի", "Երկուշաբթի", "Երեքշաբթի", "Չորեքշաբթի", "Հինգշաբթի", "Ուրբաթ", "Շաբաթ"] }, kg: { months: ["Үчтүн айы", "Бирдин айы", "Жалган Куран", "Чын Куран", "Бугу", "Кулжа", "Теке", "Баш Оона", "Аяк Оона", "Тогуздун айы", "Жетинин айы", "Бештин айы"], dayOfWeekShort: ["Жек", "Дүй", "Шей", "Шар", "Бей", "Жум", "Ише"], dayOfWeek: ["Жекшемб", "Дүйшөмб", "Шейшемб", "Шаршемб", "Бейшемби", "Жума", "Ишенб"] }, rm: { months: ["Schaner", "Favrer", "Mars", "Avrigl", "Matg", "Zercladur", "Fanadur", "Avust", "Settember", "October", "November", "December"], dayOfWeekShort: ["Du", "Gli", "Ma", "Me", "Gie", "Ve", "So"], dayOfWeek: ["Dumengia", "Glindesdi", "Mardi", "Mesemna", "Gievgia", "Venderdi", "Sonda"] }, ka: { months: ["იანვარი", "თებერვალი", "მარტი", "აპრილი", "მაისი", "ივნისი", "ივლისი", "აგვისტო", "სექტემბერი", "ოქტომბერი", "ნოემბერი", "დეკემბერი"], dayOfWeekShort: ["კვ", "ორშ", "სამშ", "ოთხ", "ხუთ", "პარ", "შაბ"], dayOfWeek: ["კვირა", "ორშაბათი", "სამშაბათი", "ოთხშაბათი", "ხუთშაბათი", "პარასკევი", "შაბათი"] } }, ownerDocument: document, contentWindow: window, value: "", rtl: !1, format: "Y/m/d H:i", formatTime: "H:i", formatDate: "Y/m/d", startDate: !1, step: 60, monthChangeSpinner: !0, closeOnDateSelect: !1, closeOnTimeSelect: !0, closeOnWithoutClick: !0, closeOnInputClick: !0, openOnFocus: !0, timepicker: !0, datepicker: !0, weeks: !1, defaultTime: !1, defaultDate: !1, minDate: !1, maxDate: !1, minTime: !1, maxTime: !1, minDateTime: !1, maxDateTime: !1, allowTimes: [], opened: !1, initTime: !0, inline: !1, theme: "", touchMovedThreshold: 5, onSelectDate: function () { }, onSelectTime: function () { }, onChangeMonth: function () { }, onGetWeekOfYear: function () { }, onChangeYear: function () { }, onChangeDateTime: function () { }, onShow: function () { }, onClose: function () { }, onGenerate: function () { }, withoutCopyright: !0, inverseButton: !1, hours12: !1, next: "xdsoft_next", prev: "xdsoft_prev", dayOfWeekStart: 0, parentID: "body", timeHeightInTimePicker: 25, timepickerScrollbar: !0, todayButton: !0, prevButton: !0, nextButton: !0, defaultSelect: !0, scrollMonth: !0, scrollTime: !0, scrollInput: !0, lazyInit: !1, mask: !1, validateOnBlur: !0, allowBlank: !0, yearStart: 1950, yearEnd: 2050, monthStart: 0, monthEnd: 11, style: "", id: "", fixed: !1, roundTime: "round", className: "", weekends: [], highlightedDates: [], highlightedPeriods: [], allowDates: [], allowDateRe: null, disabledDates: [], disabledWeekDays: [], yearOffset: 0, beforeShowDay: null, enterLikeTab: !0, showApplyButton: !1, insideParent: !1 }, E = null, n = null, R = "en", a = { meridiem: ["AM", "PM"] }, r = function () { var e = s.i18n[R], t = { days: e.dayOfWeek, daysShort: e.dayOfWeekShort, months: e.months, monthsShort: L.map(e.months, function (e) { return e.substring(0, 3) }) }; "function" == typeof DateFormatter && (E = n = new DateFormatter({ dateSettings: L.extend({}, a, t) })) }, o = { moment: { default_options: { format: "YYYY/MM/DD HH:mm", formatDate: "YYYY/MM/DD", formatTime: "HH:mm" }, formatter: { parseDate: function (e, t) { if (i(t)) return n.parseDate(e, t); var a = moment(e, t); return !!a.isValid() && a.toDate() }, formatDate: function (e, t) { return i(t) ? n.formatDate(e, t) : moment(e).format(t) }, formatMask: function (e) { return e.replace(/Y{4}/g, "9999").replace(/Y{2}/g, "99").replace(/M{2}/g, "19").replace(/D{2}/g, "39").replace(/H{2}/g, "29").replace(/m{2}/g, "59").replace(/s{2}/g, "59") } } } }; L.datetimepicker = { setLocale: function (e) { var t = s.i18n[e] ? e : "en"; R !== t && (R = t, r()) }, setDateFormatter: function (e) { if ("string" == typeof e && o.hasOwnProperty(e)) { var t = o[e]; L.extend(s, t.default_options), E = t.formatter } else E = e } }; var t = { RFC_2822: "D, d M Y H:i:s O", ATOM: "Y-m-dTH:i:sP", ISO_8601: "Y-m-dTH:i:sO", RFC_822: "D, d M y H:i:s O", RFC_850: "l, d-M-y H:i:s T", RFC_1036: "D, d M y H:i:s O", RFC_1123: "D, d M Y H:i:s O", RSS: "D, d M Y H:i:s O", W3C: "Y-m-dTH:i:sP" }, i = function (e) { return -1 !== Object.values(t).indexOf(e) }; function m(e, t, a) { this.date = e, this.desc = t, this.style = a } L.extend(L.datetimepicker, t), r(), window.getComputedStyle || (window.getComputedStyle = function (a) { return this.el = a, this.getPropertyValue = function (e) { var t = /(-([a-z]))/g; return "float" === e && (e = "styleFloat"), t.test(e) && (e = e.replace(t, function (e, t, a) { return a.toUpperCase() })), a.currentStyle[e] || null }, this }), Array.prototype.indexOf || (Array.prototype.indexOf = function (e, t) { var a, n; for (a = t || 0, n = this.length; a < n; a += 1)if (this[a] === e) return a; return -1 }), Date.prototype.countDaysInMonth = function () { return new Date(this.getFullYear(), this.getMonth() + 1, 0).getDate() }, L.fn.xdsoftScroller = function (p, D) { return this.each(function () { var o, i, s, d, u, l = L(this), a = function (e) { var t, a = { x: 0, y: 0 }; return "touchstart" === e.type || "touchmove" === e.type || "touchend" === e.type || "touchcancel" === e.type ? (t = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0], a.x = t.clientX, a.y = t.clientY) : "mousedown" !== e.type && "mouseup" !== e.type && "mousemove" !== e.type && "mouseover" !== e.type && "mouseout" !== e.type && "mouseenter" !== e.type && "mouseleave" !== e.type || (a.x = e.clientX, a.y = e.clientY), a }, f = 100, n = !1, r = 0, c = 0, m = 0, t = !1, h = 0, g = function () { }; "hide" !== D ? (L(this).hasClass("xdsoft_scroller_box") || (o = l.children().eq(0), i = l[0].clientHeight, s = o[0].offsetHeight, d = L('<div class="xdsoft_scrollbar"></div>'), u = L('<div class="xdsoft_scroller"></div>'), d.append(u), l.addClass("xdsoft_scroller_box").append(d), g = function (e) { var t = a(e).y - r + h; t < 0 && (t = 0), t + u[0].offsetHeight > m && (t = m - u[0].offsetHeight), l.trigger("scroll_element.xdsoft_scroller", [f ? t / f : 0]) }, u.on("touchstart.xdsoft_scroller mousedown.xdsoft_scroller", function (e) { i || l.trigger("resize_scroll.xdsoft_scroller", [D]), r = a(e).y, h = parseInt(u.css("margin-top"), 10), m = d[0].offsetHeight, "mousedown" === e.type || "touchstart" === e.type ? (p.ownerDocument && L(p.ownerDocument.body).addClass("xdsoft_noselect"), L([p.ownerDocument.body, p.contentWindow]).on("touchend mouseup.xdsoft_scroller", function e() { L([p.ownerDocument.body, p.contentWindow]).off("touchend mouseup.xdsoft_scroller", e).off("mousemove.xdsoft_scroller", g).removeClass("xdsoft_noselect") }), L(p.ownerDocument.body).on("mousemove.xdsoft_scroller", g)) : (t = !0, e.stopPropagation(), e.preventDefault()) }).on("touchmove", function (e) { t && (e.preventDefault(), g(e)) }).on("touchend touchcancel", function () { t = !1, h = 0 }), l.on("scroll_element.xdsoft_scroller", function (e, t) { i || l.trigger("resize_scroll.xdsoft_scroller", [t, !0]), t = 1 < t ? 1 : t < 0 || isNaN(t) ? 0 : t, u.css("margin-top", f * t), setTimeout(function () { o.css("marginTop", -parseInt((o[0].offsetHeight - i) * t, 10)) }, 10) }).on("resize_scroll.xdsoft_scroller", function (e, t, a) { var n, r; i = l[0].clientHeight, s = o[0].offsetHeight, r = (n = i / s) * d[0].offsetHeight, 1 < n ? u.hide() : (u.show(), u.css("height", parseInt(10 < r ? r : 10, 10)), f = d[0].offsetHeight - u[0].offsetHeight, !0 !== a && l.trigger("scroll_element.xdsoft_scroller", [t || Math.abs(parseInt(o.css("marginTop"), 10)) / (s - i)])) }), l.on("mousewheel", function (e) { var t = Math.abs(parseInt(o.css("marginTop"), 10)); return (t -= 20 * e.deltaY) < 0 && (t = 0), l.trigger("scroll_element.xdsoft_scroller", [t / (s - i)]), e.stopPropagation(), !1 }), l.on("touchstart", function (e) { n = a(e), c = Math.abs(parseInt(o.css("marginTop"), 10)) }), l.on("touchmove", function (e) { if (n) { e.preventDefault(); var t = a(e); l.trigger("scroll_element.xdsoft_scroller", [(c - (t.y - n.y)) / (s - i)]) } }), l.on("touchend touchcancel", function () { n = !1, c = 0 })), l.trigger("resize_scroll.xdsoft_scroller", [D])) : l.find(".xdsoft_scrollbar").hide() }) }, L.fn.datetimepicker = function (H, a) { var n, r, o = this, p = 17, D = 13, y = 27, v = 37, b = 38, k = 39, x = 40, T = 9, S = 116, M = 65, w = 67, j = 86, J = 90, z = 89, I = !1, N = L.isPlainObject(H) || !H ? L.extend(!0, {}, s, H) : L.extend(!0, {}, s), i = 0; return n = function (O) { var t, n, a, r, W, h, _ = L('<div class="xdsoft_datetimepicker xdsoft_noselect"></div>'), e = L('<div class="xdsoft_copyright"><a target="_blank" href="http://xdsoft.net/jqplugins/datetimepicker/">xdsoft.net</a></div>'), g = L('<div class="xdsoft_datepicker active"></div>'), F = L('<div class="xdsoft_monthpicker"><button type="button" class="xdsoft_prev"></button><button type="button" class="xdsoft_today_button"></button><div class="xdsoft_label xdsoft_month"><span></span><i></i></div><div class="xdsoft_label xdsoft_year"><span></span><i></i></div><button type="button" class="xdsoft_next"></button></div>'), C = L('<div class="xdsoft_calendar"></div>'), o = L('<div class="xdsoft_timepicker active"><button type="button" class="xdsoft_prev"></button><div class="xdsoft_time_box"></div><button type="button" class="xdsoft_next"></button></div>'), u = o.find(".xdsoft_time_box").eq(0), P = L('<div class="xdsoft_time_variant"></div>'), i = L('<button type="button" class="xdsoft_save_selected blue-gradient-button">Save Selected</button>'), Y = L('<div class="xdsoft_select xdsoft_monthselect"><div></div></div>'), A = L('<div class="xdsoft_select xdsoft_yearselect"><div></div></div>'), s = !1, d = 0; N.id && _.attr("id", N.id), N.style && _.attr("style", N.style), N.weeks && _.addClass("xdsoft_showweeks"), N.rtl && _.addClass("xdsoft_rtl"), _.addClass("xdsoft_" + N.theme), _.addClass(N.className), F.find(".xdsoft_month span").after(Y), F.find(".xdsoft_year span").after(A), F.find(".xdsoft_month,.xdsoft_year").on("touchstart mousedown.xdsoft", function (e) { var t, a, n = L(this).find(".xdsoft_select").eq(0), r = 0, o = 0, i = n.is(":visible"); for (F.find(".xdsoft_select").hide(), W.currentTime && (r = W.currentTime[L(this).hasClass("xdsoft_month") ? "getMonth" : "getFullYear"]()), n[i ? "hide" : "show"](), t = n.find("div.xdsoft_option"), a = 0; a < t.length && t.eq(a).data("value") !== r; a += 1)o += t[0].offsetHeight; return n.xdsoftScroller(N, o / (n.children()[0].offsetHeight - n[0].clientHeight)), e.stopPropagation(), !1 }); var l = function (e) { var t = e.originalEvent, a = t.touches ? t.touches[0] : t; this.touchStartPosition = this.touchStartPosition || a; var n = Math.abs(this.touchStartPosition.clientX - a.clientX), r = Math.abs(this.touchStartPosition.clientY - a.clientY); Math.sqrt(n * n + r * r) > N.touchMovedThreshold && (this.touchMoved = !0) }; function f() { var e, t = !1; return N.startDate ? t = W.strToDate(N.startDate) : (t = N.value || (O && O.val && O.val() ? O.val() : "")) ? (t = W.strToDateTime(t), N.yearOffset && (t = new Date(t.getFullYear() - N.yearOffset, t.getMonth(), t.getDate(), t.getHours(), t.getMinutes(), t.getSeconds(), t.getMilliseconds()))) : N.defaultDate && (t = W.strToDateTime(N.defaultDate), N.defaultTime && (e = W.strtotime(N.defaultTime), t.setHours(e.getHours()), t.setMinutes(e.getMinutes()))), t && W.isValidDate(t) ? _.data("changed", !0) : t = "", t || 0 } function c(m) { var h = function (e, t) { var a = e.replace(/([\[\]\/\{\}\(\)\-\.\+]{1})/g, "\\$1").replace(/_/g, "{digit+}").replace(/([0-9]{1})/g, "{digit$1}").replace(/\{digit([0-9]{1})\}/g, "[0-$1_]{1}").replace(/\{digit[\+]\}/g, "[0-9_]{1}"); return new RegExp(a).test(t) }, g = function (e, t) { if (!(e = "string" == typeof e || e instanceof String ? m.ownerDocument.getElementById(e) : e)) return !1; if (e.createTextRange) { var a = e.createTextRange(); return a.collapse(!0), a.moveEnd("character", t), a.moveStart("character", t), a.select(), !0 } return !!e.setSelectionRange && (e.setSelectionRange(t, t), !0) }; m.mask && O.off("keydown.xdsoft"), !0 === m.mask && (E.formatMask ? m.mask = E.formatMask(m.format) : m.mask = m.format.replace(/Y/g, "9999").replace(/F/g, "9999").replace(/m/g, "19").replace(/d/g, "39").replace(/H/g, "29").replace(/i/g, "59").replace(/s/g, "59")), "string" === L.type(m.mask) && (h(m.mask, O.val()) || (O.val(m.mask.replace(/[0-9]/g, "_")), g(O[0], 0)), O.on("paste.xdsoft", function (e) { var t = (e.clipboardData || e.originalEvent.clipboardData || window.clipboardData).getData("text"), a = this.value, n = this.selectionStart; return a = a.substr(0, n) + t + a.substr(n + t.length), n += t.length, h(m.mask, a) ? (this.value = a, g(this, n)) : "" === L.trim(a) ? this.value = m.mask.replace(/[0-9]/g, "_") : O.trigger("error_input.xdsoft"), e.preventDefault(), !1 }), O.on("keydown.xdsoft", function (e) { var t, a = this.value, n = e.which, r = this.selectionStart, o = this.selectionEnd, i = r !== o; if (48 <= n && n <= 57 || 96 <= n && n <= 105 || 8 === n || 46 === n) { for (t = 8 === n || 46 === n ? "_" : String.fromCharCode(96 <= n && n <= 105 ? n - 48 : n), 8 === n && r && !i && (r -= 1); ;) { var s = m.mask.substr(r, 1), d = r < m.mask.length, u = 0 < r; if (!(/[^0-9_]/.test(s) && d && u)) break; r += 8 !== n || i ? 1 : -1 } if (e.metaKey && (i = !(r = 0)), i) { var l = o - r, f = m.mask.replace(/[0-9]/g, "_"), c = f.substr(r, l).substr(1); a = a.substr(0, r) + (t + c) + a.substr(r + l) } else { a = a.substr(0, r) + t + a.substr(r + 1) } if ("" === L.trim(a)) a = f; else if (r === m.mask.length) return e.preventDefault(), !1; for (r += 8 === n ? 0 : 1; /[^0-9_]/.test(m.mask.substr(r, 1)) && r < m.mask.length && 0 < r;)r += 8 === n ? 0 : 1; h(m.mask, a) ? (this.value = a, g(this, r)) : "" === L.trim(a) ? this.value = m.mask.replace(/[0-9]/g, "_") : O.trigger("error_input.xdsoft") } else if (-1 !== [M, w, j, J, z].indexOf(n) && I || -1 !== [y, b, x, v, k, S, p, T, D].indexOf(n)) return !0; return e.preventDefault(), !1 })) } F.find(".xdsoft_select").xdsoftScroller(N).on("touchstart mousedown.xdsoft", function (e) { var t = e.originalEvent; this.touchMoved = !1, this.touchStartPosition = t.touches ? t.touches[0] : t, e.stopPropagation(), e.preventDefault() }).on("touchmove", ".xdsoft_option", l).on("touchend mousedown.xdsoft", ".xdsoft_option", function () { if (!this.touchMoved) { void 0 !== W.currentTime && null !== W.currentTime || (W.currentTime = W.now()); var e = W.currentTime.getFullYear(); W && W.currentTime && W.currentTime[L(this).parent().parent().hasClass("xdsoft_monthselect") ? "setMonth" : "setFullYear"](L(this).data("value")), L(this).parent().parent().hide(), _.trigger("xchange.xdsoft"), N.onChangeMonth && L.isFunction(N.onChangeMonth) && N.onChangeMonth.call(_, W.currentTime, _.data("input")), e !== W.currentTime.getFullYear() && L.isFunction(N.onChangeYear) && N.onChangeYear.call(_, W.currentTime, _.data("input")) } }), _.getValue = function () { return W.getCurrentTime() }, _.setOptions = function (e) { var l = {}; N = L.extend(!0, {}, N, e), e.allowTimes && L.isArray(e.allowTimes) && e.allowTimes.length && (N.allowTimes = L.extend(!0, [], e.allowTimes)), e.weekends && L.isArray(e.weekends) && e.weekends.length && (N.weekends = L.extend(!0, [], e.weekends)), e.allowDates && L.isArray(e.allowDates) && e.allowDates.length && (N.allowDates = L.extend(!0, [], e.allowDates)), e.allowDateRe && "[object String]" === Object.prototype.toString.call(e.allowDateRe) && (N.allowDateRe = new RegExp(e.allowDateRe)), e.highlightedDates && L.isArray(e.highlightedDates) && e.highlightedDates.length && (L.each(e.highlightedDates, function (e, t) { var a, n = L.map(t.split(","), L.trim), r = new m(E.parseDate(n[0], N.formatDate), n[1], n[2]), o = E.formatDate(r.date, N.formatDate); void 0 !== l[o] ? (a = l[o].desc) && a.length && r.desc && r.desc.length && (l[o].desc = a + "\n" + r.desc) : l[o] = r }), N.highlightedDates = L.extend(!0, [], l)), e.highlightedPeriods && L.isArray(e.highlightedPeriods) && e.highlightedPeriods.length && (l = L.extend(!0, [], N.highlightedDates), L.each(e.highlightedPeriods, function (e, t) { var a, n, r, o, i, s, d; if (L.isArray(t)) a = t[0], n = t[1], r = t[2], d = t[3]; else { var u = L.map(t.split(","), L.trim); a = E.parseDate(u[0], N.formatDate), n = E.parseDate(u[1], N.formatDate), r = u[2], d = u[3] } for (; a <= n;)o = new m(a, r, d), i = E.formatDate(a, N.formatDate), a.setDate(a.getDate() + 1), void 0 !== l[i] ? (s = l[i].desc) && s.length && o.desc && o.desc.length && (l[i].desc = s + "\n" + o.desc) : l[i] = o }), N.highlightedDates = L.extend(!0, [], l)), e.disabledDates && L.isArray(e.disabledDates) && e.disabledDates.length && (N.disabledDates = L.extend(!0, [], e.disabledDates)), e.disabledWeekDays && L.isArray(e.disabledWeekDays) && e.disabledWeekDays.length && (N.disabledWeekDays = L.extend(!0, [], e.disabledWeekDays)), !N.open && !N.opened || N.inline || O.trigger("open.xdsoft"), N.inline && (s = !0, _.addClass("xdsoft_inline"), O.after(_).hide()), N.inverseButton && (N.next = "xdsoft_prev", N.prev = "xdsoft_next"), N.datepicker ? g.addClass("active") : g.removeClass("active"), N.timepicker ? o.addClass("active") : o.removeClass("active"), N.value && (W.setCurrentTime(N.value), O && O.val && O.val(W.str)), isNaN(N.dayOfWeekStart) ? N.dayOfWeekStart = 0 : N.dayOfWeekStart = parseInt(N.dayOfWeekStart, 10) % 7, N.timepickerScrollbar || u.xdsoftScroller(N, "hide"), N.minDate && /^[\+\-](.*)$/.test(N.minDate) && (N.minDate = E.formatDate(W.strToDateTime(N.minDate), N.formatDate)), N.maxDate && /^[\+\-](.*)$/.test(N.maxDate) && (N.maxDate = E.formatDate(W.strToDateTime(N.maxDate), N.formatDate)), N.minDateTime && /^\+(.*)$/.test(N.minDateTime) && (N.minDateTime = W.strToDateTime(N.minDateTime).dateFormat(N.formatDate)), N.maxDateTime && /^\+(.*)$/.test(N.maxDateTime) && (N.maxDateTime = W.strToDateTime(N.maxDateTime).dateFormat(N.formatDate)), i.toggle(N.showApplyButton), F.find(".xdsoft_today_button").css("visibility", N.todayButton ? "visible" : "hidden"), F.find("." + N.prev).css("visibility", N.prevButton ? "visible" : "hidden"), F.find("." + N.next).css("visibility", N.nextButton ? "visible" : "hidden"), c(N), N.validateOnBlur && O.off("blur.xdsoft").on("blur.xdsoft", function () { if (N.allowBlank && (!L.trim(L(this).val()).length || "string" == typeof N.mask && L.trim(L(this).val()) === N.mask.replace(/[0-9]/g, "_"))) L(this).val(null), _.data("xdsoft_datetime").empty(); else { var e = E.parseDate(L(this).val(), N.format); if (e) L(this).val(E.formatDate(e, N.format)); else { var t = +[L(this).val()[0], L(this).val()[1]].join(""), a = +[L(this).val()[2], L(this).val()[3]].join(""); !N.datepicker && N.timepicker && 0 <= t && t < 24 && 0 <= a && a < 60 ? L(this).val([t, a].map(function (e) { return 9 < e ? e : "0" + e }).join(":")) : L(this).val(E.formatDate(W.now(), N.format)) } _.data("xdsoft_datetime").setCurrentTime(L(this).val()) } _.trigger("changedatetime.xdsoft"), _.trigger("close.xdsoft") }), N.dayOfWeekStartPrev = 0 === N.dayOfWeekStart ? 6 : N.dayOfWeekStart - 1, _.trigger("xchange.xdsoft").trigger("afterOpen.xdsoft") }, _.data("options", N).on("touchstart mousedown.xdsoft", function (e) { return e.stopPropagation(), e.preventDefault(), A.hide(), Y.hide(), !1 }), u.append(P), u.xdsoftScroller(N), _.on("afterOpen.xdsoft", function () { u.xdsoftScroller(N) }), _.append(g).append(o), !0 !== N.withoutCopyright && _.append(e), g.append(F).append(C).append(i), N.insideParent ? L(O).parent().append(_) : L(N.parentID).append(_), W = new function () { var r = this; r.now = function (e) { var t, a, n = new Date; return !e && N.defaultDate && (t = r.strToDateTime(N.defaultDate), n.setFullYear(t.getFullYear()), n.setMonth(t.getMonth()), n.setDate(t.getDate())), n.setFullYear(n.getFullYear()), !e && N.defaultTime && (a = r.strtotime(N.defaultTime), n.setHours(a.getHours()), n.setMinutes(a.getMinutes()), n.setSeconds(a.getSeconds()), n.setMilliseconds(a.getMilliseconds())), n }, r.isValidDate = function (e) { return "[object Date]" === Object.prototype.toString.call(e) && !isNaN(e.getTime()) }, r.setCurrentTime = function (e, t) { "string" == typeof e ? r.currentTime = r.strToDateTime(e) : r.isValidDate(e) ? r.currentTime = e : e || t || !N.allowBlank || N.inline ? r.currentTime = r.now() : r.currentTime = null, _.trigger("xchange.xdsoft") }, r.empty = function () { r.currentTime = null }, r.getCurrentTime = function () { return r.currentTime }, r.nextMonth = function () { void 0 !== r.currentTime && null !== r.currentTime || (r.currentTime = r.now()); var e, t = r.currentTime.getMonth() + 1; return 12 === t && (r.currentTime.setFullYear(r.currentTime.getFullYear() + 1), t = 0), e = r.currentTime.getFullYear(), r.currentTime.setDate(Math.min(new Date(r.currentTime.getFullYear(), t + 1, 0).getDate(), r.currentTime.getDate())), r.currentTime.setMonth(t), N.onChangeMonth && L.isFunction(N.onChangeMonth) && N.onChangeMonth.call(_, W.currentTime, _.data("input")), e !== r.currentTime.getFullYear() && L.isFunction(N.onChangeYear) && N.onChangeYear.call(_, W.currentTime, _.data("input")), _.trigger("xchange.xdsoft"), t }, r.prevMonth = function () { void 0 !== r.currentTime && null !== r.currentTime || (r.currentTime = r.now()); var e = r.currentTime.getMonth() - 1; return -1 === e && (r.currentTime.setFullYear(r.currentTime.getFullYear() - 1), e = 11), r.currentTime.setDate(Math.min(new Date(r.currentTime.getFullYear(), e + 1, 0).getDate(), r.currentTime.getDate())), r.currentTime.setMonth(e), N.onChangeMonth && L.isFunction(N.onChangeMonth) && N.onChangeMonth.call(_, W.currentTime, _.data("input")), _.trigger("xchange.xdsoft"), e }, r.getWeekOfYear = function (e) { if (N.onGetWeekOfYear && L.isFunction(N.onGetWeekOfYear)) { var t = N.onGetWeekOfYear.call(_, e); if (void 0 !== t) return t } var a = new Date(e.getFullYear(), 0, 1); return 4 !== a.getDay() && a.setMonth(0, 1 + (4 - a.getDay() + 7) % 7), Math.ceil(((e - a) / 864e5 + a.getDay() + 1) / 7) }, r.strToDateTime = function (e) { var t, a, n = []; return e && e instanceof Date && r.isValidDate(e) ? e : ((n = /^([+-]{1})(.*)$/.exec(e)) && (n[2] = E.parseDate(n[2], N.formatDate)), a = n && n[2] ? (t = n[2].getTime() - 6e4 * n[2].getTimezoneOffset(), new Date(r.now(!0).getTime() + parseInt(n[1] + "1", 10) * t)) : e ? E.parseDate(e, N.format) : r.now(), r.isValidDate(a) || (a = r.now()), a) }, r.strToDate = function (e) { if (e && e instanceof Date && r.isValidDate(e)) return e; var t = e ? E.parseDate(e, N.formatDate) : r.now(!0); return r.isValidDate(t) || (t = r.now(!0)), t }, r.strtotime = function (e) { if (e && e instanceof Date && r.isValidDate(e)) return e; var t = e ? E.parseDate(e, N.formatTime) : r.now(!0); return r.isValidDate(t) || (t = r.now(!0)), t }, r.str = function () { var e = N.format; return N.yearOffset && (e = (e = e.replace("Y", r.currentTime.getFullYear() + N.yearOffset)).replace("y", String(r.currentTime.getFullYear() + N.yearOffset).substring(2, 4))), E.formatDate(r.currentTime, e) }, r.currentTime = this.now() }, i.on("touchend click", function (e) { e.preventDefault(), _.data("changed", !0), W.setCurrentTime(f()), O.val(W.str()), _.trigger("close.xdsoft") }), F.find(".xdsoft_today_button").on("touchend mousedown.xdsoft", function () { _.data("changed", !0), W.setCurrentTime(0, !0), _.trigger("afterOpen.xdsoft") }).on("dblclick.xdsoft", function () { var e, t, a = W.getCurrentTime(); a = new Date(a.getFullYear(), a.getMonth(), a.getDate()), e = W.strToDate(N.minDate), a < (e = new Date(e.getFullYear(), e.getMonth(), e.getDate())) || (t = W.strToDate(N.maxDate), (t = new Date(t.getFullYear(), t.getMonth(), t.getDate())) < a || (O.val(W.str()), O.trigger("change"), _.trigger("close.xdsoft"))) }), F.find(".xdsoft_prev,.xdsoft_next").on("touchend mousedown.xdsoft", function () { var a = L(this), n = 0, r = !1; !function e(t) { a.hasClass(N.next) ? W.nextMonth() : a.hasClass(N.prev) && W.prevMonth(), N.monthChangeSpinner && (r || (n = setTimeout(e, t || 100))) }(500), L([N.ownerDocument.body, N.contentWindow]).on("touchend mouseup.xdsoft", function e() { clearTimeout(n), r = !0, L([N.ownerDocument.body, N.contentWindow]).off("touchend mouseup.xdsoft", e) }) }), o.find(".xdsoft_prev,.xdsoft_next").on("touchend mousedown.xdsoft", function () { var o = L(this), i = 0, s = !1, d = 110; !function e(t) { var a = u[0].clientHeight, n = P[0].offsetHeight, r = Math.abs(parseInt(P.css("marginTop"), 10)); o.hasClass(N.next) && n - a - N.timeHeightInTimePicker >= r ? P.css("marginTop", "-" + (r + N.timeHeightInTimePicker) + "px") : o.hasClass(N.prev) && 0 <= r - N.timeHeightInTimePicker && P.css("marginTop", "-" + (r - N.timeHeightInTimePicker) + "px"), u.trigger("scroll_element.xdsoft_scroller", [Math.abs(parseInt(P[0].style.marginTop, 10) / (n - a))]), d = 10 < d ? 10 : d - 10, s || (i = setTimeout(e, t || d)) }(500), L([N.ownerDocument.body, N.contentWindow]).on("touchend mouseup.xdsoft", function e() { clearTimeout(i), s = !0, L([N.ownerDocument.body, N.contentWindow]).off("touchend mouseup.xdsoft", e) }) }), t = 0, _.on("xchange.xdsoft", function (e) { clearTimeout(t), t = setTimeout(function () { void 0 !== W.currentTime && null !== W.currentTime || (W.currentTime = W.now()); for (var e, t, a, n, r, o, i, s, d, u, l = "", f = new Date(W.currentTime.getFullYear(), W.currentTime.getMonth(), 1, 12, 0, 0), c = 0, m = W.now(), h = !1, g = !1, p = !1, D = !1, y = [], v = !0, b = ""; f.getDay() !== N.dayOfWeekStart;)f.setDate(f.getDate() - 1); for (l += "<table><thead><tr>", N.weeks && (l += "<th></th>"), e = 0; e < 7; e += 1)l += "<th>" + N.i18n[R].dayOfWeekShort[(e + N.dayOfWeekStart) % 7] + "</th>"; for (l += "</tr></thead>", l += "<tbody>", !1 !== N.maxDate && (h = W.strToDate(N.maxDate), h = new Date(h.getFullYear(), h.getMonth(), h.getDate(), 23, 59, 59, 999)), !1 !== N.minDate && (g = W.strToDate(N.minDate), g = new Date(g.getFullYear(), g.getMonth(), g.getDate())), !1 !== N.minDateTime && (p = W.strToDate(N.minDateTime), p = new Date(p.getFullYear(), p.getMonth(), p.getDate(), p.getHours(), p.getMinutes(), p.getSeconds())), !1 !== N.maxDateTime && (D = W.strToDate(N.maxDateTime), D = new Date(D.getFullYear(), D.getMonth(), D.getDate(), D.getHours(), D.getMinutes(), D.getSeconds())), !1 !== D && (u = 31 * (12 * D.getFullYear() + D.getMonth()) + D.getDate()); c < W.currentTime.countDaysInMonth() || f.getDay() !== N.dayOfWeekStart || W.currentTime.getMonth() === f.getMonth();) { y = [], c += 1, a = f.getDay(), n = f.getDate(), r = f.getFullYear(), M = f.getMonth(), o = W.getWeekOfYear(f), d = "", y.push("xdsoft_date"), i = N.beforeShowDay && L.isFunction(N.beforeShowDay.call) ? N.beforeShowDay.call(_, f) : null, N.allowDateRe && "[object RegExp]" === Object.prototype.toString.call(N.allowDateRe) && (N.allowDateRe.test(E.formatDate(f, N.formatDate)) || y.push("xdsoft_disabled")), N.allowDates && 0 < N.allowDates.length && -1 === N.allowDates.indexOf(E.formatDate(f, N.formatDate)) && y.push("xdsoft_disabled"); var k = 31 * (12 * f.getFullYear() + f.getMonth()) + f.getDate(); (!1 !== h && h < f || !1 !== p && f < p || !1 !== g && f < g || !1 !== D && u < k || i && !1 === i[0]) && y.push("xdsoft_disabled"), -1 !== N.disabledDates.indexOf(E.formatDate(f, N.formatDate)) && y.push("xdsoft_disabled"), -1 !== N.disabledWeekDays.indexOf(a) && y.push("xdsoft_disabled"), O.is("[disabled]") && y.push("xdsoft_disabled"), i && "" !== i[1] && y.push(i[1]), W.currentTime.getMonth() !== M && y.push("xdsoft_other_month"), (N.defaultSelect || _.data("changed")) && E.formatDate(W.currentTime, N.formatDate) === E.formatDate(f, N.formatDate) && y.push("xdsoft_current"), E.formatDate(m, N.formatDate) === E.formatDate(f, N.formatDate) && y.push("xdsoft_today"), 0 !== f.getDay() && 6 !== f.getDay() && -1 === N.weekends.indexOf(E.formatDate(f, N.formatDate)) || y.push("xdsoft_weekend"), void 0 !== N.highlightedDates[E.formatDate(f, N.formatDate)] && (t = N.highlightedDates[E.formatDate(f, N.formatDate)], y.push(void 0 === t.style ? "xdsoft_highlighted_default" : t.style), d = void 0 === t.desc ? "" : t.desc), N.beforeShowDay && L.isFunction(N.beforeShowDay) && y.push(N.beforeShowDay(f)), v && (l += "<tr>", v = !1, N.weeks && (l += "<th>" + o + "</th>")), l += '<td data-date="' + n + '" data-month="' + M + '" data-year="' + r + '" class="xdsoft_date xdsoft_day_of_week' + f.getDay() + " " + y.join(" ") + '" title="' + d + '"><div>' + n + "</div></td>", f.getDay() === N.dayOfWeekStartPrev && (l += "</tr>", v = !0), f.setDate(n + 1) } l += "</tbody></table>", C.html(l), F.find(".xdsoft_label span").eq(0).text(N.i18n[R].months[W.currentTime.getMonth()]), F.find(".xdsoft_label span").eq(1).text(W.currentTime.getFullYear() + N.yearOffset), M = b = ""; var x = 0; if (!1 !== N.minTime) { var T = W.strtotime(N.minTime); x = 60 * T.getHours() + T.getMinutes() } var S = 1440; if (!1 !== N.maxTime) { T = W.strtotime(N.maxTime); S = 60 * T.getHours() + T.getMinutes() } if (!1 !== N.minDateTime) { T = W.strToDateTime(N.minDateTime); if (E.formatDate(W.currentTime, N.formatDate) === E.formatDate(T, N.formatDate)) { var M = 60 * T.getHours() + T.getMinutes(); x < M && (x = M) } } if (!1 !== N.maxDateTime) { T = W.strToDateTime(N.maxDateTime); if (E.formatDate(W.currentTime, N.formatDate) === E.formatDate(T, N.formatDate)) (M = 60 * T.getHours() + T.getMinutes()) < S && (S = M) } if (s = function (e, t) { var a, n = W.now(), r = N.allowTimes && L.isArray(N.allowTimes) && N.allowTimes.length; n.setHours(e), e = parseInt(n.getHours(), 10), n.setMinutes(t), t = parseInt(n.getMinutes(), 10), y = []; var o = 60 * e + t; (O.is("[disabled]") || S <= o || o < x) && y.push("xdsoft_disabled"), (a = new Date(W.currentTime)).setHours(parseInt(W.currentTime.getHours(), 10)), r || a.setMinutes(Math[N.roundTime](W.currentTime.getMinutes() / N.step) * N.step), (N.initTime || N.defaultSelect || _.data("changed")) && a.getHours() === parseInt(e, 10) && (!r && 59 < N.step || a.getMinutes() === parseInt(t, 10)) && (N.defaultSelect || _.data("changed") ? y.push("xdsoft_current") : N.initTime && y.push("xdsoft_init_time")), parseInt(m.getHours(), 10) === parseInt(e, 10) && parseInt(m.getMinutes(), 10) === parseInt(t, 10) && y.push("xdsoft_today"), b += '<div class="xdsoft_time ' + y.join(" ") + '" data-hour="' + e + '" data-minute="' + t + '">' + E.formatDate(n, N.formatTime) + "</div>" }, N.allowTimes && L.isArray(N.allowTimes) && N.allowTimes.length) for (c = 0; c < N.allowTimes.length; c += 1)s(W.strtotime(N.allowTimes[c]).getHours(), M = W.strtotime(N.allowTimes[c]).getMinutes()); else for (e = c = 0; c < (N.hours12 ? 12 : 24); c += 1)for (e = 0; e < 60; e += N.step) { var w = 60 * c + e; w < x || (S <= w || s((c < 10 ? "0" : "") + c, M = (e < 10 ? "0" : "") + e)) } for (P.html(b), H = "", c = parseInt(N.yearStart, 10); c <= parseInt(N.yearEnd, 10); c += 1)H += '<div class="xdsoft_option ' + (W.currentTime.getFullYear() === c ? "xdsoft_current" : "") + '" data-value="' + c + '">' + (c + N.yearOffset) + "</div>"; for (A.children().eq(0).html(H), c = parseInt(N.monthStart, 10), H = ""; c <= parseInt(N.monthEnd, 10); c += 1)H += '<div class="xdsoft_option ' + (W.currentTime.getMonth() === c ? "xdsoft_current" : "") + '" data-value="' + c + '">' + N.i18n[R].months[c] + "</div>"; Y.children().eq(0).html(H), L(_).trigger("generate.xdsoft") }, 10), e.stopPropagation() }).on("afterOpen.xdsoft", function () { var e, t, a, n; N.timepicker && (P.find(".xdsoft_current").length ? e = ".xdsoft_current" : P.find(".xdsoft_init_time").length && (e = ".xdsoft_init_time"), e ? (t = u[0].clientHeight, (a = P[0].offsetHeight) - t < (n = P.find(e).index() * N.timeHeightInTimePicker + 1) && (n = a - t), u.trigger("scroll_element.xdsoft_scroller", [parseInt(n, 10) / (a - t)])) : u.trigger("scroll_element.xdsoft_scroller", [0])) }), n = 0, C.on("touchend click.xdsoft", "td", function (e) { e.stopPropagation(), n += 1; var t = L(this), a = W.currentTime; if (null == a && (W.currentTime = W.now(), a = W.currentTime), t.hasClass("xdsoft_disabled")) return !1; a.setDate(1), a.setFullYear(t.data("year")), a.setMonth(t.data("month")), a.setDate(t.data("date")), _.trigger("select.xdsoft", [a]), O.val(W.str()), N.onSelectDate && L.isFunction(N.onSelectDate) && N.onSelectDate.call(_, W.currentTime, _.data("input"), e), _.data("changed", !0), _.trigger("xchange.xdsoft"), _.trigger("changedatetime.xdsoft"), (1 < n || !0 === N.closeOnDateSelect || !1 === N.closeOnDateSelect && !N.timepicker) && !N.inline && _.trigger("close.xdsoft"), setTimeout(function () { n = 0 }, 200) }), P.on("touchstart", "div", function (e) { this.touchMoved = !1 }).on("touchmove", "div", l).on("touchend click.xdsoft", "div", function (e) { if (!this.touchMoved) { e.stopPropagation(); var t = L(this), a = W.currentTime; if (null == a && (W.currentTime = W.now(), a = W.currentTime), t.hasClass("xdsoft_disabled")) return !1; a.setHours(t.data("hour")), a.setMinutes(t.data("minute")), _.trigger("select.xdsoft", [a]), _.data("input").val(W.str()), N.onSelectTime && L.isFunction(N.onSelectTime) && N.onSelectTime.call(_, W.currentTime, _.data("input"), e), _.data("changed", !0), _.trigger("xchange.xdsoft"), _.trigger("changedatetime.xdsoft"), !0 !== N.inline && !0 === N.closeOnTimeSelect && _.trigger("close.xdsoft") } }), g.on("mousewheel.xdsoft", function (e) { return !N.scrollMonth || (e.deltaY < 0 ? W.nextMonth() : W.prevMonth(), !1) }), O.on("mousewheel.xdsoft", function (e) { return !N.scrollInput || (!N.datepicker && N.timepicker ? (0 <= (a = P.find(".xdsoft_current").length ? P.find(".xdsoft_current").eq(0).index() : 0) + e.deltaY && a + e.deltaY < P.children().length && (a += e.deltaY), P.children().eq(a).length && P.children().eq(a).trigger("mousedown"), !1) : N.datepicker && !N.timepicker ? (g.trigger(e, [e.deltaY, e.deltaX, e.deltaY]), O.val && O.val(W.str()), _.trigger("changedatetime.xdsoft"), !1) : void 0) }), _.on("changedatetime.xdsoft", function (e) { if (N.onChangeDateTime && L.isFunction(N.onChangeDateTime)) { var t = _.data("input"); N.onChangeDateTime.call(_, W.currentTime, t, e), delete N.value, t.trigger("change") } }).on("generate.xdsoft", function () { N.onGenerate && L.isFunction(N.onGenerate) && N.onGenerate.call(_, W.currentTime, _.data("input")), s && (_.trigger("afterOpen.xdsoft"), s = !1) }).on("click.xdsoft", function (e) { e.stopPropagation() }), a = 0, h = function (e, t) { do { if (!(e = e.parentNode) || !1 === t(e)) break } while ("HTML" !== e.nodeName) }, r = function () { var e, t, a, n, r, o, i, s, d, u, l, f, c; if (e = (s = _.data("input")).offset(), t = s[0], u = "top", a = e.top + t.offsetHeight - 1, n = e.left, r = "absolute", d = L(N.contentWindow).width(), f = L(N.contentWindow).height(), c = L(N.contentWindow).scrollTop(), N.ownerDocument.documentElement.clientWidth - e.left < g.parent().outerWidth(!0)) { var m = g.parent().outerWidth(!0) - t.offsetWidth; n -= m } "rtl" === s.parent().css("direction") && (n -= _.outerWidth() - s.outerWidth()), N.fixed ? (a -= c, n -= L(N.contentWindow).scrollLeft(), r = "fixed") : (i = !1, h(t, function (e) { return null !== e && ("fixed" === N.contentWindow.getComputedStyle(e).getPropertyValue("position") ? !(i = !0) : void 0) }), i && !N.insideParent ? (r = "fixed", a + _.outerHeight() > f + c ? (u = "bottom", a = f + c - e.top) : a -= c) : a + _[0].offsetHeight > f + c && (a = e.top - _[0].offsetHeight + 1), a < 0 && (a = 0), n + t.offsetWidth > d && (n = d - t.offsetWidth)), o = _[0], h(o, function (e) { if ("relative" === N.contentWindow.getComputedStyle(e).getPropertyValue("position") && d >= e.offsetWidth) return n -= (d - e.offsetWidth) / 2, !1 }), l = { position: r, left: N.insideParent ? t.offsetLeft : n, top: "", bottom: "" }, N.insideParent ? l[u] = t.offsetTop + t.offsetHeight : l[u] = a, _.css(l) }, _.on("open.xdsoft", function (e) { var t = !0; N.onShow && L.isFunction(N.onShow) && (t = N.onShow.call(_, W.currentTime, _.data("input"), e)), !1 !== t && (_.show(), r(), L(N.contentWindow).off("resize.xdsoft", r).on("resize.xdsoft", r), N.closeOnWithoutClick && L([N.ownerDocument.body, N.contentWindow]).on("touchstart mousedown.xdsoft", function e() { _.trigger("close.xdsoft"), L([N.ownerDocument.body, N.contentWindow]).off("touchstart mousedown.xdsoft", e) })) }).on("close.xdsoft", function (e) { var t = !0; F.find(".xdsoft_month,.xdsoft_year").find(".xdsoft_select").hide(), N.onClose && L.isFunction(N.onClose) && (t = N.onClose.call(_, W.currentTime, _.data("input"), e)), !1 === t || N.opened || N.inline || _.hide(), e.stopPropagation() }).on("toggle.xdsoft", function () { _.is(":visible") ? _.trigger("close.xdsoft") : _.trigger("open.xdsoft") }).data("input", O), d = 0, _.data("xdsoft_datetime", W), _.setOptions(N), W.setCurrentTime(f()), O.data("xdsoft_datetimepicker", _).on("open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart", function () { O.is(":disabled") || O.data("xdsoft_datetimepicker").is(":visible") && N.closeOnInputClick || N.openOnFocus && (clearTimeout(d), d = setTimeout(function () { O.is(":disabled") || (s = !0, W.setCurrentTime(f(), !0), N.mask && c(N), _.trigger("open.xdsoft")) }, 100)) }).on("keydown.xdsoft", function (e) { var t, a = e.which; return -1 !== [D].indexOf(a) && N.enterLikeTab ? (t = L("input:visible,textarea:visible,button:visible,a:visible"), _.trigger("close.xdsoft"), t.eq(t.index(this) + 1).focus(), !1) : -1 !== [T].indexOf(a) ? (_.trigger("close.xdsoft"), !0) : void 0 }).on("blur.xdsoft", function () { _.trigger("close.xdsoft") }) }, r = function (e) { var t = e.data("xdsoft_datetimepicker"); t && (t.data("xdsoft_datetime", null), t.remove(), e.data("xdsoft_datetimepicker", null).off(".xdsoft"), L(N.contentWindow).off("resize.xdsoft"), L([N.contentWindow, N.ownerDocument.body]).off("mousedown.xdsoft touchstart"), e.unmousewheel && e.unmousewheel()) }, L(N.ownerDocument).off("keydown.xdsoftctrl keyup.xdsoftctrl").off("keydown.xdsoftcmd keyup.xdsoftcmd").on("keydown.xdsoftctrl", function (e) { e.keyCode === p && (I = !0) }).on("keyup.xdsoftctrl", function (e) { e.keyCode === p && (I = !1) }).on("keydown.xdsoftcmd", function (e) { 91 === e.keyCode && !0 }).on("keyup.xdsoftcmd", function (e) { 91 === e.keyCode && !1 }), this.each(function () { var t, e = L(this).data("xdsoft_datetimepicker"); if (e) { if ("string" === L.type(H)) switch (H) { case "show": L(this).select().focus(), e.trigger("open.xdsoft"); break; case "hide": e.trigger("close.xdsoft"); break; case "toggle": e.trigger("toggle.xdsoft"); break; case "destroy": r(L(this)); break; case "reset": this.value = this.defaultValue, this.value && e.data("xdsoft_datetime").isValidDate(E.parseDate(this.value, N.format)) || e.data("changed", !1), e.data("xdsoft_datetime").setCurrentTime(this.value); break; case "validate": e.data("input").trigger("blur.xdsoft"); break; default: e[H] && L.isFunction(e[H]) && (o = e[H](a)) } else e.setOptions(H); return 0 } "string" !== L.type(H) && (!N.lazyInit || N.open || N.inline ? n(L(this)) : (t = L(this)).on("open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart", function e() { t.is(":disabled") || t.data("xdsoft_datetimepicker") || (clearTimeout(i), i = setTimeout(function () { t.data("xdsoft_datetimepicker") || n(t), t.off("open.xdsoft focusin.xdsoft mousedown.xdsoft touchstart", e).trigger("open.xdsoft") }, 100)) })) }), o }, L.fn.datetimepicker.defaults = s }; !function (e) { "function" == typeof define && define.amd ? define(["jquery", "jquery-mousewheel"], e) : "object" == typeof exports ? module.exports = e(require("jquery")) : e(jQuery) }(datetimepickerFactory), function (e) { "function" == typeof define && define.amd ? define(["jquery"], e) : "object" == typeof exports ? module.exports = e : e(jQuery) }(function (c) { var m, h, e = ["wheel", "mousewheel", "DOMMouseScroll", "MozMousePixelScroll"], t = "onwheel" in document || 9 <= document.documentMode ? ["wheel"] : ["mousewheel", "DomMouseScroll", "MozMousePixelScroll"], g = Array.prototype.slice; if (c.event.fixHooks) for (var a = e.length; a;)c.event.fixHooks[e[--a]] = c.event.mouseHooks; var p = c.event.special.mousewheel = { version: "3.1.12", setup: function () { if (this.addEventListener) for (var e = t.length; e;)this.addEventListener(t[--e], n, !1); else this.onmousewheel = n; c.data(this, "mousewheel-line-height", p.getLineHeight(this)), c.data(this, "mousewheel-page-height", p.getPageHeight(this)) }, teardown: function () { if (this.removeEventListener) for (var e = t.length; e;)this.removeEventListener(t[--e], n, !1); else this.onmousewheel = null; c.removeData(this, "mousewheel-line-height"), c.removeData(this, "mousewheel-page-height") }, getLineHeight: function (e) { var t = c(e), a = t["offsetParent" in c.fn ? "offsetParent" : "parent"](); return a.length || (a = c("body")), parseInt(a.css("fontSize"), 10) || parseInt(t.css("fontSize"), 10) || 16 }, getPageHeight: function (e) { return c(e).height() }, settings: { adjustOldDeltas: !0, normalizeOffset: !0 } }; function n(e) { var t, a = e || window.event, n = g.call(arguments, 1), r = 0, o = 0, i = 0, s = 0, d = 0; if ((e = c.event.fix(a)).type = "mousewheel", "detail" in a && (i = -1 * a.detail), "wheelDelta" in a && (i = a.wheelDelta), "wheelDeltaY" in a && (i = a.wheelDeltaY), "wheelDeltaX" in a && (o = -1 * a.wheelDeltaX), "axis" in a && a.axis === a.HORIZONTAL_AXIS && (o = -1 * i, i = 0), r = 0 === i ? o : i, "deltaY" in a && (r = i = -1 * a.deltaY), "deltaX" in a && (o = a.deltaX, 0 === i && (r = -1 * o)), 0 !== i || 0 !== o) { if (1 === a.deltaMode) { var u = c.data(this, "mousewheel-line-height"); r *= u, i *= u, o *= u } else if (2 === a.deltaMode) { var l = c.data(this, "mousewheel-page-height"); r *= l, i *= l, o *= l } if (t = Math.max(Math.abs(i), Math.abs(o)), (!h || t < h) && y(a, h = t) && (h /= 40), y(a, t) && (r /= 40, o /= 40, i /= 40), r = Math[1 <= r ? "floor" : "ceil"](r / h), o = Math[1 <= o ? "floor" : "ceil"](o / h), i = Math[1 <= i ? "floor" : "ceil"](i / h), p.settings.normalizeOffset && this.getBoundingClientRect) { var f = this.getBoundingClientRect(); s = e.clientX - f.left, d = e.clientY - f.top } return e.deltaX = o, e.deltaY = i, e.deltaFactor = h, e.offsetX = s, e.offsetY = d, e.deltaMode = 0, n.unshift(e, r, o, i), m && clearTimeout(m), m = setTimeout(D, 200), (c.event.dispatch || c.event.handle).apply(this, n) } } function D() { h = null } function y(e, t) { return p.settings.adjustOldDeltas && "mousewheel" === e.type && t % 120 == 0 } c.fn.extend({ mousewheel: function (e) { return e ? this.bind("mousewheel", e) : this.trigger("mousewheel") }, unmousewheel: function (e) { return this.unbind("mousewheel", e) } }) });

/*
 *  Bootstrap Duallistbox - v3.0.7
 *  A responsive dual listbox widget optimized for Twitter Bootstrap. It works on all modern browsers and on touch devices.
 *  https://www.virtuosoft.eu/code/bootstrap-duallistbox/
 *
 *  Made by István Ujj-Mészáros
 *  Under Apache License v2.0 License
 */
;(function ($, window, document, undefined) {
  // Create the defaults once
  var pluginName = 'bootstrapDualListbox',
    defaults = {
      bootstrap2Compatible: false,
      filterTextClear: 'show all',
      filterPlaceHolder: 'Filter',
      moveSelectedLabel: 'Move selected',
      moveAllLabel: 'Move all',
      removeSelectedLabel: 'Remove selected',
      removeAllLabel: 'Remove all',
      moveOnSelect: true,                                                                 // true/false (forced true on androids, see the comment later)
      moveOnDoubleClick: true,                                                            // true/false (forced false on androids, cause moveOnSelect is forced to true)
      preserveSelectionOnMove: false,                                                     // 'all' / 'moved' / false
      selectedListLabel: false,                                                           // 'string', false
      nonSelectedListLabel: false,                                                        // 'string', false
      helperSelectNamePostfix: '_helper',                                                 // 'string_of_postfix' / false
      selectorMinimalHeight: 100,
      showFilterInputs: true,                                                             // whether to show filter inputs
      nonSelectedFilter: '',                                                              // string, filter the non selected options
      selectedFilter: '',                                                                 // string, filter the selected options
      infoText: 'Showing all {0}',                                                        // text when all options are visible / false for no info text
      infoTextFiltered: '<span class="label label-warning">Filtered</span> {0} from {1}', // when not all of the options are visible due to the filter
      infoTextEmpty: 'Empty list',                                                        // when there are no options present in the list
      filterOnValues: false,                                                              // filter by selector's values, boolean
      sortByInputOrder: false,
      eventMoveOverride: false,                                                           // boolean, allows user to unbind default event behaviour and run their own instead
      eventMoveAllOverride: false,                                                        // boolean, allows user to unbind default event behaviour and run their own instead
      eventRemoveOverride: false,                                                         // boolean, allows user to unbind default event behaviour and run their own instead
      eventRemoveAllOverride: false                                                       // boolean, allows user to unbind default event behaviour and run their own instead
    },
    // Selections are invisible on android if the containing select is styled with CSS
    // http://code.google.com/p/android/issues/detail?id=16922
    isBuggyAndroid = /android/i.test(navigator.userAgent.toLowerCase());

  // The actual plugin constructor
  function BootstrapDualListbox(element, options) {
    this.element = $(element);
    // jQuery has an extend method which merges the contents of two or
    // more objects, storing the result in the first object. The first object
    // is generally empty as we don't want to alter the default options for
    // future instances of the plugin
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }

  function triggerChangeEvent(dualListbox) {
    dualListbox.element.trigger('change');
  }

  function updateSelectionStates(dualListbox) {
    dualListbox.element.find('option').each(function(index, item) {
      var $item = $(item);
      if (typeof($item.data('original-index')) === 'undefined') {
        $item.data('original-index', dualListbox.elementCount++);
      }
      if (typeof($item.data('_selected')) === 'undefined') {
        $item.data('_selected', false);
      }
    });
  }

  function changeSelectionState(dualListbox, original_index, selected) {
    dualListbox.element.find('option').each(function(index, item) {
      var $item = $(item);
      if ($item.data('original-index') === original_index) {
        $item.prop('selected', selected);
        if(selected){
          $item.attr('data-sortindex', dualListbox.sortIndex);
          dualListbox.sortIndex++;
        } else {
          $item.removeAttr('data-sortindex');
        }
      }
    });
  }

  function formatString(s, args) {
    return s.replace(/\{(\d+)\}/g, function(match, number) {
      return typeof args[number] !== 'undefined' ? args[number] : match;
    });
  }

  function refreshInfo(dualListbox) {
    if (!dualListbox.settings.infoText) {
      return;
    }

    var visible1 = dualListbox.elements.select1.find('option').length,
      visible2 = dualListbox.elements.select2.find('option').length,
      all1 = dualListbox.element.find('option').length - dualListbox.selectedElements,
      all2 = dualListbox.selectedElements,
      content = '';

    if (all1 === 0) {
      content = dualListbox.settings.infoTextEmpty;
    } else if (visible1 === all1) {
      content = formatString(dualListbox.settings.infoText, [visible1, all1]);
    } else {
      content = formatString(dualListbox.settings.infoTextFiltered, [visible1, all1]);
    }

    dualListbox.elements.info1.html(content);
    dualListbox.elements.box1.toggleClass('filtered', !(visible1 === all1 || all1 === 0));

    if (all2 === 0) {
      content = dualListbox.settings.infoTextEmpty;
    } else if (visible2 === all2) {
      content = formatString(dualListbox.settings.infoText, [visible2, all2]);
    } else {
      content = formatString(dualListbox.settings.infoTextFiltered, [visible2, all2]);
    }

    dualListbox.elements.info2.html(content);
    dualListbox.elements.box2.toggleClass('filtered', !(visible2 === all2 || all2 === 0));
  }

  function refreshSelects(dualListbox) {
    dualListbox.selectedElements = 0;

    dualListbox.elements.select1.empty();
    dualListbox.elements.select2.empty();

    dualListbox.element.find('option').each(function(index, item) {
      var $item = $(item);
      if ($item.prop('selected')) {
        dualListbox.selectedElements++;
        dualListbox.elements.select2.append($item.clone(true).prop('selected', $item.data('_selected')));
      } else {
        dualListbox.elements.select1.append($item.clone(true).prop('selected', $item.data('_selected')));
      }
    });

    if (dualListbox.settings.showFilterInputs) {
      filter(dualListbox, 1);
      filter(dualListbox, 2);
    }
    refreshInfo(dualListbox);
  }

  function filter(dualListbox, selectIndex) {
    if (!dualListbox.settings.showFilterInputs) {
      return;
    }

    saveSelections(dualListbox, selectIndex);

    dualListbox.elements['select'+selectIndex].empty().scrollTop(0);
    var regex = new RegExp($.trim(dualListbox.elements['filterInput'+selectIndex].val()), 'gi'),
      allOptions = dualListbox.element.find('option'),
      options = dualListbox.element;

    if (selectIndex === 1) {
      options = allOptions.not(':selected');
    } else  {
      options = options.find('option:selected');
    }

    options.each(function(index, item) {
      var $item = $(item),
        isFiltered = true;
      if (item.text.match(regex) || (dualListbox.settings.filterOnValues && $item.attr('value').match(regex) ) ) {
        isFiltered = false;
        dualListbox.elements['select'+selectIndex].append($item.clone(true).prop('selected', $item.data('_selected')));
      }
      allOptions.eq($item.data('original-index')).data('filtered'+selectIndex, isFiltered);
    });

    refreshInfo(dualListbox);
  }

  function saveSelections(dualListbox, selectIndex) {
    var options = dualListbox.element.find('option');
    dualListbox.elements['select'+selectIndex].find('option').each(function(index, item) {
      var $item = $(item);
      options.eq($item.data('original-index')).data('_selected', $item.prop('selected'));
    });
  }

  function sortOptionsByInputOrder(select){
    var selectopt = select.children('option');

    selectopt.sort(function(a,b){
      var an = parseInt(a.getAttribute('data-sortindex')),
          bn = parseInt(b.getAttribute('data-sortindex'));

          if(an > bn) {
             return 1;
          }
          if(an < bn) {
            return -1;
          }
          return 0;
    });

    selectopt.detach().appendTo(select);
  }

  function sortOptions(select) {
    select.find('option').sort(function(a, b) {
      return ($(a).data('original-index') > $(b).data('original-index')) ? 1 : -1;
    }).appendTo(select);
  }

  function clearSelections(dualListbox) {
    dualListbox.elements.select1.find('option').each(function() {
      dualListbox.element.find('option').data('_selected', false);
    });
  }

  function move(dualListbox) {
    if (dualListbox.settings.preserveSelectionOnMove === 'all' && !dualListbox.settings.moveOnSelect) {
      saveSelections(dualListbox, 1);
      saveSelections(dualListbox, 2);
    } else if (dualListbox.settings.preserveSelectionOnMove === 'moved' && !dualListbox.settings.moveOnSelect) {
      saveSelections(dualListbox, 1);
    }

    dualListbox.elements.select1.find('option:selected').each(function(index, item) {
      var $item = $(item);
      if (!$item.data('filtered1')) {
        changeSelectionState(dualListbox, $item.data('original-index'), true);
      }
    });

    refreshSelects(dualListbox);
    triggerChangeEvent(dualListbox);
    if(dualListbox.settings.sortByInputOrder){
        sortOptionsByInputOrder(dualListbox.elements.select2);
    } else {
        sortOptions(dualListbox.elements.select2);
    }
  }

  function remove(dualListbox) {
    if (dualListbox.settings.preserveSelectionOnMove === 'all' && !dualListbox.settings.moveOnSelect) {
      saveSelections(dualListbox, 1);
      saveSelections(dualListbox, 2);
    } else if (dualListbox.settings.preserveSelectionOnMove === 'moved' && !dualListbox.settings.moveOnSelect) {
      saveSelections(dualListbox, 2);
    }

    dualListbox.elements.select2.find('option:selected').each(function(index, item) {
      var $item = $(item);
      if (!$item.data('filtered2')) {
        changeSelectionState(dualListbox, $item.data('original-index'), false);
      }
    });

    refreshSelects(dualListbox);
    triggerChangeEvent(dualListbox);
    sortOptions(dualListbox.elements.select1);
    if(dualListbox.settings.sortByInputOrder){
        sortOptionsByInputOrder(dualListbox.elements.select2);
    }
  }

  function moveAll(dualListbox) {
    if (dualListbox.settings.preserveSelectionOnMove === 'all' && !dualListbox.settings.moveOnSelect) {
      saveSelections(dualListbox, 1);
      saveSelections(dualListbox, 2);
    } else if (dualListbox.settings.preserveSelectionOnMove === 'moved' && !dualListbox.settings.moveOnSelect) {
      saveSelections(dualListbox, 1);
    }

    dualListbox.element.find('option').each(function(index, item) {
      var $item = $(item);
      if (!$item.data('filtered1')) {
        $item.prop('selected', true);
        $item.attr('data-sortindex', dualListbox.sortIndex);
        dualListbox.sortIndex++;
      }
    });

    refreshSelects(dualListbox);
    triggerChangeEvent(dualListbox);
  }

  function removeAll(dualListbox) {
    if (dualListbox.settings.preserveSelectionOnMove === 'all' && !dualListbox.settings.moveOnSelect) {
      saveSelections(dualListbox, 1);
      saveSelections(dualListbox, 2);
    } else if (dualListbox.settings.preserveSelectionOnMove === 'moved' && !dualListbox.settings.moveOnSelect) {
      saveSelections(dualListbox, 2);
    }

    dualListbox.element.find('option').each(function(index, item) {
      var $item = $(item);
      if (!$item.data('filtered2')) {
        $item.prop('selected', false);
        $item.removeAttr('data-sortindex');
      }
    });

    refreshSelects(dualListbox);
    triggerChangeEvent(dualListbox);
  }

  function bindEvents(dualListbox) {
    dualListbox.elements.form.submit(function(e) {
      if (dualListbox.elements.filterInput1.is(':focus')) {
        e.preventDefault();
        dualListbox.elements.filterInput1.focusout();
      } else if (dualListbox.elements.filterInput2.is(':focus')) {
        e.preventDefault();
        dualListbox.elements.filterInput2.focusout();
      }
    });

    dualListbox.element.on('bootstrapDualListbox.refresh', function(e, mustClearSelections){
      dualListbox.refresh(mustClearSelections);
    });

    dualListbox.elements.filterClear1.on('click', function() {
      dualListbox.setNonSelectedFilter('', true);
    });

    dualListbox.elements.filterClear2.on('click', function() {
      dualListbox.setSelectedFilter('', true);
    });

    if (dualListbox.settings.eventMoveOverride === false) {
      dualListbox.elements.moveButton.on('click', function() {
        move(dualListbox);
      });
    }

    if (dualListbox.settings.eventMoveAllOverride === false) {
      dualListbox.elements.moveAllButton.on('click', function() {
        moveAll(dualListbox);
      });
    }

    if (dualListbox.settings.eventRemoveOverride === false) {
      dualListbox.elements.removeButton.on('click', function() {
        remove(dualListbox);
      });
    }

    if (dualListbox.settings.eventRemoveAllOverride === false) {
      dualListbox.elements.removeAllButton.on('click', function() {
        removeAll(dualListbox);
      });
    }

    dualListbox.elements.filterInput1.on('change keyup', function() {
      filter(dualListbox, 1);
    });

    dualListbox.elements.filterInput2.on('change keyup', function() {
      filter(dualListbox, 2);
    });
  }

  BootstrapDualListbox.prototype = {
    init: function () {
      // Add the custom HTML template
      this.container = $('' +
        '<div class="bootstrap-duallistbox-container">' +
        ' <div class="box1">' +
        '   <label></label>' +
        '   <span class="info-container">' +
        '     <span class="info"></span>' +
        '     <button type="button" class="btn clear1 pull-right"></button>' +
        '   </span>' +
        '   <input class="filter" type="text">' +
        '   <div class="btn-group buttons">' +
        '     <button type="button" class="btn moveall">' +
        '       <i></i>' +
        '       <i></i>' +
        '     </button>' +
        '     <button type="button" class="btn move">' +
        '       <i></i>' +
        '     </button>' +
        '   </div>' +
        '   <select multiple="multiple"></select>' +
        ' </div>' +
        ' <div class="box2">' +
        '   <label></label>' +
        '   <span class="info-container">' +
        '     <span class="info"></span>' +
        '     <button type="button" class="btn clear2 pull-right"></button>' +
        '   </span>' +
        '   <input class="filter" type="text">' +
        '   <div class="btn-group buttons">' +
        '     <button type="button" class="btn remove">' +
        '       <i></i>' +
        '     </button>' +
        '     <button type="button" class="btn removeall">' +
        '       <i></i>' +
        '       <i></i>' +
        '     </button>' +
        '   </div>' +
        '   <select multiple="multiple"></select>' +
        ' </div>' +
        '</div>')
        .insertBefore(this.element);

      // Cache the inner elements
      this.elements = {
        originalSelect: this.element,
        box1: $('.box1', this.container),
        box2: $('.box2', this.container),
        filterInput1: $('.box1 .filter', this.container),
        filterInput2: $('.box2 .filter', this.container),
        filterClear1: $('.box1 .clear1', this.container),
        filterClear2: $('.box2 .clear2', this.container),
        label1: $('.box1 > label', this.container),
        label2: $('.box2 > label', this.container),
        info1: $('.box1 .info', this.container),
        info2: $('.box2 .info', this.container),
        select1: $('.box1 select', this.container),
        select2: $('.box2 select', this.container),
        moveButton: $('.box1 .move', this.container),
        removeButton: $('.box2 .remove', this.container),
        moveAllButton: $('.box1 .moveall', this.container),
        removeAllButton: $('.box2 .removeall', this.container),
        form: $($('.box1 .filter', this.container)[0].form)
      };

      // Set select IDs
      this.originalSelectName = this.element.attr('name') || '';
      var select1Id = 'bootstrap-duallistbox-nonselected-list_' + this.originalSelectName,
        select2Id = 'bootstrap-duallistbox-selected-list_' + this.originalSelectName;
      this.elements.select1.attr('id', select1Id);
      this.elements.select2.attr('id', select2Id);
      this.elements.label1.attr('for', select1Id);
      this.elements.label2.attr('for', select2Id);

      // Apply all settings
      this.selectedElements = 0;
      this.sortIndex = 0;
      this.elementCount = 0;
      this.setBootstrap2Compatible(this.settings.bootstrap2Compatible);
      this.setFilterTextClear(this.settings.filterTextClear);
      this.setFilterPlaceHolder(this.settings.filterPlaceHolder);
      this.setMoveSelectedLabel(this.settings.moveSelectedLabel);
      this.setMoveAllLabel(this.settings.moveAllLabel);
      this.setRemoveSelectedLabel(this.settings.removeSelectedLabel);
      this.setRemoveAllLabel(this.settings.removeAllLabel);
      this.setMoveOnSelect(this.settings.moveOnSelect);
      this.setMoveOnDoubleClick(this.settings.moveOnDoubleClick);
      this.setPreserveSelectionOnMove(this.settings.preserveSelectionOnMove);
      this.setSelectedListLabel(this.settings.selectedListLabel);
      this.setNonSelectedListLabel(this.settings.nonSelectedListLabel);
      this.setHelperSelectNamePostfix(this.settings.helperSelectNamePostfix);
      this.setSelectOrMinimalHeight(this.settings.selectorMinimalHeight);

      updateSelectionStates(this);

      this.setShowFilterInputs(this.settings.showFilterInputs);
      this.setNonSelectedFilter(this.settings.nonSelectedFilter);
      this.setSelectedFilter(this.settings.selectedFilter);
      this.setInfoText(this.settings.infoText);
      this.setInfoTextFiltered(this.settings.infoTextFiltered);
      this.setInfoTextEmpty(this.settings.infoTextEmpty);
      this.setFilterOnValues(this.settings.filterOnValues);
      this.setSortByInputOrder(this.settings.sortByInputOrder);
      this.setEventMoveOverride(this.settings.eventMoveOverride);
      this.setEventMoveAllOverride(this.settings.eventMoveAllOverride);
      this.setEventRemoveOverride(this.settings.eventRemoveOverride);
      this.setEventRemoveAllOverride(this.settings.eventRemoveAllOverride);

      // Hide the original select
      this.element.hide();

      bindEvents(this);
      refreshSelects(this);

      return this.element;
    },
    setBootstrap2Compatible: function(value, refresh) {
      this.settings.bootstrap2Compatible = value;
      if (value) {
        this.container.removeClass('row').addClass('row-fluid bs2compatible');
        this.container.find('.box1, .box2').removeClass('col-md-6').addClass('span6');
        this.container.find('.clear1, .clear2').removeClass('btn-default btn-xs').addClass('btn-mini');
        this.container.find('input, select').removeClass('form-control');
        this.container.find('.btn').removeClass('btn-default');
        this.container.find('.moveall > i, .move > i').removeClass('glyphicon glyphicon-arrow-right').addClass('icon-arrow-right');
        this.container.find('.removeall > i, .remove > i').removeClass('glyphicon glyphicon-arrow-left').addClass('icon-arrow-left');
      } else {
        this.container.removeClass('row-fluid bs2compatible').addClass('row');
        this.container.find('.box1, .box2').removeClass('span6').addClass('col-md-6');
        this.container.find('.clear1, .clear2').removeClass('btn-mini').addClass('btn-default btn-xs');
        this.container.find('input, select').addClass('form-control');
        this.container.find('.btn').addClass('btn-default');
        this.container.find('.moveall > i, .move > i').removeClass('icon-arrow-right').addClass('glyphicon glyphicon-arrow-right');
        this.container.find('.removeall > i, .remove > i').removeClass('icon-arrow-left').addClass('glyphicon glyphicon-arrow-left');
      }
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setFilterTextClear: function(value, refresh) {
      this.settings.filterTextClear = value;
      this.elements.filterClear1.html(value);
      this.elements.filterClear2.html(value);
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setFilterPlaceHolder: function(value, refresh) {
      this.settings.filterPlaceHolder = value;
      this.elements.filterInput1.attr('placeholder', value);
      this.elements.filterInput2.attr('placeholder', value);
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setMoveSelectedLabel: function(value, refresh) {
      this.settings.moveSelectedLabel = value;
      this.elements.moveButton.attr('title', value);
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setMoveAllLabel: function(value, refresh) {
      this.settings.moveAllLabel = value;
      this.elements.moveAllButton.attr('title', value);
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setRemoveSelectedLabel: function(value, refresh) {
      this.settings.removeSelectedLabel = value;
      this.elements.removeButton.attr('title', value);
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setRemoveAllLabel: function(value, refresh) {
      this.settings.removeAllLabel = value;
      this.elements.removeAllButton.attr('title', value);
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setMoveOnSelect: function(value, refresh) {
      if (isBuggyAndroid) {
        value = true;
      }
      this.settings.moveOnSelect = value;
      if (this.settings.moveOnSelect) {
        this.container.addClass('moveonselect');
        var self = this;
        this.elements.select1.on('change', function() {
          move(self);
        });
        this.elements.select2.on('change', function() {
          remove(self);
        });
      } else {
        this.container.removeClass('moveonselect');
        this.elements.select1.off('change');
        this.elements.select2.off('change');
      }
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setMoveOnDoubleClick: function(value, refresh) {
      if (isBuggyAndroid) {
        value = false;
      }
      this.settings.moveOnDoubleClick = value;
      if (this.settings.moveOnDoubleClick) {
        this.container.addClass('moveondoubleclick');
        var self = this;
        this.elements.select1.on('dblclick', function() {
          move(self);
        });
        this.elements.select2.on('dblclick', function() {
          remove(self);
        });
      } else {
        this.container.removeClass('moveondoubleclick');
        this.elements.select1.off('dblclick');
        this.elements.select2.off('dblclick');
      }
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setPreserveSelectionOnMove: function(value, refresh) {
      // We are forcing to move on select and disabling preserveSelectionOnMove on Android
      if (isBuggyAndroid) {
        value = false;
      }
      this.settings.preserveSelectionOnMove = value;
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setSelectedListLabel: function(value, refresh) {
      this.settings.selectedListLabel = value;
      if (value) {
        this.elements.label2.show().html(value);
      } else {
        this.elements.label2.hide().html(value);
      }
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setNonSelectedListLabel: function(value, refresh) {
      this.settings.nonSelectedListLabel = value;
      if (value) {
        this.elements.label1.show().html(value);
      } else {
        this.elements.label1.hide().html(value);
      }
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setHelperSelectNamePostfix: function(value, refresh) {
      this.settings.helperSelectNamePostfix = value;
      if (value) {
        this.elements.select1.attr('name', this.originalSelectName + value + '1');
        this.elements.select2.attr('name', this.originalSelectName + value + '2');
      } else {
        this.elements.select1.removeAttr('name');
        this.elements.select2.removeAttr('name');
      }
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setSelectOrMinimalHeight: function(value, refresh) {
      this.settings.selectorMinimalHeight = value;
      var height = this.element.height();
      if (this.element.height() < value) {
        height = value;
      }
      this.elements.select1.height(height);
      this.elements.select2.height(height);
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setShowFilterInputs: function(value, refresh) {
      if (!value) {
        this.setNonSelectedFilter('');
        this.setSelectedFilter('');
        refreshSelects(this);
        this.elements.filterInput1.hide();
        this.elements.filterInput2.hide();
      } else {
        this.elements.filterInput1.show();
        this.elements.filterInput2.show();
      }
      this.settings.showFilterInputs = value;
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setNonSelectedFilter: function(value, refresh) {
      if (this.settings.showFilterInputs) {
        this.settings.nonSelectedFilter = value;
        this.elements.filterInput1.val(value);
        if (refresh) {
          refreshSelects(this);
        }
        return this.element;
      }
    },
    setSelectedFilter: function(value, refresh) {
      if (this.settings.showFilterInputs) {
        this.settings.selectedFilter = value;
        this.elements.filterInput2.val(value);
        if (refresh) {
          refreshSelects(this);
        }
        return this.element;
      }
    },
    setInfoText: function(value, refresh) {
      this.settings.infoText = value;
      if (value) {
        this.elements.info1.show();
        this.elements.info2.show();
      } else {
        this.elements.info1.hide();
        this.elements.info2.hide();
      }
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setInfoTextFiltered: function(value, refresh) {
      this.settings.infoTextFiltered = value;
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setInfoTextEmpty: function(value, refresh) {
      this.settings.infoTextEmpty = value;
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setFilterOnValues: function(value, refresh) {
      this.settings.filterOnValues = value;
      if (refresh) {
        refreshSelects(this);
      }
      return this.element;
    },
    setSortByInputOrder: function(value, refresh){
        this.settings.sortByInputOrder = value;
        if (refresh) {
          refreshSelects(this);
        }
        return this.element;
    },
    setEventMoveOverride: function(value, refresh) {
        this.settings.eventMoveOverride = value;
        if (refresh) {
          refreshSelects(this);
        }
        return this.element;
    },
    setEventMoveAllOverride: function(value, refresh) {
        this.settings.eventMoveAllOverride = value;
        if (refresh) {
          refreshSelects(this);
        }
        return this.element;
    },
    setEventRemoveOverride: function(value, refresh) {
        this.settings.eventRemoveOverride = value;
        if (refresh) {
          refreshSelects(this);
        }
        return this.element;
    },
    setEventRemoveAllOverride: function(value, refresh) {
        this.settings.eventRemoveAllOverride = value;
        if (refresh) {
          refreshSelects(this);
        }
        return this.element;
    },
    getContainer: function() {
      return this.container;
    },
    refresh: function(mustClearSelections) {
      updateSelectionStates(this);

      if (!mustClearSelections) {
        saveSelections(this, 1);
        saveSelections(this, 2);
      } else {
        clearSelections(this);
      }

      refreshSelects(this);
    },
    destroy: function() {
      this.container.remove();
      this.element.show();
      $.data(this, 'plugin_' + pluginName, null);
      return this.element;
    }
  };

  // A really lightweight plugin wrapper around the constructor,
  // preventing against multiple instantiations
  $.fn[ pluginName ] = function (options) {
    var args = arguments;

    // Is the first parameter an object (options), or was omitted, instantiate a new instance of the plugin.
    if (options === undefined || typeof options === 'object') {
      return this.each(function () {
        // If this is not a select
        if (!$(this).is('select')) {
          $(this).find('select').each(function(index, item) {
            // For each nested select, instantiate the Dual List Box
            $(item).bootstrapDualListbox(options);
          });
        } else if (!$.data(this, 'plugin_' + pluginName)) {
          // Only allow the plugin to be instantiated once so we check that the element has no plugin instantiation yet

          // if it has no instance, create a new one, pass options to our plugin constructor,
          // and store the plugin instance in the elements jQuery data object.
          $.data(this, 'plugin_' + pluginName, new BootstrapDualListbox(this, options));
        }
      });
      // If the first parameter is a string and it doesn't start with an underscore or "contains" the `init`-function,
      // treat this as a call to a public method.
    } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {

      // Cache the method call to make it possible to return a value
      var returns;

      this.each(function () {
        var instance = $.data(this, 'plugin_' + pluginName);
        // Tests that there's already a plugin-instance and checks that the requested public method exists
        if (instance instanceof BootstrapDualListbox && typeof instance[options] === 'function') {
          // Call the method of our plugin instance, and pass it the supplied arguments.
          returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
        }
      });

      // If the earlier cached method gives a value back return the value,
      // otherwise return this to preserve chainability.
      return returns !== undefined ? returns : this;
    }

  };

})(jQuery, window, document);

/**
 * jQuery transfer
 */
;(function($) {

    var Transfer = function(element, options) {
        this.$element = element;
        // default options
        this.defaults = {
            // data item name
            itemName: "item",
            // group data item name
            groupItemName: "groupItem",
            // group data array name
            groupArrayName: "groupArray",
            // data value name
            valueName: "value",
            // tab text
            tabNameText: "items",
            // right tab text
            rightTabNameText: "selected items",
            // search placeholder text
            searchPlaceholderText: "search",
            // items data array
            dataArray: [],
            // group data array
            groupDataArray: []
        };
        // merge options
        this.settings = $.extend(this.defaults, options);

        // tab text
        this.tabNameText = this.settings.tabNameText;
        // right tab text
        this.rightTabNameText = this.settings.rightTabNameText;
        // search placeholder text
        this.searchPlaceholderText = this.settings.searchPlaceholderText;
        // default total number text template
        this.default_total_num_text_template = "pre_num/total_num";
        // default zero item
        this.default_right_item_total_num_text = get_total_num_text(this.default_total_num_text_template, 0, 0);
        // item total number
        this.item_total_num = this.settings.dataArray.length;
        // group item total number
        this.group_item_total_num = get_group_items_num(this.settings.groupDataArray, this.settings.groupArrayName);
        // use group
        this.isGroup = this.group_item_total_num > 0;
        // inner data
        this._data = new InnerMap();
        // inner group data
        this._group_data = new InnerMap();

        // Id
        this.id = (getId())();
        // id selector for the item searcher
        this.itemSearcherId = "#listSearch_" + this.id;
        // id selector for the group item searcher
        this.groupItemSearcherId = "#groupListSearch_" + this.id;
        // id selector for the right searcher
        this.selectedItemSearcherId = "#selectedListSearch_" + this.id;

        // class selector for the transfer-double-list-ul
        this.transferDoubleListUlClass = ".transfer-double-list-ul-" + this.id;
        // class selector for the transfer-double-list-li
        this.transferDoubleListLiClass = ".transfer-double-list-li-" + this.id;
        // class selector for the left checkbox item
        this.checkboxItemClass = ".checkbox-item-" + this.id;
        // class selector for the left checkbox item label
        this.checkboxItemLabelClass = ".checkbox-name-" + this.id;
        // class selector for the left item total number label
        this.totalNumLabelClass = ".total_num_" + this.id;
        // id selector for the left item select all
        this.leftItemSelectAllId = "#leftItemSelectAll_" + this.id;

        // class selector for the transfer-double-group-list-ul
        this.transferDoubleGroupListUlClass = ".transfer-double-group-list-ul-" + this.id;
        // class selector for the transfer-double-group-list-li
        this.transferDoubleGroupListLiClass = ".transfer-double-group-list-li-" + this.id;
        // class selector for the group select all
        this.groupSelectAllClass = ".group-select-all-" + this.id;
        // class selector fro the transfer-double-group-list-li-ul-li
        this.transferDoubleGroupListLiUlLiClass = ".transfer-double-group-list-li-ul-li-" + this.id;
        // class selector for the group-checkbox-item
        this.groupCheckboxItemClass = ".group-checkbox-item-" + this.id;
        // class selector for the group-checkbox-name
        this.groupCheckboxNameLabelClass = ".group-checkbox-name-" + this.id;
        // class selector for the left group item total number label
        this.groupTotalNumLabelClass = ".group_total_num_" + this.id;
        // id selector for the left group item select all
        this.groupItemSelectAllId = "#groupItemSelectAll_" + this.id;

        // class selector for the transfer-double-selected-list-ul
        this.transferDoubleSelectedListUlClass = ".transfer-double-selected-list-ul-" + this.id;
        // class selector for the transfer-double-selected-list-li
        this.transferDoubleSelectedListLiClass = ".transfer-double-selected-list-li-" + this.id;
        // class selector for the right select checkbox item
        this.checkboxSelectedItemClass = ".checkbox-selected-item-" + this.id;
        // id selector for the right item select all
        this.rightItemSelectAllId = "#rightItemSelectAll_" + this.id;
        // class selector for the
        this.selectedTotalNumLabelClass = ".selected_total_num_" + this.id;
        // id selector for the add button
        this.addSelectedButtonId = "#add_selected_" + this.id;
        // id selector for the delete button
        this.deleteSelectedButtonId = "#delete_selected_" + this.id;
    }

    $.fn.transfer = function (options) {
        // new Transfer
        var transfer = new Transfer(this, options);
        // init
        transfer.init();

        return {
            // get selected items
            getSelectedItems: function () {
                return get_selected_items(transfer);
            },
            id: transfer.id
        };
    };

    /**
     * init
     */
    Transfer.prototype.init = function() {
        // generate transfer
        this.$element.append(this.generate_transfer());

        if (this.isGroup) {
            // fill group data
            this.fill_group_data();

            // left group checkbox item click handler
            this.left_group_checkbox_item_click_handler();
            // group select all handler
            this.group_select_all_handler();
            // group item select all handler
            this.group_item_select_all_handler();
            // left group items search handler
            this.left_group_items_search_handler();

        } else {
            // fill data
            this.fill_data();

            // left checkbox item click handler
            this.left_checkbox_item_click_handler();
            // left item select all handler
            this.left_item_select_all_handler();
            // left items search handler
            this.left_items_search_handler();
        }

        // right checkbox item click handler
        this.right_checkbox_item_click_handler();
        // move the pre-selection items to the right handler
        this.move_pre_selection_items_handler();
        // move the selected item to the left handler
        this.move_selected_items_handler();
        // right items search handler
        this.right_items_search_handler();
        // right item select all handler
        this.right_item_select_all_handler();
    }

    /**
     * generate transfer
     */
    Transfer.prototype.generate_transfer = function() {

        var template = parseHTMLTemplate(function() {
            /*
            <div class="transfer-double" id="transfer_double_{{= self.id }}">
                <div class="transfer-double-header"></div>
                <div class="transfer-double-content clearfix">

                    {{ // left part start }}

                    <div class="transfer-double-content-left">
                        <div class="transfer-double-content-param">
                            <div class="param-item">{{= self.tabNameText }}</div>
                        </div>

                        {{= self.isGroup ? self.generate_group_items_container() : self.generate_items_container() }}

                    </div>

                    {{ //  left part end }}

                    <div class="transfer-double-content-middle">
                        <div class="btn-select-arrow" id="add_selected_{{= self.id }}"><span class="mdi mdi-arrow-collapse-right"></span></div>
                        <div class="btn-select-arrow" id="delete_selected_{{= self.id }}"><span class="mdi mdi-arrow-collapse-left"></span></div>
                    </div>

                    {{ // right part start }}

                    <div class="transfer-double-content-right">
                        <div class="transfer-double-content-param">
                            <div class="param-item">{{= self.rightTabNameText }}</div>
                        </div>
                        <div class="transfer-double-selected-list">
                            <div class="transfer-double-selected-list-header">
                                <div class="transfer-double-selected-list-search d-none">
                                    <input class="transfer-double-selected-list-search-input" type="text" id="selectedListSearch_{{= self.id }}" placeholder="{{= self.searchPlaceholderText }}" value="" />
                                </div>
                            </div>
                            <div class="transfer-double-selected-list-content">
                                <div class="transfer-double-selected-list-main">
                                    <ul class="transfer-double-selected-list-ul transfer-double-selected-list-ul-{{= self.id }}"></ul>
                                </div>
                            </div>
                            <div class="transfer-double-list-footer">
                                <div class="checkbox-group">
                                    <input type="checkbox" class="checkbox-normal" id="rightItemSelectAll_{{= self.id }}">
                                    <label for="rightItemSelectAll_{{= self.id }}" class="selected_total_num_{{= self.id }}"></label>
                                </div>
                            </div>
                        </div>
                    </div>

                    {{ // right part end }}

                </div>
                <div class="transfer-double-footer"></div>
            </div>
            */
        })

        var compiled = $.template(template);
        return compiled({ self: this })
    }

    /**
     * generate group items container
     */
    Transfer.prototype.generate_group_items_container = function() {

        var template = parseHTMLTemplate(function() {
            /*
            <div class="transfer-double-list transfer-double-list-{{= self.id }}">
                <div class="transfer-double-list-header">
                    <div class="transfer-double-list-search d-none">
                        <input class="transfer-double-list-search-input" type="text" id="groupListSearch_{{= self.id }}" placeholder="{{= self.searchPlaceholderText }}" value="" />
                    </div>
                </div>
                <div class="transfer-double-list-content">
                    <div class="transfer-double-list-main">
                        <ul class="transfer-double-group-list-ul transfer-double-group-list-ul-{{= self.id }}"></ul>
                    </div>
                </div>
                <div class="transfer-double-list-footer">
                    <div class="checkbox-group">
                        <input type="checkbox" class="checkbox-normal" id="groupItemSelectAll_{{= self.id }}"><label for="groupItemSelectAll_{{= self.id }}" class="group_total_num_{{= self.id }}"></label>
                    </div>
                </div>
            </div>
            */
        })

        var compiled = $.template(template);
        return compiled({ self: this })
    }

    /**
     * generate items container
     */
    Transfer.prototype.generate_items_container = function() {

        var template = parseHTMLTemplate(function() {
            /*
            <div class="transfer-double-list transfer-double-list-{{= self.id }}">
                <div class="transfer-double-list-header">
                    <div class="transfer-double-list-search d-none">
                        <input class="transfer-double-list-search-input" type="text" id="listSearch_{{= self.id }}" placeholder="{{= self.searchPlaceholderText }}" value="" />
                    </div>
                </div>
                <div class="transfer-double-list-content">
                    <div class="transfer-double-list-main">
                        <ul class="transfer-double-list-ul transfer-double-list-ul-{{= self.id }}"></ul>
                    </div>
                </div>
                <div class="transfer-double-list-footer">
                    <div class="checkbox-group">
                        <input type="checkbox" class="checkbox-normal" id="leftItemSelectAll_{{= self.id }}"><label for="leftItemSelectAll_{{= self.id }}" class="total_num_{{= self.id }}"></label>
                    </div>
                </div>
            </div>
           */ 
        })

        var compiled = $.template(template);
        return compiled({ self: this })
    }

    /**
     * fill data
     */
    Transfer.prototype.fill_data = function() {
        this.$element.find(this.transferDoubleListUlClass).empty();
        this.$element.find(this.transferDoubleListUlClass).append(this.generate_left_items());

        this.$element.find(this.transferDoubleSelectedListUlClass).empty();
        this.$element.find(this.transferDoubleSelectedListUlClass).append(this.generate_right_items());

        // render total num
        this.$element.find(this.totalNumLabelClass).empty();
        this.$element.find(this.totalNumLabelClass).append(get_total_num_text(this.default_total_num_text_template, 0, this._data.get("left_total_count")));

        // render right total num
        this.$element.find(this.selectedTotalNumLabelClass).empty();
        this.$element.find(this.selectedTotalNumLabelClass).append(get_total_num_text(this.default_total_num_text_template, 0, this._data.get("right_total_count")));
    }

    /**
     * fill group data
     */
    Transfer.prototype.fill_group_data = function() {
        this.$element.find(this.transferDoubleGroupListUlClass).empty();
        this.$element.find(this.transferDoubleGroupListUlClass).append(this.generate_left_group_items());

        this.$element.find(this.transferDoubleSelectedListUlClass).empty();
        this.$element.find(this.transferDoubleSelectedListUlClass).append(this.generate_right_group_items());

        var self = this;
        var left_total_count = 0;
        this._group_data.forEach(function(key, value) {
            left_total_count += value["left_total_count"]
            value["left_total_count"] == 0 ? self.$element.find("#" + key).prop("disabled", true).prop("checked", true) : void(0)
        })

        // render total num
        this.$element.find(this.groupTotalNumLabelClass).empty();
        this.$element.find(this.groupTotalNumLabelClass).append(get_total_num_text(this.default_total_num_text_template, 0, left_total_count));

        // render right total num
        this.$element.find(this.selectedTotalNumLabelClass).empty();
        this.$element.find(this.selectedTotalNumLabelClass).append(get_total_num_text(this.default_total_num_text_template, 0, this._data.get("right_total_count")));
    }

    /**
     * generate left items
     */
    Transfer.prototype.generate_left_items = function() {
        var html = "";
        var dataArray = this.settings.dataArray;
        var itemName = this.settings.itemName;
        var valueName = this.settings.valueName;

        var template = parseHTMLTemplate(function() {
            /*
            <li class="transfer-double-list-li transfer-double-list-li-{{= self.id }} {{= selected ? 'selected-hidden' : ' ' }}">
                <div class="checkbox-group">
                    <input {{= disabled ? disabled="disabled" : "" }} type="checkbox" value="{{= dataArray[i][valueName] }}" class="checkbox-normal checkbox-item-{{= self.id }}" id="itemCheckbox_{{= i }}_{{= self.id }}">
                    <label class="checkbox-name-{{= self.id }}" for="itemCheckbox_{{= i }}_{{= self.id }}">{{= dataArray[i][itemName] }}</label>
                </div>
            </li>
            */
        })

        for (var i = 0; i < dataArray.length; i++) {

            var selected = dataArray[i].selected || false;
            var disabled = dataArray[i].disabled || false;
            var right_total_count = this._data.get("right_total_count") || 0;
            var disabled_count = this._data.get("left_disabled_count") || 0;
            this._data.get("right_total_count") == undefined ? this._data.put("right_total_count", right_total_count) : void(0)
            selected ? this._data.put("right_total_count", ++right_total_count) : void(0)
            !selected && disabled ? this._data.put("left_disabled_count", ++disabled_count) : void(0)

            var compiled = $.template(template);
            html += compiled({ self: this, dataArray: dataArray, i: i, itemName: itemName, valueName: valueName, selected: selected, disabled: disabled })
        }

        this._data.put("left_pre_selection_count", 0);
        this._data.put("left_total_count", dataArray.length - this._data.get("right_total_count"));

        return html;
    }

    /**
     * render left group items
     */
    Transfer.prototype.generate_left_group_items = function() {
        var html = "";
        var id = this.id;
        var groupDataArray = this.settings.groupDataArray;
        var groupItemName = this.settings.groupItemName;
        var groupArrayName = this.settings.groupArrayName;
        var itemName = this.settings.itemName;
        var valueName = this.settings.valueName;

        var groupItemTemplate = parseHTMLTemplate(function() {
            /*
            <li class="transfer-double-group-list-li-ul-li transfer-double-group-list-li-ul-li-{{= self.id }} {{= selected ? 'selected-hidden' : '' }}">
                <div class="checkbox-group">
                    <input type="checkbox" value="{{= groupDataArray[i][groupArrayName][j][valueName] }}" class="checkbox-normal group-checkbox-item-{{= self.id }} belongs-group-{{= i }}-{{= self.id }}" id="group_{{= i }}_checkbox_{{= j }}_{{= self.id }}">
                    <label for="group_{{= i }}_checkbox_{{= j }}_{{= self.id }}" class="group-checkbox-name-{{= self.id }}">{{= groupDataArray[i][groupArrayName][j][itemName] }}</label>
                </div>
            </li>
            */
        })

        var groupTemplate = parseHTMLTemplate(function() {
            /*
            <li class="transfer-double-group-list-li transfer-double-group-list-li-{{= self.id }}">
                <div class="checkbox-group">
                    <input type="checkbox" class="checkbox-normal group-select-all-{{= self.id }}" id="group_{{= i }}_{{= self.id }}">
                    <label for="group_{{= i }}_{{= self.id }}" class="group-name-{{= self.id }}">{{= groupDataArray[i][groupItemName] }}</label>
                </div>
                <ul class="transfer-double-group-list-li-ul transfer-double-group-list-li-ul-{{= self.id }}">
            */
        })
        
        for (var i = 0; i < groupDataArray.length; i++) {
            if (groupDataArray[i][groupArrayName] && groupDataArray[i][groupArrayName].length > 0) {

                var _value = {};
                _value["left_pre_selection_count"] = 0
                _value["left_total_count"] = groupDataArray[i][groupArrayName].length
                this._group_data.put('group_' + i + '_' + this.id, _value);

                var groupTemplateCompiled = $.template(groupTemplate);
                html += groupTemplateCompiled({ self: this, groupDataArray: groupDataArray, i: i, groupItemName: groupItemName })

                for (var j = 0; j < groupDataArray[i][groupArrayName].length; j++) {

                    var selected = groupDataArray[i][groupArrayName][j].selected || false;
                    var right_total_count = this._data.get("right_total_count") || 0;
                    this._data.get("right_total_count") == undefined ? this._data.put("right_total_count", right_total_count) : void(0)
                    selected ? this._data.put("right_total_count", ++right_total_count) : void(0)

                    var groupItem = this._group_data.get('group_' + i + '_' + this.id);
                    selected ? groupItem["left_total_count"] -= 1 : void(0)

                    var groupItemTemplateCompiled = $.template(groupItemTemplate);
                    html += groupItemTemplateCompiled({ self: this, groupDataArray: groupDataArray, i: i, j: j, groupArrayName: groupArrayName, itemName: itemName, valueName: valueName, selected: selected })
                }
                html += '</ul></li>'
            }
        }

        return html;
    }

    /**
     * generate right items
     */
    Transfer.prototype.generate_right_items = function() {
        var html = "";
        var dataArray = this.settings.dataArray;
        var itemName = this.settings.itemName;
        var valueName = this.settings.valueName;
        var selected_count = 0;
        var disabled_count = 0;

        this._data.put("right_pre_selection_count", selected_count);
        this._data.put("right_total_count", selected_count);

        for (var i = 0; i < dataArray.length; i++) {
            if (dataArray[i].selected || false) {
                var disabled = dataArray[i].disabled || false;
                disabled ? disabled_count++ : void(0)
                this._data.put("right_total_count", ++selected_count);
                html += this.generate_item(this.id, i, dataArray[i][valueName], dataArray[i][itemName], disabled);
            }
        }

        this._data.put("right_disabled_count", disabled_count);

        if (this._data.get("right_total_count") == 0) {
            $(this.rightItemSelectAllId).prop("checked", true).prop("disabled", "disabled");
        }

        return html;
    }

    /**
     * generate right group items
     */
    Transfer.prototype.generate_right_group_items = function() {
        var html = "";
        var groupDataArray = this.settings.groupDataArray;
        var groupArrayName = this.settings.groupArrayName;
        var itemName = this.settings.itemName;
        var valueName = this.settings.valueName;
        var selected_count = 0;

        this._data.put("right_pre_selection_count", selected_count);
        this._data.put("right_total_count", selected_count);

        for (var i = 0; i < groupDataArray.length; i++) {
            if (groupDataArray[i][groupArrayName] && groupDataArray[i][groupArrayName].length > 0) {
                for (var j = 0; j < groupDataArray[i][groupArrayName].length; j++) {
                    if (groupDataArray[i][groupArrayName][j].selected || false) {
                        this._data.put("right_total_count", ++selected_count);
                        html += this.generate_group_item(this.id, i, j, groupDataArray[i][groupArrayName][j][valueName], groupDataArray[i][groupArrayName][j][itemName]);
                    }
                }
            }
        }

        if (this._data.get("right_total_count") == 0) {
            $(this.rightItemSelectAllId).prop("checked", true).prop("disabled", "disabled");
        }

        return html;
    }

    /**
     * left checkbox item click handler
     */
    Transfer.prototype.left_checkbox_item_click_handler = function() {
        var self = this;
        self.$element.on("click", self.checkboxItemClass, function () {
            var pre_selection_num = 0;
            $(this).is(":checked") ? pre_selection_num++ : pre_selection_num--

            var left_pre_selection_count = self._data.get("left_pre_selection_count");
            self._data.put("left_pre_selection_count", left_pre_selection_count + pre_selection_num);
            self.$element.find(self.totalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, self._data.get("left_pre_selection_count"), self._data.get("left_total_count")));

            if (self._data.get("left_pre_selection_count") > 0) {
                $(self.addSelectedButtonId).addClass("btn-arrow-active");
            } else {
                $(self.addSelectedButtonId).removeClass("btn-arrow-active");
            }

            if (self._data.get("left_pre_selection_count") < self._data.get("left_total_count")) {
                $(self.leftItemSelectAllId).prop("checked", false);
            } else if (self._data.get("left_pre_selection_count") == self._data.get("left_total_count")) {
                $(self.leftItemSelectAllId).prop("checked", true);
            }
            if (self._data.get("left_pre_selection_count") == (self._data.get("left_total_count") - self._data.get("left_disabled_count"))) {
                $(self.leftItemSelectAllId).prop("checked", true);
            }
        });
    }

    /**
     * left group checkbox item click handler
     */
    Transfer.prototype.left_group_checkbox_item_click_handler = function() {
        var self = this;
        self.$element.on("click", self.groupCheckboxItemClass, function () {
            var pre_selection_num = 0;
            var total_pre_selection_num = 0;
            var remain_left_total_count = 0

            $(this).is(":checked") ? pre_selection_num++ : pre_selection_num--

            var groupIndex = $(this).prop("id").split("_")[1];
            var groupItem =  self._group_data.get('group_' + groupIndex + '_' + self.id);
            var left_pre_selection_count = groupItem["left_pre_selection_count"];
            groupItem["left_pre_selection_count"] = left_pre_selection_count + pre_selection_num

            self._group_data.forEach(function(key, value) {
                total_pre_selection_num += value["left_pre_selection_count"]
                remain_left_total_count += value["left_total_count"]
            });

            self.$element.find(self.groupTotalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, total_pre_selection_num, remain_left_total_count));

            if (total_pre_selection_num > 0) {
                $(self.addSelectedButtonId).addClass("btn-arrow-active");
            } else {
                $(self.addSelectedButtonId).removeClass("btn-arrow-active");
            }

            if (groupItem["left_pre_selection_count"] < groupItem["left_total_count"]) {
                self.$element.find("#group_" + groupIndex + "_" + self.id).prop("checked", false);
            } else if (groupItem["left_pre_selection_count"] == groupItem["left_total_count"]) {
                self.$element.find("#group_" + groupIndex + "_" + self.id).prop("checked", true);
            }

            if (total_pre_selection_num == remain_left_total_count) {
                $(self.groupItemSelectAllId).prop("checked", true);
            } else {
                $(self.groupItemSelectAllId).prop("checked", false);
            }
        });
    }

    /**
     * group select all handler
     */
    Transfer.prototype.group_select_all_handler = function() {
        var self = this;
        $(self.groupSelectAllClass).on("click", function () {
            // group index
            var groupIndex = ($(this).attr("id")).split("_")[1];
            var groups =  self.$element.find(".belongs-group-" + groupIndex + "-" + self.id);
            var left_pre_selection_count = 0;
            var left_total_count = 0;

            // a group is checked
            if ($(this).is(':checked')) {
                // active button
                $(self.addSelectedButtonId).addClass("btn-arrow-active");
                for (var i = 0; i < groups.length; i++) {
                    if (!groups.eq(i).is(':checked') && groups.eq(i).parent("div").parent("li").css("display") != "none") {
                        groups.eq(i).prop("checked", true);
                    }
                }

                var groupItem = self._group_data.get($(this).prop("id"));
                groupItem["left_pre_selection_count"] = groupItem["left_total_count"];

                self._group_data.forEach(function(key, value) {
                    left_pre_selection_count += value["left_pre_selection_count"];
                    left_total_count += value["left_total_count"];
                })

                if (left_pre_selection_count == left_total_count) {
                    $(self.groupItemSelectAllId).prop("checked", true);
                }
            } else {
                for (var j = 0; j < groups.length; j++) {
                    if (groups.eq(j).is(':checked') && groups.eq(j).parent("div").parent("li").css("display") != "none") {
                        groups.eq(j).prop("checked", false);
                    }
                }

                self._group_data.get($(this).prop("id"))["left_pre_selection_count"] = 0;

                self._group_data.forEach(function(key, value) {
                    left_pre_selection_count += value["left_pre_selection_count"];
                    left_total_count += value["left_total_count"];
                })

                if (left_pre_selection_count != left_total_count) {
                    $(self.groupItemSelectAllId).prop("checked", false);
                }

                if (left_pre_selection_count == 0) {
                    $(self.addSelectedButtonId).removeClass("btn-arrow-active");
                }
            }
            self.$element.find(self.groupTotalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, left_pre_selection_count, left_total_count));
        });
    }

    /**
     * group item select all handler
     */
    Transfer.prototype.group_item_select_all_handler = function() {
        var self = this;
        $(self.groupItemSelectAllId).on("click", function () {
            var groupCheckboxItems = self.$element.find(self.groupCheckboxItemClass);
            var left_pre_selection_count = 0;
            var left_total_count = 0;
            if ($(this).is(':checked')) {
                for (var i = 0; i < groupCheckboxItems.length; i++) {
                    if (groupCheckboxItems.parent("div").parent("li").eq(i).css('display') != "none" && !groupCheckboxItems.eq(i).is(':checked')) {
                        groupCheckboxItems.eq(i).prop("checked", true);
                        var groupIndex = groupCheckboxItems.eq(i).prop("id").split("_")[1];
                        if (!self.$element.find(self.groupSelectAllClass).eq(groupIndex).is(':checked')) {
                            self.$element.find(self.groupSelectAllClass).eq(groupIndex).prop("checked", true);
                        }
                    }
                }

                self._group_data.forEach(function (key, value) {
                    value["left_pre_selection_count"] = value["left_total_count"];
                    left_pre_selection_count += value["left_pre_selection_count"];
                    left_total_count += value["left_total_count"];
                })

                $(self.addSelectedButtonId).addClass("btn-arrow-active");
            } else {
                for (var i = 0; i < groupCheckboxItems.length; i++) {
                    if (groupCheckboxItems.parent("div").parent("li").eq(i).css('display') != "none" && groupCheckboxItems.eq(i).is(':checked')) {
                        groupCheckboxItems.eq(i).prop("checked", false);
                        var groupIndex = groupCheckboxItems.eq(i).prop("id").split("_")[1];
                        if (self.$element.find(self.groupSelectAllClass).eq(groupIndex).is(':checked')) {
                            self.$element.find(self.groupSelectAllClass).eq(groupIndex).prop("checked", false);
                        }
                    }
                }

                self._group_data.forEach(function (key, value) {
                    value["left_pre_selection_count"] = 0;
                    left_pre_selection_count = 0;
                    left_total_count += value["left_total_count"];
                })

                $(self.addSelectedButtonId).removeClass("btn-arrow-active");
            }
            self.$element.find(self.groupTotalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, left_pre_selection_count, left_total_count));
        });
    }

    /**
     * left group items search handler
     */
    Transfer.prototype.left_group_items_search_handler = function() {
        var self = this;
        $(self.groupItemSearcherId).on("keyup", function () {
            self.$element.find(self.transferDoubleGroupListUlClass).css('display', 'block');
            var transferDoubleGroupListLiUlLis = self.$element.find(self.transferDoubleGroupListLiUlLiClass);
            if ($(self.groupItemSearcherId).val() == "") {
                for (var i = 0; i < transferDoubleGroupListLiUlLis.length; i++) {
                    if (!transferDoubleGroupListLiUlLis.eq(i).hasClass("selected-hidden")) {
                        transferDoubleGroupListLiUlLis.eq(i).parent("ul").parent("li").css('display', 'block');
                        transferDoubleGroupListLiUlLis.eq(i).css('display', 'block');
                    } else {
                        transferDoubleGroupListLiUlLis.eq(i).parent("ul").parent("li").css('display', 'block');
                    }
                }
                return;
            }

            // Mismatch
            self.$element.find(self.transferDoubleGroupListLiClass).css('display', 'none');
            transferDoubleGroupListLiUlLis.css('display', 'none');

            for (var j = 0; j < transferDoubleGroupListLiUlLis.length; j++) {
                if (!transferDoubleGroupListLiUlLis.eq(j).hasClass("selected-hidden")
                    && transferDoubleGroupListLiUlLis.eq(j).text().trim()
                        .substr(0, $(self.groupItemSearcherId).val().length).toLowerCase() == $(self.groupItemSearcherId).val().toLowerCase()) {
                            transferDoubleGroupListLiUlLis.eq(j).parent("ul").parent("li").css('display', 'block');
                            transferDoubleGroupListLiUlLis.eq(j).css('display', 'block');
                }
            }
        });
    }

    /**
     * left item select all handler
     */
    Transfer.prototype.left_item_select_all_handler = function() {
        var self = this;
        $(self.leftItemSelectAllId).on("click", function () {
            var checkboxItems = self.$element.find(self.checkboxItemClass);
            var pre_selection_num = self._data.get("left_pre_selection_count");
            if ($(this).is(':checked')) {
                for (var i = 0; i < checkboxItems.length; i++) {
                    if (!checkboxItems.eq(i).prop("disabled")) {
                        if (checkboxItems.eq(i).parent("div").parent("li").css('display') != "none" && !checkboxItems.eq(i).is(':checked') && !checkboxItems.eq(i).prop('disabled')) {
                            checkboxItems.eq(i).prop("checked", true);
                            self._data.put("left_pre_selection_count", ++pre_selection_num);
                        }
                    }
                }
                $(self.addSelectedButtonId).addClass("btn-arrow-active");
            } else {
                for (var i = 0; i < checkboxItems.length; i++) {
                    if (checkboxItems.eq(i).parent("div").parent("li").css('display') != "none" && checkboxItems.eq(i).is(':checked')) {
                        checkboxItems.eq(i).prop("checked", false);
                    }
                }
                $(self.addSelectedButtonId).removeClass("btn-arrow-active");
                self._data.put("left_pre_selection_count", 0);
            }
            self.$element.find(self.totalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, self._data.get("left_pre_selection_count"), self._data.get("left_total_count")));
        });
    }

    /**
     * right item select all handler
     */
    Transfer.prototype.right_item_select_all_handler = function() {
        var self = this;
        $(self.rightItemSelectAllId).on("click", function () {
            var checkboxSelectedItems = self.$element.find(self.checkboxSelectedItemClass);
            if ($(this).is(':checked')) {
                self._data.put("right_pre_selection_count", 0);
                var right_pre_selection_count = self._data.get("right_pre_selection_count");
                for (var i = 0; i < checkboxSelectedItems.length; i++) {
                    if (checkboxSelectedItems.eq(i).parent("div").parent("li").css('display') != "none" && !checkboxSelectedItems.eq(i).prop("disabled")) {
                        checkboxSelectedItems.eq(i).prop("checked", true);
                        self._data.put("right_pre_selection_count", ++right_pre_selection_count);
                    }
                }

                $(self.deleteSelectedButtonId).addClass("btn-arrow-active");
    
                if (self._data.get("right_pre_selection_count") < self._data.get("right_total_count")) {
                    $(self.rightItemSelectAllId).prop("checked", false);
                } else if (self._data.get("right_pre_selection_count") == self._data.get("right_total_count")) {
                    $(self.rightItemSelectAllId).prop("checked", true);
                }
                if (self._data.get("right_pre_selection_count") == self._data.get("right_total_count") - self._data.get("right_disabled_count")) {
                    $(self.rightItemSelectAllId).prop("checked", true);
                }

            } else {
                for (var i = 0; i < checkboxSelectedItems.length; i++) {
                    if (checkboxSelectedItems.eq(i).parent("div").parent("li").css('display') != "none" && checkboxSelectedItems.eq(i).is(':checked')) {
                        checkboxSelectedItems.eq(i).prop("checked", false);
                    }
                }
                $(self.deleteSelectedButtonId).removeClass("btn-arrow-active");
                self._data.put("right_pre_selection_count", 0);
            }

            self.$element.find(self.selectedTotalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, self._data.get("right_pre_selection_count"), self._data.get("right_total_count")));

        });
    }

    /**
     * left items search handler
     */
    Transfer.prototype.left_items_search_handler = function() {
        var self = this;
        $(self.itemSearcherId).on("keyup", function () {
            var transferDoubleListLis = self.$element.find(self.transferDoubleListLiClass);
            self.$element.find(self.transferDoubleListUlClass).css('display', 'block');
            if ($(self.itemSearcherId).val() == "") {
                for (var i = 0; i < transferDoubleListLis.length; i++) {
                    if (!transferDoubleListLis.eq(i).hasClass("selected-hidden")) {
                        self.$element.find(self.transferDoubleListLiClass).eq(i).css('display', 'block');
                    }
                }
                return;
            }

            transferDoubleListLis.css('display', 'none');

            for (var j = 0; j < transferDoubleListLis.length; j++) {
                if (!transferDoubleListLis.eq(j).hasClass("selected-hidden")
                    && transferDoubleListLis.eq(j).text().trim()
                        .substr(0, $(self.itemSearcherId).val().length).toLowerCase() == $(self.itemSearcherId).val().toLowerCase()) {
                            transferDoubleListLis.eq(j).css('display', 'block');
                }
            }
        });
    }

    /**
     * right checkbox item click handler
     */
    Transfer.prototype.right_checkbox_item_click_handler = function() {
        var self = this;
        self.$element.on("click", self.checkboxSelectedItemClass, function () {
            var pre_selection_num = 0;
            $(this).is(":checked") ? pre_selection_num++ : pre_selection_num--

            var right_pre_selection_count = self._data.get("right_pre_selection_count");
            self._data.put("right_pre_selection_count", right_pre_selection_count + pre_selection_num);
            self.$element.find(self.selectedTotalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, self._data.get("right_pre_selection_count"), self._data.get("right_total_count")));

            if (self._data.get("right_pre_selection_count") > 0) {
                $(self.deleteSelectedButtonId).addClass("btn-arrow-active");
            } else {
                $(self.deleteSelectedButtonId).removeClass("btn-arrow-active");
            }

            if (self._data.get("right_pre_selection_count") < self._data.get("right_total_count")) {
                $(self.rightItemSelectAllId).prop("checked", false);
            } else if (self._data.get("right_pre_selection_count") == self._data.get("right_total_count")) {
                $(self.rightItemSelectAllId).prop("checked", true);
            }
            if (self._data.get("right_pre_selection_count") == self._data.get("right_total_count") - self._data.get("right_disabled_count")) {
                $(self.rightItemSelectAllId).prop("checked", true);
            }

        });
    }

    /**
     * move the pre-selection items to the right handler
     */
    Transfer.prototype.move_pre_selection_items_handler = function() {
        var self = this;
        $(self.addSelectedButtonId).on("click", function () {
            if ($(this).hasClass("btn-arrow-active")) {
                self.isGroup ? self.move_pre_selection_group_items() : self.move_pre_selection_items()
                // callable
                applyCallable(self);
            }
        });
    }

    /**
     * move the pre-selection group items to the right
     */
    Transfer.prototype.move_pre_selection_group_items = function() {
        var pre_selection_num = 0;
        var html = "";
        var groupCheckboxItems = this.$element.find(this.groupCheckboxItemClass);
        for (var i = 0; i < groupCheckboxItems.length; i++) {
            if (!groupCheckboxItems.eq(i).parent("div").parent("li").hasClass("selected-hidden") && groupCheckboxItems.eq(i).is(':checked')) {
                var checkboxItemId = groupCheckboxItems.eq(i).attr("id");
                var groupIndex = checkboxItemId.split("_")[1];
                var itemIndex = checkboxItemId.split("_")[3];
                var labelText = this.$element.find(this.groupCheckboxNameLabelClass).eq(i).text();
                var value = groupCheckboxItems.eq(i).val();

                html += this.generate_group_item(this.id, groupIndex, itemIndex, value, labelText);
                groupCheckboxItems.parent("div").parent("li").eq(i).css("display", "").addClass("selected-hidden");
                pre_selection_num++;

                var groupItem = this._group_data.get('group_' + groupIndex + '_' + this.id);
                var left_total_count = groupItem["left_total_count"];
                var left_pre_selection_count = groupItem["left_pre_selection_count"];
                var right_total_count = this._data.get("right_total_count");
                groupItem["left_total_count"] = --left_total_count;
                groupItem["left_pre_selection_count"] = --left_pre_selection_count;
                this._data.put("right_total_count", ++right_total_count);
            }
        }

        if (pre_selection_num > 0) {
            var groupSelectAllArray = this.$element.find(this.groupSelectAllClass);
            for (var j = 0; j < groupSelectAllArray.length; j++) {
                if (groupSelectAllArray.eq(j).is(":checked")) {
                    groupSelectAllArray.eq(j).prop("disabled", "disabled");
                }
            }

            var remain_left_total_count = 0;
            this._group_data.forEach(function(key, value) {
                remain_left_total_count += value["left_total_count"];
            })

            var groupTotalNumLabel = this.$element.find(this.groupTotalNumLabelClass);
            groupTotalNumLabel.text(get_total_num_text(this.default_total_num_text_template, 0, remain_left_total_count));
            this.$element.find(this.selectedTotalNumLabelClass).text(get_total_num_text(this.default_total_num_text_template, 0, this._data.get("right_total_count")));

            if (remain_left_total_count == 0) {
                $(this.groupItemSelectAllId).prop("checked", true).prop("disabled", "disabled");
            }

            if (this._data.get("right_total_count") > 0) {
                $(this.rightItemSelectAllId).prop("checked", false).removeAttr("disabled");
            }

            $(this.addSelectedButtonId).removeClass("btn-arrow-active");
            var transferDoubleSelectedListUl = this.$element.find(this.transferDoubleSelectedListUlClass);
            transferDoubleSelectedListUl.append(html);
        }
    }

    /**
     * move the pre-selection items to the right
     */
    Transfer.prototype.move_pre_selection_items = function() {
        var pre_selection_num = 0;
        var html = "";
        var self = this;
        var checkboxItems = self.$element.find(self.checkboxItemClass);
        for (var i = 0; i < checkboxItems.length; i++) {
            if (checkboxItems.eq(i).parent("div").parent("li").css("display") != "none" && checkboxItems.eq(i).is(':checked')) {
                var checkboxItemId = checkboxItems.eq(i).attr("id");
                // checkbox item index
                var index = checkboxItemId.split("_")[1];
                var labelText = self.$element.find(self.checkboxItemLabelClass).eq(i).text();
                var value = checkboxItems.eq(i).val();
                self.$element.find(self.transferDoubleListLiClass).eq(i).css("display", "").addClass("selected-hidden");
                html += self.generate_item(self.id, index, value, labelText, false);
                pre_selection_num++;

                var left_pre_selection_count = self._data.get("left_pre_selection_count");
                var left_total_count = self._data.get("left_total_count");
                var right_total_count = self._data.get("right_total_count");
                self._data.put("left_pre_selection_count", --left_pre_selection_count);
                self._data.put("left_total_count", --left_total_count);
                self._data.put("right_total_count", ++right_total_count);
            }
        }

        if (self._data.get("right_total_count") > 0) {
            $(self.rightItemSelectAllId).prop("checked", false).removeAttr("disabled");
        }

        if (pre_selection_num > 0) {
            var totalNumLabel = self.$element.find(self.totalNumLabelClass);
            self.$element.find(self.totalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, self._data.get("left_pre_selection_count"), self._data.get("left_total_count")));
            totalNumLabel.text(get_total_num_text(self.default_total_num_text_template, self._data.get("left_pre_selection_count"), self._data.get("left_total_count")));
            self.$element.find(self.selectedTotalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, 0, self._data.get("right_total_count")));
            if (self._data.get("left_total_count") == 0 || (self._data.get("left_disabled_count") == self._data.get("left_total_count"))) {
                $(self.leftItemSelectAllId).prop("checked", true).prop("disabled", "disabled");
            }

            $(self.addSelectedButtonId).removeClass("btn-arrow-active");
            self.$element.find(self.transferDoubleSelectedListUlClass).append(html);
        }
    }

    /**
     * move the selected item to the left handler
     */
    Transfer.prototype.move_selected_items_handler = function() {
        var self = this;
        $(self.deleteSelectedButtonId).on("click", function () {
            if ($(this).hasClass("btn-arrow-active")) {
                self.isGroup ? self.move_selected_group_items() : self.move_selected_items()
                $(self.deleteSelectedButtonId).removeClass("btn-arrow-active");
                // callable
                applyCallable(self);
            }
        });
    }

    /**
     * move the selected group item to the left
     */
    Transfer.prototype.move_selected_group_items = function() {
        var pre_selection_num = 0;
        var checkboxSelectedItems = this.$element.find(this.checkboxSelectedItemClass);        
        for (var i = 0; i < checkboxSelectedItems.length;) {
            var another_checkboxSelectedItems = this.$element.find(this.checkboxSelectedItemClass);
            if (another_checkboxSelectedItems.eq(i).parent("div").parent("li").css("display") != "none" && another_checkboxSelectedItems.eq(i).is(':checked')) {
                var checkboxSelectedItemId = another_checkboxSelectedItems.eq(i).attr("id");
                var groupIndex = checkboxSelectedItemId.split("_")[1];
                var index = checkboxSelectedItemId.split("_")[3];

                another_checkboxSelectedItems.parent("div").parent("li").eq(i).remove();
                this.$element.find("#group_" + groupIndex + "_" + this.id).prop("checked", false).removeAttr("disabled");
                this.$element.find("#group_" + groupIndex + "_checkbox_" + index + "_" + this.id)
                    .prop("checked", false).parent("div").parent("li").css("display", "").removeClass("selected-hidden");

                pre_selection_num++;

                var groupItem = this._group_data.get('group_' + groupIndex + '_' + this.id);
                var left_total_count = groupItem["left_total_count"];
                var right_pre_selection_count = this._data.get("right_pre_selection_count");
                var right_total_count = this._data.get("right_total_count");
                groupItem["left_total_count"] = ++left_total_count;
                this._data.put("right_total_count", --right_total_count);
                this._data.put("right_pre_selection_count", --right_pre_selection_count);

            } else {
                i++;
            }
        }
        if (pre_selection_num > 0) {
            this.$element.find(this.groupTotalNumLabelClass).empty();

            var remain_left_total_count = 0;
            this._group_data.forEach(function(key, value) {
                remain_left_total_count += value["left_total_count"];
            })

            if (this._data.get("right_total_count") == 0) {
                $(this.rightItemSelectAllId).prop("checked", true).prop("disabled", "disabled");
            }

            this.$element.find(this.groupTotalNumLabelClass).text(get_total_num_text(this.default_total_num_text_template, 0, remain_left_total_count));
            this.$element.find(this.selectedTotalNumLabelClass).text(get_total_num_text(this.default_total_num_text_template, 0, this._data.get("right_total_count")));
            if ($(this.groupItemSelectAllId).is(':checked')) {
                $(this.groupItemSelectAllId).prop("checked", false).removeAttr("disabled");
            }
        }
    }

    /**
     * move the selected item to the left
     */
    Transfer.prototype.move_selected_items = function() {
        var pre_selection_num = 0;
        var self = this;

        for (var i = 0; i < self.$element.find(self.checkboxSelectedItemClass).length;) {
            var checkboxSelectedItems = self.$element.find(self.checkboxSelectedItemClass);
            if (checkboxSelectedItems.eq(i).parent("div").parent("li").css("display") != "none" && checkboxSelectedItems.eq(i).is(':checked')) {
                var index = checkboxSelectedItems.eq(i).attr("id").split("_")[1];
                checkboxSelectedItems.parent("div").parent("li").eq(i).remove();
                self.$element.find(self.checkboxItemClass).eq(index).prop("checked", false);
                self.$element.find(self.transferDoubleListLiClass).eq(index).css("display", "").removeClass("selected-hidden");

                pre_selection_num++;

                var right_total_count = self._data.get("right_total_count");
                var right_pre_selection_count = self._data.get("right_pre_selection_count");
                self._data.put("right_total_count", --right_total_count);
                self._data.put("right_pre_selection_count", --right_pre_selection_count);

                var left_total_count = self._data.get("left_total_count");
                self._data.put("left_total_count", ++left_total_count);


            } else {
                i++;
            }
        }

        if (self._data.get("right_total_count") == 0 || (self._data.get("right_pre_selection_count") == self._data.get("right_total_count") - self._data.get("right_disabled_count"))) {
            $(self.rightItemSelectAllId).prop("checked", true).prop("disabled", "disabled");
        }


        if (pre_selection_num > 0) {
            self.$element.find(self.totalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, self._data.get("left_pre_selection_count"), self._data.get("left_total_count")));
            self.$element.find(self.selectedTotalNumLabelClass).text(get_total_num_text(self.default_total_num_text_template, self._data.get("right_pre_selection_count"), self._data.get("right_total_count")));
            if ($(self.leftItemSelectAllId).is(':checked')) {
                $(self.leftItemSelectAllId).prop("checked", false).removeAttr("disabled");
            }
        }
    }

    /**
     * right items search handler
     */
    Transfer.prototype.right_items_search_handler = function() {
        var self = this;
        $(self.selectedItemSearcherId).keyup(function () {
            var transferDoubleSelectedListLis = self.$element.find(self.transferDoubleSelectedListLiClass);
            self.$element.find(self.transferDoubleSelectedListUlClass).css('display', 'block');

            if ($(self.selectedItemSearcherId).val() == "") {
                transferDoubleSelectedListLis.css('display', 'block');
                return;
            }

            transferDoubleSelectedListLis.css('display', 'none');

            for (var i = 0; i < transferDoubleSelectedListLis.length; i++) {
                if (transferDoubleSelectedListLis.eq(i).text().trim()
                        .substr(0, $(self.selectedItemSearcherId).val().length).toLowerCase() == $(self.selectedItemSearcherId).val().toLowerCase()) {
                            transferDoubleSelectedListLis.eq(i).css('display', 'block');
                }
            }
        });
    }

    /**
     * generate item
     */
    Transfer.prototype.generate_item = function(id, index, value, labelText, disabled) {

        var template = parseHTMLTemplate(function() {
            /*
            <li class="transfer-double-selected-list-li  transfer-double-selected-list-li-{{= id }} .clearfix">
                <div class="checkbox-group">
                    <input {{= disabled ? disabled="disabled" : " " }} type="checkbox" value="{{= value }}" class="checkbox-normal checkbox-selected-item-{{= id }}" id="selectedCheckbox_{{= index }}_{{= id }}">
                    <label class="checkbox-selected-name-{{= id }}" for="selectedCheckbox_{{= index }}_{{= id }}">{{= labelText }}</label>
                </div>
            </li>
            */
        })

        var compiled = $.template(template);
        return compiled({ id: id, index: index, value: value, labelText: labelText, disabled: disabled })
    }

    /**
     * generate group item
     */
    Transfer.prototype.generate_group_item = function(id, groupIndex, itemIndex, value, labelText) {

        var template = parseHTMLTemplate(function() {
            /*
            <li class="transfer-double-selected-list-li transfer-double-selected-list-li-{{= id }} .clearfix">
                <div class="checkbox-group">
                    <input type="checkbox" value="{{= value }}" class="checkbox-normal checkbox-selected-item-{{= id }}" id="group_{{= groupIndex }}_selectedCheckbox_{{= itemIndex }}_{{= id }}">
                    <label class="checkbox-selected-name-{{= id }}" for="group_{{= groupIndex }}_selectedCheckbox_{{= itemIndex }}_{{= id }}">{{= labelText }}</label>
                </div>
            </li>
            */
        })

        var compiled = $.template(template);
        return compiled({ id: id, groupIndex: groupIndex, itemIndex: itemIndex, value: value, labelText: labelText });
    }

    /**
     * apply callable
     */
    function applyCallable(transfer) {
        if (Object.prototype.toString.call(transfer.settings.callable) === "[object Function]") {
          var selected_items = get_selected_items(transfer);

            // send reply in case of empty array
            //if (selected_items.length > 0) {
              transfer.settings.callable.call(transfer, selected_items);
            //}
        }
    }

    /**
     * get selected items
     */
    function get_selected_items(transfer) {
        var selected = [];
        var transferDoubleSelectedListLiArray = transfer.$element.find(transfer.transferDoubleSelectedListLiClass);
        for (var i = 0; i < transferDoubleSelectedListLiArray.length; i++) {
            var checkboxGroup = transferDoubleSelectedListLiArray.eq(i).find(".checkbox-group");

            var item = {};
            item[transfer.settings.itemName] = checkboxGroup.find("label").text();
            item[transfer.settings.valueName] = checkboxGroup.find("input").val();
            selected.push(item);
        }
        return selected;
    }

    /**
     * get group items number
     * @param {Array} groupDataArray
     * @param {string}  groupArrayName
     */
    function get_group_items_num(groupDataArray, groupArrayName) {
        var group_item_total_num = 0;
        for (var i = 0; i < groupDataArray.length; i++) {
            var groupItemData = groupDataArray[i][groupArrayName];
            if (groupItemData && groupItemData.length > 0) {
                group_item_total_num = group_item_total_num + groupItemData.length;
            }
        }
        return group_item_total_num;
    }

    /**
     * replacing the template
     * @param {*} template
     * @param {*} pre_num
     * @param {*} total_num
     */
    function get_total_num_text(template, pre_num, total_num) {
        var _template = template;
        return _template.replace("pre_num", pre_num).replace("total_num", total_num);
    }

    /**
     * Inner Map
     */
    function InnerMap() {
        this.keys = new Array();
        this.values = new Object();

        this.put = function(key, value) {
            if (this.values[key] == null) {
                this.keys.push(key);
            }
            this.values[key] = value;
        }
        this.get = function(key) {
            return this.values[key];
        }
        this.remove = function(key) {
            for (var i = 0; i < this.keys.length; i++) {
                if (this.keys[i] === key) {
                    this.keys.splice(i, 1);
                }
            }
            delete this.values[key];
        }
        this.forEach = function(fn) {
            for (var i = 0; i < this.keys.length; i++) {
                var key = this.keys[i];
                var value = this.values[key];
                fn(key, value);
            }
        }
        this.isEmpty = function() {
            return this.keys.length == 0;
        }
        this.size = function() {
            return this.keys.length;
        }
    }

    /**
     * get id
     */
    function getId() {
        var counter = 0;
        return function(prefix) {
            var id = (+new Date()).toString(32), i = 0;
            for (; i < 5; i++) {
                id += Math.floor(Math.random() * 65535).toString(32);
            }
            return (prefix || '') + id + (counter++).toString(32);
        }
    }

    /**
     * parse html template
     * @param {*} f 
     */
    function parseHTMLTemplate(func) {
        return func.toString().match(/\/\*([\s\S]*?)\*\//)[1]
    }

}(jQuery));


/**
 * underscore.template
 */
;(function ($) {
    var escapes = {
        "'":      "'",
        '\\':     '\\',
        '\r':     'r',
        '\n':     'n',
        '\u2028': 'u2028',
        '\u2029': 'u2029'
    }, escapeMap = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#x27;',
        '`': '&#x60;'
    };
    var escapeChar = function(match) {
        return '\\' + escapes[match];
    };
    var createEscaper = function(map) {
        var escaper = function(match) {
            return map[match];
        };
        var source = "(?:&|<|>|\"|'|`)";
        var testRegexp = RegExp(source);
        var replaceRegexp = RegExp(source, 'g');
        return function(string) {
            string = string == null ? '' : '' + string;
            return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
        };
    };
    var escape = createEscaper(escapeMap);
    $.extend({
        templateSettings: {
            escape: /{{-([\s\S]+?)}}/g,
            interpolate : /{{=([\s\S]+?)}}/g,
            evaluate: /{{([\s\S]+?)}}/g
        },
        escapeHtml: escape,
        template: function (text, settings) {
            var options = $.extend(true, {}, this.templateSettings, settings);
            var matcher = RegExp([options.escape.source,
			options.interpolate.source,
			options.evaluate.source].join('|') + '|$', 'g');
            var index = 0;
            var source = "__p+='";
            text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
                source += text.slice(index, offset).replace(/\\|'|\r|\n|\u2028|\u2029/g, escapeChar);
                index = offset + match.length;
                if (escape) {
                    source += "'+\n((__t=(" + escape + "))==null?'':$.escapeHtml(__t))+\n'";
                } else if (interpolate) {
                    source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
                } else if (evaluate) {
                    source += "';\n" + evaluate + "\n__p+='";
                }
                return match;
            });
            source += "';\n";
            if (!options.variable) source = 'with(obj||{}){\n' + source + '}\n';
            source = "var __t,__p='',__j=Array.prototype.join," +
                "print=function(){__p+=__j.call(arguments,'');};\n" +
                source + 'return __p;\n';
            try {
                var render = new Function(options.variable || 'obj', source);
            } catch (e) {
                e.source = source;
                throw e;
            }
            var template = function(data) {
                return render.call(this, data);
            };
            var argument = options.variable || 'obj';
            template.source = 'function(' + argument + '){\n' + source + '}';
            return template;
        }
    });
})(jQuery);
$(function () {
    var activeTab;

    $('.employee-type input[type=radio]').change(function () {
        ShowCreditTypeTab();

        if ($(this).val() === 'ESO' || $(this).val() === 'JRS') {
            $('select.service-type').prop('disabled', true);
            $('#call-ERS-error').removeClass('hidden');
        }
        else {
            $('select.service-type').prop('disabled', false);
            $('#call-ERS-error').addClass('hidden');
        }
    });

    $('select.service-type').change(function () {
        ShowCreditTypeTab();
        $(this).find('option:not(:selected)').prop('disabled', true);
        $('.employee-type input[type=radio]:not(:checked)').prop('disabled',true);

        $('.employee-type').addClass('disabled');

        activeTab = $('#service-purchase-tabs div.tab-pane.active');
        activeTab.find('input[type=radio], select').change(function () {
            var controls = activeTab.find('div.form-group');

            switch(activeTab.attr('id'))
            {
                case 'tab-waiting-period':
                    var waitingValues = [
                        activeTab.find('div.form-group[data-waiting-index=0] input[type=radio]:checked').val(),
                        activeTab.find('div.form-group[data-waiting-index=1] input[type=radio]:checked').val()
                    ];

                    controls.each(function (index, obj) { if ($(obj).is(':checked')) { waitingValues[index % 2] = $(obj).val(); } });

                    if ($.inArray(undefined, waitingValues) === -1 && $.inArray('Yes', waitingValues) !== -1) {
                        $('#submit-request').prop('disabled', false);
                    }
                    else {
                        $('#submit-request').prop('disabled', true);
                    }

                    if ($.inArray(undefined, waitingValues) === -1 && waitingValues[0] === 'No' && waitingValues[1] === 'No')
                        activeTab.find('.ineligible-text').removeClass('hidden');
                    else
                        activeTab.find('.ineligible-text').addClass('hidden');

                    break;
                case 'tab-withdrawn':
                    var parentContainer = $(this).closest('div.tab-pane');
                    var questionIndex = $(this).closest('div.form-group').attr('data-withdrawn-index');
                    var questionContainer = parentContainer.find('*[data-question-index=' + questionIndex + ']');
                    var controls = questionContainer.find('input, select');

                    switch (questionIndex) {
                        case '0':
                            if ($(this).val() === 'No') {
                                parentContainer.find('.ineligible-withdrawn-text').removeClass('hidden');
                                $('#submit-request').prop('disabled', true);
                            }
                            else {
                                var nextQuestion = $('div.form-group[data-withdrawn-index=1]');
                                nextQuestion.find('*[disabled]').each(function () { $(this).prop('disabled', false); });
                                parentContainer.find('.ineligible-withdrawn-text').addClass('hidden');
                                parentContainer.find('.ineligible-returned-text').addClass('hidden');
                            }
                            break;
                        case '1':
                            if ($(this).val() === 'No') {
                                parentContainer.find('.ineligible-returned-text').removeClass('hidden');
                                $('#submit-request').prop('disabled', true);
                            }
                            else {
                                var nextQuestion = $('div.form-group[data-withdrawn-index=2]');
                                nextQuestion.find('*[disabled]').each(function () { $(this).prop('disabled', false); });
                                parentContainer.find('.ineligible-returned-text').addClass('hidden');
                                parentContainer.find('.ineligible-returned-text').addClass('hidden');
                            }
                            break;
                        case '2':
                            $('#submit-request').prop('disabled', $(this).val() === '');
                            break;
                    }

                    if (questionIndex < 2 && $(this).val() === 'Yes') {
                        var nextQuestion = $('div.form-group[data-withdrawn-index=' + (questionIndex + 1) + ']');
                        nextQuestion.find('*[disabled]').each(function () { $(this).prop('disabled', false); });
                        parentContainer.find('.ineligible-withdrawn-text').addClass('hidden');
                        parentContainer.find('.ineligible-returned-text').addClass('hidden');
                    }

                    controls.prop('disabled', true);
                    break;
                case 'tab-additional-service':
                    var parent = $(this).closest('div.panel');
                    var radioParent = $(this).closest('div.form-group');

                    if (radioParent.data('asc-index') === 0 && radioParent.data('asc-index') !== undefined) {
                        if ($(this).val() === 'Yes') {
                            //$('#asc-calculation').removeClass('hidden');
                          $('#submit-request').prop('disabled', false);
                        }
                        else {
                            $('#submit-request').prop('disabled', true);
                            parent.find('.ineligible-asc-text').removeClass('hidden');
                        }
                    }

                    parent.find('input[type=radio]:not(:checked)').prop('disabled', true);

                    break;
                case 'tab-military':
                    var parentContainer = $(this).closest('div.tab-pane');
                    var questionIndex = $(this).closest('div.form-group').attr('data-military-index');
                    var questionContainer = parentContainer.find('*[data-question-index=' + questionIndex + ']');

                    switch (questionIndex) {
                        case '0':
                            if ($(this).val() === 'Yes') {
                                $('div.ineligible-text-military-retirement').removeClass('hidden');
                                DisableControls(parentContainer);
                            }
                            else {
                                var nextQuestion = $('div.form-group[data-military-index=1]');
                                nextQuestion.find('*[disabled]').each(function () { $(this).prop('disabled', false); });
                                nextQuestion.find('*.disabled').removeClass('disabled');
                                $('div.ineligible-text-military-retirement').addClass('hidden');
                            }
                            break;
                        case '1':
                            if ($(this).val() === 'Yes') {
                                $('div.ineligible-text-discharge').removeClass('hidden');
                                DisableControls(parentContainer);
                            }
                            else {
                                var nextQuestion = $('div.form-group[data-military-index=2]');
                                nextQuestion.find('*[disabled]').each(function () { $(this).prop('disabled', false); });
                                nextQuestion.find('*.disabled').removeClass('disabled');
                                $('div.ineligible-text-discharge').addClass('hidden');
                            }
                            break;
                        case '2':
                            if ($(this).val() === 'No') {
                                $('div.ineligible-text-service-record').removeClass('hidden');
                                DisableControls(parentContainer);
                                $('#submit-request').prop('disabled', true);
                            }
                            else {
                                $('#submit-request').prop('disabled', false);
                                $('div.ineligible-text-service-record').addClass('hidden');
                            }
                            break;
                    }
                    break;
            }
        });
    });

    function ShowCreditTypeTab()
    {
        var employeeType = $('.employee-type input:checked').val();
        var serviceType = $('select.service-type').val();

        if (employeeType !== undefined && serviceType !== undefined && serviceType !== '') {
            $('a[href="#tab-' + serviceType + '"]').tab('show');
            $('.employee-type input:checked').prop('disabled');
            $('.employee-type input:checked').prop('disabled');
        }
    }

    function ShowSubmitRequest(disableButton) {
        $('input#submit-request').prop('disabled', disableButton)
    }

    $('#submit-request').click(function () {
        $('.nav-tabs a[href="#tab-submit"]').tab('show');
        $('#nav-buttons').addClass('hidden');
        $('#initial-options').addClass('hidden');
    });

    function DisableControls(parentElement)
    {
        parentElement.find('input, select').prop('disabled', true);
        parentElement.find('.form-group').addClass('disabled');
    }
});

function CalculateCost() {
    var salary = $('#grossSalary').val();
    var age = $('#currentAge').val();
    var service = $('#yearsOfService').val();
    var employeeType = $('.employee-type input[type=radio]:checked').val();

    $.ajax({
        url: '/rest/customtableitem.customtable.ASC_Factors',
        data: {
            format: 'json',
            where: 'Age=' + age + ' AND ServiceYears=' + service + ' AND ServiceType=\'' + employeeType + '\''
        },
        type: 'GET',
        beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', 'Basic UmF0ZVVzZXI6UGFzc3dvcmQxIQ==') },
        success: function (result, status, xhr) {
            var factorObject = result.customtableitem_customtable_ASC_Factors[0];
            var factorTable = factorObject.customtable_ASC_Factors[0];
            
            numeral.zeroFormat('N/A');
            numeral.nullFormat('N/A');
          
            $('#estimate-table').removeClass('hidden');
            $('#estimate-table table tbody tr').empty();
            $('#estimate-table table tbody tr').append('<td>' + numeral((salary * 12) * factorTable.Year1).format('$0,0.00') + '</td>');
            $('#estimate-table table tbody tr').append('<td>' + numeral((salary * 12) * factorTable.Year2).format('$0,0.00') + '</td>');
            $('#estimate-table table tbody tr').append('<td>' + numeral((salary * 12) * factorTable.Year3).format('$0,0.00') + '</td>');
            $('#confirm-purchase input').prop('disabled', false);
            $('#confirm-purchase div.radio').removeClass('disabled');
            $('#confirmPurchaseYes').click(function () { $('#submit-request').prop('disabled', false); });
            $('#confirmPurchaseNo').click(function () { $('#submit-request').prop('disabled', true); });
        },
        error: function(xhr, status, error){
            alert('Please check inputs and try again.');
        }
    });
}

window.kentico = window.kentico || {};

window.kentico.updatableFormHelper = (function () {

    // Duration for which user must not type anything in order for the form to be submitted.
    var KEY_UP_DEBOUNCE_DURATION = 800;

    /**
     * Registers event listeners and updates the form upon changes of the form data.
     * @param {object} config Configuration object.
     * @param {string} config.formId ID of the form element.
     * @param {string} config.targetAttributeName Data attribute of element that is used to be replaced by HTML received from the server.
     * @param {string} config.unobservedAttributeName Data attribute which marks an input as not being observed for changes.
     */
    function registerEventListeners(config) {
        if (!config || !config.formId || !config.targetAttributeName || !config.unobservedAttributeName) {
            throw new Error("Invalid configuration passed.");
        }

        var writeableTypes = ["email", "number", "password", "search", "tel", "text", "time"];

        var observedForm = document.getElementById(config.formId);
        if (!(observedForm && observedForm.getAttribute(config.targetAttributeName))) {
            return;
        }

        for (i = 0; i < observedForm.length; i++) {
            var observedFormElement = observedForm.elements[i];
            var handleElement = !observedFormElement.hasAttribute(config.unobservedAttributeName) &&
                observedFormElement.type !== "submit";

            if (handleElement) {
                var isWriteableElement = (observedFormElement.tagName === "INPUT" && writeableTypes.indexOf(observedFormElement.type) !== -1) || observedFormElement.tagName === "TEXTAREA";

                if (isWriteableElement) {
                    observedFormElement.previousValue = observedFormElement.value;

                    observedFormElement.addEventListener("keyup", debounce(function (e) {
                        setTimeout(function () {
                            if (!observedForm.updating && e.target.previousValue !== e.target.value) {
                                observedForm.keyupUpdate = true;
                                updateForm(observedForm, e.target);
                            }
                        }, 0);
                    }, KEY_UP_DEBOUNCE_DURATION));

                    observedFormElement.addEventListener("blur", function (e) {
                        setTimeout(function () {
                            if (!observedForm.updating && e.target.previousValue !== e.target.value) {
                                updateForm(observedForm, e.relatedTarget);
                            }
                        }, 0);
                    });
                }

                observedFormElement.addEventListener("change", function (e) {
                    setTimeout(function () {
                        if (!observedForm.updating) {
                            updateForm(observedForm);
                        }
                    }, 0);
                });
            }
        }
    }

    /**
     * Updates the form markup.
     * @param {HTMLElement} form Element of the form to update.
     * @param {Element} nextFocusElement Element which shout get focus after update.
     */
    function updateForm(form, nextFocusElement) {
        if (!form) {
            return;
        }

        // If form is not updatable then do nothing 
        var elementIdSelector = form.getAttribute("data-ktc-ajax-update");
        if (!elementIdSelector) {
            return;
        }

        $(form).find("input[type='submit']").attr("onclick", "return false;");
        form.updating = true;

        var formData = new FormData(form);
        formData.append("kentico_update_form", "true");

        var focus = nextFocusElement || document.activeElement;

        var onResponse = function (event) {
            if (!event.target.response.data) {
                var selectionStart = selectionEnd = null;
                if (focus && (focus.type === "text" || focus.type === "search" || focus.type === "password" || focus.type === "tel" || focus.type === "url")) {
                    selectionStart = focus.selectionStart;
                    selectionEnd = focus.selectionEnd;
                }

                var currentScrollPosition = $(window).scrollTop();
                $(elementIdSelector).replaceWith(event.target.responseText);
                $(window).scrollTop(currentScrollPosition);

                if (focus.id) {
                    var newInput = document.getElementById(focus.id);
                    if (newInput) {
                        newInput.focus();
                        setCaretPosition(newInput, selectionStart, selectionEnd);
                    }
                }
            }
        };

        createRequest(form, formData, onResponse);
    }

    function submitForm(event) {
        event.preventDefault();
        var form = event.target;
        var formData = new FormData(form);
        FormSubmit(form);

        var onResponse = function(event) {
            var contentType = event.target.getResponseHeader("Content-Type");

            if (contentType.indexOf("application/json") === -1) {
                var currentScrollPosition = $(window).scrollTop();
                var replaceTarget = form.getAttribute("data-ktc-ajax-update");

                $(replaceTarget).replaceWith(event.target.response);
                $(window).scrollTop(currentScrollPosition);
            } else {
                var json = JSON.parse(event.target.response);

                location.href = json.redirectTo;
            }
        };

        createRequest(form, formData, onResponse);
    }

    function createRequest(form, formData, onResponse) {
        var xhr = new XMLHttpRequest();

        xhr.addEventListener("load", onResponse);

        xhr.open("POST", form.action);
        xhr.send(formData);
    }

    /**
     * Sets the caret position.
     * @param {HTMLInputElement} input Input element in which the caret position should be set.
     * @param {number} selectionStart Selection start position.
     * @param {number} selectionEnd Selection end position.
     */
    function setCaretPosition(input, selectionStart, selectionEnd) {
        if (selectionStart === null && selectionEnd === null) {
            return;
        }

        if (input.setSelectionRange) {
            input.setSelectionRange(selectionStart, selectionEnd);
        }
    }

    function debounce(func, wait, immediate) {
        var timeout;

        return function () {
            var context = this,
                args = arguments;

            var later = function () {
                timeout = null;

                if (!immediate) {
                    func.apply(context, args);
                }
            };

            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait || 200);

            if (callNow) {
                func.apply(context, args);
            }
        };
    }

    return {
        registerEventListeners: registerEventListeners,
        updateForm: updateForm,
        submitForm: submitForm
    };
}());

