/* Minification failed. Returning unminified contents.
(5712,13-16): run-time error JS1009: Expected '}': ...
(5713,19): run-time error JS1004: Expected ';'
(5713,19-20): run-time error JS1195: Expected expression: :
(5714,9-10): run-time error JS1195: Expected expression: }
(5714,10-11): run-time error JS1006: Expected ')': ;
(5960,1-2): run-time error JS1002: Syntax error: }
(5960,2-3): run-time error JS1195: Expected expression: )
 */
(function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('jquery')) :
        typeof define === 'function' && define.amd ? define(['jquery'], factory) :
            (global = global || self, factory(global.jQuery));
}(this, function ($) {
    'use strict';

    $ = $ && $.hasOwnProperty('default') ? $['default'] : $;

    function _typeof(obj) {
        if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
            _typeof = function (obj) {
                return typeof obj;
            };
        } else {
            _typeof = function (obj) {
                return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
            };
        }

        return _typeof(obj);
    }

    function _classCallCheck(instance, Constructor) {
        if (!(instance instanceof Constructor)) {
            throw new TypeError("Cannot call a class as a function");
        }
    }

    function _defineProperties(target, props) {
        for (var i = 0; i < props.length; i++) {
            var descriptor = props[i];
            descriptor.enumerable = descriptor.enumerable || false;
            descriptor.configurable = true;
            if ("value" in descriptor) descriptor.writable = true;
            Object.defineProperty(target, descriptor.key, descriptor);
        }
    }

    function _createClass(Constructor, protoProps, staticProps) {
        if (protoProps) _defineProperties(Constructor.prototype, protoProps);
        if (staticProps) _defineProperties(Constructor, staticProps);
        return Constructor;
    }

    function _slicedToArray(arr, i) {
        return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _toConsumableArray(arr) {
        return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
    }

    function _arrayWithoutHoles(arr) {
        if (Array.isArray(arr)) {
            for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i];

            return arr2;
        }
    }

    function _arrayWithHoles(arr) {
        if (Array.isArray(arr)) return arr;
    }

    function _iterableToArray(iter) {
        if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _iterableToArrayLimit(arr, i) {
        if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
            return;
        }

        var _arr = [];
        var _n = true;
        var _d = false;
        var _e = undefined;

        try {
            for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
                _arr.push(_s.value);

                if (i && _arr.length === i) break;
            }
        } catch (err) {
            _d = true;
            _e = err;
        } finally {
            try {
                if (!_n && _i["return"] != null) _i["return"]();
            } finally {
                if (_d) throw _e;
            }
        }

        return _arr;
    }

    function _nonIterableSpread() {
        throw new TypeError("Invalid attempt to spread non-iterable instance");
    }

    function _nonIterableRest() {
        throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};

    function createCommonjsModule(fn, module) {
        return module = { exports: {} }, fn(module, module.exports), module.exports;
    }

    var O = 'object';
    var check = function (it) {
        return it && it.Math == Math && it;
    };

    // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
    var global_1 =
        // eslint-disable-next-line no-undef
        check(typeof globalThis == O && globalThis) ||
        check(typeof window == O && window) ||
        check(typeof self == O && self) ||
        check(typeof commonjsGlobal == O && commonjsGlobal) ||
        // eslint-disable-next-line no-new-func
        Function('return this')();

    var fails = function (exec) {
        try {
            return !!exec();
        } catch (error) {
            return true;
        }
    };

    // Thank's IE8 for his funny defineProperty
    var descriptors = !fails(function () {
        return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
    });

    var nativePropertyIsEnumerable = {}.propertyIsEnumerable;
    var getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

    // Nashorn ~ JDK8 bug
    var NASHORN_BUG = getOwnPropertyDescriptor && !nativePropertyIsEnumerable.call({ 1: 2 }, 1);

    // `Object.prototype.propertyIsEnumerable` method implementation
    // https://tc39.github.io/ecma262/#sec-object.prototype.propertyisenumerable
    var f = NASHORN_BUG ? function propertyIsEnumerable(V) {
        var descriptor = getOwnPropertyDescriptor(this, V);
        return !!descriptor && descriptor.enumerable;
    } : nativePropertyIsEnumerable;

    var objectPropertyIsEnumerable = {
        f: f
    };

    var createPropertyDescriptor = function (bitmap, value) {
        return {
            enumerable: !(bitmap & 1),
            configurable: !(bitmap & 2),
            writable: !(bitmap & 4),
            value: value
        };
    };

    var toString = {}.toString;

    var classofRaw = function (it) {
        return toString.call(it).slice(8, -1);
    };

    var split = ''.split;

    // fallback for non-array-like ES3 and non-enumerable old V8 strings
    var indexedObject = fails(function () {
        // throws an error in rhino, see https://github.com/mozilla/rhino/issues/346
        // eslint-disable-next-line no-prototype-builtins
        return !Object('z').propertyIsEnumerable(0);
    }) ? function (it) {
        return classofRaw(it) == 'String' ? split.call(it, '') : Object(it);
    } : Object;

    // `RequireObjectCoercible` abstract operation
    // https://tc39.github.io/ecma262/#sec-requireobjectcoercible
    var requireObjectCoercible = function (it) {
        if (it == undefined) throw TypeError("Can't call method on " + it);
        return it;
    };

    // toObject with fallback for non-array-like ES3 strings



    var toIndexedObject = function (it) {
        return indexedObject(requireObjectCoercible(it));
    };

    var isObject = function (it) {
        return typeof it === 'object' ? it !== null : typeof it === 'function';
    };

    // `ToPrimitive` abstract operation
    // https://tc39.github.io/ecma262/#sec-toprimitive
    // instead of the ES6 spec version, we didn't implement @@toPrimitive case
    // and the second argument - flag - preferred type is a string
    var toPrimitive = function (input, PREFERRED_STRING) {
        if (!isObject(input)) return input;
        var fn, val;
        if (PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
        if (typeof (fn = input.valueOf) == 'function' && !isObject(val = fn.call(input))) return val;
        if (!PREFERRED_STRING && typeof (fn = input.toString) == 'function' && !isObject(val = fn.call(input))) return val;
        throw TypeError("Can't convert object to primitive value");
    };

    var hasOwnProperty = {}.hasOwnProperty;

    var has = function (it, key) {
        return hasOwnProperty.call(it, key);
    };

    var document$1 = global_1.document;
    // typeof document.createElement is 'object' in old IE
    var EXISTS = isObject(document$1) && isObject(document$1.createElement);

    var documentCreateElement = function (it) {
        return EXISTS ? document$1.createElement(it) : {};
    };

    // Thank's IE8 for his funny defineProperty
    var ie8DomDefine = !descriptors && !fails(function () {
        return Object.defineProperty(documentCreateElement('div'), 'a', {
            get: function () { return 7; }
        }).a != 7;
    });

    var nativeGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;

    // `Object.getOwnPropertyDescriptor` method
    // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptor
    var f$1 = descriptors ? nativeGetOwnPropertyDescriptor : function getOwnPropertyDescriptor(O, P) {
        O = toIndexedObject(O);
        P = toPrimitive(P, true);
        if (ie8DomDefine) try {
            return nativeGetOwnPropertyDescriptor(O, P);
        } catch (error) { /* empty */ }
        if (has(O, P)) return createPropertyDescriptor(!objectPropertyIsEnumerable.f.call(O, P), O[P]);
    };

    var objectGetOwnPropertyDescriptor = {
        f: f$1
    };

    var anObject = function (it) {
        if (!isObject(it)) {
            throw TypeError(String(it) + ' is not an object');
        } return it;
    };

    var nativeDefineProperty = Object.defineProperty;

    // `Object.defineProperty` method
    // https://tc39.github.io/ecma262/#sec-object.defineproperty
    var f$2 = descriptors ? nativeDefineProperty : function defineProperty(O, P, Attributes) {
        anObject(O);
        P = toPrimitive(P, true);
        anObject(Attributes);
        if (ie8DomDefine) try {
            return nativeDefineProperty(O, P, Attributes);
        } catch (error) { /* empty */ }
        if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported');
        if ('value' in Attributes) O[P] = Attributes.value;
        return O;
    };

    var objectDefineProperty = {
        f: f$2
    };

    var hide = descriptors ? function (object, key, value) {
        return objectDefineProperty.f(object, key, createPropertyDescriptor(1, value));
    } : function (object, key, value) {
        object[key] = value;
        return object;
    };

    var setGlobal = function (key, value) {
        try {
            hide(global_1, key, value);
        } catch (error) {
            global_1[key] = value;
        } return value;
    };

    var shared = createCommonjsModule(function (module) {
        var SHARED = '__core-js_shared__';
        var store = global_1[SHARED] || setGlobal(SHARED, {});

        (module.exports = function (key, value) {
            return store[key] || (store[key] = value !== undefined ? value : {});
        })('versions', []).push({
            version: '3.2.1',
            mode: 'global',
            copyright: '© 2019 Denis Pushkarev (zloirock.ru)'
        });
    });

    var functionToString = shared('native-function-to-string', Function.toString);

    var WeakMap = global_1.WeakMap;

    var nativeWeakMap = typeof WeakMap === 'function' && /native code/.test(functionToString.call(WeakMap));

    var id = 0;
    var postfix = Math.random();

    var uid = function (key) {
        return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36);
    };

    var keys = shared('keys');

    var sharedKey = function (key) {
        return keys[key] || (keys[key] = uid(key));
    };

    var hiddenKeys = {};

    var WeakMap$1 = global_1.WeakMap;
    var set, get, has$1;

    var enforce = function (it) {
        return has$1(it) ? get(it) : set(it, {});
    };

    var getterFor = function (TYPE) {
        return function (it) {
            var state;
            if (!isObject(it) || (state = get(it)).type !== TYPE) {
                throw TypeError('Incompatible receiver, ' + TYPE + ' required');
            } return state;
        };
    };

    if (nativeWeakMap) {
        var store = new WeakMap$1();
        var wmget = store.get;
        var wmhas = store.has;
        var wmset = store.set;
        set = function (it, metadata) {
            wmset.call(store, it, metadata);
            return metadata;
        };
        get = function (it) {
            return wmget.call(store, it) || {};
        };
        has$1 = function (it) {
            return wmhas.call(store, it);
        };
    } else {
        var STATE = sharedKey('state');
        hiddenKeys[STATE] = true;
        set = function (it, metadata) {
            hide(it, STATE, metadata);
            return metadata;
        };
        get = function (it) {
            return has(it, STATE) ? it[STATE] : {};
        };
        has$1 = function (it) {
            return has(it, STATE);
        };
    }

    var internalState = {
        set: set,
        get: get,
        has: has$1,
        enforce: enforce,
        getterFor: getterFor
    };

    var redefine = createCommonjsModule(function (module) {
        var getInternalState = internalState.get;
        var enforceInternalState = internalState.enforce;
        var TEMPLATE = String(functionToString).split('toString');

        shared('inspectSource', function (it) {
            return functionToString.call(it);
        });

        (module.exports = function (O, key, value, options) {
            var unsafe = options ? !!options.unsafe : false;
            var simple = options ? !!options.enumerable : false;
            var noTargetGet = options ? !!options.noTargetGet : false;
            if (typeof value == 'function') {
                if (typeof key == 'string' && !has(value, 'name')) hide(value, 'name', key);
                enforceInternalState(value).source = TEMPLATE.join(typeof key == 'string' ? key : '');
            }
            if (O === global_1) {
                if (simple) O[key] = value;
                else setGlobal(key, value);
                return;
            } else if (!unsafe) {
                delete O[key];
            } else if (!noTargetGet && O[key]) {
                simple = true;
            }
            if (simple) O[key] = value;
            else hide(O, key, value);
            // add fake Function#toString for correct work wrapped methods / constructors with methods like LoDash isNative
        })(Function.prototype, 'toString', function toString() {
            return typeof this == 'function' && getInternalState(this).source || functionToString.call(this);
        });
    });

    var path = global_1;

    var aFunction = function (variable) {
        return typeof variable == 'function' ? variable : undefined;
    };

    var getBuiltIn = function (namespace, method) {
        return arguments.length < 2 ? aFunction(path[namespace]) || aFunction(global_1[namespace])
            : path[namespace] && path[namespace][method] || global_1[namespace] && global_1[namespace][method];
    };

    var ceil = Math.ceil;
    var floor = Math.floor;

    // `ToInteger` abstract operation
    // https://tc39.github.io/ecma262/#sec-tointeger
    var toInteger = function (argument) {
        return isNaN(argument = +argument) ? 0 : (argument > 0 ? floor : ceil)(argument);
    };

    var min = Math.min;

    // `ToLength` abstract operation
    // https://tc39.github.io/ecma262/#sec-tolength
    var toLength = function (argument) {
        return argument > 0 ? min(toInteger(argument), 0x1FFFFFFFFFFFFF) : 0; // 2 ** 53 - 1 == 9007199254740991
    };

    var max = Math.max;
    var min$1 = Math.min;

    // Helper for a popular repeating case of the spec:
    // Let integer be ? ToInteger(index).
    // If integer < 0, let result be max((length + integer), 0); else let result be min(length, length).
    var toAbsoluteIndex = function (index, length) {
        var integer = toInteger(index);
        return integer < 0 ? max(integer + length, 0) : min$1(integer, length);
    };

    // `Array.prototype.{ indexOf, includes }` methods implementation
    var createMethod = function (IS_INCLUDES) {
        return function ($this, el, fromIndex) {
            var O = toIndexedObject($this);
            var length = toLength(O.length);
            var index = toAbsoluteIndex(fromIndex, length);
            var value;
            // Array#includes uses SameValueZero equality algorithm
            // eslint-disable-next-line no-self-compare
            if (IS_INCLUDES && el != el) while (length > index) {
                value = O[index++];
                // eslint-disable-next-line no-self-compare
                if (value != value) return true;
                // Array#indexOf ignores holes, Array#includes - not
            } else for (; length > index; index++) {
                if ((IS_INCLUDES || index in O) && O[index] === el) return IS_INCLUDES || index || 0;
            } return !IS_INCLUDES && -1;
        };
    };

    var arrayIncludes = {
        // `Array.prototype.includes` method
        // https://tc39.github.io/ecma262/#sec-array.prototype.includes
        includes: createMethod(true),
        // `Array.prototype.indexOf` method
        // https://tc39.github.io/ecma262/#sec-array.prototype.indexof
        indexOf: createMethod(false)
    };

    var indexOf = arrayIncludes.indexOf;


    var objectKeysInternal = function (object, names) {
        var O = toIndexedObject(object);
        var i = 0;
        var result = [];
        var key;
        for (key in O) !has(hiddenKeys, key) && has(O, key) && result.push(key);
        // Don't enum bug & hidden keys
        while (names.length > i) if (has(O, key = names[i++])) {
            ~indexOf(result, key) || result.push(key);
        }
        return result;
    };

    // IE8- don't enum bug keys
    var enumBugKeys = [
        'constructor',
        'hasOwnProperty',
        'isPrototypeOf',
        'propertyIsEnumerable',
        'toLocaleString',
        'toString',
        'valueOf'
    ];

    var hiddenKeys$1 = enumBugKeys.concat('length', 'prototype');

    // `Object.getOwnPropertyNames` method
    // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
    var f$3 = Object.getOwnPropertyNames || function getOwnPropertyNames(O) {
        return objectKeysInternal(O, hiddenKeys$1);
    };

    var objectGetOwnPropertyNames = {
        f: f$3
    };

    var f$4 = Object.getOwnPropertySymbols;

    var objectGetOwnPropertySymbols = {
        f: f$4
    };

    // all object keys, includes non-enumerable and symbols
    var ownKeys = getBuiltIn('Reflect', 'ownKeys') || function ownKeys(it) {
        var keys = objectGetOwnPropertyNames.f(anObject(it));
        var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
        return getOwnPropertySymbols ? keys.concat(getOwnPropertySymbols(it)) : keys;
    };

    var copyConstructorProperties = function (target, source) {
        var keys = ownKeys(source);
        var defineProperty = objectDefineProperty.f;
        var getOwnPropertyDescriptor = objectGetOwnPropertyDescriptor.f;
        for (var i = 0; i < keys.length; i++) {
            var key = keys[i];
            if (!has(target, key)) defineProperty(target, key, getOwnPropertyDescriptor(source, key));
        }
    };

    var replacement = /#|\.prototype\./;

    var isForced = function (feature, detection) {
        var value = data[normalize(feature)];
        return value == POLYFILL ? true
            : value == NATIVE ? false
                : typeof detection == 'function' ? fails(detection)
                    : !!detection;
    };

    var normalize = isForced.normalize = function (string) {
        return String(string).replace(replacement, '.').toLowerCase();
    };

    var data = isForced.data = {};
    var NATIVE = isForced.NATIVE = 'N';
    var POLYFILL = isForced.POLYFILL = 'P';

    var isForced_1 = isForced;

    var getOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;






    /*
      options.target      - name of the target object
      options.global      - target is the global object
      options.stat        - export as static methods of target
      options.proto       - export as prototype methods of target
      options.real        - real prototype method for the `pure` version
      options.forced      - export even if the native feature is available
      options.bind        - bind methods to the target, required for the `pure` version
      options.wrap        - wrap constructors to preventing global pollution, required for the `pure` version
      options.unsafe      - use the simple assignment of property instead of delete + defineProperty
      options.sham        - add a flag to not completely full polyfills
      options.enumerable  - export as enumerable property
      options.noTargetGet - prevent calling a getter on target
    */
    var _export = function (options, source) {
        var TARGET = options.target;
        var GLOBAL = options.global;
        var STATIC = options.stat;
        var FORCED, target, key, targetProperty, sourceProperty, descriptor;
        if (GLOBAL) {
            target = global_1;
        } else if (STATIC) {
            target = global_1[TARGET] || setGlobal(TARGET, {});
        } else {
            target = (global_1[TARGET] || {}).prototype;
        }
        if (target) for (key in source) {
            sourceProperty = source[key];
            if (options.noTargetGet) {
                descriptor = getOwnPropertyDescriptor$1(target, key);
                targetProperty = descriptor && descriptor.value;
            } else targetProperty = target[key];
            FORCED = isForced_1(GLOBAL ? key : TARGET + (STATIC ? '.' : '#') + key, options.forced);
            // contained in target
            if (!FORCED && targetProperty !== undefined) {
                if (typeof sourceProperty === typeof targetProperty) continue;
                copyConstructorProperties(sourceProperty, targetProperty);
            }
            // add a flag to not completely full polyfills
            if (options.sham || (targetProperty && targetProperty.sham)) {
                hide(sourceProperty, 'sham', true);
            }
            // extend global
            redefine(target, key, sourceProperty, options);
        }
    };

    var nativeSymbol = !!Object.getOwnPropertySymbols && !fails(function () {
        // Chrome 38 Symbol has incorrect toString conversion
        // eslint-disable-next-line no-undef
        return !String(Symbol());
    });

    var Symbol$1 = global_1.Symbol;
    var store$1 = shared('wks');

    var wellKnownSymbol = function (name) {
        return store$1[name] || (store$1[name] = nativeSymbol && Symbol$1[name]
            || (nativeSymbol ? Symbol$1 : uid)('Symbol.' + name));
    };

    // `Object.keys` method
    // https://tc39.github.io/ecma262/#sec-object.keys
    var objectKeys = Object.keys || function keys(O) {
        return objectKeysInternal(O, enumBugKeys);
    };

    // `Object.defineProperties` method
    // https://tc39.github.io/ecma262/#sec-object.defineproperties
    var objectDefineProperties = descriptors ? Object.defineProperties : function defineProperties(O, Properties) {
        anObject(O);
        var keys = objectKeys(Properties);
        var length = keys.length;
        var index = 0;
        var key;
        while (length > index) objectDefineProperty.f(O, key = keys[index++], Properties[key]);
        return O;
    };

    var html = getBuiltIn('document', 'documentElement');

    var IE_PROTO = sharedKey('IE_PROTO');

    var PROTOTYPE = 'prototype';
    var Empty = function () { /* empty */ };

    // Create object with fake `null` prototype: use iframe Object with cleared prototype
    var createDict = function () {
        // Thrash, waste and sodomy: IE GC bug
        var iframe = documentCreateElement('iframe');
        var length = enumBugKeys.length;
        var lt = '<';
        var script = 'script';
        var gt = '>';
        var js = 'java' + script + ':';
        var iframeDocument;
        iframe.style.display = 'none';
        html.appendChild(iframe);
        iframe.src = String(js);
        iframeDocument = iframe.contentWindow.document;
        iframeDocument.open();
        iframeDocument.write(lt + script + gt + 'document.F=Object' + lt + '/' + script + gt);
        iframeDocument.close();
        createDict = iframeDocument.F;
        while (length--) delete createDict[PROTOTYPE][enumBugKeys[length]];
        return createDict();
    };

    // `Object.create` method
    // https://tc39.github.io/ecma262/#sec-object.create
    var objectCreate = Object.create || function create(O, Properties) {
        var result;
        if (O !== null) {
            Empty[PROTOTYPE] = anObject(O);
            result = new Empty();
            Empty[PROTOTYPE] = null;
            // add "__proto__" for Object.getPrototypeOf polyfill
            result[IE_PROTO] = O;
        } else result = createDict();
        return Properties === undefined ? result : objectDefineProperties(result, Properties);
    };

    hiddenKeys[IE_PROTO] = true;

    var UNSCOPABLES = wellKnownSymbol('unscopables');
    var ArrayPrototype = Array.prototype;

    // Array.prototype[@@unscopables]
    // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
    if (ArrayPrototype[UNSCOPABLES] == undefined) {
        hide(ArrayPrototype, UNSCOPABLES, objectCreate(null));
    }

    // add a key to Array.prototype[@@unscopables]
    var addToUnscopables = function (key) {
        ArrayPrototype[UNSCOPABLES][key] = true;
    };

    var $includes = arrayIncludes.includes;


    // `Array.prototype.includes` method
    // https://tc39.github.io/ecma262/#sec-array.prototype.includes
    _export({ target: 'Array', proto: true }, {
        includes: function includes(el /* , fromIndex = 0 */) {
            return $includes(this, el, arguments.length > 1 ? arguments[1] : undefined);
        }
    });

    // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
    addToUnscopables('includes');

    // `ToObject` abstract operation
    // https://tc39.github.io/ecma262/#sec-toobject
    var toObject = function (argument) {
        return Object(requireObjectCoercible(argument));
    };

    var nativeAssign = Object.assign;

    // `Object.assign` method
    // https://tc39.github.io/ecma262/#sec-object.assign
    // should work with symbols and should have deterministic property order (V8 bug)
    var objectAssign = !nativeAssign || fails(function () {
        var A = {};
        var B = {};
        // eslint-disable-next-line no-undef
        var symbol = Symbol();
        var alphabet = 'abcdefghijklmnopqrst';
        A[symbol] = 7;
        alphabet.split('').forEach(function (chr) { B[chr] = chr; });
        return nativeAssign({}, A)[symbol] != 7 || objectKeys(nativeAssign({}, B)).join('') != alphabet;
    }) ? function assign(target, source) { // eslint-disable-line no-unused-vars
        var T = toObject(target);
        var argumentsLength = arguments.length;
        var index = 1;
        var getOwnPropertySymbols = objectGetOwnPropertySymbols.f;
        var propertyIsEnumerable = objectPropertyIsEnumerable.f;
        while (argumentsLength > index) {
            var S = indexedObject(arguments[index++]);
            var keys = getOwnPropertySymbols ? objectKeys(S).concat(getOwnPropertySymbols(S)) : objectKeys(S);
            var length = keys.length;
            var j = 0;
            var key;
            while (length > j) {
                key = keys[j++];
                if (!descriptors || propertyIsEnumerable.call(S, key)) T[key] = S[key];
            }
        } return T;
    } : nativeAssign;

    // `Object.assign` method
    // https://tc39.github.io/ecma262/#sec-object.assign
    _export({ target: 'Object', stat: true, forced: Object.assign !== objectAssign }, {
        assign: objectAssign
    });

    var MATCH = wellKnownSymbol('match');

    // `IsRegExp` abstract operation
    // https://tc39.github.io/ecma262/#sec-isregexp
    var isRegexp = function (it) {
        var isRegExp;
        return isObject(it) && ((isRegExp = it[MATCH]) !== undefined ? !!isRegExp : classofRaw(it) == 'RegExp');
    };

    var notARegexp = function (it) {
        if (isRegexp(it)) {
            throw TypeError("The method doesn't accept regular expressions");
        } return it;
    };

    var MATCH$1 = wellKnownSymbol('match');

    var correctIsRegexpLogic = function (METHOD_NAME) {
        var regexp = /./;
        try {
            '/./'[METHOD_NAME](regexp);
        } catch (e) {
            try {
                regexp[MATCH$1] = false;
                return '/./'[METHOD_NAME](regexp);
            } catch (f) { /* empty */ }
        } return false;
    };

    // `String.prototype.includes` method
    // https://tc39.github.io/ecma262/#sec-string.prototype.includes
    _export({ target: 'String', proto: true, forced: !correctIsRegexpLogic('includes') }, {
        includes: function includes(searchString /* , position = 0 */) {
            return !!~String(requireObjectCoercible(this))
                .indexOf(notARegexp(searchString), arguments.length > 1 ? arguments[1] : undefined);
        }
    });

    // a string of all valid unicode whitespaces
    // eslint-disable-next-line max-len
    var whitespaces = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029\uFEFF';

    var whitespace = '[' + whitespaces + ']';
    var ltrim = RegExp('^' + whitespace + whitespace + '*');
    var rtrim = RegExp(whitespace + whitespace + '*$');

    // `String.prototype.{ trim, trimStart, trimEnd, trimLeft, trimRight }` methods implementation
    var createMethod$1 = function (TYPE) {
        return function ($this) {
            var string = String(requireObjectCoercible($this));
            if (TYPE & 1) string = string.replace(ltrim, '');
            if (TYPE & 2) string = string.replace(rtrim, '');
            return string;
        };
    };

    var stringTrim = {
        // `String.prototype.{ trimLeft, trimStart }` methods
        // https://tc39.github.io/ecma262/#sec-string.prototype.trimstart
        start: createMethod$1(1),
        // `String.prototype.{ trimRight, trimEnd }` methods
        // https://tc39.github.io/ecma262/#sec-string.prototype.trimend
        end: createMethod$1(2),
        // `String.prototype.trim` method
        // https://tc39.github.io/ecma262/#sec-string.prototype.trim
        trim: createMethod$1(3)
    };

    var non = '\u200B\u0085\u180E';

    // check that a method works with the correct list
    // of whitespaces and has a correct name
    var forcedStringTrimMethod = function (METHOD_NAME) {
        return fails(function () {
            return !!whitespaces[METHOD_NAME]() || non[METHOD_NAME]() != non || whitespaces[METHOD_NAME].name !== METHOD_NAME;
        });
    };

    var $trim = stringTrim.trim;


    // `String.prototype.trim` method
    // https://tc39.github.io/ecma262/#sec-string.prototype.trim
    _export({ target: 'String', proto: true, forced: forcedStringTrimMethod('trim') }, {
        trim: function trim() {
            return $trim(this);
        }
    });

    var VERSION = '1.5.2';
    var BLOCK_ROWS = 50;
    var CLUSTER_BLOCKS = 4;
    var DEFAULTS = {
        name: '',
        placeholder: '',
        data: undefined,
        locale: undefined,
        selectAll: true,
        single: undefined,
        singleRadio: false,
        multiple: false,
        hideOptgroupCheckboxes: false,
        multipleWidth: 80,
        width: undefined,
        dropWidth: undefined,
        maxHeight: 250,
        maxHeightUnit: 'px',
        position: 'bottom',
        displayValues: false,
        displayTitle: false,
        displayDelimiter: ', ',
        minimumCountSelected: 3,
        ellipsis: false,
        isOpen: false,
        keepOpen: false,
        openOnHover: false,
        container: null,
        filter: false,
        filterGroup: false,
        filterPlaceholder: '',
        filterAcceptOnEnter: false,
        filterByDataLength: undefined,
        customFilter: function customFilter(label, text) {
            // originalLabel, originalText
            return label.includes(text);
        },
        showClear: false,
        animate: undefined,
        styler: function styler() {
            return false;
        },
        textTemplate: function textTemplate($elm) {
            return $elm[0].innerHTML.trim();
        },
        labelTemplate: function labelTemplate($elm) {
            return $elm[0].getAttribute('label');
        },
        onOpen: function onOpen() {
            return false;
        },
        onClose: function onClose() {
            return false;
        },
        onCheckAll: function onCheckAll() {
            return false;
        },
        onUncheckAll: function onUncheckAll() {
            return false;
        },
        onFocus: function onFocus() {
            return false;
        },
        onBlur: function onBlur() {
            return false;
        },
        onOptgroupClick: function onOptgroupClick() {
            return false;
        },
        onClick: function onClick() {
            return false;
        },
        onFilter: function onFilter() {
            return false;
        },
        onClear: function onClear() {
            return false;
        },
        onAfterCreate: function onAfterCreate() {
            return false;
        }
    };
    var EN = {
        formatSelectAll: function formatSelectAll() {
            return '[Select all]';
        },
        formatAllSelected: function formatAllSelected() {
            return 'All selected';
        },
        formatCountSelected: function formatCountSelected(count, total) {
            return count + ' of ' + total + ' selected';
        },
        formatNoMatchesFound: function formatNoMatchesFound() {
            return 'No matches found';
        }
    };
    var METHODS = ['getOptions', 'refreshOptions', 'getSelects', 'setSelects', 'enable', 'disable', 'open', 'close', 'check', 'uncheck', 'checkAll', 'uncheckAll', 'checkInvert', 'focus', 'blur', 'refresh', 'destroy'];
    Object.assign(DEFAULTS, EN);
    var Constants = {
        VERSION: VERSION,
        BLOCK_ROWS: BLOCK_ROWS,
        CLUSTER_BLOCKS: CLUSTER_BLOCKS,
        DEFAULTS: DEFAULTS,
        METHODS: METHODS,
        LOCALES: {
            en: EN,
            'en-US': EN
        }
    };

    // `IsArray` abstract operation
    // https://tc39.github.io/ecma262/#sec-isarray
    var isArray = Array.isArray || function isArray(arg) {
        return classofRaw(arg) == 'Array';
    };

    var nativeGetOwnPropertyNames = objectGetOwnPropertyNames.f;

    var toString$1 = {}.toString;

    var windowNames = typeof window == 'object' && window && Object.getOwnPropertyNames
        ? Object.getOwnPropertyNames(window) : [];

    var getWindowNames = function (it) {
        try {
            return nativeGetOwnPropertyNames(it);
        } catch (error) {
            return windowNames.slice();
        }
    };

    // fallback for IE11 buggy Object.getOwnPropertyNames with iframe and window
    var f$5 = function getOwnPropertyNames(it) {
        return windowNames && toString$1.call(it) == '[object Window]'
            ? getWindowNames(it)
            : nativeGetOwnPropertyNames(toIndexedObject(it));
    };

    var objectGetOwnPropertyNamesExternal = {
        f: f$5
    };

    var f$6 = wellKnownSymbol;

    var wrappedWellKnownSymbol = {
        f: f$6
    };

    var defineProperty = objectDefineProperty.f;

    var defineWellKnownSymbol = function (NAME) {
        var Symbol = path.Symbol || (path.Symbol = {});
        if (!has(Symbol, NAME)) defineProperty(Symbol, NAME, {
            value: wrappedWellKnownSymbol.f(NAME)
        });
    };

    var defineProperty$1 = objectDefineProperty.f;



    var TO_STRING_TAG = wellKnownSymbol('toStringTag');

    var setToStringTag = function (it, TAG, STATIC) {
        if (it && !has(it = STATIC ? it : it.prototype, TO_STRING_TAG)) {
            defineProperty$1(it, TO_STRING_TAG, { configurable: true, value: TAG });
        }
    };

    var aFunction$1 = function (it) {
        if (typeof it != 'function') {
            throw TypeError(String(it) + ' is not a function');
        } return it;
    };

    // optional / simple context binding
    var bindContext = function (fn, that, length) {
        aFunction$1(fn);
        if (that === undefined) return fn;
        switch (length) {
            case 0: return function () {
                return fn.call(that);
            };
            case 1: return function (a) {
                return fn.call(that, a);
            };
            case 2: return function (a, b) {
                return fn.call(that, a, b);
            };
            case 3: return function (a, b, c) {
                return fn.call(that, a, b, c);
            };
        }
        return function (/* ...args */) {
            return fn.apply(that, arguments);
        };
    };

    var SPECIES = wellKnownSymbol('species');

    // `ArraySpeciesCreate` abstract operation
    // https://tc39.github.io/ecma262/#sec-arrayspeciescreate
    var arraySpeciesCreate = function (originalArray, length) {
        var C;
        if (isArray(originalArray)) {
            C = originalArray.constructor;
            // cross-realm fallback
            if (typeof C == 'function' && (C === Array || isArray(C.prototype))) C = undefined;
            else if (isObject(C)) {
                C = C[SPECIES];
                if (C === null) C = undefined;
            }
        } return new (C === undefined ? Array : C)(length === 0 ? 0 : length);
    };

    var push = [].push;

    // `Array.prototype.{ forEach, map, filter, some, every, find, findIndex }` methods implementation
    var createMethod$2 = function (TYPE) {
        var IS_MAP = TYPE == 1;
        var IS_FILTER = TYPE == 2;
        var IS_SOME = TYPE == 3;
        var IS_EVERY = TYPE == 4;
        var IS_FIND_INDEX = TYPE == 6;
        var NO_HOLES = TYPE == 5 || IS_FIND_INDEX;
        return function ($this, callbackfn, that, specificCreate) {
            var O = toObject($this);
            var self = indexedObject(O);
            var boundFunction = bindContext(callbackfn, that, 3);
            var length = toLength(self.length);
            var index = 0;
            var create = specificCreate || arraySpeciesCreate;
            var target = IS_MAP ? create($this, length) : IS_FILTER ? create($this, 0) : undefined;
            var value, result;
            for (; length > index; index++) if (NO_HOLES || index in self) {
                value = self[index];
                result = boundFunction(value, index, O);
                if (TYPE) {
                    if (IS_MAP) target[index] = result; // map
                    else if (result) switch (TYPE) {
                        case 3: return true;              // some
                        case 5: return value;             // find
                        case 6: return index;             // findIndex
                        case 2: push.call(target, value); // filter
                    } else if (IS_EVERY) return false;  // every
                }
            }
            return IS_FIND_INDEX ? -1 : IS_SOME || IS_EVERY ? IS_EVERY : target;
        };
    };

    var arrayIteration = {
        // `Array.prototype.forEach` method
        // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
        forEach: createMethod$2(0),
        // `Array.prototype.map` method
        // https://tc39.github.io/ecma262/#sec-array.prototype.map
        map: createMethod$2(1),
        // `Array.prototype.filter` method
        // https://tc39.github.io/ecma262/#sec-array.prototype.filter
        filter: createMethod$2(2),
        // `Array.prototype.some` method
        // https://tc39.github.io/ecma262/#sec-array.prototype.some
        some: createMethod$2(3),
        // `Array.prototype.every` method
        // https://tc39.github.io/ecma262/#sec-array.prototype.every
        every: createMethod$2(4),
        // `Array.prototype.find` method
        // https://tc39.github.io/ecma262/#sec-array.prototype.find
        find: createMethod$2(5),
        // `Array.prototype.findIndex` method
        // https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
        findIndex: createMethod$2(6)
    };

    var $forEach = arrayIteration.forEach;

    var HIDDEN = sharedKey('hidden');
    var SYMBOL = 'Symbol';
    var PROTOTYPE$1 = 'prototype';
    var TO_PRIMITIVE = wellKnownSymbol('toPrimitive');
    var setInternalState = internalState.set;
    var getInternalState = internalState.getterFor(SYMBOL);
    var ObjectPrototype = Object[PROTOTYPE$1];
    var $Symbol = global_1.Symbol;
    var JSON = global_1.JSON;
    var nativeJSONStringify = JSON && JSON.stringify;
    var nativeGetOwnPropertyDescriptor$1 = objectGetOwnPropertyDescriptor.f;
    var nativeDefineProperty$1 = objectDefineProperty.f;
    var nativeGetOwnPropertyNames$1 = objectGetOwnPropertyNamesExternal.f;
    var nativePropertyIsEnumerable$1 = objectPropertyIsEnumerable.f;
    var AllSymbols = shared('symbols');
    var ObjectPrototypeSymbols = shared('op-symbols');
    var StringToSymbolRegistry = shared('string-to-symbol-registry');
    var SymbolToStringRegistry = shared('symbol-to-string-registry');
    var WellKnownSymbolsStore = shared('wks');
    var QObject = global_1.QObject;
    // Don't use setters in Qt Script, https://github.com/zloirock/core-js/issues/173
    var USE_SETTER = !QObject || !QObject[PROTOTYPE$1] || !QObject[PROTOTYPE$1].findChild;

    // fallback for old Android, https://code.google.com/p/v8/issues/detail?id=687
    var setSymbolDescriptor = descriptors && fails(function () {
        return objectCreate(nativeDefineProperty$1({}, 'a', {
            get: function () { return nativeDefineProperty$1(this, 'a', { value: 7 }).a; }
        })).a != 7;
    }) ? function (O, P, Attributes) {
        var ObjectPrototypeDescriptor = nativeGetOwnPropertyDescriptor$1(ObjectPrototype, P);
        if (ObjectPrototypeDescriptor) delete ObjectPrototype[P];
        nativeDefineProperty$1(O, P, Attributes);
        if (ObjectPrototypeDescriptor && O !== ObjectPrototype) {
            nativeDefineProperty$1(ObjectPrototype, P, ObjectPrototypeDescriptor);
        }
    } : nativeDefineProperty$1;

    var wrap = function (tag, description) {
        var symbol = AllSymbols[tag] = objectCreate($Symbol[PROTOTYPE$1]);
        setInternalState(symbol, {
            type: SYMBOL,
            tag: tag,
            description: description
        });
        if (!descriptors) symbol.description = description;
        return symbol;
    };

    var isSymbol = nativeSymbol && typeof $Symbol.iterator == 'symbol' ? function (it) {
        return typeof it == 'symbol';
    } : function (it) {
        return Object(it) instanceof $Symbol;
    };

    var $defineProperty = function defineProperty(O, P, Attributes) {
        if (O === ObjectPrototype) $defineProperty(ObjectPrototypeSymbols, P, Attributes);
        anObject(O);
        var key = toPrimitive(P, true);
        anObject(Attributes);
        if (has(AllSymbols, key)) {
            if (!Attributes.enumerable) {
                if (!has(O, HIDDEN)) nativeDefineProperty$1(O, HIDDEN, createPropertyDescriptor(1, {}));
                O[HIDDEN][key] = true;
            } else {
                if (has(O, HIDDEN) && O[HIDDEN][key]) O[HIDDEN][key] = false;
                Attributes = objectCreate(Attributes, { enumerable: createPropertyDescriptor(0, false) });
            } return setSymbolDescriptor(O, key, Attributes);
        } return nativeDefineProperty$1(O, key, Attributes);
    };

    var $defineProperties = function defineProperties(O, Properties) {
        anObject(O);
        var properties = toIndexedObject(Properties);
        var keys = objectKeys(properties).concat($getOwnPropertySymbols(properties));
        $forEach(keys, function (key) {
            if (!descriptors || $propertyIsEnumerable.call(properties, key)) $defineProperty(O, key, properties[key]);
        });
        return O;
    };

    var $create = function create(O, Properties) {
        return Properties === undefined ? objectCreate(O) : $defineProperties(objectCreate(O), Properties);
    };

    var $propertyIsEnumerable = function propertyIsEnumerable(V) {
        var P = toPrimitive(V, true);
        var enumerable = nativePropertyIsEnumerable$1.call(this, P);
        if (this === ObjectPrototype && has(AllSymbols, P) && !has(ObjectPrototypeSymbols, P)) return false;
        return enumerable || !has(this, P) || !has(AllSymbols, P) || has(this, HIDDEN) && this[HIDDEN][P] ? enumerable : true;
    };

    var $getOwnPropertyDescriptor = function getOwnPropertyDescriptor(O, P) {
        var it = toIndexedObject(O);
        var key = toPrimitive(P, true);
        if (it === ObjectPrototype && has(AllSymbols, key) && !has(ObjectPrototypeSymbols, key)) return;
        var descriptor = nativeGetOwnPropertyDescriptor$1(it, key);
        if (descriptor && has(AllSymbols, key) && !(has(it, HIDDEN) && it[HIDDEN][key])) {
            descriptor.enumerable = true;
        }
        return descriptor;
    };

    var $getOwnPropertyNames = function getOwnPropertyNames(O) {
        var names = nativeGetOwnPropertyNames$1(toIndexedObject(O));
        var result = [];
        $forEach(names, function (key) {
            if (!has(AllSymbols, key) && !has(hiddenKeys, key)) result.push(key);
        });
        return result;
    };

    var $getOwnPropertySymbols = function getOwnPropertySymbols(O) {
        var IS_OBJECT_PROTOTYPE = O === ObjectPrototype;
        var names = nativeGetOwnPropertyNames$1(IS_OBJECT_PROTOTYPE ? ObjectPrototypeSymbols : toIndexedObject(O));
        var result = [];
        $forEach(names, function (key) {
            if (has(AllSymbols, key) && (!IS_OBJECT_PROTOTYPE || has(ObjectPrototype, key))) {
                result.push(AllSymbols[key]);
            }
        });
        return result;
    };

    // `Symbol` constructor
    // https://tc39.github.io/ecma262/#sec-symbol-constructor
    if (!nativeSymbol) {
        $Symbol = function Symbol() {
            if (this instanceof $Symbol) throw TypeError('Symbol is not a constructor');
            var description = !arguments.length || arguments[0] === undefined ? undefined : String(arguments[0]);
            var tag = uid(description);
            var setter = function (value) {
                if (this === ObjectPrototype) setter.call(ObjectPrototypeSymbols, value);
                if (has(this, HIDDEN) && has(this[HIDDEN], tag)) this[HIDDEN][tag] = false;
                setSymbolDescriptor(this, tag, createPropertyDescriptor(1, value));
            };
            if (descriptors && USE_SETTER) setSymbolDescriptor(ObjectPrototype, tag, { configurable: true, set: setter });
            return wrap(tag, description);
        };

        redefine($Symbol[PROTOTYPE$1], 'toString', function toString() {
            return getInternalState(this).tag;
        });

        objectPropertyIsEnumerable.f = $propertyIsEnumerable;
        objectDefineProperty.f = $defineProperty;
        objectGetOwnPropertyDescriptor.f = $getOwnPropertyDescriptor;
        objectGetOwnPropertyNames.f = objectGetOwnPropertyNamesExternal.f = $getOwnPropertyNames;
        objectGetOwnPropertySymbols.f = $getOwnPropertySymbols;

        if (descriptors) {
            // https://github.com/tc39/proposal-Symbol-description
            nativeDefineProperty$1($Symbol[PROTOTYPE$1], 'description', {
                configurable: true,
                get: function description() {
                    return getInternalState(this).description;
                }
            });
            {
                redefine(ObjectPrototype, 'propertyIsEnumerable', $propertyIsEnumerable, { unsafe: true });
            }
        }

        wrappedWellKnownSymbol.f = function (name) {
            return wrap(wellKnownSymbol(name), name);
        };
    }

    _export({ global: true, wrap: true, forced: !nativeSymbol, sham: !nativeSymbol }, {
        Symbol: $Symbol
    });

    $forEach(objectKeys(WellKnownSymbolsStore), function (name) {
        defineWellKnownSymbol(name);
    });

    _export({ target: SYMBOL, stat: true, forced: !nativeSymbol }, {
        // `Symbol.for` method
        // https://tc39.github.io/ecma262/#sec-symbol.for
        'for': function (key) {
            var string = String(key);
            if (has(StringToSymbolRegistry, string)) return StringToSymbolRegistry[string];
            var symbol = $Symbol(string);
            StringToSymbolRegistry[string] = symbol;
            SymbolToStringRegistry[symbol] = string;
            return symbol;
        },
        // `Symbol.keyFor` method
        // https://tc39.github.io/ecma262/#sec-symbol.keyfor
        keyFor: function keyFor(sym) {
            if (!isSymbol(sym)) throw TypeError(sym + ' is not a symbol');
            if (has(SymbolToStringRegistry, sym)) return SymbolToStringRegistry[sym];
        },
        useSetter: function () { USE_SETTER = true; },
        useSimple: function () { USE_SETTER = false; }
    });

    _export({ target: 'Object', stat: true, forced: !nativeSymbol, sham: !descriptors }, {
        // `Object.create` method
        // https://tc39.github.io/ecma262/#sec-object.create
        create: $create,
        // `Object.defineProperty` method
        // https://tc39.github.io/ecma262/#sec-object.defineproperty
        defineProperty: $defineProperty,
        // `Object.defineProperties` method
        // https://tc39.github.io/ecma262/#sec-object.defineproperties
        defineProperties: $defineProperties,
        // `Object.getOwnPropertyDescriptor` method
        // https://tc39.github.io/ecma262/#sec-object.getownpropertydescriptors
        getOwnPropertyDescriptor: $getOwnPropertyDescriptor
    });

    _export({ target: 'Object', stat: true, forced: !nativeSymbol }, {
        // `Object.getOwnPropertyNames` method
        // https://tc39.github.io/ecma262/#sec-object.getownpropertynames
        getOwnPropertyNames: $getOwnPropertyNames,
        // `Object.getOwnPropertySymbols` method
        // https://tc39.github.io/ecma262/#sec-object.getownpropertysymbols
        getOwnPropertySymbols: $getOwnPropertySymbols
    });

    // Chrome 38 and 39 `Object.getOwnPropertySymbols` fails on primitives
    // https://bugs.chromium.org/p/v8/issues/detail?id=3443
    _export({ target: 'Object', stat: true, forced: fails(function () { objectGetOwnPropertySymbols.f(1); }) }, {
        getOwnPropertySymbols: function getOwnPropertySymbols(it) {
            return objectGetOwnPropertySymbols.f(toObject(it));
        }
    });

    // `JSON.stringify` method behavior with symbols
    // https://tc39.github.io/ecma262/#sec-json.stringify
    JSON && _export({
        target: 'JSON', stat: true, forced: !nativeSymbol || fails(function () {
            var symbol = $Symbol();
            // MS Edge converts symbol values to JSON as {}
            return nativeJSONStringify([symbol]) != '[null]'
                // WebKit converts symbol values to JSON as null
                || nativeJSONStringify({ a: symbol }) != '{}'
                // V8 throws on boxed symbols
                || nativeJSONStringify(Object(symbol)) != '{}';
        })
    }, {
        stringify: function stringify(it) {
            var args = [it];
            var index = 1;
            var replacer, $replacer;
            while (arguments.length > index) args.push(arguments[index++]);
            $replacer = replacer = args[1];
            if (!isObject(replacer) && it === undefined || isSymbol(it)) return; // IE8 returns string on undefined
            if (!isArray(replacer)) replacer = function (key, value) {
                if (typeof $replacer == 'function') value = $replacer.call(this, key, value);
                if (!isSymbol(value)) return value;
            };
            args[1] = replacer;
            return nativeJSONStringify.apply(JSON, args);
        }
    });

    // `Symbol.prototype[@@toPrimitive]` method
    // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@toprimitive
    if (!$Symbol[PROTOTYPE$1][TO_PRIMITIVE]) hide($Symbol[PROTOTYPE$1], TO_PRIMITIVE, $Symbol[PROTOTYPE$1].valueOf);
    // `Symbol.prototype[@@toStringTag]` property
    // https://tc39.github.io/ecma262/#sec-symbol.prototype-@@tostringtag
    setToStringTag($Symbol, SYMBOL);

    hiddenKeys[HIDDEN] = true;

    var defineProperty$2 = objectDefineProperty.f;


    var NativeSymbol = global_1.Symbol;

    if (descriptors && typeof NativeSymbol == 'function' && (!('description' in NativeSymbol.prototype) ||
        // Safari 12 bug
        NativeSymbol().description !== undefined
    )) {
        var EmptyStringDescriptionStore = {};
        // wrap Symbol constructor for correct work with undefined description
        var SymbolWrapper = function Symbol() {
            var description = arguments.length < 1 || arguments[0] === undefined ? undefined : String(arguments[0]);
            var result = this instanceof SymbolWrapper
                ? new NativeSymbol(description)
                // in Edge 13, String(Symbol(undefined)) === 'Symbol(undefined)'
                : description === undefined ? NativeSymbol() : NativeSymbol(description);
            if (description === '') EmptyStringDescriptionStore[result] = true;
            return result;
        };
        copyConstructorProperties(SymbolWrapper, NativeSymbol);
        var symbolPrototype = SymbolWrapper.prototype = NativeSymbol.prototype;
        symbolPrototype.constructor = SymbolWrapper;

        var symbolToString = symbolPrototype.toString;
        var native = String(NativeSymbol('test')) == 'Symbol(test)';
        var regexp = /^Symbol\((.*)\)[^)]+$/;
        defineProperty$2(symbolPrototype, 'description', {
            configurable: true,
            get: function description() {
                var symbol = isObject(this) ? this.valueOf() : this;
                var string = symbolToString.call(symbol);
                if (has(EmptyStringDescriptionStore, symbol)) return '';
                var desc = native ? string.slice(7, -1) : string.replace(regexp, '$1');
                return desc === '' ? undefined : desc;
            }
        });

        _export({ global: true, forced: true }, {
            Symbol: SymbolWrapper
        });
    }

    // `Symbol.iterator` well-known symbol
    // https://tc39.github.io/ecma262/#sec-symbol.iterator
    defineWellKnownSymbol('iterator');

    var createProperty = function (object, key, value) {
        var propertyKey = toPrimitive(key);
        if (propertyKey in object) objectDefineProperty.f(object, propertyKey, createPropertyDescriptor(0, value));
        else object[propertyKey] = value;
    };

    var SPECIES$1 = wellKnownSymbol('species');

    var arrayMethodHasSpeciesSupport = function (METHOD_NAME) {
        return !fails(function () {
            var array = [];
            var constructor = array.constructor = {};
            constructor[SPECIES$1] = function () {
                return { foo: 1 };
            };
            return array[METHOD_NAME](Boolean).foo !== 1;
        });
    };

    var IS_CONCAT_SPREADABLE = wellKnownSymbol('isConcatSpreadable');
    var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
    var MAXIMUM_ALLOWED_INDEX_EXCEEDED = 'Maximum allowed index exceeded';

    var IS_CONCAT_SPREADABLE_SUPPORT = !fails(function () {
        var array = [];
        array[IS_CONCAT_SPREADABLE] = false;
        return array.concat()[0] !== array;
    });

    var SPECIES_SUPPORT = arrayMethodHasSpeciesSupport('concat');

    var isConcatSpreadable = function (O) {
        if (!isObject(O)) return false;
        var spreadable = O[IS_CONCAT_SPREADABLE];
        return spreadable !== undefined ? !!spreadable : isArray(O);
    };

    var FORCED = !IS_CONCAT_SPREADABLE_SUPPORT || !SPECIES_SUPPORT;

    // `Array.prototype.concat` method
    // https://tc39.github.io/ecma262/#sec-array.prototype.concat
    // with adding support of @@isConcatSpreadable and @@species
    _export({ target: 'Array', proto: true, forced: FORCED }, {
        concat: function concat(arg) { // eslint-disable-line no-unused-vars
            var O = toObject(this);
            var A = arraySpeciesCreate(O, 0);
            var n = 0;
            var i, k, length, len, E;
            for (i = -1, length = arguments.length; i < length; i++) {
                E = i === -1 ? O : arguments[i];
                if (isConcatSpreadable(E)) {
                    len = toLength(E.length);
                    if (n + len > MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
                    for (k = 0; k < len; k++, n++) if (k in E) createProperty(A, n, E[k]);
                } else {
                    if (n >= MAX_SAFE_INTEGER) throw TypeError(MAXIMUM_ALLOWED_INDEX_EXCEEDED);
                    createProperty(A, n++, E);
                }
            }
            A.length = n;
            return A;
        }
    });

    var $filter = arrayIteration.filter;


    // `Array.prototype.filter` method
    // https://tc39.github.io/ecma262/#sec-array.prototype.filter
    // with adding support of @@species
    _export({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('filter') }, {
        filter: function filter(callbackfn /* , thisArg */) {
            return $filter(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
        }
    });

    var $find = arrayIteration.find;


    var FIND = 'find';
    var SKIPS_HOLES = true;

    // Shouldn't skip holes
    if (FIND in []) Array(1)[FIND](function () { SKIPS_HOLES = false; });

    // `Array.prototype.find` method
    // https://tc39.github.io/ecma262/#sec-array.prototype.find
    _export({ target: 'Array', proto: true, forced: SKIPS_HOLES }, {
        find: function find(callbackfn /* , that = undefined */) {
            return $find(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
        }
    });

    // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
    addToUnscopables(FIND);

    var correctPrototypeGetter = !fails(function () {
        function F() { /* empty */ }
        F.prototype.constructor = null;
        return Object.getPrototypeOf(new F()) !== F.prototype;
    });

    var IE_PROTO$1 = sharedKey('IE_PROTO');
    var ObjectPrototype$1 = Object.prototype;

    // `Object.getPrototypeOf` method
    // https://tc39.github.io/ecma262/#sec-object.getprototypeof
    var objectGetPrototypeOf = correctPrototypeGetter ? Object.getPrototypeOf : function (O) {
        O = toObject(O);
        if (has(O, IE_PROTO$1)) return O[IE_PROTO$1];
        if (typeof O.constructor == 'function' && O instanceof O.constructor) {
            return O.constructor.prototype;
        } return O instanceof Object ? ObjectPrototype$1 : null;
    };

    var ITERATOR = wellKnownSymbol('iterator');
    var BUGGY_SAFARI_ITERATORS = false;

    var returnThis = function () { return this; };

    // `%IteratorPrototype%` object
    // https://tc39.github.io/ecma262/#sec-%iteratorprototype%-object
    var IteratorPrototype, PrototypeOfArrayIteratorPrototype, arrayIterator;

    if ([].keys) {
        arrayIterator = [].keys();
        // Safari 8 has buggy iterators w/o `next`
        if (!('next' in arrayIterator)) BUGGY_SAFARI_ITERATORS = true;
        else {
            PrototypeOfArrayIteratorPrototype = objectGetPrototypeOf(objectGetPrototypeOf(arrayIterator));
            if (PrototypeOfArrayIteratorPrototype !== Object.prototype) IteratorPrototype = PrototypeOfArrayIteratorPrototype;
        }
    }

    if (IteratorPrototype == undefined) IteratorPrototype = {};

    // 25.1.2.1.1 %IteratorPrototype%[@@iterator]()
    if (!has(IteratorPrototype, ITERATOR)) hide(IteratorPrototype, ITERATOR, returnThis);

    var iteratorsCore = {
        IteratorPrototype: IteratorPrototype,
        BUGGY_SAFARI_ITERATORS: BUGGY_SAFARI_ITERATORS
    };

    var IteratorPrototype$1 = iteratorsCore.IteratorPrototype;

    var createIteratorConstructor = function (IteratorConstructor, NAME, next) {
        var TO_STRING_TAG = NAME + ' Iterator';
        IteratorConstructor.prototype = objectCreate(IteratorPrototype$1, { next: createPropertyDescriptor(1, next) });
        setToStringTag(IteratorConstructor, TO_STRING_TAG, false);
        return IteratorConstructor;
    };

    var aPossiblePrototype = function (it) {
        if (!isObject(it) && it !== null) {
            throw TypeError("Can't set " + String(it) + ' as a prototype');
        } return it;
    };

    // `Object.setPrototypeOf` method
    // https://tc39.github.io/ecma262/#sec-object.setprototypeof
    // Works with __proto__ only. Old v8 can't work with null proto objects.
    /* eslint-disable no-proto */
    var objectSetPrototypeOf = Object.setPrototypeOf || ('__proto__' in {} ? function () {
        var CORRECT_SETTER = false;
        var test = {};
        var setter;
        try {
            setter = Object.getOwnPropertyDescriptor(Object.prototype, '__proto__').set;
            setter.call(test, []);
            CORRECT_SETTER = test instanceof Array;
        } catch (error) { /* empty */ }
        return function setPrototypeOf(O, proto) {
            anObject(O);
            aPossiblePrototype(proto);
            if (CORRECT_SETTER) setter.call(O, proto);
            else O.__proto__ = proto;
            return O;
        };
    }() : undefined);

    var IteratorPrototype$2 = iteratorsCore.IteratorPrototype;
    var BUGGY_SAFARI_ITERATORS$1 = iteratorsCore.BUGGY_SAFARI_ITERATORS;
    var ITERATOR$1 = wellKnownSymbol('iterator');
    var KEYS = 'keys';
    var VALUES = 'values';
    var ENTRIES = 'entries';

    var returnThis$1 = function () { return this; };

    var defineIterator = function (Iterable, NAME, IteratorConstructor, next, DEFAULT, IS_SET, FORCED) {
        createIteratorConstructor(IteratorConstructor, NAME, next);

        var getIterationMethod = function (KIND) {
            if (KIND === DEFAULT && defaultIterator) return defaultIterator;
            if (!BUGGY_SAFARI_ITERATORS$1 && KIND in IterablePrototype) return IterablePrototype[KIND];
            switch (KIND) {
                case KEYS: return function keys() { return new IteratorConstructor(this, KIND); };
                case VALUES: return function values() { return new IteratorConstructor(this, KIND); };
                case ENTRIES: return function entries() { return new IteratorConstructor(this, KIND); };
            } return function () { return new IteratorConstructor(this); };
        };

        var TO_STRING_TAG = NAME + ' Iterator';
        var INCORRECT_VALUES_NAME = false;
        var IterablePrototype = Iterable.prototype;
        var nativeIterator = IterablePrototype[ITERATOR$1]
            || IterablePrototype['@@iterator']
            || DEFAULT && IterablePrototype[DEFAULT];
        var defaultIterator = !BUGGY_SAFARI_ITERATORS$1 && nativeIterator || getIterationMethod(DEFAULT);
        var anyNativeIterator = NAME == 'Array' ? IterablePrototype.entries || nativeIterator : nativeIterator;
        var CurrentIteratorPrototype, methods, KEY;

        // fix native
        if (anyNativeIterator) {
            CurrentIteratorPrototype = objectGetPrototypeOf(anyNativeIterator.call(new Iterable()));
            if (IteratorPrototype$2 !== Object.prototype && CurrentIteratorPrototype.next) {
                if (objectGetPrototypeOf(CurrentIteratorPrototype) !== IteratorPrototype$2) {
                    if (objectSetPrototypeOf) {
                        objectSetPrototypeOf(CurrentIteratorPrototype, IteratorPrototype$2);
                    } else if (typeof CurrentIteratorPrototype[ITERATOR$1] != 'function') {
                        hide(CurrentIteratorPrototype, ITERATOR$1, returnThis$1);
                    }
                }
                // Set @@toStringTag to native iterators
                setToStringTag(CurrentIteratorPrototype, TO_STRING_TAG, true);
            }
        }

        // fix Array#{values, @@iterator}.name in V8 / FF
        if (DEFAULT == VALUES && nativeIterator && nativeIterator.name !== VALUES) {
            INCORRECT_VALUES_NAME = true;
            defaultIterator = function values() { return nativeIterator.call(this); };
        }

        // define iterator
        if (IterablePrototype[ITERATOR$1] !== defaultIterator) {
            hide(IterablePrototype, ITERATOR$1, defaultIterator);
        }

        // export additional methods
        if (DEFAULT) {
            methods = {
                values: getIterationMethod(VALUES),
                keys: IS_SET ? defaultIterator : getIterationMethod(KEYS),
                entries: getIterationMethod(ENTRIES)
            };
            if (FORCED) for (KEY in methods) {
                if (BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME || !(KEY in IterablePrototype)) {
                    redefine(IterablePrototype, KEY, methods[KEY]);
                }
            } else _export({ target: NAME, proto: true, forced: BUGGY_SAFARI_ITERATORS$1 || INCORRECT_VALUES_NAME }, methods);
        }

        return methods;
    };

    var ARRAY_ITERATOR = 'Array Iterator';
    var setInternalState$1 = internalState.set;
    var getInternalState$1 = internalState.getterFor(ARRAY_ITERATOR);

    // `Array.prototype.entries` method
    // https://tc39.github.io/ecma262/#sec-array.prototype.entries
    // `Array.prototype.keys` method
    // https://tc39.github.io/ecma262/#sec-array.prototype.keys
    // `Array.prototype.values` method
    // https://tc39.github.io/ecma262/#sec-array.prototype.values
    // `Array.prototype[@@iterator]` method
    // https://tc39.github.io/ecma262/#sec-array.prototype-@@iterator
    // `CreateArrayIterator` internal method
    // https://tc39.github.io/ecma262/#sec-createarrayiterator
    var es_array_iterator = defineIterator(Array, 'Array', function (iterated, kind) {
        setInternalState$1(this, {
            type: ARRAY_ITERATOR,
            target: toIndexedObject(iterated), // target
            index: 0,                          // next index
            kind: kind                         // kind
        });
        // `%ArrayIteratorPrototype%.next` method
        // https://tc39.github.io/ecma262/#sec-%arrayiteratorprototype%.next
    }, function () {
        var state = getInternalState$1(this);
        var target = state.target;
        var kind = state.kind;
        var index = state.index++;
        if (!target || index >= target.length) {
            state.target = undefined;
            return { value: undefined, done: true };
        }
        if (kind == 'keys') return { value: index, done: false };
        if (kind == 'values') return { value: target[index], done: false };
        return { value: [index, target[index]], done: false };
    }, 'values');

    // https://tc39.github.io/ecma262/#sec-array.prototype-@@unscopables
    addToUnscopables('keys');
    addToUnscopables('values');
    addToUnscopables('entries');

    var sloppyArrayMethod = function (METHOD_NAME, argument) {
        var method = [][METHOD_NAME];
        return !method || !fails(function () {
            // eslint-disable-next-line no-useless-call,no-throw-literal
            method.call(null, argument || function () { throw 1; }, 1);
        });
    };

    var nativeJoin = [].join;

    var ES3_STRINGS = indexedObject != Object;
    var SLOPPY_METHOD = sloppyArrayMethod('join', ',');

    // `Array.prototype.join` method
    // https://tc39.github.io/ecma262/#sec-array.prototype.join
    _export({ target: 'Array', proto: true, forced: ES3_STRINGS || SLOPPY_METHOD }, {
        join: function join(separator) {
            return nativeJoin.call(toIndexedObject(this), separator === undefined ? ',' : separator);
        }
    });

    var $map = arrayIteration.map;


    // `Array.prototype.map` method
    // https://tc39.github.io/ecma262/#sec-array.prototype.map
    // with adding support of @@species
    _export({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('map') }, {
        map: function map(callbackfn /* , thisArg */) {
            return $map(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
        }
    });

    var SPECIES$2 = wellKnownSymbol('species');
    var nativeSlice = [].slice;
    var max$1 = Math.max;

    // `Array.prototype.slice` method
    // https://tc39.github.io/ecma262/#sec-array.prototype.slice
    // fallback for not array-like ES3 strings and DOM objects
    _export({ target: 'Array', proto: true, forced: !arrayMethodHasSpeciesSupport('slice') }, {
        slice: function slice(start, end) {
            var O = toIndexedObject(this);
            var length = toLength(O.length);
            var k = toAbsoluteIndex(start, length);
            var fin = toAbsoluteIndex(end === undefined ? length : end, length);
            // inline `ArraySpeciesCreate` for usage native `Array#slice` where it's possible
            var Constructor, result, n;
            if (isArray(O)) {
                Constructor = O.constructor;
                // cross-realm fallback
                if (typeof Constructor == 'function' && (Constructor === Array || isArray(Constructor.prototype))) {
                    Constructor = undefined;
                } else if (isObject(Constructor)) {
                    Constructor = Constructor[SPECIES$2];
                    if (Constructor === null) Constructor = undefined;
                }
                if (Constructor === Array || Constructor === undefined) {
                    return nativeSlice.call(O, k, fin);
                }
            }
            result = new (Constructor === undefined ? Array : Constructor)(max$1(fin - k, 0));
            for (n = 0; k < fin; k++, n++) if (k in O) createProperty(result, n, O[k]);
            result.length = n;
            return result;
        }
    });

    var defineProperty$3 = objectDefineProperty.f;

    var FunctionPrototype = Function.prototype;
    var FunctionPrototypeToString = FunctionPrototype.toString;
    var nameRE = /^\s*function ([^ (]*)/;
    var NAME = 'name';

    // Function instances `.name` property
    // https://tc39.github.io/ecma262/#sec-function-instances-name
    if (descriptors && !(NAME in FunctionPrototype)) {
        defineProperty$3(FunctionPrototype, NAME, {
            configurable: true,
            get: function () {
                try {
                    return FunctionPrototypeToString.call(this).match(nameRE)[1];
                } catch (error) {
                    return '';
                }
            }
        });
    }

    var propertyIsEnumerable = objectPropertyIsEnumerable.f;

    // `Object.{ entries, values }` methods implementation
    var createMethod$3 = function (TO_ENTRIES) {
        return function (it) {
            var O = toIndexedObject(it);
            var keys = objectKeys(O);
            var length = keys.length;
            var i = 0;
            var result = [];
            var key;
            while (length > i) {
                key = keys[i++];
                if (!descriptors || propertyIsEnumerable.call(O, key)) {
                    result.push(TO_ENTRIES ? [key, O[key]] : O[key]);
                }
            }
            return result;
        };
    };

    var objectToArray = {
        // `Object.entries` method
        // https://tc39.github.io/ecma262/#sec-object.entries
        entries: createMethod$3(true),
        // `Object.values` method
        // https://tc39.github.io/ecma262/#sec-object.values
        values: createMethod$3(false)
    };

    var $entries = objectToArray.entries;

    // `Object.entries` method
    // https://tc39.github.io/ecma262/#sec-object.entries
    _export({ target: 'Object', stat: true }, {
        entries: function entries(O) {
            return $entries(O);
        }
    });

    var FAILS_ON_PRIMITIVES = fails(function () { objectKeys(1); });

    // `Object.keys` method
    // https://tc39.github.io/ecma262/#sec-object.keys
    _export({ target: 'Object', stat: true, forced: FAILS_ON_PRIMITIVES }, {
        keys: function keys(it) {
            return objectKeys(toObject(it));
        }
    });

    var TO_STRING_TAG$1 = wellKnownSymbol('toStringTag');
    // ES3 wrong here
    var CORRECT_ARGUMENTS = classofRaw(function () { return arguments; }()) == 'Arguments';

    // fallback for IE11 Script Access Denied error
    var tryGet = function (it, key) {
        try {
            return it[key];
        } catch (error) { /* empty */ }
    };

    // getting tag from ES6+ `Object.prototype.toString`
    var classof = function (it) {
        var O, tag, result;
        return it === undefined ? 'Undefined' : it === null ? 'Null'
            // @@toStringTag case
            : typeof (tag = tryGet(O = Object(it), TO_STRING_TAG$1)) == 'string' ? tag
                // builtinTag case
                : CORRECT_ARGUMENTS ? classofRaw(O)
                    // ES3 arguments fallback
                    : (result = classofRaw(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : result;
    };

    var TO_STRING_TAG$2 = wellKnownSymbol('toStringTag');
    var test = {};

    test[TO_STRING_TAG$2] = 'z';

    // `Object.prototype.toString` method implementation
    // https://tc39.github.io/ecma262/#sec-object.prototype.tostring
    var objectToString = String(test) !== '[object z]' ? function toString() {
        return '[object ' + classof(this) + ']';
    } : test.toString;

    var ObjectPrototype$2 = Object.prototype;

    // `Object.prototype.toString` method
    // https://tc39.github.io/ecma262/#sec-object.prototype.tostring
    if (objectToString !== ObjectPrototype$2.toString) {
        redefine(ObjectPrototype$2, 'toString', objectToString, { unsafe: true });
    }

    // `String.prototype.{ codePointAt, at }` methods implementation
    var createMethod$4 = function (CONVERT_TO_STRING) {
        return function ($this, pos) {
            var S = String(requireObjectCoercible($this));
            var position = toInteger(pos);
            var size = S.length;
            var first, second;
            if (position < 0 || position >= size) return CONVERT_TO_STRING ? '' : undefined;
            first = S.charCodeAt(position);
            return first < 0xD800 || first > 0xDBFF || position + 1 === size
                || (second = S.charCodeAt(position + 1)) < 0xDC00 || second > 0xDFFF
                ? CONVERT_TO_STRING ? S.charAt(position) : first
                : CONVERT_TO_STRING ? S.slice(position, position + 2) : (first - 0xD800 << 10) + (second - 0xDC00) + 0x10000;
        };
    };

    var stringMultibyte = {
        // `String.prototype.codePointAt` method
        // https://tc39.github.io/ecma262/#sec-string.prototype.codepointat
        codeAt: createMethod$4(false),
        // `String.prototype.at` method
        // https://github.com/mathiasbynens/String.prototype.at
        charAt: createMethod$4(true)
    };

    var charAt = stringMultibyte.charAt;



    var STRING_ITERATOR = 'String Iterator';
    var setInternalState$2 = internalState.set;
    var getInternalState$2 = internalState.getterFor(STRING_ITERATOR);

    // `String.prototype[@@iterator]` method
    // https://tc39.github.io/ecma262/#sec-string.prototype-@@iterator
    defineIterator(String, 'String', function (iterated) {
        setInternalState$2(this, {
            type: STRING_ITERATOR,
            string: String(iterated),
            index: 0
        });
        // `%StringIteratorPrototype%.next` method
        // https://tc39.github.io/ecma262/#sec-%stringiteratorprototype%.next
    }, function next() {
        var state = getInternalState$2(this);
        var string = state.string;
        var index = state.index;
        var point;
        if (index >= string.length) return { value: undefined, done: true };
        point = charAt(string, index);
        state.index += point.length;
        return { value: point, done: false };
    });

    // `RegExp.prototype.flags` getter implementation
    // https://tc39.github.io/ecma262/#sec-get-regexp.prototype.flags
    var regexpFlags = function () {
        var that = anObject(this);
        var result = '';
        if (that.global) result += 'g';
        if (that.ignoreCase) result += 'i';
        if (that.multiline) result += 'm';
        if (that.dotAll) result += 's';
        if (that.unicode) result += 'u';
        if (that.sticky) result += 'y';
        return result;
    };

    var nativeExec = RegExp.prototype.exec;
    // This always refers to the native implementation, because the
    // String#replace polyfill uses ./fix-regexp-well-known-symbol-logic.js,
    // which loads this file before patching the method.
    var nativeReplace = String.prototype.replace;

    var patchedExec = nativeExec;

    var UPDATES_LAST_INDEX_WRONG = (function () {
        var re1 = /a/;
        var re2 = /b*/g;
        nativeExec.call(re1, 'a');
        nativeExec.call(re2, 'a');
        return re1.lastIndex !== 0 || re2.lastIndex !== 0;
    })();

    // nonparticipating capturing group, copied from es5-shim's String#split patch.
    var NPCG_INCLUDED = /()??/.exec('')[1] !== undefined;

    var PATCH = UPDATES_LAST_INDEX_WRONG || NPCG_INCLUDED;

    if (PATCH) {
        patchedExec = function exec(str) {
            var re = this;
            var lastIndex, reCopy, match, i;

            if (NPCG_INCLUDED) {
                reCopy = new RegExp('^' + re.source + '$(?!\\s)', regexpFlags.call(re));
            }
            if (UPDATES_LAST_INDEX_WRONG) lastIndex = re.lastIndex;

            match = nativeExec.call(re, str);

            if (UPDATES_LAST_INDEX_WRONG && match) {
                re.lastIndex = re.global ? match.index + match[0].length : lastIndex;
            }
            if (NPCG_INCLUDED && match && match.length > 1) {
                // Fix browsers whose `exec` methods don't consistently return `undefined`
                // for NPCG, like IE8. NOTE: This doesn' work for /(.?)?/
                nativeReplace.call(match[0], reCopy, function () {
                    for (i = 1; i < arguments.length - 2; i++) {
                        if (arguments[i] === undefined) match[i] = undefined;
                    }
                });
            }

            return match;
        };
    }

    var regexpExec = patchedExec;

    var SPECIES$3 = wellKnownSymbol('species');

    var REPLACE_SUPPORTS_NAMED_GROUPS = !fails(function () {
        // #replace needs built-in support for named groups.
        // #match works fine because it just return the exec results, even if it has
        // a "grops" property.
        var re = /./;
        re.exec = function () {
            var result = [];
            result.groups = { a: '7' };
            return result;
        };
        return ''.replace(re, '$<a>') !== '7';
    });

    // Chrome 51 has a buggy "split" implementation when RegExp#exec !== nativeExec
    // Weex JS has frozen built-in prototypes, so use try / catch wrapper
    var SPLIT_WORKS_WITH_OVERWRITTEN_EXEC = !fails(function () {
        var re = /(?:)/;
        var originalExec = re.exec;
        re.exec = function () { return originalExec.apply(this, arguments); };
        var result = 'ab'.split(re);
        return result.length !== 2 || result[0] !== 'a' || result[1] !== 'b';
    });

    var fixRegexpWellKnownSymbolLogic = function (KEY, length, exec, sham) {
        var SYMBOL = wellKnownSymbol(KEY);

        var DELEGATES_TO_SYMBOL = !fails(function () {
            // String methods call symbol-named RegEp methods
            var O = {};
            O[SYMBOL] = function () { return 7; };
            return ''[KEY](O) != 7;
        });

        var DELEGATES_TO_EXEC = DELEGATES_TO_SYMBOL && !fails(function () {
            // Symbol-named RegExp methods call .exec
            var execCalled = false;
            var re = /a/;
            re.exec = function () { execCalled = true; return null; };

            if (KEY === 'split') {
                // RegExp[@@split] doesn't call the regex's exec method, but first creates
                // a new one. We need to return the patched regex when creating the new one.
                re.constructor = {};
                re.constructor[SPECIES$3] = function () { return re; };
            }

            re[SYMBOL]('');
            return !execCalled;
        });

        if (
            !DELEGATES_TO_SYMBOL ||
            !DELEGATES_TO_EXEC ||
            (KEY === 'replace' && !REPLACE_SUPPORTS_NAMED_GROUPS) ||
            (KEY === 'split' && !SPLIT_WORKS_WITH_OVERWRITTEN_EXEC)
        ) {
            var nativeRegExpMethod = /./[SYMBOL];
            var methods = exec(SYMBOL, ''[KEY], function (nativeMethod, regexp, str, arg2, forceStringMethod) {
                if (regexp.exec === regexpExec) {
                    if (DELEGATES_TO_SYMBOL && !forceStringMethod) {
                        // The native String method already delegates to @@method (this
                        // polyfilled function), leasing to infinite recursion.
                        // We avoid it by directly calling the native @@method method.
                        return { done: true, value: nativeRegExpMethod.call(regexp, str, arg2) };
                    }
                    return { done: true, value: nativeMethod.call(str, regexp, arg2) };
                }
                return { done: false };
            });
            var stringMethod = methods[0];
            var regexMethod = methods[1];

            redefine(String.prototype, KEY, stringMethod);
            redefine(RegExp.prototype, SYMBOL, length == 2
                // 21.2.5.8 RegExp.prototype[@@replace](string, replaceValue)
                // 21.2.5.11 RegExp.prototype[@@split](string, limit)
                ? function (string, arg) { return regexMethod.call(string, this, arg); }
                // 21.2.5.6 RegExp.prototype[@@match](string)
                // 21.2.5.9 RegExp.prototype[@@search](string)
                : function (string) { return regexMethod.call(string, this); }
            );
            if (sham) hide(RegExp.prototype[SYMBOL], 'sham', true);
        }
    };

    var SPECIES$4 = wellKnownSymbol('species');

    // `SpeciesConstructor` abstract operation
    // https://tc39.github.io/ecma262/#sec-speciesconstructor
    var speciesConstructor = function (O, defaultConstructor) {
        var C = anObject(O).constructor;
        var S;
        return C === undefined || (S = anObject(C)[SPECIES$4]) == undefined ? defaultConstructor : aFunction$1(S);
    };

    var charAt$1 = stringMultibyte.charAt;

    // `AdvanceStringIndex` abstract operation
    // https://tc39.github.io/ecma262/#sec-advancestringindex
    var advanceStringIndex = function (S, index, unicode) {
        return index + (unicode ? charAt$1(S, index).length : 1);
    };

    // `RegExpExec` abstract operation
    // https://tc39.github.io/ecma262/#sec-regexpexec
    var regexpExecAbstract = function (R, S) {
        var exec = R.exec;
        if (typeof exec === 'function') {
            var result = exec.call(R, S);
            if (typeof result !== 'object') {
                throw TypeError('RegExp exec method returned something other than an Object or null');
            }
            return result;
        }

        if (classofRaw(R) !== 'RegExp') {
            throw TypeError('RegExp#exec called on incompatible receiver');
        }

        return regexpExec.call(R, S);
    };

    var arrayPush = [].push;
    var min$2 = Math.min;
    var MAX_UINT32 = 0xFFFFFFFF;

    // babel-minify transpiles RegExp('x', 'y') -> /x/y and it causes SyntaxError
    var SUPPORTS_Y = !fails(function () { return !RegExp(MAX_UINT32, 'y'); });

    // @@split logic
    fixRegexpWellKnownSymbolLogic('split', 2, function (SPLIT, nativeSplit, maybeCallNative) {
        var internalSplit;
        if (
            'abbc'.split(/(b)*/)[1] == 'c' ||
            'test'.split(/(?:)/, -1).length != 4 ||
            'ab'.split(/(?:ab)*/).length != 2 ||
            '.'.split(/(.?)(.?)/).length != 4 ||
            '.'.split(/()()/).length > 1 ||
            ''.split(/.?/).length
        ) {
            // based on es5-shim implementation, need to rework it
            internalSplit = function (separator, limit) {
                var string = String(requireObjectCoercible(this));
                var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
                if (lim === 0) return [];
                if (separator === undefined) return [string];
                // If `separator` is not a regex, use native split
                if (!isRegexp(separator)) {
                    return nativeSplit.call(string, separator, lim);
                }
                var output = [];
                var flags = (separator.ignoreCase ? 'i' : '') +
                    (separator.multiline ? 'm' : '') +
                    (separator.unicode ? 'u' : '') +
                    (separator.sticky ? 'y' : '');
                var lastLastIndex = 0;
                // Make `global` and avoid `lastIndex` issues by working with a copy
                var separatorCopy = new RegExp(separator.source, flags + 'g');
                var match, lastIndex, lastLength;
                while (match = regexpExec.call(separatorCopy, string)) {
                    lastIndex = separatorCopy.lastIndex;
                    if (lastIndex > lastLastIndex) {
                        output.push(string.slice(lastLastIndex, match.index));
                        if (match.length > 1 && match.index < string.length) arrayPush.apply(output, match.slice(1));
                        lastLength = match[0].length;
                        lastLastIndex = lastIndex;
                        if (output.length >= lim) break;
                    }
                    if (separatorCopy.lastIndex === match.index) separatorCopy.lastIndex++; // Avoid an infinite loop
                }
                if (lastLastIndex === string.length) {
                    if (lastLength || !separatorCopy.test('')) output.push('');
                } else output.push(string.slice(lastLastIndex));
                return output.length > lim ? output.slice(0, lim) : output;
            };
            // Chakra, V8
        } else if ('0'.split(undefined, 0).length) {
            internalSplit = function (separator, limit) {
                return separator === undefined && limit === 0 ? [] : nativeSplit.call(this, separator, limit);
            };
        } else internalSplit = nativeSplit;

        return [
            // `String.prototype.split` method
            // https://tc39.github.io/ecma262/#sec-string.prototype.split
            function split(separator, limit) {
                var O = requireObjectCoercible(this);
                var splitter = separator == undefined ? undefined : separator[SPLIT];
                return splitter !== undefined
                    ? splitter.call(separator, O, limit)
                    : internalSplit.call(String(O), separator, limit);
            },
            // `RegExp.prototype[@@split]` method
            // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@split
            //
            // NOTE: This cannot be properly polyfilled in engines that don't support
            // the 'y' flag.
            function (regexp, limit) {
                var res = maybeCallNative(internalSplit, regexp, this, limit, internalSplit !== nativeSplit);
                if (res.done) return res.value;

                var rx = anObject(regexp);
                var S = String(this);
                var C = speciesConstructor(rx, RegExp);

                var unicodeMatching = rx.unicode;
                var flags = (rx.ignoreCase ? 'i' : '') +
                    (rx.multiline ? 'm' : '') +
                    (rx.unicode ? 'u' : '') +
                    (SUPPORTS_Y ? 'y' : 'g');

                // ^(? + rx + ) is needed, in combination with some S slicing, to
                // simulate the 'y' flag.
                var splitter = new C(SUPPORTS_Y ? rx : '^(?:' + rx.source + ')', flags);
                var lim = limit === undefined ? MAX_UINT32 : limit >>> 0;
                if (lim === 0) return [];
                if (S.length === 0) return regexpExecAbstract(splitter, S) === null ? [S] : [];
                var p = 0;
                var q = 0;
                var A = [];
                while (q < S.length) {
                    splitter.lastIndex = SUPPORTS_Y ? q : 0;
                    var z = regexpExecAbstract(splitter, SUPPORTS_Y ? S : S.slice(q));
                    var e;
                    if (
                        z === null ||
                        (e = min$2(toLength(splitter.lastIndex + (SUPPORTS_Y ? 0 : q)), S.length)) === p
                    ) {
                        q = advanceStringIndex(S, q, unicodeMatching);
                    } else {
                        A.push(S.slice(p, q));
                        if (A.length === lim) return A;
                        for (var i = 1; i <= z.length - 1; i++) {
                            A.push(z[i]);
                            if (A.length === lim) return A;
                        }
                        q = p = e;
                    }
                }
                A.push(S.slice(p));
                return A;
            }
        ];
    }, !SUPPORTS_Y);

    // iterable DOM collections
    // flag - `iterable` interface - 'entries', 'keys', 'values', 'forEach' methods
    var domIterables = {
        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
    };

    var $forEach$1 = arrayIteration.forEach;


    // `Array.prototype.forEach` method implementation
    // https://tc39.github.io/ecma262/#sec-array.prototype.foreach
    var arrayForEach = sloppyArrayMethod('forEach') ? function forEach(callbackfn /* , thisArg */) {
        return $forEach$1(this, callbackfn, arguments.length > 1 ? arguments[1] : undefined);
    } : [].forEach;

    for (var COLLECTION_NAME in domIterables) {
        var Collection = global_1[COLLECTION_NAME];
        var CollectionPrototype = Collection && Collection.prototype;
        // some Chrome versions have non-configurable methods on DOMTokenList
        if (CollectionPrototype && CollectionPrototype.forEach !== arrayForEach) try {
            hide(CollectionPrototype, 'forEach', arrayForEach);
        } catch (error) {
            CollectionPrototype.forEach = arrayForEach;
        }
    }

    var ITERATOR$2 = wellKnownSymbol('iterator');
    var TO_STRING_TAG$3 = wellKnownSymbol('toStringTag');
    var ArrayValues = es_array_iterator.values;

    for (var COLLECTION_NAME$1 in domIterables) {
        var Collection$1 = global_1[COLLECTION_NAME$1];
        var CollectionPrototype$1 = Collection$1 && Collection$1.prototype;
        if (CollectionPrototype$1) {
            // some Chrome versions have non-configurable methods on DOMTokenList
            if (CollectionPrototype$1[ITERATOR$2] !== ArrayValues) try {
                hide(CollectionPrototype$1, ITERATOR$2, ArrayValues);
            } catch (error) {
                CollectionPrototype$1[ITERATOR$2] = ArrayValues;
            }
            if (!CollectionPrototype$1[TO_STRING_TAG$3]) hide(CollectionPrototype$1, TO_STRING_TAG$3, COLLECTION_NAME$1);
            if (domIterables[COLLECTION_NAME$1]) for (var METHOD_NAME in es_array_iterator) {
                // some Chrome versions have non-configurable methods on DOMTokenList
                if (CollectionPrototype$1[METHOD_NAME] !== es_array_iterator[METHOD_NAME]) try {
                    hide(CollectionPrototype$1, METHOD_NAME, es_array_iterator[METHOD_NAME]);
                } catch (error) {
                    CollectionPrototype$1[METHOD_NAME] = es_array_iterator[METHOD_NAME];
                }
            }
        }
    }

    var VirtualScroll =
        /*#__PURE__*/
        function () {
            function VirtualScroll(options) {
                var _this = this;

                _classCallCheck(this, VirtualScroll);

                this.rows = options.rows;
                this.scrollEl = options.scrollEl;
                this.contentEl = options.contentEl;
                this.callback = options.callback;
                this.cache = {};
                this.scrollTop = this.scrollEl.scrollTop;
                this.initDOM(this.rows);
                this.scrollEl.scrollTop = this.scrollTop;
                this.lastCluster = 0;

                var onScroll = function onScroll() {
                    if (_this.lastCluster !== (_this.lastCluster = _this.getNum())) {
                        _this.initDOM(_this.rows);

                        _this.callback();
                    }
                };

                this.scrollEl.addEventListener('scroll', onScroll, false);

                this.destroy = function () {
                    _this.contentEl.innerHtml = '';

                    _this.scrollEl.removeEventListener('scroll', onScroll, false);
                };
            }

            _createClass(VirtualScroll, [{
                key: "initDOM",
                value: function initDOM(rows) {
                    if (typeof this.clusterHeight === 'undefined') {
                        this.cache.scrollTop = this.scrollEl.scrollTop;
                        this.cache.data = this.contentEl.innerHTML = rows[0] + rows[0] + rows[0];
                        this.getRowsHeight(rows);
                    }

                    var data = this.initData(rows, this.getNum());
                    var thisRows = data.rows.join('');
                    var dataChanged = this.checkChanges('data', thisRows);
                    var topOffsetChanged = this.checkChanges('top', data.topOffset);
                    var bottomOffsetChanged = this.checkChanges('bottom', data.bottomOffset);
                    var html = [];

                    if (dataChanged && topOffsetChanged) {
                        if (data.topOffset) {
                            html.push(this.getExtra('top', data.topOffset));
                        }

                        html.push(thisRows);

                        if (data.bottomOffset) {
                            html.push(this.getExtra('bottom', data.bottomOffset));
                        }

                        this.contentEl.innerHTML = html.join('');
                    } else if (bottomOffsetChanged) {
                        this.contentEl.lastChild.style.height = "".concat(data.bottomOffset, "px");
                    }
                }
            }, {
                key: "getRowsHeight",
                value: function getRowsHeight() {
                    if (typeof this.itemHeight === 'undefined') {
                        var nodes = this.contentEl.children;
                        var node = nodes[Math.floor(nodes.length / 2)];
                        this.itemHeight = node.offsetHeight;
                    }

                    this.blockHeight = this.itemHeight * Constants.BLOCK_ROWS;
                    this.clusterRows = Constants.BLOCK_ROWS * Constants.CLUSTER_BLOCKS;
                    this.clusterHeight = this.blockHeight * Constants.CLUSTER_BLOCKS;
                }
            }, {
                key: "getNum",
                value: function getNum() {
                    this.scrollTop = this.scrollEl.scrollTop;
                    return Math.floor(this.scrollTop / (this.clusterHeight - this.blockHeight)) || 0;
                }
            }, {
                key: "initData",
                value: function initData(rows, num) {
                    if (rows.length < Constants.BLOCK_ROWS) {
                        return {
                            topOffset: 0,
                            bottomOffset: 0,
                            rowsAbove: 0,
                            rows: rows
                        };
                    }

                    var start = Math.max((this.clusterRows - Constants.BLOCK_ROWS) * num, 0);
                    var end = start + this.clusterRows;
                    var topOffset = Math.max(start * this.itemHeight, 0);
                    var bottomOffset = Math.max((rows.length - end) * this.itemHeight, 0);
                    var thisRows = [];
                    var rowsAbove = start;

                    if (topOffset < 1) {
                        rowsAbove++;
                    }

                    for (var i = start; i < end; i++) {
                        rows[i] && thisRows.push(rows[i]);
                    }

                    this.dataStart = start;
                    this.dataEnd = end;
                    return {
                        topOffset: topOffset,
                        bottomOffset: bottomOffset,
                        rowsAbove: rowsAbove,
                        rows: thisRows
                    };
                }
            }, {
                key: "checkChanges",
                value: function checkChanges(type, value) {
                    var changed = value !== this.cache[type];
                    this.cache[type] = value;
                    return changed;
                }
            }, {
                key: "getExtra",
                value: function getExtra(className, height) {
                    var tag = document.createElement('li');
                    tag.className = "virtual-scroll-".concat(className);

                    if (height) {
                        tag.style.height = "".concat(height, "px");
                    }

                    return tag.outerHTML;
                }
            }]);

            return VirtualScroll;
        }();

    var max$2 = Math.max;
    var min$3 = Math.min;
    var floor$1 = Math.floor;
    var SUBSTITUTION_SYMBOLS = /\$([$&'`]|\d\d?|<[^>]*>)/g;
    var SUBSTITUTION_SYMBOLS_NO_NAMED = /\$([$&'`]|\d\d?)/g;

    var maybeToString = function (it) {
        return it === undefined ? it : String(it);
    };

    // @@replace logic
    fixRegexpWellKnownSymbolLogic('replace', 2, function (REPLACE, nativeReplace, maybeCallNative) {
        return [
            // `String.prototype.replace` method
            // https://tc39.github.io/ecma262/#sec-string.prototype.replace
            function replace(searchValue, replaceValue) {
                var O = requireObjectCoercible(this);
                var replacer = searchValue == undefined ? undefined : searchValue[REPLACE];
                return replacer !== undefined
                    ? replacer.call(searchValue, O, replaceValue)
                    : nativeReplace.call(String(O), searchValue, replaceValue);
            },
            // `RegExp.prototype[@@replace]` method
            // https://tc39.github.io/ecma262/#sec-regexp.prototype-@@replace
            function (regexp, replaceValue) {
                var res = maybeCallNative(nativeReplace, regexp, this, replaceValue);
                if (res.done) return res.value;

                var rx = anObject(regexp);
                var S = String(this);

                var functionalReplace = typeof replaceValue === 'function';
                if (!functionalReplace) replaceValue = String(replaceValue);

                var global = rx.global;
                if (global) {
                    var fullUnicode = rx.unicode;
                    rx.lastIndex = 0;
                }
                var results = [];
                while (true) {
                    var result = regexpExecAbstract(rx, S);
                    if (result === null) break;

                    results.push(result);
                    if (!global) break;

                    var matchStr = String(result[0]);
                    if (matchStr === '') rx.lastIndex = advanceStringIndex(S, toLength(rx.lastIndex), fullUnicode);
                }

                var accumulatedResult = '';
                var nextSourcePosition = 0;
                for (var i = 0; i < results.length; i++) {
                    result = results[i];

                    var matched = String(result[0]);
                    var position = max$2(min$3(toInteger(result.index), S.length), 0);
                    var captures = [];
                    // NOTE: This is equivalent to
                    //   captures = result.slice(1).map(maybeToString)
                    // but for some reason `nativeSlice.call(result, 1, result.length)` (called in
                    // the slice polyfill when slicing native arrays) "doesn't work" in safari 9 and
                    // causes a crash (https://pastebin.com/N21QzeQA) when trying to debug it.
                    for (var j = 1; j < result.length; j++) captures.push(maybeToString(result[j]));
                    var namedCaptures = result.groups;
                    if (functionalReplace) {
                        var replacerArgs = [matched].concat(captures, position, S);
                        if (namedCaptures !== undefined) replacerArgs.push(namedCaptures);
                        var replacement = String(replaceValue.apply(undefined, replacerArgs));
                    } else {
                        replacement = getSubstitution(matched, S, position, captures, namedCaptures, replaceValue);
                    }
                    if (position >= nextSourcePosition) {
                        accumulatedResult += S.slice(nextSourcePosition, position) + replacement;
                        nextSourcePosition = position + matched.length;
                    }
                }
                return accumulatedResult + S.slice(nextSourcePosition);
            }
        ];

        // https://tc39.github.io/ecma262/#sec-getsubstitution
        function getSubstitution(matched, str, position, captures, namedCaptures, replacement) {
            var tailPos = position + matched.length;
            var m = captures.length;
            var symbols = SUBSTITUTION_SYMBOLS_NO_NAMED;
            if (namedCaptures !== undefined) {
                namedCaptures = toObject(namedCaptures);
                symbols = SUBSTITUTION_SYMBOLS;
            }
            return nativeReplace.call(replacement, symbols, function (match, ch) {
                var capture;
                switch (ch.charAt(0)) {
                    case '$': return '$';
                    case '&': return matched;
                    case '`': return str.slice(0, position);
                    case "'": return str.slice(tailPos);
                    case '<':
                        capture = namedCaptures[ch.slice(1, -1)];
                        break;
                    default: // \d\d?
                        var n = +ch;
                        if (n === 0) return match;
                        if (n > m) {
                            var f = floor$1(n / 10);
                            if (f === 0) return match;
                            if (f <= m) return captures[f - 1] === undefined ? ch.charAt(1) : captures[f - 1] + ch.charAt(1);
                            return match;
                        }
                        capture = captures[n - 1];
                }
                return capture === undefined ? '' : capture;
            });
        }
    });

    var compareObjects = function compareObjects(objectA, objectB, compareLength) {
        var aKeys = Object.keys(objectA);
        var bKeys = Object.keys(objectB);

        if (compareLength && aKeys.length !== bKeys.length) {
            return false;
        }

        for (var _i = 0, _aKeys = aKeys; _i < _aKeys.length; _i++) {
            var key = _aKeys[_i];

            if (bKeys.includes(key) && objectA[key] !== objectB[key]) {
                return false;
            }
        }

        return true;
    };

    var removeDiacritics = function removeDiacritics(str) {
        if (str.normalize) {
            return str.normalize('NFD').replace(/[\u0300-\u036F]/g, '');
        }

        var defaultDiacriticsRemovalMap = [{
            'base': 'A',
            'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g
        }, {
            'base': 'AA',
            'letters': /[\uA732]/g
        }, {
            'base': 'AE',
            'letters': /[\u00C6\u01FC\u01E2]/g
        }, {
            'base': 'AO',
            'letters': /[\uA734]/g
        }, {
            'base': 'AU',
            'letters': /[\uA736]/g
        }, {
            'base': 'AV',
            'letters': /[\uA738\uA73A]/g
        }, {
            'base': 'AY',
            'letters': /[\uA73C]/g
        }, {
            'base': 'B',
            'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g
        }, {
            'base': 'C',
            'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g
        }, {
            'base': 'D',
            'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g
        }, {
            'base': 'DZ',
            'letters': /[\u01F1\u01C4]/g
        }, {
            'base': 'Dz',
            'letters': /[\u01F2\u01C5]/g
        }, {
            'base': 'E',
            'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g
        }, {
            'base': 'F',
            'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g
        }, {
            'base': 'G',
            'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g
        }, {
            'base': 'H',
            'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g
        }, {
            'base': 'I',
            'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g
        }, {
            'base': 'J',
            'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g
        }, {
            'base': 'K',
            'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g
        }, {
            'base': 'L',
            'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g
        }, {
            'base': 'LJ',
            'letters': /[\u01C7]/g
        }, {
            'base': 'Lj',
            'letters': /[\u01C8]/g
        }, {
            'base': 'M',
            'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g
        }, {
            'base': 'N',
            'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g
        }, {
            'base': 'NJ',
            'letters': /[\u01CA]/g
        }, {
            'base': 'Nj',
            'letters': /[\u01CB]/g
        }, {
            'base': 'O',
            'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g
        }, {
            'base': 'OI',
            'letters': /[\u01A2]/g
        }, {
            'base': 'OO',
            'letters': /[\uA74E]/g
        }, {
            'base': 'OU',
            'letters': /[\u0222]/g
        }, {
            'base': 'P',
            'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g
        }, {
            'base': 'Q',
            'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g
        }, {
            'base': 'R',
            'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g
        }, {
            'base': 'S',
            'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g
        }, {
            'base': 'T',
            'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g
        }, {
            'base': 'TZ',
            'letters': /[\uA728]/g
        }, {
            'base': 'U',
            'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g
        }, {
            'base': 'V',
            'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g
        }, {
            'base': 'VY',
            'letters': /[\uA760]/g
        }, {
            'base': 'W',
            'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g
        }, {
            'base': 'X',
            'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g
        }, {
            'base': 'Y',
            'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g
        }, {
            'base': 'Z',
            'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g
        }, {
            'base': 'a',
            'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g
        }, {
            'base': 'aa',
            'letters': /[\uA733]/g
        }, {
            'base': 'ae',
            'letters': /[\u00E6\u01FD\u01E3]/g
        }, {
            'base': 'ao',
            'letters': /[\uA735]/g
        }, {
            'base': 'au',
            'letters': /[\uA737]/g
        }, {
            'base': 'av',
            'letters': /[\uA739\uA73B]/g
        }, {
            'base': 'ay',
            'letters': /[\uA73D]/g
        }, {
            'base': 'b',
            'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g
        }, {
            'base': 'c',
            'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g
        }, {
            'base': 'd',
            'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g
        }, {
            'base': 'dz',
            'letters': /[\u01F3\u01C6]/g
        }, {
            'base': 'e',
            'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g
        }, {
            'base': 'f',
            'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g
        }, {
            'base': 'g',
            'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g
        }, {
            'base': 'h',
            'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g
        }, {
            'base': 'hv',
            'letters': /[\u0195]/g
        }, {
            'base': 'i',
            'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g
        }, {
            'base': 'j',
            'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g
        }, {
            'base': 'k',
            'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g
        }, {
            'base': 'l',
            'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g
        }, {
            'base': 'lj',
            'letters': /[\u01C9]/g
        }, {
            'base': 'm',
            'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g
        }, {
            'base': 'n',
            'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g
        }, {
            'base': 'nj',
            'letters': /[\u01CC]/g
        }, {
            'base': 'o',
            'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g
        }, {
            'base': 'oi',
            'letters': /[\u01A3]/g
        }, {
            'base': 'ou',
            'letters': /[\u0223]/g
        }, {
            'base': 'oo',
            'letters': /[\uA74F]/g
        }, {
            'base': 'p',
            'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g
        }, {
            'base': 'q',
            'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g
        }, {
            'base': 'r',
            'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g
        }, {
            'base': 's',
            'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g
        }, {
            'base': 't',
            'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g
        }, {
            'base': 'tz',
            'letters': /[\uA729]/g
        }, {
            'base': 'u',
            'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g
        }, {
            'base': 'v',
            'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g
        }, {
            'base': 'vy',
            'letters': /[\uA761]/g
        }, {
            'base': 'w',
            'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g
        }, {
            'base': 'x',
            'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g
        }, {
            'base': 'y',
            'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g
        }, {
            'base': 'z',
            'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g
        }];
        return defaultDiacriticsRemovalMap.reduce(function (string, _ref) {
            var letters = _ref.letters,
                base = _ref.base;
            return string.replace(letters, base);
        }, str);
    };

    var setDataKeys = function setDataKeys(data) {
        var total = 0;
        data.forEach(function (row, i) {
            if (row.type === 'optgroup') {
                row._key = "group_".concat(i);
                row.visible = typeof row.visible === 'undefined' ? true : row.visible;
                row.children.forEach(function (child, j) {
                    child._key = "option_".concat(i, "_").concat(j);
                    child.visible = typeof child.visible === 'undefined' ? true : child.visible;
                });
                total += row.children.length;
            } else {
                row._key = "option_".concat(i);
                row.visible = typeof row.visible === 'undefined' ? true : row.visible;
                total += 1;
            }
        });
        return total;
    };

    var findByParam = function findByParam(data, param, value) {
        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
            for (var _iterator = data[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                var row = _step.value;

                if (row[param] === value || row[param] === +row[param] + '' && +row[param] === value) {
                    return row;
                }

                if (row.type === 'optgroup') {
                    var _iteratorNormalCompletion2 = true;
                    var _didIteratorError2 = false;
                    var _iteratorError2 = undefined;

                    try {
                        for (var _iterator2 = row.children[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                            var child = _step2.value;

                            if (child[param] === value || child[param] === +child[param] + '' && +child[param] === value) {
                                return child;
                            }
                        }
                    } catch (err) {
                        _didIteratorError2 = true;
                        _iteratorError2 = err;
                    } finally {
                        try {
                            if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
                                _iterator2.return();
                            }
                        } finally {
                            if (_didIteratorError2) {
                                throw _iteratorError2;
                            }
                        }
                    }
                }
            }
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally {
            try {
                if (!_iteratorNormalCompletion && _iterator.return != null) {
                    _iterator.return();
                }
            } finally {
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }
    };

    var removeUndefined = function removeUndefined(obj) {
        Object.keys(obj).forEach(function (key) {
            return obj[key] === undefined ? delete obj[key] : '';
        });
        return obj;
    };

    var getDocumentClickEvent = function getDocumentClickEvent() {
        var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
        id = id || "".concat(+new Date()).concat(~~(Math.random() * 1000000));
        return "click.multiple-select-".concat(id);
    };

    var MultipleSelect =
        /*#__PURE__*/
        function () {
            function MultipleSelect($el, options) {
                _classCallCheck(this, MultipleSelect);

                this.$el = $el;
                this.options = $.extend({}, Constants.DEFAULTS, options);
            }

            _createClass(MultipleSelect, [{
                key: "init",
                value: function init() {
                    this.initLocale();
                    this.initContainer();
                    this.initData();
                    this.initSelected(true);
                    this.initFilter();
                    this.initDrop();
                    this.initView();
                    this.options.onAfterCreate();
                }
            }, {
                key: "initLocale",
                value: function initLocale() {
                    if (this.options.locale) {
                        var locales = $.fn.multipleSelect.locales;
                        var parts = this.options.locale.split(/-|_/);
                        parts[0] = parts[0].toLowerCase();

                        if (parts[1]) {
                            parts[1] = parts[1].toUpperCase();
                        }

                        if (locales[this.options.locale]) {
                            $.extend(this.options, locales[this.options.locale]);
                        } else if (locales[parts.join('-')]) {
                            $.extend(this.options, locales[parts.join('-')]);
                        } else if (locales[parts[0]]) {
                            $.extend(this.options, locales[parts[0]]);
                        }
                    }
                }
            }, {
                key: "initContainer",
                value: function initContainer() {
                    var _this = this;

                    var el = this.$el[0];
                    var name = el.getAttribute('name') || this.options.name || ''; // hide select element

                    this.$el.hide(); // label element

                    this.$label = this.$el.closest('label');

                    if (!this.$label.length && this.$el.attr('id')) {
                        this.$label = $("label[for=\"".concat(this.$el.attr('id'), "\"]"));
                    }

                    if (this.$label.find('>input').length) {
                        this.$label = null;
                    } // single or multiple


                    if (typeof this.options.single === 'undefined') {
                        this.options.single = el.getAttribute('multiple') === null;
                    } // restore class and title from select element


                    this.$parent = $("\n      <div class=\"ms-parent ".concat(el.getAttribute('class') || '', "\"\n      title=\"").concat(el.getAttribute('title') || '', "\" />\n    ")); // add placeholder to choice button

                    this.options.placeholder = this.options.placeholder || el.getAttribute('placeholder') || '';
                    this.tabIndex = el.getAttribute('tabindex');
                    var tabIndex = '';

                    if (this.tabIndex !== null) {
                        this.$el.attr('tabindex', -1);
                        tabIndex = this.tabIndex && "tabindex=\"".concat(this.tabIndex, "\"");
                    }

                    this.$choice = $("\n      <button type=\"button\" class=\"ms-choice\"".concat(tabIndex, ">\n      <span class=\"placeholder\">").concat(this.options.placeholder, "</span>\n      ").concat(this.options.showClear ? '<div class="icon-close"></div>' : '', "\n      <div class=\"icon-caret\"></div>\n      </button>\n    ")); // default position is bottom

                    this.$drop = $("<div class=\"ms-drop ".concat(this.options.position, "\" />"));
                    this.$close = this.$choice.find('.icon-close');

                    if (this.options.dropWidth) {
                        this.$drop.css('width', this.options.dropWidth);
                    }

                    this.$el.after(this.$parent);
                    this.$parent.append(this.$choice);
                    this.$parent.append(this.$drop);

                    if (el.disabled) {
                        this.$choice.addClass('disabled');
                    }

                    this.selectAllName = "data-name=\"selectAll".concat(name, "\"");
                    this.selectGroupName = "data-name=\"selectGroup".concat(name, "\"");
                    this.selectItemName = "data-name=\"selectItem".concat(name, "\"");

                    if (!this.options.keepOpen) {
                        var clickEvent = getDocumentClickEvent(this.$el.attr('id'));
                        $(document).off(clickEvent).on(clickEvent, function (e) {
                            if ($(e.target)[0] === _this.$choice[0] || $(e.target).parents('.ms-choice')[0] === _this.$choice[0]) {
                                return;
                            }

                            if (($(e.target)[0] === _this.$drop[0] || $(e.target).parents('.ms-drop')[0] !== _this.$drop[0] && e.target !== el) && _this.options.isOpen) {
                                _this.close();
                            }
                        });
                    }
                }
            }, {
                key: "initData",
                value: function initData() {
                    var _this2 = this;

                    var data = [];

                    if (this.options.data) {
                        if (Array.isArray(this.options.data)) {
                            this.data = this.options.data.map(function (it) {
                                if (typeof it === 'string' || typeof it === 'number') {
                                    return {
                                        text: it,
                                        value: it
                                    };
                                }

                                return it;
                            });
                        } else if (_typeof(this.options.data) === 'object') {
                            for (var _i = 0, _Object$entries = Object.entries(this.options.data); _i < _Object$entries.length; _i++) {
                                var _Object$entries$_i = _slicedToArray(_Object$entries[_i], 2),
                                    value = _Object$entries$_i[0],
                                    text = _Object$entries$_i[1];

                                data.push({
                                    value: value,
                                    text: text
                                });
                            }

                            this.data = data;
                        }
                    } else {
                        $.each(this.$el.children(), function (i, elm) {
                            var row = _this2.initRow(i, elm);

                            if (row) {
                                data.push(_this2.initRow(i, elm));
                            }
                        });
                        this.options.data = data;
                        this.data = data;
                        this.fromHtml = true;
                    }

                    this.dataTotal = setDataKeys(this.data);
                }
            }, {
                key: "initRow",
                value: function initRow(i, elm, groupDisabled) {
                    var _this3 = this;

                    var row = {};
                    var $elm = $(elm);

                    if ($elm.is('option')) {
                        row.type = 'option';
                        row.text = this.options.textTemplate($elm);
                        row.value = elm.value;
                        row.visible = true;
                        row.selected = !!elm.selected;
                        row.disabled = groupDisabled || elm.disabled;
                        row.classes = elm.getAttribute('class') || '';
                        row.title = elm.getAttribute('title') || '';

                        if ($elm.data('value')) {
                            row._value = $elm.data('value'); // value for object
                        }

                        if (Object.keys($elm.data()).length) {
                            row._data = $elm.data();
                        }

                        return row;
                    }

                    if ($elm.is('optgroup')) {
                        row.type = 'optgroup';
                        row.label = this.options.labelTemplate($elm);
                        row.visible = true;
                        row.selected = !!elm.selected;
                        row.disabled = elm.disabled;
                        row.children = [];

                        if (Object.keys($elm.data()).length) {
                            row._data = $elm.data();
                        }

                        $.each($elm.children(), function (j, elem) {
                            row.children.push(_this3.initRow(j, elem, row.disabled));
                        });
                        return row;
                    }

                    return null;
                }
            }, {
                key: "initSelected",
                value: function initSelected(ignoreTrigger) {
                    var selectedTotal = 0;
                    var _iteratorNormalCompletion = true;
                    var _didIteratorError = false;
                    var _iteratorError = undefined;

                    try {
                        for (var _iterator = this.data[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                            var row = _step.value;

                            if (row.type === 'optgroup') {
                                var selectedCount = row.children.filter(function (child) {
                                    return child.selected && !child.disabled && child.visible;
                                }).length;
                                row.selected = selectedCount && selectedCount === row.children.filter(function (child) {
                                    return !child.disabled && child.visible;
                                }).length;
                                selectedTotal += selectedCount;
                            } else {
                                selectedTotal += row.selected && !row.disabled && row.visible ? 1 : 0;
                            }
                        }
                    } catch (err) {
                        _didIteratorError = true;
                        _iteratorError = err;
                    } finally {
                        try {
                            if (!_iteratorNormalCompletion && _iterator.return != null) {
                                _iterator.return();
                            }
                        } finally {
                            if (_didIteratorError) {
                                throw _iteratorError;
                            }
                        }
                    }

                    this.allSelected = this.data.filter(function (row) {
                        return row.selected && !row.disabled && row.visible;
                    }).length === this.data.filter(function (row) {
                        return !row.disabled && row.visible;
                    }).length;

                    if (!ignoreTrigger) {
                        if (this.allSelected) {
                            this.options.onCheckAll();
                        } else if (selectedTotal === 0) {
                            this.options.onUncheckAll();
                        }
                    }
                }
            }, {
                key: "initFilter",
                value: function initFilter() {
                    this.filterText = '';

                    if (this.options.filter || !this.options.filterByDataLength) {
                        return;
                    }

                    var length = 0;
                    var _iteratorNormalCompletion2 = true;
                    var _didIteratorError2 = false;
                    var _iteratorError2 = undefined;

                    try {
                        for (var _iterator2 = this.data[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
                            var option = _step2.value;

                            if (option.type === 'optgroup') {
                                length += option.children.length;
                            } else {
                                length += 1;
                            }
                        }
                    } catch (err) {
                        _didIteratorError2 = true;
                        _iteratorError2 = err;
                    } finally {
                        try {
                            if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
                                _iterator2.return();
                            }
                        } finally {
                            if (_didIteratorError2) {
                                throw _iteratorError2;
                            }
                        }
                    }

                    this.options.filter = length > this.options.filterByDataLength;
                }
            }, {
                key: "initDrop",
                value: function initDrop() {
                    var _this4 = this;

                    this.initList();
                    this.update(true);

                    if (this.options.isOpen) {
                        setTimeout(function () {
                            _this4.open();
                        }, 50);
                    }

                    if (this.options.openOnHover) {
                        this.$parent.hover(function () {
                            _this4.open();
                        }, function () {
                            _this4.close();
                        });
                    }
                }
            }, {
                key: "initList",
                value: function initList() {
                    var html = [];

                    if (this.options.filter) {
                        html.push("\n        <div class=\"ms-search\">\n          <input type=\"text\" autocomplete=\"off\" autocorrect=\"off\"\n            autocapitalize=\"off\" spellcheck=\"false\"\n            placeholder=\"".concat(this.options.filterPlaceholder, "\">\n        </div>\n      "));
                    }

                    html.push('<ul></ul>');
                    this.$drop.html(html.join(''));
                    this.$ul = this.$drop.find('>ul');
                    this.initListItems();
                }
            }, {
                key: "initListItems",
                value: function initListItems() {
                    var _this5 = this;

                    var rows = this.getListRows();
                    var offset = 0;

                    if (this.options.selectAll && !this.options.single) {
                        offset = -1;
                    }

                    if (rows.length > Constants.BLOCK_ROWS * Constants.CLUSTER_BLOCKS) {
                        if (this.virtualScroll) {
                            this.virtualScroll.destroy();
                        }

                        var dropVisible = this.$drop.is(':visible');

                        if (!dropVisible) {
                            this.$drop.css('left', -10000).show();
                        }

                        var updateDataOffset = function updateDataOffset() {
                            _this5.updateDataStart = _this5.virtualScroll.dataStart + offset;
                            _this5.updateDataEnd = _this5.virtualScroll.dataEnd + offset;

                            if (_this5.updateDataStart < 0) {
                                _this5.updateDataStart = 0;
                            }

                            if (_this5.updateDataEnd > _this5.data.length) {
                                _this5.updateDataEnd = _this5.data.length;
                            }
                        };

                        this.virtualScroll = new VirtualScroll({
                            rows: rows,
                            scrollEl: this.$ul[0],
                            contentEl: this.$ul[0],
                            callback: function callback() {
                                updateDataOffset();

                                _this5.events();
                            }
                        });
                        updateDataOffset();

                        if (!dropVisible) {
                            this.$drop.css('left', 0).hide();
                        }
                    } else {
                        this.$ul.html(rows.join(''));
                        this.updateDataStart = 0;
                        this.updateDataEnd = this.updateData.length;
                        this.virtualScroll = null;
                    }

                    this.events();
                }
            }, {
                key: "getListRows",
                value: function getListRows() {
                    var _this6 = this;

                    var rows = [];

                    if (this.options.selectAll && !this.options.single) {
                        rows.push("\n        <li class=\"ms-select-all\">\n        <label>\n        <input type=\"checkbox\" ".concat(this.selectAllName).concat(this.allSelected ? ' checked="checked"' : '', " />\n        <span>").concat(this.options.formatSelectAll(), "</span>\n        </label>\n        </li>\n      "));
                    }

                    this.updateData = [];
                    this.data.forEach(function (row) {
                        rows.push.apply(rows, _toConsumableArray(_this6.initListItem(row)));
                    });
                    rows.push("<li class=\"ms-no-results\">".concat(this.options.formatNoMatchesFound(), "</li>"));
                    return rows;
                }
            }, {
                key: "initListItem",
                value: function initListItem(row) {
                    var _this7 = this;

                    var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
                    var title = row.title ? "title=\"".concat(row.title, "\"") : '';
                    var multiple = this.options.multiple ? 'multiple' : '';
                    var type = this.options.single ? 'radio' : 'checkbox';
                    var classes = '';

                    if (!row.visible) {
                        return [];
                    }

                    this.updateData.push(row);

                    if (this.options.single && !this.options.singleRadio) {
                        classes = 'hide-radio ';
                    }

                    if (row.selected) {
                        classes += 'selected ';
                    }

                    if (row.type === 'optgroup') {
                        var _customStyle = this.options.styler(row);

                        var _style = _customStyle ? "style=\"".concat(_customStyle, "\"") : '';

                        var html = [];
                        var group = this.options.hideOptgroupCheckboxes || this.options.single ? "<span ".concat(this.selectGroupName, " data-key=\"").concat(row._key, "\"></span>") : "<input type=\"checkbox\"\n          ".concat(this.selectGroupName, "\n          data-key=\"").concat(row._key, "\"\n          ").concat(row.selected ? ' checked="checked"' : '', "\n          ").concat(row.disabled ? ' disabled="disabled"' : '', "\n        >");

                        if (!classes.includes('hide-radio') && (this.options.hideOptgroupCheckboxes || this.options.single)) {
                            classes += 'hide-radio ';
                        }

                        html.push("\n        <li class=\"group ".concat(classes, "\" ").concat(_style, ">\n        <label class=\"optgroup").concat(this.options.single || row.disabled ? ' disabled' : '', "\">\n        ").concat(group).concat(row.label, "\n        </label>\n        </li>\n      "));
                        row.children.forEach(function (child) {
                            html.push.apply(html, _toConsumableArray(_this7.initListItem(child, 1)));
                        });
                        return html;
                    }

                    var customStyle = this.options.styler(row);
                    var style = customStyle ? "style=\"".concat(customStyle, "\"") : '';
                    classes += row.classes || '';

                    if (level && this.options.single) {
                        classes += "option-level-".concat(level, " ");
                    }

                    return ["\n      <li class=\"".concat(multiple, " ").concat(classes, "\" ").concat(title, " ").concat(style, ">\n      <label class=\"").concat(row.disabled ? 'disabled' : '', "\">\n      <input type=\"").concat(type, "\"\n        value=\"").concat(row.value, "\"\n        data-key=\"").concat(row._key, "\"\n        ").concat(this.selectItemName, "\n        ").concat(row.selected ? ' checked="checked"' : '', "\n        ").concat(row.disabled ? ' disabled="disabled"' : '', "\n      >\n      <span>").concat(row.text, "</span>\n      </label>\n      </li>\n    ")];
                }
            }, {
                key: "events",
                value: function events() {
                    var _this8 = this;

                    this.$searchInput = this.$drop.find('.ms-search input');
                    this.$selectAll = this.$drop.find("input[".concat(this.selectAllName, "]"));
                    this.$selectGroups = this.$drop.find("input[".concat(this.selectGroupName, "],span[").concat(this.selectGroupName, "]"));
                    this.$selectItems = this.$drop.find("input[".concat(this.selectItemName, "]:enabled"));
                    this.$disableItems = this.$drop.find("input[".concat(this.selectItemName, "]:disabled"));
                    this.$noResults = this.$drop.find('.ms-no-results');

                    var toggleOpen = function toggleOpen(e) {
                        e.preventDefault();

                        if ($(e.target).hasClass('icon-close')) {
                            return;
                        }

                        _this8[_this8.options.isOpen ? 'close' : 'open']();
                    };

                    if (this.$label && this.$label.length) {
                        this.$label.off('click').on('click', function (e) {
                            if (e.target.nodeName.toLowerCase() !== 'label') {
                                return;
                            }

                            toggleOpen(e);

                            if (!_this8.options.filter || !_this8.options.isOpen) {
                                _this8.focus();
                            }

                            e.stopPropagation(); // Causes lost focus otherwise
                        });
                    }

                    this.$choice.off('click').on('click', toggleOpen).off('focus').on('focus', this.options.onFocus).off('blur').on('blur', this.options.onBlur);
                    this.$parent.off('keydown').on('keydown', function (e) {
                        // esc key
                        if (e.which === 27 && !_this8.options.keepOpen) {
                            _this8.close();

                            _this8.$choice.focus();
                        }
                    });
                    this.$close.off('click').on('click', function (e) {
                        e.preventDefault();

                        _this8._checkAll(false, true);

                        _this8.initSelected(false);

                        _this8.updateSelected();

                        _this8.update();

                        _this8.options.onClear();
                    });
                    this.$searchInput.off('keydown').on('keydown', function (e) {
                        // Ensure shift-tab causes lost focus from filter as with clicking away
                        if (e.keyCode === 9 && e.shiftKey) {
                            _this8.close();
                        }
                    }).off('keyup').on('keyup', function (e) {
                        // enter or space
                        // Avoid selecting/deselecting if no choices made
                        if (_this8.options.filterAcceptOnEnter && [13, 32].includes(e.which) && _this8.$searchInput.val()) {
                            if (_this8.options.single) {
                                var $items = _this8.$selectItems.closest('li').filter(':visible');

                                if ($items.length) {
                                    _this8.setSelects([$items.first().find("input[".concat(_this8.selectItemName, "]")).val()]);
                                }
                            } else {
                                _this8.$selectAll.click();
                            }

                            _this8.close();

                            _this8.focus();

                            return;
                        }

                        _this8.filter();
                    });
                    this.$selectAll.off('click').on('click', function (e) {
                        _this8._checkAll($(e.currentTarget).prop('checked'));
                    });
                    this.$selectGroups.off('click').on('click', function (e) {
                        var $this = $(e.currentTarget);
                        var checked = $this.prop('checked');
                        var group = findByParam(_this8.data, '_key', $this.data('key'));

                        _this8._checkGroup(group, checked);

                        _this8.options.onOptgroupClick(removeUndefined({
                            label: group.label,
                            selected: group.selected,
                            data: group._data,
                            children: group.children.map(function (child) {
                                return removeUndefined({
                                    text: child.text,
                                    value: child.value,
                                    selected: child.selected,
                                    disabled: child.disabled,
                                    data: child._data
                                });
                            })
                        }));
                    });
                    this.$selectItems.off('click').on('click', function (e) {
                        var $this = $(e.currentTarget);
                        var checked = $this.prop('checked');
                        var option = findByParam(_this8.data, '_key', $this.data('key'));

                        _this8._check(option, checked);

                        _this8.options.onClick(removeUndefined({
                            text: option.text,
                            value: option.value,
                            selected: option.selected,
                            data: option._data
                        }));

                        if (_this8.options.single && _this8.options.isOpen && !_this8.options.keepOpen) {
                            _this8.close();
                        }
                    });
                }
            }, {
                key: "initView",
                value: function initView() {
                    var computedWidth;

                    if (window.getComputedStyle) {
                        computedWidth = window.getComputedStyle(this.$el[0]).width;

                        if (computedWidth === 'auto') {
                            computedWidth = this.$drop.outerWidth() + 20;
                        }
                    } else {
                        computedWidth = this.$el.outerWidth() + 20;
                    }

                    this.$parent.css('width', this.options.width || computedWidth);
                    this.$el.show().addClass('ms-offscreen');
                }
            }, {
                key: "open",
                value: function open() {
                    if (this.$choice.hasClass('disabled')) {
                        return;
                    }

                    this.options.isOpen = true;
                    this.$choice.find('>div').addClass('open');
                    this.$drop[this.animateMethod('show')](); // fix filter bug: no results show

                    this.$selectAll.parent().show();
                    this.$noResults.hide(); // Fix #77: 'All selected' when no options

                    if (!this.data.length) {
                        this.$selectAll.parent().hide();
                        this.$noResults.show();
                    }

                    if (this.options.container) {
                        var offset = this.$drop.offset();
                        this.$drop.appendTo($(this.options.container));
                        this.$drop.offset({
                            top: offset.top,
                            left: offset.left
                        }).css('min-width', 'auto').outerWidth(this.$parent.outerWidth());
                    }

                    var maxHeight = this.options.maxHeight;

                    if (this.options.maxHeightUnit === 'row') {
                        maxHeight = this.$drop.find('>ul>li').first().outerHeight() * this.options.maxHeight;
                    }

                    this.$drop.find('>ul').css('max-height', "".concat(maxHeight, "px"));
                    this.$drop.find('.multiple').css('width', "".concat(this.options.multipleWidth, "px"));

                    if (this.data.length && this.options.filter) {
                        this.$searchInput.val('');
                        this.$searchInput.focus();
                        this.filter(true);
                    }

                    this.options.onOpen();
                }
            }, {
                key: "close",
                value: function close() {
                    this.options.isOpen = false;
                    this.$choice.find('>div').removeClass('open');
                    this.$drop[this.animateMethod('hide')]();

                    if (this.options.container) {
                        this.$parent.append(this.$drop);
                        this.$drop.css({
                            'top': 'auto',
                            'left': 'auto'
                        });
                    }

                    this.options.onClose();
                }
            }, {
                key: "animateMethod",
                value: function animateMethod(method) {
                    var methods = {
                        show: {
                            fade: 'fadeIn',
                            slide: 'slideDown'
                        },
                        hide: {
                            fade: 'fadeOut',
                            slide: 'slideUp'
                        }
                    };
                    return methods[method][this.options.animate] || method;
                }
            }, {
                key: "update",
                value: function update(ignoreTrigger) {
                    var valueSelects = this.getSelects();
                    var textSelects = this.getSelects('text');

                    if (this.options.displayValues) {
                        textSelects = valueSelects;
                    }

                    var $span = this.$choice.find('>span');
                    var sl = valueSelects.length;
                    var html = '';

                    if (sl === 0) {
                        $span.addClass('placeholder').html(this.options.placeholder);
                    } else if (sl < this.options.minimumCountSelected) {
                        html = textSelects.join(this.options.displayDelimiter);
                    } else if (this.options.formatAllSelected() && sl === this.dataTotal) {
                        html = this.options.formatAllSelected();
                    } else if (this.options.ellipsis && sl > this.options.minimumCountSelected) {
                        html = "".concat(textSelects.slice(0, this.options.minimumCountSelected).join(this.options.displayDelimiter), "...");
                    } else if (this.options.formatCountSelected() && sl > this.options.minimumCountSelected) {
                        html = this.options.formatCountSelected(sl, this.dataTotal);
                    } else {
                        html = textSelects.join(this.options.displayDelimiter);
                    }

                    if (html) {
                        $span.removeClass('placeholder').html(html);
                    }

                    if (this.options.displayTitle) {
                        $span.prop('title', this.getSelects('text'));
                    } // set selects to select


                    this.$el.val(this.getSelects()); // trigger <select> change event

                    if (!ignoreTrigger) {
                        this.$el.trigger('change');
                    }
                }
            }, {
                key: "updateSelected",
                value: function updateSelected() {
                    for (var i = this.updateDataStart; i < this.updateDataEnd; i++) {
                        var row = this.updateData[i];
                        this.$drop.find("input[data-key=".concat(row._key, "]")).prop('checked', row.selected).closest('li').toggleClass('selected', row.selected);
                    }

                    var noResult = this.data.filter(function (row) {
                        return row.visible;
                    }).length === 0;

                    if (this.$selectAll.length) {
                        this.$selectAll.prop('checked', this.allSelected).closest('li').toggle(!noResult);
                    }

                    this.$noResults.toggle(noResult);

                    if (this.virtualScroll) {
                        this.virtualScroll.rows = this.getListRows();
                    }
                }
            }, {
                key: "getOptions",
                value: function getOptions() {
                    // deep copy and remove data
                    var options = $.extend({}, this.options);
                    delete options.data;
                    return $.extend(true, {}, options);
                }
            }, {
                key: "refreshOptions",
                value: function refreshOptions(options) {
                    // If the objects are equivalent then avoid the call of destroy / init methods
                    if (compareObjects(this.options, options, true)) {
                        return;
                    }

                    this.options = $.extend(this.options, options);
                    this.destroy();
                    this.init();
                } // value html, or text, default: 'value'

            }, {
                key: "getSelects",
                value: function getSelects() {
                    var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'value';
                    var values = [];
                    var _iteratorNormalCompletion3 = true;
                    var _didIteratorError3 = false;
                    var _iteratorError3 = undefined;

                    try {
                        for (var _iterator3 = this.data[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
                            var row = _step3.value;

                            if (row.type === 'optgroup') {
                                var selectedChildren = row.children.filter(function (child) {
                                    return child.selected;
                                });

                                if (!selectedChildren.length) {
                                    continue;
                                }

                                if (type === 'value' || this.options.single) {
                                    values.push.apply(values, _toConsumableArray(selectedChildren.map(function (child) {
                                        return type === 'value' ? child._value || child[type] : child[type];
                                    })));
                                } else {
                                    var value = [];
                                    value.push('[');
                                    value.push(row.label);
                                    value.push(": ".concat(selectedChildren.map(function (child) {
                                        return child[type];
                                    }).join(', ')));
                                    value.push(']');
                                    values.push(value.join(''));
                                }
                            } else if (row.selected) {
                                values.push(type === 'value' ? row._value || row[type] : row[type]);
                            }
                        }
                    } catch (err) {
                        _didIteratorError3 = true;
                        _iteratorError3 = err;
                    } finally {
                        try {
                            if (!_iteratorNormalCompletion3 && _iterator3.return != null) {
                                _iterator3.return();
                            }
                        } finally {
                            if (_didIteratorError3) {
                                throw _iteratorError3;
                            }
                        }
                    }

                    return values;
                }
            }, {
                key: "setSelects",
                value: function setSelects(values, ignoreTrigger) {
                    var hasChanged = false;

                    var _setSelects = function _setSelects(rows) {
                        var _iteratorNormalCompletion4 = true;
                        var _didIteratorError4 = false;
                        var _iteratorError4 = undefined;

                        try {
                            for (var _iterator4 = rows[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
                                var row = _step4.value;
                                var selected = values.includes(row._value || row.value);

                                if (!selected && row.value === +row.value + '') {
                                    selected = values.includes(+row.value);
                                }

                                if (row.selected !== selected) {
                                    hasChanged = true;
                                }

                                row.selected = selected;
                            }
                        } catch (err) {
                            _didIteratorError4 = true;
                            _iteratorError4 = err;
                        } finally {
                            try {
                                if (!_iteratorNormalCompletion4 && _iterator4.return != null) {
                                    _iterator4.return();
                                }
                            } finally {
                                if (_didIteratorError4) {
                                    throw _iteratorError4;
                                }
                            }
                        }
                    };

                    var _iteratorNormalCompletion5 = true;
                    var _didIteratorError5 = false;
                    var _iteratorError5 = undefined;

                    try {
                        for (var _iterator5 = this.data[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
                            var row = _step5.value;

                            if (row.type === 'optgroup') {
                                _setSelects(row.children);
                            } else {
                                _setSelects([row]);
                            }
                        }
                    } catch (err) {
                        _didIteratorError5 = true;
                        _iteratorError5 = err;
                    } finally {
                        try {
                            if (!_iteratorNormalCompletion5 && _iterator5.return != null) {
                                _iterator5.return();
                            }
                        } finally {
                            if (_didIteratorError5) {
                                throw _iteratorError5;
                            }
                        }
                    }

                    if (hasChanged) {
                        this.initSelected(ignoreTrigger);
                        this.updateSelected();
                        this.update(ignoreTrigger);
                    }
                }
            }, {
                key: "enable",
                value: function enable() {
                    this.$choice.removeClass('disabled');
                }
            }, {
                key: "disable",
                value: function disable() {
                    this.$choice.addClass('disabled');
                }
            }, {
                key: "check",
                value: function check(value) {
                    var option = findByParam(this.data, 'value', value);

                    if (!option) {
                        return;
                    }

                    this._check(option, true);
                }
            }, {
                key: "uncheck",
                value: function uncheck(value) {
                    var option = findByParam(this.data, 'value', value);

                    if (!option) {
                        return;
                    }

                    this._check(option, false);
                }
            }, {
                key: "_check",
                value: function _check(option, checked) {
                    if (this.options.single) {
                        this._checkAll(false, true);
                    }

                    option.selected = checked;
                    this.initSelected();
                    this.updateSelected();
                    this.update();
                }
            }, {
                key: "checkAll",
                value: function checkAll() {
                    this._checkAll(true);
                }
            }, {
                key: "uncheckAll",
                value: function uncheckAll() {
                    this._checkAll(false);
                }
            }, {
                key: "_checkAll",
                value: function _checkAll(checked, ignoreUpdate) {
                    var _iteratorNormalCompletion6 = true;
                    var _didIteratorError6 = false;
                    var _iteratorError6 = undefined;

                    try {
                        for (var _iterator6 = this.data[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
                            var row = _step6.value;

                            if (row.type === 'optgroup') {
                                this._checkGroup(row, checked, true);
                            } else if (!row.disabled && (ignoreUpdate || row.visible)) {
                                row.selected = checked;
                            }
                        }
                    } catch (err) {
                        _didIteratorError6 = true;
                        _iteratorError6 = err;
                    } finally {
                        try {
                            if (!_iteratorNormalCompletion6 && _iterator6.return != null) {
                                _iterator6.return();
                            }
                        } finally {
                            if (_didIteratorError6) {
                                throw _iteratorError6;
                            }
                        }
                    }

                    if (!ignoreUpdate) {
                        this.initSelected();
                        this.updateSelected();
                        this.update();
                    }
                }
            }, {
                key: "_checkGroup",
                value: function _checkGroup(group, checked, ignoreUpdate) {
                    group.selected = checked;
                    group.children.forEach(function (row) {
                        if (!row.disabled && (ignoreUpdate || row.visible)) {
                            row.selected = checked;
                        }
                    });

                    if (!ignoreUpdate) {
                        this.initSelected();
                        this.updateSelected();
                        this.update();
                    }
                }
            }, {
                key: "checkInvert",
                value: function checkInvert() {
                    if (this.options.single) {
                        return;
                    }

                    var _iteratorNormalCompletion7 = true;
                    var _didIteratorError7 = false;
                    var _iteratorError7 = undefined;

                    try {
                        for (var _iterator7 = this.data[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
                            var row = _step7.value;

                            if (row.type === 'optgroup') {
                                var _iteratorNormalCompletion8 = true;
                                var _didIteratorError8 = false;
                                var _iteratorError8 = undefined;

                                try {
                                    for (var _iterator8 = row.children[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
                                        var child = _step8.value;
                                        child.selected = !child.selected;
                                    }
                                } catch (err) {
                                    _didIteratorError8 = true;
                                    _iteratorError8 = err;
                                } finally {
                                    try {
                                        if (!_iteratorNormalCompletion8 && _iterator8.return != null) {
                                            _iterator8.return();
                                        }
                                    } finally {
                                        if (_didIteratorError8) {
                                            throw _iteratorError8;
                                        }
                                    }
                                }
                            } else {
                                row.selected = !row.selected;
                            }
                        }
                    } catch (err) {
                        _didIteratorError7 = true;
                        _iteratorError7 = err;
                    } finally {
                        try {
                            if (!_iteratorNormalCompletion7 && _iterator7.return != null) {
                                _iterator7.return();
                            }
                        } finally {
                            if (_didIteratorError7) {
                                throw _iteratorError7;
                            }
                        }
                    }

                    this.initSelected();
                    this.updateSelected();
                    this.update();
                }
            }, {
                key: "focus",
                value: function focus() {
                    this.$choice.focus();
                    this.options.onFocus();
                }
            }, {
                key: "blur",
                value: function blur() {
                    this.$choice.blur();
                    this.options.onBlur();
                }
            }, {
                key: "refresh",
                value: function refresh() {
                    this.destroy();
                    this.init();
                }
            }, {
                key: "filter",
                value: function filter(ignoreTrigger) {
                    var originalText = $.trim(this.$searchInput.val());
                    var text = originalText.toLowerCase();

                    if (this.filterText === text) {
                        return;
                    }

                    this.filterText = text;
                    var _iteratorNormalCompletion9 = true;
                    var _didIteratorError9 = false;
                    var _iteratorError9 = undefined;

                    try {
                        for (var _iterator9 = this.data[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
                            var row = _step9.value;

                            if (row.type === 'optgroup') {
                                if (this.options.filterGroup) {
                                    var visible = this.options.customFilter(removeDiacritics(row.label.toLowerCase()), removeDiacritics(text), row.label, originalText);
                                    row.visible = visible;
                                    var _iteratorNormalCompletion10 = true;
                                    var _didIteratorError10 = false;
                                    var _iteratorError10 = undefined;

                                    try {
                                        for (var _iterator10 = row.children[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
                                            var child = _step10.value;
                                            child.visible = visible;
                                        }
                                    } catch (err) {
                                        _didIteratorError10 = true;
                                        _iteratorError10 = err;
                                    } finally {
                                        try {
                                            if (!_iteratorNormalCompletion10 && _iterator10.return != null) {
                                                _iterator10.return();
                                            }
                                        } finally {
                                            if (_didIteratorError10) {
                                                throw _iteratorError10;
                                            }
                                        }
                                    }
                                } else {
                                    var _iteratorNormalCompletion11 = true;
                                    var _didIteratorError11 = false;
                                    var _iteratorError11 = undefined;

                                    try {
                                        for (var _iterator11 = row.children[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
                                            var _child = _step11.value;
                                            _child.visible = this.options.customFilter(removeDiacritics(_child.text.toLowerCase()), removeDiacritics(text), _child.text, originalText);
                                        }
                                    } catch (err) {
                                        _didIteratorError11 = true;
                                        _iteratorError11 = err;
                                    } finally {
                                        try {
                                            if (!_iteratorNormalCompletion11 && _iterator11.return != null) {
                                                _iterator11.return();
                                            }
                                        } finally {
                                            if (_didIteratorError11) {
                                                throw _iteratorError11;
                                            }
                                        }
                                    }

                                    row.visible = row.children.filter(function (child) {
                                        return child.visible;
                                    }).length > 0;
                                }
                            } else {
                                row.visible = this.options.customFilter(removeDiacritics(row.text.toLowerCase()), removeDiacritics(text), row.text, originalText);
                            }
                        }
                    } catch (err) {
                        _didIteratorError9 = true;
                        _iteratorError9 = err;
                    } finally {
                        try {
                            if (!_iteratorNormalCompletion9 && _iterator9.return != null) {
                                _iterator9.return();
                            }
                        } finally {
                            if (_didIteratorError9) {
                                throw _iteratorError9;
                            }
                        }
                    }

                    this.initListItems();
                    this.initSelected(ignoreTrigger);
                    this.updateSelected();

                    if (!ignoreTrigger) {
                        this.options.onFilter(text);
                    }
                }
            }, {
                key: "destroy",
                value: function destroy() {
                    if (!this.$parent) {
                        return;
                    }

                    this.$el.before(this.$parent).removeClass('ms-offscreen');

                    if (this.tabIndex !== null) {
                        this.$el.attr('tabindex', this.tabIndex);
                    }

                    this.$parent.remove();

                    if (this.fromHtml) {
                        delete this.options.data;
                        this.fromHtml = false;
                    }
                }
            }]);

            return MultipleSelect;
        }();

    $.fn.multipleSelect = function (option) {
        for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            args[_key - 1] = arguments[_key];
        }

        var value;
        this.each(function (i, el) {
            var $this = $(el);
            var data = $this.data('multipleSelect');
            var options = $.extend({}, $this.data(), _typeof(option) === 'object' && option);

            if (!data) {
                data = new MultipleSelect($this, options);
                $this.data('multipleSelect', data);
            }

            if (typeof option === 'string') {
                var _data;

                if ($.inArray(option, Constants.METHODS) < 0) {
                    throw new Error("Unknown method: ".concat(option));
                }

                value = (_data = data)[option].apply(_data, args);

                if (option === 'destroy') {
                    $this.removeData('multipleSelect');
                }
            } else {
                data.init();
            }
        });
        return typeof value !== 'undefined' ? value : this;
    };

    $.fn.multipleSelect.defaults = Constants.DEFAULTS;
    $.fn.multipleSelect.locales = Constants.LOCALES;
    $.fn.multipleSelect.methods = Constants.METHODS;

}));;
/*
 * FTWrapper
 * @desc Wrapper for Focus Trapper
 * @developer David Vo
 * @version 0.1
 */

/*
 * Event Listener Example
 * 
 * // Listen for Disabled
 * document.addEventListener('ftDisabled', function _listener() {
 *      // ADDITIONAL CODE HERE
 *      document.removeEventListener("ftDisabled", _listener, true);
 * }, false);
 * 
 */ 

class FTWrapper {


    /*
     * Constructor
     * @el {string} el ID/Class
     * @options {obj}
     * - lastFocus | false
     * - initFocus | false
     */
    constructor(el, options) {
        this.el = el;
        this.lastFocus = false;
        this.iframeSupport = false;
        this.ariaHide = "";
        this.dispatchEnabled = false;
        this.dispatchDisabled = false;
        this.dispatchEnabledEvent = '';
        this.dispatchDisabledEvent = '';
        this.focusableSelectors = "a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), [role='button']";
      
        if (options !== undefined) {
            if (typeof options.lastFocus === "boolean") {
                this.lastFocus = options.lastFocus;
            }

            if (typeof options.initFocus === "string") {
                this.initFocus = options.initFocus;
            }

            if (typeof options.iframeSupport === "boolean") {
                this.iframeSupport = options.iframeSupport;
            }

            if (typeof options.ariaHide === "string") {
                this.ariaHide = options.ariaHide;
            }

            if (typeof options.dispatchEnabledEvent === "string") {
                this.dispatchEnabled = true;
                this.dispatchEnabledEvent = options.dispatchEnabledEvent;
            }

            if (typeof options.dispatchDisabledEvent === "string") {
                this.dispatchDisabled = true;
                this.dispatchDisabledEvent = options.dispatchDisabledEvent;
            }

        }

        if (this.lastFocus) {
            this.lastEl = $(':focus');
        }
        this.enable();


        // L I S T E N E R S      

        $(this.el).on('click keydown', function (e) {
            if ($(this.el).hasClass('uk-open') === false && $(this.el).hasClass('active') === false) {
                $(this.el).off('click keydown');
                this.disable();
                clearInterval(this.iframeInterval);
            }
            // Kipsu Support
            else if ($(this.el).hasClass('active') === true && $(this.el).hasClass('min') === true) {
                $(this.el).off('click keydown');
                this.disable();
                clearInterval(this.iframeInterval);
            }

            this.keyDirection = e.shiftKey ? "backward" : "forward";
        }.bind(this));

        if (this.iframeSupport) {
            this.iframeInterval = window.setInterval(this.checkIFrameFocus.bind(this), 500); 
        }
    }

    /*
     * Check IFrame Focus
     */ 
    checkIFrameFocus() {
        if ($(document.activeElement).is('iframe')) {
            if (!$($(document.activeElement).next()).hasClass('iframe-exit')) {
                // attach exit node
                $(document.activeElement).after('<div class="iframe-exit" tabindex="0"></div>');
            }            
        }
        else if ($(document.activeElement).hasClass('iframe-exit')) {
            $(this.el).find(this.firstNode).focus();
            // remove exit node
            $(this.el).find('.iframe-exit').remove();
        }
    }

    /*
     * Find All Child Nodes
     */ 
    findAllChildNodes() {
        var focusableElements = $(this.el).find(this.focusableSelectors);
        this.firstNode = focusableElements[0];
        this.lastNode = focusableElements[focusableElements.length - 1];
    }

    /*
     * Enable
     */ 
    enable() {
        $(this.el).closest('focus-trapper').attr('trapped', true);
        this.findAllChildNodes();

        // initial focus
        if (this.initFocus) {
            setTimeout(function () {
                $(this.el).find(this.initFocus).focus();
            }.bind(this), 500);
        }

        // aria hide
        if (this.ariaHide.length > 0) {
            var ariaElementsArray = this.ariaHide.split(",");
            for (var i = 0; i < ariaElementsArray.length; i++) {
                $(ariaElementsArray[i]).attr('aria-hidden', 'true');
            }

            //var ariaElements = $(this.ariaHide);
            //$.each(ariaElements, function (index, val) {
            //    $(val).attr('aria-hidden', 'true');
            //});
        }

        // Dispatch the event
        if (this.dispatchEnabled) {
            document.dispatchEvent(new CustomEvent(this.dispatchEnabledEvent));
        }       
    }

    /*
     * Disable
     */ 
    disable() {
        $(this.el).closest('focus-trapper').removeAttr('trapped');

        // aria un-hide
        if (this.ariaHide.length > 0) {
            var ariaElementsArray = this.ariaHide.split(",");
            for (var i = 0; i < ariaElementsArray.length; i++) {
                $(ariaElementsArray[i]).removeAttr('aria-hidden');
            }

            //var ariaElements = $(this.ariaHide);
            //$.each(ariaElements, function (index, val) {
            //    $(val).removeAttr('aria-hidden');
            //});
        }

        // pre trap focus
        if (this.lastFocus) {
            this.lastEl.focus();
        }

        // Dispatch the event
        if (this.dispatchDisabled) {
            document.dispatchEvent(new CustomEvent(this.dispatchDisabled));
        }
        
    }
};
/*! UIkit 2.10.0 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */

!function(a){if("function"==typeof define&&define.amd&&define("uikit",function(){var b=a(window,window.jQuery,window.document);return b.load=function(a,c,d,e){var f,g=a.split(","),h=[],i=(e.config&&e.config.uikit&&e.config.uikit.base?e.config.uikit.base:"").replace(/\/+$/g,"");if(!i)throw new Error("Please define base path to UIkit in the requirejs config.");for(f=0;f<g.length;f+=1){var j=g[f].replace(/\./g,"/");h.push(i+"/js/addons/"+j)}c(h,function(){d(b)})},b}),!window.jQuery)throw new Error("UIkit requires jQuery");window&&window.jQuery&&a(window,window.jQuery,window.document)}(function(a,b,c){"use strict";var d=b.UIkit||{},e=b("html"),f=b(window),g=b(document);if(d.fn)return d;if(d.version="2.10.0",d.$doc=g,d.$win=f,d.fn=function(a,c){var e=arguments,f=a.match(/^([a-z\-]+)(?:\.([a-z]+))?/i),g=f[1],h=f[2];return d[g]?this.each(function(){var a=b(this),f=a.data(g);f||a.data(g,f=d[g](this,h?void 0:c)),h&&f[h].apply(f,Array.prototype.slice.call(e,1))}):(b.error("UIkit component ["+g+"] does not exist."),this)},d.support={},d.support.transition=function(){var a=function(){var a,b=c.body||c.documentElement,d={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(a in d)if(void 0!==b.style[a])return d[a]}();return a&&{end:a}}(),d.support.animation=function(){var a=function(){var a,b=c.body||c.documentElement,d={WebkitAnimation:"webkitAnimationEnd",MozAnimation:"animationend",OAnimation:"oAnimationEnd oanimationend",animation:"animationend"};for(a in d)if(void 0!==b.style[a])return d[a]}();return a&&{end:a}}(),d.support.requestAnimationFrame=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||function(a){setTimeout(a,1e3/60)},d.support.touch="ontouchstart"in window&&navigator.userAgent.toLowerCase().match(/mobile|tablet/)||a.DocumentTouch&&document instanceof a.DocumentTouch||a.navigator.msPointerEnabled&&a.navigator.msMaxTouchPoints>0||a.navigator.pointerEnabled&&a.navigator.maxTouchPoints>0||!1,d.support.mutationobserver=a.MutationObserver||a.WebKitMutationObserver||null,d.Utils={},d.Utils.debounce=function(a,b,c){var d;return function(){var e=this,f=arguments,g=function(){d=null,c||a.apply(e,f)},h=c&&!d;clearTimeout(d),d=setTimeout(g,b),h&&a.apply(e,f)}},d.Utils.removeCssRules=function(a){var b,c,d,e,f,g,h,i,j,k;a&&setTimeout(function(){try{for(k=document.styleSheets,e=0,h=k.length;h>e;e++){for(d=k[e],c=[],d.cssRules=d.cssRules,b=f=0,i=d.cssRules.length;i>f;b=++f)d.cssRules[b].type===CSSRule.STYLE_RULE&&a.test(d.cssRules[b].selectorText)&&c.unshift(b);for(g=0,j=c.length;j>g;g++)d.deleteRule(c[g])}}catch(l){}},0)},d.Utils.isInView=function(a,c){var d=b(a);if(!d.is(":visible"))return!1;var e=f.scrollLeft(),g=f.scrollTop(),h=d.offset(),i=h.left,j=h.top;return c=b.extend({topoffset:0,leftoffset:0},c),j+d.height()>=g&&j-c.topoffset<=g+f.height()&&i+d.width()>=e&&i-c.leftoffset<=e+f.width()?!0:!1},d.Utils.checkDisplay=function(a){b("[data-uk-margin], [data-uk-grid-match], [data-uk-grid-margin], [data-uk-check-display]",a||document).trigger("uk-check-display")},d.Utils.options=function(a){if(b.isPlainObject(a))return a;var c=a?a.indexOf("{"):-1,d={};if(-1!=c)try{d=new Function("","var json = "+a.substr(c)+"; return JSON.parse(JSON.stringify(json));")()}catch(e){}return d},d.Utils.template=function(a,b){for(var c,d,e,f,g=a.replace(/\n/g,"\\n").replace(/\{\{\{\s*(.+?)\s*\}\}\}/g,"{{!$1}}").split(/(\{\{\s*(.+?)\s*\}\})/g),h=0,i=[],j=0;h<g.length;){if(c=g[h],c.match(/\{\{\s*(.+?)\s*\}\}/))switch(h+=1,c=g[h],d=c[0],e=c.substring(c.match(/^(\^|\#|\!|\~|\:)/)?1:0),d){case"~":i.push("for(var $i=0;$i<"+e+".length;$i++) { var $item = "+e+"[$i];"),j++;break;case":":i.push("for(var $key in "+e+") { var $val = "+e+"[$key];"),j++;break;case"#":i.push("if("+e+") {"),j++;break;case"^":i.push("if(!"+e+") {"),j++;break;case"/":i.push("}"),j--;break;case"!":i.push("__ret.push("+e+");");break;default:i.push("__ret.push(escape("+e+"));")}else i.push("__ret.push('"+c.replace(/\'/g,"\\'")+"');");h+=1}f=["var __ret = [];","try {","with($data){",j?'__ret = ["Not all blocks are closed correctly."]':i.join(""),"};","}catch(e){__ret = [e.message];}",'return __ret.join("").replace(/\\n\\n/g, "\\n");',"function escape(html) { return String(html).replace(/&/g, '&amp;').replace(/\"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');}"].join("\n");var k=new Function("$data",f);return b?k(b):k},d.Utils.events={},d.Utils.events.click=d.support.touch?"tap":"click",b.UIkit=d,b.fn.uk=d.fn,b.UIkit.langdirection="rtl"==e.attr("dir")?"right":"left",d.domObservers=[],d.domObserve=function(a,c){d.support.mutationobserver&&b(a).each(function(){var a=this;try{var e=new d.support.mutationobserver(d.Utils.debounce(function(){c.apply(a,[]),b(a).trigger("uk.dom.changed")},50));e.observe(a,{childList:!0,subtree:!0})}catch(f){}})},d.ready=function(a){b(function(){a(document)}),d.domObservers.push(a)},g.on("uk.domready",function(){d.domObservers.forEach(function(a){a(document)}),g.trigger("uk.dom.changed")}),b(function(){setInterval(function(){var a={x:window.pageXOffset,y:window.pageYOffset},c=function(){(a.x!=window.pageXOffset||a.y!=window.pageYOffset)&&(a={x:window.pageXOffset,y:window.pageYOffset},g.trigger("uk-scroll",[a]))};return b.UIkit.support.touch&&g.on("touchmove touchend MSPointerMove MSPointerUp",c),(a.x||a.y)&&c(),c}(),15),d.domObserve("[data-uk-observe]",function(){var a=this;d.domObservers.forEach(function(b){b(a)})}),d.support.touch&&navigator.userAgent.match(/(iPad|iPhone|iPod)/g)&&d.$win.on("load orientationchange resize",d.Utils.debounce(function(){var a=function(){return b(".uk-height-viewport").css("height",window.innerHeight),a};return a()}(),100))}),e.addClass(d.support.touch?"uk-touch":"uk-notouch"),d.support.touch){var h,i=!1,j=".uk-overlay, .uk-overlay-toggle, .uk-has-hover";g.on("touchstart MSPointerDown",j,function(){i&&b(".uk-hover").removeClass("uk-hover"),i=b(this).addClass("uk-hover")}).on("touchend MSPointerUp",function(a){h=b(a.target).parents(j),i&&i.not(h).removeClass("uk-hover")})}return d}),function(a,b){"use strict";b.components={},b.component=function(c,d){var e=function(b,d){var f=this;this.element=b?a(b):null,this.options=a.extend(!0,{},this.defaults,d),this.plugins={},this.element&&this.element.data(c,this),this.init(),(this.options.plugins.length?this.options.plugins:Object.keys(e.plugins)).forEach(function(a){e.plugins[a].init&&(e.plugins[a].init(f),f.plugins[a]=!0)}),this.trigger("init",[this])};return e.plugins={},a.extend(!0,e.prototype,{defaults:{plugins:[]},init:function(){},on:function(){return a(this.element||this).on.apply(this.element||this,arguments)},one:function(){return a(this.element||this).one.apply(this.element||this,arguments)},off:function(b){return a(this.element||this).off(b)},trigger:function(b,c){return a(this.element||this).trigger(b,c)},find:function(b){return this.element?this.element.find(b):a([])},proxy:function(a,b){var c=this;b.split(" ").forEach(function(b){c[b]||(c[b]=function(){return a[b].apply(a,arguments)})})},mixin:function(a,b){var c=this;b.split(" ").forEach(function(b){c[b]||(c[b]=a[b].bind(c))})}},d),this.components[c]=e,this[c]=function(){var d,e;if(arguments.length)switch(arguments.length){case 1:"string"==typeof arguments[0]||arguments[0].nodeType||arguments[0]instanceof jQuery?d=a(arguments[0]):e=arguments[0];break;case 2:d=a(arguments[0]),e=arguments[1]}return d&&d.data(c)?d.data(c):new b.components[c](d,e)},e},b.plugin=function(a,b,c){this.components[a].plugins[b]=c}}(jQuery,jQuery.UIkit),function(a,b){"use strict";var c=[];b.component("stackMargin",{defaults:{cls:"uk-margin-small-top"},init:function(){var d=this;this.columns=this.element.children(),this.columns.length&&(b.$win.on("resize orientationchange",function(){var c=function(){d.process()};return a(function(){c(),b.$win.on("load",c)}),b.Utils.debounce(c,50)}()),b.$doc.on("uk.dom.changed",function(){d.columns=d.element.children(),d.process()}),this.on("uk-check-display",function(){this.element.is(":visible")&&this.process()}.bind(this)),c.push(this))},process:function(){var b=this;this.revert();var c=!1,d=this.columns.filter(":visible:first"),e=d.length?d.offset().top:!1;if(e!==!1)return this.columns.each(function(){var d=a(this);d.is(":visible")&&(c?d.addClass(b.options.cls):d.offset().top!=e&&(d.addClass(b.options.cls),c=!0))}),this},revert:function(){return this.columns.removeClass(this.options.cls),this}}),b.ready(function(c){a("[data-uk-margin]",c).each(function(){var c,d=a(this);d.data("stackMargin")||(c=b.stackMargin(d,b.Utils.options(d.attr("data-uk-margin"))))})})}(jQuery,jQuery.UIkit),function(a){function b(a,b,c,d){return Math.abs(a-b)>=Math.abs(c-d)?a-b>0?"Left":"Right":c-d>0?"Up":"Down"}function c(){j=null,l.last&&(l.el.trigger("longTap"),l={})}function d(){j&&clearTimeout(j),j=null}function e(){g&&clearTimeout(g),h&&clearTimeout(h),i&&clearTimeout(i),j&&clearTimeout(j),g=h=i=j=null,l={}}function f(a){return a.pointerType==a.MSPOINTER_TYPE_TOUCH&&a.isPrimary}var g,h,i,j,k,l={},m=750;a(function(){var n,o,p,q=0,r=0;"MSGesture"in window&&(k=new MSGesture,k.target=document.body),a(document).bind("MSGestureEnd",function(a){var b=a.originalEvent.velocityX>1?"Right":a.originalEvent.velocityX<-1?"Left":a.originalEvent.velocityY>1?"Down":a.originalEvent.velocityY<-1?"Up":null;b&&(l.el.trigger("swipe"),l.el.trigger("swipe"+b))}).on("touchstart MSPointerDown",function(b){("MSPointerDown"!=b.type||f(b.originalEvent))&&(p="MSPointerDown"==b.type?b:b.originalEvent.touches[0],n=Date.now(),o=n-(l.last||n),l.el=a("tagName"in p.target?p.target:p.target.parentNode),g&&clearTimeout(g),l.x1=p.pageX,l.y1=p.pageY,o>0&&250>=o&&(l.isDoubleTap=!0),l.last=n,j=setTimeout(c,m),k&&"MSPointerDown"==b.type&&k.addPointer(b.originalEvent.pointerId))}).on("touchmove MSPointerMove",function(a){("MSPointerMove"!=a.type||f(a.originalEvent))&&(p="MSPointerMove"==a.type?a:a.originalEvent.touches[0],d(),l.x2=p.pageX,l.y2=p.pageY,q+=Math.abs(l.x1-l.x2),r+=Math.abs(l.y1-l.y2))}).on("touchend MSPointerUp",function(c){("MSPointerUp"!=c.type||f(c.originalEvent))&&(d(),l.x2&&Math.abs(l.x1-l.x2)>30||l.y2&&Math.abs(l.y1-l.y2)>30?i=setTimeout(function(){l.el.trigger("swipe"),l.el.trigger("swipe"+b(l.x1,l.x2,l.y1,l.y2)),l={}},0):"last"in l&&(isNaN(q)||30>q&&30>r?h=setTimeout(function(){var b=a.Event("tap");b.cancelTouch=e,l.el.trigger(b),l.isDoubleTap?(l.el.trigger("doubleTap"),l={}):g=setTimeout(function(){g=null,l.el.trigger("singleTap"),l={}},250)},0):l={},q=r=0))}).on("touchcancel MSPointerCancel",e),a(window).on("scroll",e)}),["swipe","swipeLeft","swipeRight","swipeUp","swipeDown","doubleTap","tap","singleTap","longTap"].forEach(function(b){a.fn[b]=function(c){return a(this).on(b,c)}})}(jQuery),function(a,b){"use strict";b.component("alert",{defaults:{fade:!0,duration:200,trigger:".uk-alert-close"},init:function(){var a=this;this.on("click",this.options.trigger,function(b){b.preventDefault(),a.close()})},close:function(){function a(){b.trigger("closed").remove()}var b=this.trigger("close");this.options.fade?b.css("overflow","hidden").css("max-height",b.height()).animate({height:0,opacity:0,"padding-top":0,"padding-bottom":0,"margin-top":0,"margin-bottom":0},this.options.duration,a):a()}}),b.$doc.on("click.alert.uikit","[data-uk-alert]",function(c){var d=a(this);if(!d.data("alert")){var e=b.alert(d,b.Utils.options(d.data("uk-alert")));a(c.target).is(d.data("alert").options.trigger)&&(c.preventDefault(),e.close())}})}(jQuery,jQuery.UIkit),function(a,b){"use strict";b.component("buttonRadio",{defaults:{target:".uk-button"},init:function(){var b=this;this.on("click",this.options.target,function(c){a(this).is('a[href="#"]')&&c.preventDefault(),b.find(b.options.target).not(this).removeClass("uk-active").blur(),b.trigger("change",[a(this).addClass("uk-active")])})},getSelected:function(){return this.find(".uk-active")}}),b.component("buttonCheckbox",{defaults:{target:".uk-button"},init:function(){var b=this;this.on("click",this.options.target,function(c){a(this).is('a[href="#"]')&&c.preventDefault(),b.trigger("change",[a(this).toggleClass("uk-active").blur()])})},getSelected:function(){return this.find(".uk-active")}}),b.component("button",{defaults:{},init:function(){var a=this;this.on("click",function(b){a.element.is('a[href="#"]')&&b.preventDefault(),a.toggle(),a.trigger("change",[a.element.blur().hasClass("uk-active")])})},toggle:function(){this.element.toggleClass("uk-active")}}),b.$doc.on("click.buttonradio.uikit","[data-uk-button-radio]",function(c){var d=a(this);if(!d.data("buttonRadio")){var e=b.buttonRadio(d,b.Utils.options(d.attr("data-uk-button-radio")));a(c.target).is(e.options.target)&&a(c.target).trigger("click")}}),b.$doc.on("click.buttoncheckbox.uikit","[data-uk-button-checkbox]",function(c){var d=a(this);if(!d.data("buttonCheckbox")){var e=b.buttonCheckbox(d,b.Utils.options(d.attr("data-uk-button-checkbox"))),f=a(c.target);f.is(e.options.target)&&d.trigger("change",[f.toggleClass("uk-active").blur()])}}),b.$doc.on("click.button.uikit","[data-uk-button]",function(){var c=a(this);if(!c.data("button")){{b.button(c,b.Utils.options(c.attr("data-uk-button")))}c.trigger("click")}})}(jQuery,jQuery.UIkit),function(a,b){"use strict";var c,d=!1;b.component("dropdown",{defaults:{mode:"hover",remaintime:800,justify:!1,boundary:b.$win,delay:0},remainIdle:!1,init:function(){var e=this;this.dropdown=this.find(".uk-dropdown"),this.centered=this.dropdown.hasClass("uk-dropdown-center"),this.justified=this.options.justify?a(this.options.justify):!1,this.boundary=a(this.options.boundary),this.flipped=this.dropdown.hasClass("uk-dropdown-flip"),this.boundary.length||(this.boundary=b.$win),"click"==this.options.mode||b.support.touch?this.on("click",function(b){var c=a(b.target);c.parents(".uk-dropdown").length||((c.is("a[href='#']")||c.parent().is("a[href='#']"))&&b.preventDefault(),c.blur()),e.element.hasClass("uk-open")?(c.is("a:not(.js-uk-prevent)")||c.is(".uk-dropdown-close")||!e.dropdown.find(b.target).length)&&(e.element.removeClass("uk-open"),d=!1):e.show()}):this.on("mouseenter",function(){e.remainIdle&&clearTimeout(e.remainIdle),c&&clearTimeout(c),c=setTimeout(e.show.bind(e),e.options.delay)}).on("mouseleave",function(){c&&clearTimeout(c),e.remainIdle=setTimeout(function(){e.element.removeClass("uk-open"),e.remainIdle=!1,d&&d[0]==e.element[0]&&(d=!1)},e.options.remaintime)}).on("click",function(b){var c=a(b.target);e.remainIdle&&clearTimeout(e.remainIdle),(c.is("a[href='#']")||c.parent().is("a[href='#']"))&&b.preventDefault(),e.show()})},show:function(){d&&d[0]!=this.element[0]&&d.removeClass("uk-open"),c&&clearTimeout(c),this.checkDimensions(),this.element.addClass("uk-open"),this.trigger("uk.dropdown.show",[this]),b.Utils.checkDisplay(this.dropdown),d=this.element,this.registerOuterClick()},registerOuterClick:function(){var e=this;b.$doc.off("click.outer.dropdown"),setTimeout(function(){b.$doc.on("click.outer.dropdown",function(f){c&&clearTimeout(c);var g=a(f.target);d&&d[0]==e.element[0]&&(g.is("a:not(.js-uk-prevent)")||g.is(".uk-dropdown-close")||!e.dropdown.find(f.target).length)&&(d.removeClass("uk-open"),b.$doc.off("click.outer.dropdown"))})},10)},checkDimensions:function(){if(this.dropdown.length){this.justified&&this.justified.length&&this.dropdown.css("min-width","");var b=this,c=this.dropdown.css("margin-"+a.UIkit.langdirection,""),d=c.show().offset(),e=c.outerWidth(),f=this.boundary.width(),g=this.boundary.offset()?this.boundary.offset().left:0;if(this.centered&&(c.css("margin-"+a.UIkit.langdirection,-1*(parseFloat(e)/2-c.parent().width()/2)),d=c.offset(),(e+d.left>f||d.left<0)&&(c.css("margin-"+a.UIkit.langdirection,""),d=c.offset())),this.justified&&this.justified.length){var h=this.justified.outerWidth();if(c.css("min-width",h),"right"==a.UIkit.langdirection){var i=f-(this.justified.offset().left+h),j=f-(c.offset().left+c.outerWidth());c.css("margin-right",i-j)}else c.css("margin-left",this.justified.offset().left-d.left);d=c.offset()}e+(d.left-g)>f&&(c.addClass("uk-dropdown-flip"),d=c.offset()),d.left-g<0&&(c.addClass("uk-dropdown-stack"),c.hasClass("uk-dropdown-flip")&&(this.flipped||(c.removeClass("uk-dropdown-flip"),d=c.offset(),c.addClass("uk-dropdown-flip")),setTimeout(function(){(c.offset().left-g<0||!b.flipped&&c.outerWidth()+(d.left-g)<f)&&c.removeClass("uk-dropdown-flip")},0)),this.trigger("uk.dropdown.stack",[this])),c.css("display","")}}});var e=b.support.touch?"click":"mouseenter";b.$doc.on(e+".dropdown.uikit","[data-uk-dropdown]",function(c){var d=a(this);if(!d.data("dropdown")){var f=b.dropdown(d,b.Utils.options(d.data("uk-dropdown")));("click"==e||"mouseenter"==e&&"hover"==f.options.mode)&&f.element.trigger(e),f.element.find(".uk-dropdown").length&&c.preventDefault()}})}(jQuery,jQuery.UIkit),function(a,b){"use strict";var c=[];b.component("gridMatchHeight",{defaults:{target:!1,row:!0},init:function(){var d=this;this.columns=this.element.children(),this.elements=this.options.target?this.find(this.options.target):this.columns,this.columns.length&&(b.$win.on("resize orientationchange",function(){var c=function(){d.match()};return a(function(){c(),b.$win.on("load",c)}),b.Utils.debounce(c,50)}()),b.$doc.on("uk.dom.changed",function(){d.columns=d.element.children(),d.elements=d.options.target?d.find(d.options.target):d.columns,d.match()}),this.on("uk-check-display",function(){this.element.is(":visible")&&this.match()}.bind(this)),c.push(this))},match:function(){this.revert();var b=this.columns.filter(":visible:first");if(b.length){var c=Math.ceil(100*parseFloat(b.css("width"))/parseFloat(b.parent().css("width")))>=100?!0:!1,d=this;if(!c)return this.options.row?(this.element.width(),setTimeout(function(){var b=!1,c=[];d.elements.each(function(){var e=a(this),f=e.offset().top;f!=b&&c.length&&(d.matchHeights(a(c)),c=[],f=e.offset().top),c.push(e),b=f}),c.length&&d.matchHeights(a(c))},0)):this.matchHeights(this.elements),this}},revert:function(){return this.elements.css("min-height",""),this},matchHeights:function(b){if(!(b.length<2)){var c=0;b.each(function(){c=Math.max(c,a(this).outerHeight())}).each(function(){var b=a(this),d=c-(b.outerHeight()-b.height());b.css("min-height",d+"px")})}}}),b.component("gridMargin",{defaults:{cls:"uk-grid-margin"},init:function(){b.stackMargin(this.element,this.options)}}),b.ready(function(c){a("[data-uk-grid-match],[data-uk-grid-margin]",c).each(function(){var c,d=a(this);d.is("[data-uk-grid-match]")&&!d.data("gridMatchHeight")&&(c=b.gridMatchHeight(d,b.Utils.options(d.attr("data-uk-grid-match")))),d.is("[data-uk-grid-margin]")&&!d.data("gridMargin")&&(c=b.gridMargin(d,b.Utils.options(d.attr("data-uk-grid-margin"))))})})}(jQuery,jQuery.UIkit),function(a,b){"use strict";function c(b,c){return c?("object"==typeof b?(b=b instanceof jQuery?b:a(b),b.parent().length&&(c.persist=b,c.persist.data("modalPersistParent",b.parent()))):b=a("<div></div>").html("string"==typeof b||"number"==typeof b?b:"$.UIkitt.modal Error: Unsupported data type: "+typeof b),b.appendTo(c.element.find(".uk-modal-dialog")),c):void 0}var d,e=!1,f=a("html");b.component("modal",{defaults:{keyboard:!0,bgclose:!0,minScrollHeight:150},scrollable:!1,transition:!1,init:function(){d||(d=a("body"));var c=this;this.transition=b.support.transition,this.dialog=this.find(".uk-modal-dialog"),this.on("click",".uk-modal-close",function(a){a.preventDefault(),c.hide()}).on("click",function(b){var d=a(b.target);d[0]==c.element[0]&&c.options.bgclose&&c.hide()})},toggle:function(){return this[this.isActive()?"hide":"show"]()},show:function(){if(!this.isActive())return e&&e.hide(!0),this.element.removeClass("uk-open").show(),this.resize(),e=this,f.addClass("uk-modal-page").height(),this.element.addClass("uk-open").trigger("uk.modal.show"),b.Utils.checkDisplay(this.dialog),this},hide:function(a){if(this.isActive()){if(!a&&b.support.transition){var c=this;this.one(b.support.transition.end,function(){c._hide()}).removeClass("uk-open")}else this._hide();return this}},resize:function(){var a="padding-"+("left"==b.langdirection?"left":"right"),c="margin-"+("left"==b.langdirection?"left":"right"),e=d.width();this.scrollbarwidth=window.innerWidth-e,f.css(c,-1*this.scrollbarwidth),this.element.css(a,""),this.dialog.offset().left>this.scrollbarwidth&&this.element.css(a,this.scrollbarwidth-(this.element[0].scrollHeight==window.innerHeight?0:this.scrollbarwidth)),this.updateScrollable()},updateScrollable:function(){var a=this.dialog.find(".uk-overflow-container:visible:first");if(a){a.css("height",0);var b=Math.abs(parseInt(this.dialog.css("margin-top"),10)),c=this.dialog.outerHeight(),d=window.innerHeight,e=d-2*(20>b?20:b)-c;a.css("height",e<this.options.minScrollHeight?"":e)}},_hide:function(){this.element.hide().removeClass("uk-open"),f.removeClass("uk-modal-page").css("margin-"+("left"==b.langdirection?"left":"right"),""),e===this&&(e=!1),this.trigger("uk.modal.hide")},isActive:function(){return e==this}}),b.component("modalTrigger",{init:function(){var c=this;this.options=a.extend({target:c.element.is("a")?c.element.attr("href"):!1},this.options),this.modal=b.modal(this.options.target,this.options),this.on("click",function(a){a.preventDefault(),c.show()}),this.proxy(this.modal,"show hide isActive")}}),b.modal.dialog=function(d,e){var f=b.modal(a(b.modal.dialog.template).appendTo("body"),e);return f.on("uk.modal.hide",function(){f.persist&&(f.persist.appendTo(f.persist.data("modalPersistParent")),f.persist=!1),f.element.remove()}),c(d,f),f},b.modal.dialog.template='<div class="uk-modal"><div class="uk-modal-dialog"></div></div>',b.modal.alert=function(c,d){b.modal.dialog(['<div class="uk-margin uk-modal-content">'+String(c)+"</div>",'<div class="uk-modal-buttons"><button class="uk-button uk-button-primary uk-modal-close">Ok</button></div>'].join(""),a.extend({bgclose:!1,keyboard:!1},d)).show()},b.modal.confirm=function(c,d,e){d=a.isFunction(d)?d:function(){};var f=b.modal.dialog(['<div class="uk-margin uk-modal-content">'+String(c)+"</div>",'<div class="uk-modal-buttons"><button class="uk-button uk-button-primary js-modal-confirm">Ok</button> <button class="uk-button uk-modal-close">Cancel</button></div>'].join(""),a.extend({bgclose:!1,keyboard:!1},e));f.element.find(".js-modal-confirm").on("click",function(){d(),f.hide()}),f.show()},b.$doc.on("click.modal.uikit","[data-uk-modal]",function(c){var d=a(this);if(d.is("a")&&c.preventDefault(),!d.data("modalTrigger")){var e=b.modalTrigger(d,b.Utils.options(d.attr("data-uk-modal")));e.show()}}),b.$doc.on("keydown.modal.uikit",function(a){e&&27===a.keyCode&&e.options.keyboard&&(a.preventDefault(),e.hide())}),b.$win.on("resize orientationchange",b.Utils.debounce(function(){e&&e.resize()},150))}(jQuery,jQuery.UIkit),function(a,b){"use strict";var c={x:window.scrollX,y:window.scrollY},d=b.$win,e=b.$doc,f=a("html"),g={show:function(b){if(b=a(b),b.length){var h=a("body"),i=(d.width(),b.find(".uk-offcanvas-bar:first")),j="right"==a.UIkit.langdirection,k=i.hasClass("uk-offcanvas-bar-flip")?-1:1,l=k*(j?-1:1);c={x:window.pageXOffset,y:window.pageYOffset},b.addClass("uk-active"),h.css({width:window.innerWidth,height:d.height()}).addClass("uk-offcanvas-page"),h.css(j?"margin-right":"margin-left",(j?-1:1)*i.outerWidth()*l).width(),f.css("margin-top",-1*c.y),i.addClass("uk-offcanvas-bar-show"),b.off(".ukoffcanvas").on("click.ukoffcanvas swipeRight.ukoffcanvas swipeLeft.ukoffcanvas",function(b){var c=a(b.target);if(!b.type.match(/swipe/)&&!c.hasClass("uk-offcanvas-close")){if(c.hasClass("uk-offcanvas-bar"))return;if(c.parents(".uk-offcanvas-bar:first").length)return}b.stopImmediatePropagation(),g.hide()}),e.on("keydown.ukoffcanvas",function(a){27===a.keyCode&&g.hide()}),e.trigger("uk.offcanvas.show",[b,i])}},hide:function(b){var d=a("body"),g=a(".uk-offcanvas.uk-active"),h="right"==a.UIkit.langdirection,i=g.find(".uk-offcanvas-bar:first"),j=function(){d.removeClass("uk-offcanvas-page").css({width:"",height:"","margin-left":"","margin-right":""}),g.removeClass("uk-active"),i.removeClass("uk-offcanvas-bar-show"),f.css("margin-top",""),window.scrollTo(c.x,c.y),e.trigger("uk.offcanvas.hide",[g,i])};g.length&&(a.UIkit.support.transition&&!b?(d.one(a.UIkit.support.transition.end,function(){j()}).css(h?"margin-right":"margin-left",""),setTimeout(function(){i.removeClass("uk-offcanvas-bar-show")},0)):j(),g.off(".ukoffcanvas"),e.off(".ukoffcanvas"))}};b.component("offcanvasTrigger",{init:function(){var b=this;this.options=a.extend({target:b.element.is("a")?b.element.attr("href"):!1},this.options),this.on("click",function(a){a.preventDefault(),g.show(b.options.target)})}}),b.offcanvas=g,e.on("click.offcanvas.uikit","[data-uk-offcanvas]",function(c){c.preventDefault();var d=a(this);if(!d.data("offcanvasTrigger")){{b.offcanvasTrigger(d,b.Utils.options(d.attr("data-uk-offcanvas")))}d.trigger("click")}})}(jQuery,jQuery.UIkit),function(a,b){"use strict";function c(b){var c=a(b),d="auto";if(c.is(":visible"))d=c.outerHeight();else{var e={position:c.css("position"),visibility:c.css("visibility"),display:c.css("display")};d=c.css({position:"absolute",visibility:"hidden",display:"block"}).outerHeight(),c.css(e)}return d}b.component("nav",{defaults:{toggle:">li.uk-parent > a[href='#']",lists:">li.uk-parent > ul",multiple:!1},init:function(){var b=this;this.on("click",this.options.toggle,function(c){c.preventDefault();var d=a(this);b.open(d.parent()[0]==b.element[0]?d:d.parent("li"))}),this.find(this.options.lists).each(function(){var c=a(this),d=c.parent(),e=d.hasClass("uk-active");c.wrap('<div style="overflow:hidden;height:0;position:relative;"></div>'),d.data("list-container",c.parent()),e&&b.open(d,!0)})},open:function(b,d){var e=this.element,f=a(b);this.options.multiple||e.children(".uk-open").not(b).each(function(){a(this).data("list-container")&&a(this).data("list-container").stop().animate({height:0},function(){a(this).parent().removeClass("uk-open")})}),f.toggleClass("uk-open"),f.data("list-container")&&(d?f.data("list-container").stop().height(f.hasClass("uk-open")?"auto":0):f.data("list-container").stop().animate({height:f.hasClass("uk-open")?c(f.data("list-container").find("ul:first")):0}))}}),b.ready(function(c){a("[data-uk-nav]",c).each(function(){var c=a(this);if(!c.data("nav")){b.nav(c,b.Utils.options(c.attr("data-uk-nav")))}})})}(jQuery,jQuery.UIkit),function(a,b,c){"use strict";var d,e,f;b.component("tooltip",{defaults:{offset:5,pos:"top",animation:!1,delay:0,cls:"",src:function(){return this.attr("title")}},tip:"",init:function(){var b=this;d||(d=a('<div class="uk-tooltip"></div>').appendTo("body")),this.on({focus:function(){b.show()},blur:function(){b.hide()},mouseenter:function(){b.show()},mouseleave:function(){b.hide()}}),this.tip="function"==typeof this.options.src?this.options.src.call(this.element):this.options.src,this.element.attr("data-cached-title",this.element.attr("title")).attr("title","")},show:function(){if(e&&clearTimeout(e),f&&clearTimeout(f),this.tip.length){d.stop().css({top:-2e3,visibility:"hidden"}).show(),d.html('<div class="uk-tooltip-inner">'+this.tip+"</div>");var b=this,c=a.extend({},this.element.offset(),{width:this.element[0].offsetWidth,height:this.element[0].offsetHeight}),g=d[0].offsetWidth,h=d[0].offsetHeight,i="function"==typeof this.options.offset?this.options.offset.call(this.element):this.options.offset,j="function"==typeof this.options.pos?this.options.pos.call(this.element):this.options.pos,k=j.split("-"),l={display:"none",visibility:"visible",top:c.top+c.height+h,left:c.left};if("fixed"==a("html").css("position")||"fixed"==a("body").css("position")){var m=a("body").offset(),n=a("html").offset(),o={top:n.top+m.top,left:n.left+m.left};c.left-=o.left,c.top-=o.top}"left"!=k[0]&&"right"!=k[0]||"right"!=a.UIkit.langdirection||(k[0]="left"==k[0]?"right":"left");var p={bottom:{top:c.top+c.height+i,left:c.left+c.width/2-g/2},top:{top:c.top-h-i,left:c.left+c.width/2-g/2},left:{top:c.top+c.height/2-h/2,left:c.left-g-i},right:{top:c.top+c.height/2-h/2,left:c.left+c.width+i}};a.extend(l,p[k[0]]),2==k.length&&(l.left="left"==k[1]?c.left:c.left+c.width-g);var q=this.checkBoundary(l.left,l.top,g,h);if(q){switch(q){case"x":j=2==k.length?k[0]+"-"+(l.left<0?"left":"right"):l.left<0?"right":"left";break;case"y":j=2==k.length?(l.top<0?"bottom":"top")+"-"+k[1]:l.top<0?"bottom":"top";break;case"xy":j=2==k.length?(l.top<0?"bottom":"top")+"-"+(l.left<0?"left":"right"):l.left<0?"right":"left"}k=j.split("-"),a.extend(l,p[k[0]]),2==k.length&&(l.left="left"==k[1]?c.left:c.left+c.width-g)}l.left-=a("body").position().left,e=setTimeout(function(){d.css(l).attr("class",["uk-tooltip","uk-tooltip-"+j,b.options.cls].join(" ")),b.options.animation?d.css({opacity:0,display:"block"}).animate({opacity:1},parseInt(b.options.animation,10)||400):d.show(),e=!1,f=setInterval(function(){b.element.is(":visible")||b.hide()},150)},parseInt(this.options.delay,10)||0)}},hide:function(){this.element.is("input")&&this.element[0]===document.activeElement||(e&&clearTimeout(e),f&&clearTimeout(f),d.stop(),this.options.animation?d.fadeOut(parseInt(this.options.animation,10)||400):d.hide())},content:function(){return this.tip},checkBoundary:function(a,b,d,e){var f="";return(0>a||a-c.scrollLeft()+d>window.innerWidth)&&(f+="x"),(0>b||b-c.scrollTop()+e>window.innerHeight)&&(f+="y"),f}}),b.$doc.on("mouseenter.tooltip.uikit focus.tooltip.uikit","[data-uk-tooltip]",function(){var c=a(this);if(!c.data("tooltip")){{b.tooltip(c,b.Utils.options(c.attr("data-uk-tooltip")))}c.trigger("mouseenter")}})}(jQuery,jQuery.UIkit,jQuery(window)),function(a,b){"use strict";b.component("switcher",{defaults:{connect:!1,toggle:">*",active:0},init:function(){var b=this;if(this.on("click",this.options.toggle,function(a){a.preventDefault(),b.show(this)}),this.options.connect){this.connect=a(this.options.connect).find(".uk-active").removeClass(".uk-active").end(),this.connect.length&&this.connect.on("click","[data-uk-switcher-item]",function(c){c.preventDefault();var d=a(this).data("ukSwitcherItem");if(b.index!=d)switch(d){case"next":case"previous":b.show(b.index+("next"==d?1:-1));break;default:b.show(d)}});var c=this.find(this.options.toggle),d=c.filter(".uk-active");d.length?this.show(d):(d=c.eq(this.options.active),this.show(d.length?d:c.eq(0)))}},show:function(c){c=isNaN(c)?a(c):this.find(this.options.toggle).eq(c);var d=this,e=c;e.hasClass("uk-disabled")||(this.find(this.options.toggle).filter(".uk-active").removeClass("uk-active"),e.addClass("uk-active"),this.options.connect&&this.connect.length&&(this.index=this.find(this.options.toggle).index(e),-1==this.index&&(this.index=0),this.connect.each(function(){a(this).children().removeClass("uk-active").eq(d.index).addClass("uk-active"),b.Utils.checkDisplay(this)})),this.trigger("uk.switcher.show",[e]))}}),b.ready(function(c){a("[data-uk-switcher]",c).each(function(){var c=a(this);if(!c.data("switcher")){b.switcher(c,b.Utils.options(c.attr("data-uk-switcher")))}})})}(jQuery,jQuery.UIkit),function(a,b){"use strict";b.component("tab",{defaults:{target:">li:not(.uk-tab-responsive, .uk-disabled)",connect:!1,active:0},init:function(){var c=this;this.on("click",this.options.target,function(b){b.preventDefault(),c.find(c.options.target).not(this).removeClass("uk-active").blur(),c.trigger("uk.tab.change",[a(this).addClass("uk-active")])}),this.options.connect&&(this.connect=a(this.options.connect)),this.responsivetab=a('<li class="uk-tab-responsive uk-active"><a></a></li>').append('<div class="uk-dropdown uk-dropdown-small"><ul class="uk-nav uk-nav-dropdown"></ul><div>'),this.responsivetab.dropdown=this.responsivetab.find(".uk-dropdown"),this.responsivetab.lst=this.responsivetab.dropdown.find("ul"),this.responsivetab.caption=this.responsivetab.find("a:first"),this.element.hasClass("uk-tab-bottom")&&this.responsivetab.dropdown.addClass("uk-dropdown-up"),this.responsivetab.lst.on("click","a",function(b){b.preventDefault(),b.stopPropagation();
var d=a(this);c.element.children(":not(.uk-tab-responsive)").eq(d.data("index")).trigger("click")}),this.on("uk.switcher.show uk.tab.change",function(a,b){c.responsivetab.caption.html(b.text())}),this.element.append(this.responsivetab),this.options.connect&&b.switcher(this.element,{toggle:">li:not(.uk-tab-responsive)",connect:this.options.connect,active:this.options.active}),b.dropdown(this.responsivetab,{mode:"click"}),c.trigger("uk.tab.change",[this.element.find(this.options.target).filter(".uk-active")]),this.check(),b.$win.on("resize orientationchange",b.Utils.debounce(function(){c.check()},100))},check:function(){var b=this.element.children(":not(.uk-tab-responsive)").removeClass("uk-hidden");if(!(b.length<2)){var c,d,e=b.eq(0).offset().top+Math.ceil(b.eq(0).height()/2),f=!1;if(this.responsivetab.lst.empty(),b.each(function(){a(this).offset().top>e&&(f=!0)}),f)for(var g=0;g<b.length;g++)c=b.eq(g),d=c.find("a"),"none"==c.css("float")||c.attr("uk-dropdown")||(c.addClass("uk-hidden"),c.hasClass("uk-disabled")||this.responsivetab.lst.append('<li><a href="'+d.attr("href")+'" data-index="'+g+'">'+d.html()+"</a></li>"));this.responsivetab[this.responsivetab.lst.children().length?"removeClass":"addClass"]("uk-hidden")}}}),b.ready(function(c){a("[data-uk-tab]",c).each(function(){var c=a(this);if(!c.data("tab")){b.tab(c,b.Utils.options(c.attr("data-uk-tab")))}})})}(jQuery,jQuery.UIkit),function(a,b){"use strict";var c=b.$win,d=b.$doc,e=[],f=function(){for(var a=0;a<e.length;a++)b.support.requestAnimationFrame.apply(window,[e[a].check])};b.component("scrollspy",{defaults:{cls:"uk-scrollspy-inview",initcls:"uk-scrollspy-init-inview",topoffset:0,leftoffset:0,repeat:!1,delay:0},init:function(){var a,c,d,f=this,g=function(){var e=b.Utils.isInView(f.element,f.options);e&&!c&&(a&&clearTimeout(a),d||(f.element.addClass(f.options.initcls),f.offset=f.element.offset(),d=!0,f.trigger("uk.scrollspy.init")),a=setTimeout(function(){e&&f.element.addClass("uk-scrollspy-inview").addClass(f.options.cls).width()},f.options.delay),c=!0,f.trigger("uk.scrollspy.inview")),!e&&c&&f.options.repeat&&(f.element.removeClass("uk-scrollspy-inview").removeClass(f.options.cls),c=!1,f.trigger("uk.scrollspy.outview"))};g(),this.check=g,e.push(this)}});var g=[],h=function(){for(var a=0;a<g.length;a++)b.support.requestAnimationFrame.apply(window,[g[a].check])};b.component("scrollspynav",{defaults:{cls:"uk-active",closest:!1,topoffset:0,leftoffset:0,smoothscroll:!1},init:function(){var d,e=[],f=this.find("a[href^='#']").each(function(){e.push(a(this).attr("href"))}),h=a(e.join(",")),i=this,j=function(){d=[];for(var a=0;a<h.length;a++)b.Utils.isInView(h.eq(a),i.options)&&d.push(h.eq(a));if(d.length){var e=c.scrollTop(),g=function(){for(var a=0;a<d.length;a++)if(d[a].offset().top>=e)return d[a]}();if(!g)return;i.options.closest?f.closest(i.options.closest).removeClass(i.options.cls).end().filter("a[href='#"+g.attr("id")+"']").closest(i.options.closest).addClass(i.options.cls):f.removeClass(i.options.cls).filter("a[href='#"+g.attr("id")+"']").addClass(i.options.cls)}};this.options.smoothscroll&&b.smoothScroll&&f.each(function(){b.smoothScroll(this,i.options.smoothscroll)}),j(),this.element.data("scrollspynav",this),this.check=j,g.push(this)}});var i=function(){f(),h()};d.on("uk-scroll",i),c.on("resize orientationchange",b.Utils.debounce(i,50)),b.ready(function(c){a("[data-uk-scrollspy]",c).each(function(){var c=a(this);if(!c.data("scrollspy")){b.scrollspy(c,b.Utils.options(c.attr("data-uk-scrollspy")))}}),a("[data-uk-scrollspy-nav]",c).each(function(){var c=a(this);if(!c.data("scrollspynav")){b.scrollspynav(c,b.Utils.options(c.attr("data-uk-scrollspy-nav")))}})})}(jQuery,jQuery.UIkit),function(a,b){"use strict";b.component("smoothScroll",{defaults:{duration:1e3,transition:"easeOutExpo",offset:0,complete:function(){}},init:function(){var c=this;this.on("click",function(){{var d=a(a(this.hash).length?this.hash:"body"),e=d.offset().top-c.options.offset,f=b.$doc.height(),g=b.$win.height();d.outerHeight()}return e+g>f&&(e=f-g),a("html,body").stop().animate({scrollTop:e},c.options.duration,c.options.transition).promise().done(c.options.complete),!1})}}),a.easing.easeOutExpo||(a.easing.easeOutExpo=function(a,b,c,d,e){return b==e?c+d:d*(-Math.pow(2,-10*b/e)+1)+c}),b.$doc.on("click.smooth-scroll.uikit","[data-uk-smooth-scroll]",function(){var c=a(this);if(!c.data("smoothScroll")){{b.smoothScroll(c,b.Utils.options(c.attr("data-uk-smooth-scroll")))}c.trigger("click")}return!1})}(jQuery,jQuery.UIkit),function(a,b,c){var d=[];c.component("toggle",{defaults:{target:!1,cls:"uk-hidden"},init:function(){var a=this;this.getTogglers(),this.on("click",function(b){a.element.is('a[href="#"]')&&b.preventDefault(),a.toggle()}),d.push(this)},toggle:function(){this.totoggle.length&&(this.totoggle.toggleClass(this.options.cls),"uk-hidden"==this.options.cls&&c.Utils.checkDisplay(this.totoggle))},getTogglers:function(){this.totoggle=this.options.target?b(this.options.target):[]}}),c.ready(function(a){b("[data-uk-toggle]",a).each(function(){var a=b(this);if(!a.data("toggle")){c.toggle(a,c.Utils.options(a.attr("data-uk-toggle")))}}),setTimeout(function(){d.forEach(function(a){a.getTogglers()})},0)})}(this,jQuery,jQuery.UIkit);;
/*
 * Media Query
 * Matches Bootstrap Grid
 */
const _MEDIAQUERY = {
    "max-sm": "(max-width: 575.98px)",
    "max-md": "(max-width: 767.98px)",
    "max-lg": "(max-width: 991.98px)",
    "max-xl": "(max-width: 1199.98px)",
    "max-xxl": "(max-width: 1399.98px)",
    "min-sm": "(min-width: 576px)",
    "min-md": "(min-width: 768px)",
    "min-lg": "(min-width: 992px)",
    "min-xl": "(min-width: 1200px)",
    "min-xxl": "(min-width: 1400px)"
};

/*
 * Custom Events
 */
const hamburgerShowEvent = new CustomEvent('hamburgerNavEvent', {
    detail: {
        name: "show",
    }
});
const hamburgerHideEvent = new CustomEvent('hamburgerNavEvent', {
    detail: {
        name: "hide",
    }
});
const hamburgerHiddenEvent = new CustomEvent('hamburgerNavEvent', {
    detail: {
        name: "hidden",
    }
});
const hamburgerShownEvent = new CustomEvent('hamburgerNavEvent', {
    detail: {
        name: "shown",
    }
});
const footerEnterEvent = new CustomEvent('footerEvent', {
    detail: {
        name: "enter",
    }
});
const footerEnteredEvent = new CustomEvent('footerEvent', {
    detail: {
        name: "entered",
    }
});
const footerExitEvent = new CustomEvent('footerEvent', {
    detail: {
        name: "exit",
    }
});
const footerExitedEvent = new CustomEvent('footerEvent', {
    detail: {
        name: "exited",
    }
});
const chatMaximizeEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "widget",
        value: "maximized",
    }
});
const chatMinimizeEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "widget",
        value: "minimized",
    }
});
const chatCloseEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "widget",
        value: "close",
    }
});
const chatAutoCloseEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "none",
        value: "close",
    }
});
const chatLinkEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "kipsu",
        value: "Chat",
    }
});
const chatPhoneEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "kipsu",
        value: "Phone",
    }
});
const chatCTALinkEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "kipsu",
        value: "cta_chat",
    }
});
const chatCTAsmsEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "kipsu",
        value: "cta_sms",
    }
});
const chatTopNavEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "kipsu",
        value: "Top Nav",
    }
});
const chatIconEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "kipsu",
        value: "Icon",
    }
});
const chatAutoOpenEvent = new CustomEvent('chatEvent', {
    detail: {
        action: "kipsu",
        value: "Auto",
    }
});
const bodyStyleObserverEvent = new CustomEvent('observerEvent', {
    detail: {
        name: "body",
        attr: "style",
    }
});
const trustarcCookieOpenEvent = new CustomEvent('trustarcUpdate', {
    detail: {
        name: "cookie",
        status: "open",
    }
});
const trustarcCookieClosedEvent = new CustomEvent('trustarcUpdate', {
    detail: {
        name: "cookie",
        status: "closed",
    }
});
const trustarcCookieClosingEvent = new CustomEvent('trustarcUpdate', {
    detail: {
        name: "cookie",
        status: "closing",
    }
});
const doubleSpaceUpdateEvent = new CustomEvent('doublespaceEvent', {
    detail: {
        name: "doublespace",
        status: "update",
    }
});
const trustarcTakeoverOpenEvent = new CustomEvent('takeoverEvent', {
    detail: {
        name: "open"
    }
});
const trustarcTakeoverClosedEvent = new CustomEvent('takeoverEvent', {
    detail: {
        name: "close"
    }
});
;
/*
 * Debounce
 * TODO.
 * There is a jquery library being used. Need to consider using that to avoid duplication.
 */
function debounce(func, wait, immediate) {
    var timeout;

    return function executedFunction() {
        var context = this;
        var args = arguments;

        var later = function () {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };

        var callNow = immediate && !timeout;

        clearTimeout(timeout);

        timeout = setTimeout(later, wait);

        if (callNow) func.apply(context, args);
    };
}

/*
 * Create Cookie
 */
function createCookie(name, value, days) {
    var expires;

    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

/*
 * Read Cookie
 */
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

/*
 * Erase Cookie
 */
function eraseCookie(name) {
    createCookie(name, "", -1);
}

/*
 * Is Colliding
 * Detects if two elements are colliding
 *
 * @param $div1
 * @param $el2
 * @returns {boolean}
 */
function isColliding($el1, $el2) {
    var el1_offset = $el1.offset();
    var el1_height = $el1.outerHeight(true);
    var el1_width = $el1.outerWidth(true);
    var el1_distance_from_top = el1_offset.top + el1_height;
    var el1_distance_from_left = el1_offset.left + el1_width;

    var el2_offset = $el2.offset();
    var el2_height = $el2.outerHeight(true);
    var el2_width = $el2.outerWidth(true);
    var el2_distance_from_top = el2_offset.top + el2_height;
    var el2_distance_from_left = el2_offset.left + el2_width;

    var not_colliding = (el1_distance_from_top < el2_offset.top || el1_offset.top > el2_distance_from_top || el1_distance_from_left < el2_offset.left || el1_offset.left > el2_distance_from_left);

    return !not_colliding;
}

/*
 * Get Equal Height | Shuffle.js Extension
 * @childItemSelector element to target
 */
function getEqualHeightForShuffleItems(childItemSelector) {
    var maxOuterHeight = false;
    //selects all items
    var elements = $(childItemSelector);
    //rest all heights
    elements.map(function (index, element) { $(element).css('height', 'auto'); });

    // limit to media-query
    if (window.matchMedia(_MEDIAQUERY["min-sm"]).matches) {
        //puts the height of all items in an array
        var heights = [];
        elements.each(function (index) {
            heights.push(Number($(this).height()));
        });
        var outerHeights = [];
        elements.each(function (index) {
            outerHeights.push(Number($(this).outerHeight(true)));
        });
        //gets the highest value out of the array
        var maxHeight = Math.max.apply(null, heights);
        maxOuterHeight = Math.max.apply(null, outerHeights);
        //sets height of all the items to be the same as the highest one
        elements.map(function (index, element) { $(element).height(maxHeight); });
    }

    return maxOuterHeight;
}

/*
 * Get Query String Param
 */
function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

/*
 * Get IE Version
 */
function getIEVersion() {
    var agent = navigator.userAgent;
    var reg = /MSIE\s?(\d+)(?:\.(\d+))?/i;
    var matches = agent.match(reg);
    if (matches !== null) {
        return { major: matches[1], minor: matches[2] };
    }
    return { major: "-1", minor: "-1" };
};
$(function () {
    /*
     * Body DOM Listener
     */
    const bodyObserver = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            // mobile nav adds a right padding when disabling scroll. need to capture this value and add to the hamburger nav and mobile pencile nav.
            if (mutation.target.nodeName === "BODY" && mutation.attributeName === "style") {
                // Dispatch Close Event
                document.dispatchEvent(bodyStyleObserverEvent);
            }
        });
    });

    bodyObserver.observe(document, {
        childList: false,
        subtree: true,
        attributes: true
    });

    // Footer Events
    document.addEventListener('footerEvent', function (e) {
        switch (e.detail.name) {
            case "enter":
                $('.backtotop-container').removeClass('stuck');
                break;
            case "exited":
                $('.backtotop-container').addClass('stuck');
                break;
        }
    });

    // DoubleSpace Events
    document.addEventListener('doublespaceEvent', function (e) {
        if (e.detail.name === "doublespace" && e.detail.status === 'update') {
            convertDoubleSpaceToBreak();
        }
    });

    // Back to Top
    // Basic check to see if a data-backtotop is present in the DOM.
    if ($('*[data-backtotop="true"').length > 0) {
        $('.backtotop-container').removeClass('d-none');
    }

    /*
     * Update Nav Hash
     * used to remove 'back to top' hash
     */
    function updateNavHash() {
        if (window.location.hash === "#bodycontent") {
            history.replaceState(null, null, ' ');
        }
    }


    /*!
     * RTE - Double Space Line Break
     * looks for data-double-sapce is true attribute. initial display of none is set in styles.
     */
    function convertDoubleSpaceToBreak() {
        $('[data-double-space="true"]').each(function (i) {
            var string = $(this).html();
            string = string.replace(/  +/g, '<br/>');
            $(this).html(string).fadeIn(100);
        });
    }

    $(window).on('hashchange', function (e) {
        updateNavHash();
    });

    // I N I T
    convertDoubleSpaceToBreak();
});;
$(function () {
    function setupWaypoint() {
        //var stickyWaypoint = new Waypoint.Sticky({
        //    element: $('.kipsu-icon-container')[0]
        //});

        inviewWaypoint = new Waypoint.Inview({
            element: $('footer')[0],
            enter: function (direction) {
                //console.log("footer enter " + direction);
                
                // Dispatch Enter Event
                document.dispatchEvent(footerEnterEvent);
            },
            entered: function (direction) {
                //console.log("footer entered " + direction);

                // Dispatch Entered Event
                document.dispatchEvent(footerEnteredEvent);
            },
            exit: function (direction) {
                //console.log("footer exit " + direction);

                // Dispatch Exit Event
                document.dispatchEvent(footerExitEvent);
            },
            exited: function (direction) {
                //console.log("footer exited " + direction);

                // Dispatch Exited Event
                document.dispatchEvent(footerExitedEvent);
            }
        });
    }

    $(function () {
        setupWaypoint();
    });

});;
$(function () {
    var navbarFunc;

    /*
     * Hamburger Collapse Listener
     */
    $('#navbarToggler').on('show.bs.offcanvas', function () {
        $('header .navbar-toggler').addClass('is-active');
        $('header .navbar-collapse').addClass('show');
        $('body').addClass('mobile-is-active');
        //$('header').addClass('mobile-is-active');

        // Dispatch Show Event
        document.dispatchEvent(hamburgerShowEvent);
    });
    $('#navbarToggler').on('shown.bs.offcanvas', function (e) {
        $('.hamburger').attr('aria-expanded', true);

        // attach listeners
        $('header').on('click', menuDropdownListener);
        $(document).on('keydown', headerListener);
        $('header .hamburger').on('keydown', hamburgerListener);

        if ($('header .utilities-top-container .search-container').attr('data-search') === 'mobile') {
            // reset search tracker
            $('header .utilities-top-container .search-container').attr('data-search', '');
            // set foucs on search
            $('header .navbar .search-container input').focus();
        } 

        //window.addEventListener('resize', navbarFunc);

        // Dispatch Hide Event
        document.dispatchEvent(hamburgerShownEvent);
    });
    $('#navbarToggler').on('hide.bs.offcanvas', function () {
        $('header .hamburger').attr('aria-expanded', false);
        $('header .navbar-toggler').removeClass('is-active');

        // Dispatch Hide Event
        document.dispatchEvent(hamburgerHideEvent);
    });
    $('#navbarToggler').on('hidden.bs.offcanvas', function () {
        $('body').removeClass('mobile-is-active');
        $('header .navbar-collapse').removeClass('show');
        //$('header').removeClass('mobile-is-active');

        // remove listeners
        $('header').off('click', menuDropdownListener);
        $(document).off('keydown', headerListener);

        // collapse accordion
        $('header nav .accordion .accordion-collapse').collapse('hide');

        //console.log('navbartoggler hidden');
        //updateInPageHash();

        // Dispatch Hidden Event
        document.dispatchEvent(hamburgerHiddenEvent);
    });

    // Debounce for Hamburger 
    navbarFunc = debounce(function () {
        if (window.matchMedia(_MEDIAQUERY["min-xl"]).matches) {
            // TODO
            //$('#navbarToggler').collapse('hide');
        }
    }, 250);


    /*
     * Menu Dropdown Listener
     */
    $('header .navbar .nav-item').on('show.bs.dropdown', function (e) {
        // attach data-collapsed-height to element for reference
        $(e.currentTarget).find('> a').attr('data-collapsed-height', $(e.currentTarget).find('> a').outerHeight());
    });

    $('header .navbar .nav-item').on('shown.bs.dropdown', function (e) {
        var collapsedHeight = Number($(e.currentTarget).find('> a').attr('data-collapsed-height'));
        var currentHeight = $(e.currentTarget).find('> a').outerHeight();

        //$(e.currentTarget).closest('ul').find('li.nav-item:not(.show) a').addClass('hidden');

        //// identify if nav-item is more than 1 line based on height change
        //if (currentHeight > collapsedHeight) {
        //    var currentMargin = Number($(e.currentTarget).find('> .dropdown-menu.show ul').css('margin-top').slice(0, -2));
        //    var newMargin = Math.round(currentHeight - collapsedHeight) + currentMargin;

        //    $(e.currentTarget).find('> .dropdown-menu.show ul').css('margin-top', newMargin + 'px');
        //}


        // attach hover when mouse leaves dropdown 
        $('header .navbar-nav .dropdown-menu.show').hover(
            function (e) {
                //console.log('dropdown-menu mouseenter');
            },
            function (e) {
                //console.log('dropdown-menu mouseleave');
                if (window.matchMedia(_MEDIAQUERY["min-xl"]).matches) {
                    $('header .navbar-nav .dropdown-menu.show').unbind('mouseleave mouseenter');
                    $('header .navbar-nav a.nav-link[aria-expanded="true"]').dropdown('toggle');
                }
            });
    });

    $('header .navbar .nav-item').on('hide.bs.dropdown', function (e) {
        $(e.currentTarget).closest('ul').find('li.nav-item a').removeClass('hidden');

        // remove attached style from 'shown.bs.dropdown'
        $(e.currentTarget).find('> .dropdown-menu.show ul').css('margin-top', '');
    });


    /*
     * Nav Menu Dropdown Keyboard Listeners
     */

    function menuDropdownListener(e) {
        //console.log("menuDropdownListener");

        if (!$('body').hasClass('mobile-is-active')) return;

        if ($('header .navbar .dropdown-menu').hasClass('show') && e.which === 1 && $(e.target).closest('.navbar').length > 0) {
            e.stopPropagation();
        }
        // For Navbar at top
        else if ($('header .navbar .dropdown-menu').hasClass('show') && e.which === 1 && $(e.target).hasClass('navbar-brand-container')) {
            e.stopPropagation();
        }
    }

    function headerListener(e) {
        //console.log("headerListener");
        if (!$('body').hasClass('mobile-is-active')) return;

        var subNav = $('header').find('li:not(.disabled):visible .dropdown-menu.show');
        //var propDropdown = $('header').find('.properties-dropdown .dropdown-menu.show');

        // Close main menu if everything is collapsed
        if (e.which === 27 && subNav.length === 0 && propDropdown.length === 0) {
            $('#navbarToggler').collapse('hide');
            $('header .hamburger').focus();
        }
        // For Lost Focus if submenu was mouse-clicked
        else if (e.which === 27 && subNav.length > 0 && propDropdown.length === 0) {
            $('header .navbar .dropdown-menu.show').prev().dropdown('hide').attr('aria-expanded', false).focus();
        }
    }

    function hamburgerListener(e) {
        //console.log("hamburgerListener");
        if (!$('body').hasClass('mobile-is-active')) return;

        if (e.shiftKey && e.which === 9) {
            e.preventDefault();
            //$('header .properties-dropdown-container .dropdown-toggle').focus();
        }
    }


    /*
     * Nav Menu Click & Hovers
     */
    $('header .navbar-nav a.nav-link[data-bs-toggle="dropdown"]').hover(
        function (e) {
            //console.log('mouseenter');

            // if desktop nav and not already expanded
            if (window.matchMedia(_MEDIAQUERY["min-xl"]).matches && $(e.currentTarget).attr('aria-expanded') === "false") {
                $(e.currentTarget).dropdown('toggle');
            }
        },
        function (e) {
            //console.log('mouseleave on expanded');

            if (window.matchMedia(_MEDIAQUERY["min-xl"]).matches) {
                var itemTop = $(e.currentTarget).offset().top;
                var itemBottom = $(e.currentTarget).offset().top + $(e.currentTarget).outerHeight();

                // if cursor moved up
                if (itemTop >= e.pageY) {
                    $('header .navbar-nav .dropdown-menu.show').unbind('mouseleave mouseenter');
                    $('header .navbar-nav a.nav-link[aria-expanded="true"]').dropdown('toggle');
                }
                // if cursor is within top and bottom. assume cursor has gone left/right.
                else if (itemTop <= e.pageY && itemBottom > e.pageY) {
                    $('header .navbar-nav .dropdown-menu.show').unbind('mouseleave mouseenter');
                    $('header .navbar-nav a.nav-link[aria-expanded="true"]').dropdown('toggle');
                }
                // if cursor moved down
                else {
                    // no action needed
                }

                // if focus is still sticking, remove it
                if ($(':focus').length > 0) {
                    $($(':focus')[0]).blur();
                }
            }

        });

    $('header .navbar-nav a.nav-link').on('click', function (e) {
        // bs suppresses click on nav-link. manually trigger this action.
        // restrict to data-bs-toggle as a dropdown as well
        if (window.matchMedia(_MEDIAQUERY["min-xl"]).matches && $(e.currentTarget).attr('data-bs-toggle') === "dropdown") {
            // limit check to just _blank in case it's empty or undefined
            var target = e.currentTarget.attributes.target.value !== "_blank" ? "_self" : "_blank";
            window.open(e.currentTarget.href, target);
            // bs will trigger an expand. force collapse.
            $(e.currentTarget).dropdown('hide');
            // remove aria-expanded
            $(e.currentTarget).removeAttr('aria-expanded');
        }
    });

    $('header .navbar-nav a.nav-link:not([data-bs-toggle="dropdown"])').hover(
        function (e) {
            //console.log('not mouseenter');

            if (window.matchMedia(_MEDIAQUERY["min-xl"]).matches) {
                $('header .navbar-nav a.nav-link[aria-expanded="true"]').dropdown('toggle');
            }
        },
        function (e) {
            //console.log('mouseleave on no expanded');
        });

    $('header .navbar-nav a.dropdown-item').on('click', function (e) {
        // check if the url has a hash and matches the current page
        if ($(e.currentTarget).attr('href').indexOf('#') > -1 && $(e.currentTarget).attr('href').indexOf(window.location.pathname) > -1) {
            $('header .navbar').attr('data-hash', e.currentTarget.hash);


            //e.preventDefault();
            // need to manually collapse mobile menu due to preventDefault()
            if (window.matchMedia(_MEDIAQUERY["max-xl"]).matches) {
                //console.log('mobile detected');
                //$('#navbarToggler').collapse('hide');

                $('#navbarToggler').offcanvas('hide');

            } else {
                //console.log('desktop detected');
                //updateInPageHash();
            }
        }
    });

    // support in-page anchoring. data-hash=true must be present.
    //$('header .navbar-nav a[data-hash="true"]').on('click', function (e) {
    //    var clickDelay = 0;

    //    e.preventDefault();
    //    // need to manually collapse mobile menu due to preventDefault()
    //    if (window.matchMedia(_MEDIAQUERY["max-xl"]).matches) {
    //        // add small delay to allow nav to collpase first. more of a visual.
    //        clickDelay = 750;
    //        $('#navbarToggler').collapse('hide');
    //    }

    //    var hash = e.currentTarget.hash;
    //    // manually append hash
    //    if (hash === "") {
    //        history.pushState(undefined, undefined, window.location.pathname + window.location.search);
    //    } else {
    //        history.pushState(undefined, undefined, hash);
    //    }
    //    // buffer based on nav state
    //    // desktop nav
    //    var buffer = $('header').hasClass('pencil-is-active') ? 20 : -45;
    //    // mobile nav
    //    if (window.matchMedia(_MEDIAQUERY["max-xl"]).matches) {
    //        buffer = 80;
    //    }
    //    var el = $(hash);
    //    var newPos = hash === "" ? 0 : el.offset().top - $('body > header').height() - buffer;
    //    var windowPos = $(window).scrollTop() - buffer;
    //    var duration = Math.abs(windowPos - newPos) / 3;

    //    setTimeout(function () {
    //        $('html, body').animate({
    //            scrollTop: newPos
    //        }, duration, function () {
    //            el.focus();
    //        });
    //    }, clickDelay);
    //});


    /*
     * Search Menu Listener
     */
    $('header .utilities-top-container .search-container .icon-container').on('shown.bs.dropdown', function (e) {
        $(e.currentTarget).find('form input').focus();
    });

    $('header .utilities-top-container .search-container .icon-container').on('hide.bs.dropdown', function (e) {
        if ($('header').hasClass('pencil-is-active')) {
            $(e.currentTarget).focus();
        }
    });


    /*
     * Search Listeners
     */
    $('header .utilities-top-container .search-container .icon-container a').on('click', function (e) {
        // refine to mobile only
        if (window.matchMedia(_MEDIAQUERY["max-xl"]).matches) {
            e.preventDefault();
            //$('#navbarToggler').find('.search-container input').focus();
            $("#navbarToggler").offcanvas('show');
            
            //console.log($(e.target).closest('.search-container'));
            $(e.target).closest('.search-container').attr('data-search', 'mobile');
        }
    });
    // force scroll-top for mobile because search bar may be out of view
    //$('#navbarToggler').find('.search-container input').on('focus', function (e) {
    //    console.log('on focus');
    //    // refine to mobile only and landscape
    //    if (window.matchMedia(_MEDIAQUERY["max-sm"]).matches + "and orientation:landscape") {
    //        console.log("media found 3");
    //        //window.scrollTo(0, 0);
    //        //document.body.scrollTop = 0;

    //        // add a delay to allow mobile keyboard to kick in
    //        //setTimeout(function () {
    //        //    $('header .navbar .offcanvas .collapse.show').scrollTop(0);
    //        //}, 1500);
            
    //    }
    //});


    /*
     * Chat Click
     */
    $('header .utilities-top-container .chat-container a').on('click', function (e) {
        e.preventDefault();

        // refine to mobile and desktop only
        if (window.matchMedia(_MEDIAQUERY["max-xl"]).matches) {
            // check status of chat window
            if ($('.kipsu-chat-container').hasClass('active')) {
                // Dispatch Close Event
                document.dispatchEvent(chatCloseEvent);
            } else {
                // Dispatch Open Event
                document.dispatchEvent(chatTopNavEvent);
            }
        }
    });


    /*
     * Listeners
     */

    // Chat (Kipsu) Event
    document.addEventListener('chatEvent', function (e) {
        switch (e.detail.name) {
            case "open":
                // refine to tablet
                if (window.matchMedia(_MEDIAQUERY["min-xs"]).matches && window.matchMedia(_MEDIAQUERY["max-xl"]).matches) {
                    $('header .utilities-top-container .chat-container a').attr('aria-expanded', true);
                }

                break;
            case "close":
                $('header .utilities-top-container .chat-container a').attr('aria-expanded', false);
                break;
        }
    });

    // Mutation Observer
    document.addEventListener('observerEvent', function (e) {
        switch (e.detail.name) {
            case "body":
                // refine to attr-style
                if (e.detail.attr === "style") {
                    // mobile nav adds a right padding when disabling scroll. need to capture this value and add to the hamburger nav and mobile pencil nav.
                    $('header .hamburger').css('margin-right', $('body').css('padding-right'));
                    $('header .utilities-top-container.stuck').css('padding-right', $('body').css('padding-right'));
                }

                break;
        }
    });


    /*
     * Waypoint
     */
    var position = $(window).scrollTop();
    var navbarOffset = 85; // manually added due to complexity. this height matches css $('header nav')[0].offsetTop;
    //var navbarOffset = $('header nav')[0].offsetTop;
    //var utilsOffset = $('header .utilities-top-container')[0].offsetTop;
    var brandLogo = {
         desktop: {
            no_pencil: {
                predict: true
            },
            pencil: {
                predict: true
            }

        }
    };

    function checkNavOffset() {
        // for Desktop Nav
        if (window.matchMedia(_MEDIAQUERY["min-xl"]).matches) {
            // stick it
            if (position > navbarOffset) {
                //console.log('desktop: stick it');

                $($('header nav')[0]).addClass('stuck');
                $('header').addClass('pencil-is-active');
                $('main').addClass('pencil-is-active');

                // set styles
                var paddingLeft = Math.round($('header .navbar-brand-container').outerWidth() + $('header .navbar-brand').position().left);
                var paddingRight = Math.round($('header .navbar .nav-btn-container .btn').outerWidth() + $('header .navbar .nav-btn-container .btn').position().left) + 25;
                $('header .utilities-top-container > .container').css({ 'padding-left': paddingLeft + "px", 'padding-right': paddingRight + "px" });

                // means nav loaded as a pencil nav
                if (brandLogo.desktop.pencil.predict == true) {
                    brandLogo.desktop.pencil.predict = false;

                    brandLogo.desktop.pencil.width = $('header .navbar-brand').outerWidth();
                    brandLogo.desktop.pencil.height = $('header .navbar-brand').outerHeight();
                }
            }
            // unstick it
            else {
                //console.log('desktop: unstick it');

                $($('header nav')[0]).removeClass('stuck');
                $('header').removeClass('pencil-is-active');
                $('main').removeClass('pencil-is-active');

                // collapse search if open
                $('header .utilities-top-container .search-container .icon-container a[aria-expanded="true"]').dropdown('toggle');

                // reset styles
                $('header .utilities-top-container > .container').css({ 'padding-left': '', 'padding-right': '' });

                // means nav loaded as no-pencile nav
                if (brandLogo.desktop.no_pencil.predict == true) {
                    // conditional to only accept once
                    brandLogo.desktop.no_pencil.predict = false;

                    brandLogo.desktop.no_pencil.width = $('header .navbar-brand').outerWidth();
                    brandLogo.desktop.no_pencil.height = $('header .navbar-brand').outerHeight();
                }

                // means pencil nav is still predicted
                if (brandLogo.desktop.pencil.predict == true) {
                    if (brandLogo.desktop.no_pencil.width > brandLogo.desktop.no_pencil.height) {
                        brandLogo.desktop.pencil.width = 150; // this is the max-width
                        brandLogo.desktop.pencil.height = Math.round(brandLogo.desktop.no_pencil.width / (150 * brandLogo.desktop.no_pencil.height));
                    } else {
                        brandLogo.desktop.pencil.width = Math.round((brandLogo.desktop.no_pencil.width * 50) / brandLogo.desktop.no_pencil.height);
                        brandLogo.desktop.pencil.height = 50; // this is the max-height
                    }
                }

            }

            // add max-width based on offset
            var maxWidthOffset = Math.round((brandLogo.desktop.pencil.width + $('header .utilities-top-container .mall-hours-container .icon-link-container').outerWidth() + 50) * 2);
            $('header .nav-item-container').css('max-width', 'calc(100vw - ' + maxWidthOffset + 'px)');

            // update bs data to main nav as dropdown
            $('header nav .nav-link').attr('data-bs-toggle', 'dropdown');
            // empty bs data for supressed nav links
            $('header nav .nav-link[data-dropdown-supress="true"]').attr('data-bs-toggle', '');

            // remove aria-expanded for suppressed nav links
            $('header nav .nav-link[data-dropdown-supress="true"]').removeAttr('aria-expanded');

            // add bs data for search
            $('header .utilities-top-container .search-container .icon-container a').attr('data-bs-toggle', 'dropdown');

            // reset search click tracker
            $('header .utilities-top-container .search-container').attr('data-search', '');

            // reset mobile specific
            $($('header .utilities-top-container')[0]).removeClass('stuck');
        }
        // for Mobile Nav
        else {            
            // stick it
            if (position > navbarOffset ||
                $('header').attr('data-pencil').toLowerCase() === "true") {
                //console.log('mobile: stick it');

                $($('header .utilities-top-container')[0]).addClass('stuck');
                $('header').addClass('pencil-is-active');
                $('main').addClass('pencil-is-active');
            }
            // unstick it
            else {
                //console.log('mobile: unstick it');

                $($('header .utilities-top-container')[0]).removeClass('stuck');
                $('header').removeClass('pencil-is-active');
                $('main').removeClass('pencil-is-active');
            }

            $('header .nav-item-container').css('max-width', '');

            // update bs data to main nav as collapse (accordion)
            $('header nav .nav-link').attr('data-bs-toggle', 'collapse');

            // add aria-expanded for suppressed nav links
            $('header nav .nav-link[data-dropdown-supress="true"]').each(function (i) {
                // only add if aria-expanded does not exist.
                if ($(this).attr('aria-expanded') === undefined) {
                    $(this).attr('aria-expanded', 'false');
                }
            });

            // reset desktop specific
            $($('header nav')[0]).removeClass('stuck');

            // collapse search if open
            $('header .utilities-top-container .search-container .icon-container a[aria-expanded="true"]').dropdown('toggle');

            // remove bs data from search
            $('header .utilities-top-container .search-container .icon-container a').attr('data-bs-toggle', '');

            // reset styles
            $('header .utilities-top-container > .container').css({ 'padding-left': '', 'padding-right': '' });
        }
    }

    /*
     * Update Nav Hash
     * suppress additional active (class) if they do not match the url
     * add additional active (class) if managed by JS
     */
    function updateNavHash() {
        // if url has ?nav query, accept entire url. otherwise, only grab pathname and possible hashes
        var activeURL = window.location.href.includes('?nav=') ? window.location.href.replace(window.location.origin, '') : window.location.pathname + window.location.hash;
        
        $('header #navbarMenu').find('a.dropdown-item').each(function (i) {
            if ($(this).attr('href').toLowerCase() !== activeURL.toLowerCase()) {
                if ($(this).hasClass('active')) {
                    $(this).addClass('suppress-active');
                }
                $(this).removeClass('manual-active');
            } else {
                if ($(this).hasClass('active')) {
                    $(this).removeClass('suppress-active');
                } else {
                    // active state applied after DOM load
                    $(this).addClass('manual-active');
                }
                
            }
        })
    }

    /*
     * Update In-Page Hash
     * if hash is for in-page, suppress native action with animate and update browser history
     */ 
    function updateInPageHash() {
        var hash = $('header .navbar').attr('data-hash');

        // manually append hash
        if (hash === "") {
            history.pushState(undefined, undefined, window.location.pathname + window.location.search);
        } else {
            history.pushState(undefined, undefined, hash);
        }

        // buffer based on nav state
        var buffer = $('header').hasClass('pencil-is-active') ? 155 : 70;
        var el = $(hash);
        //console.log(el);
        var newPos = hash === "" ? 0 : el.offset().top - buffer;
        var windowPos = position - buffer;
        //console.log('header height: ' + $('body > header').height());
        //console.log('newPos: ' + newPos);
        //console.log('windowPos: ' + windowPos);
        var duration = Math.abs(windowPos - newPos) / 3;

        $('html, body').animate({
            scrollTop: newPos
        }, {
            duration: 200,
            complete: function () {
                el.focus();
            }
        });
    }

    /*
     * On Scroll (Standard)
     */ 
    $(window).scroll(function () {
        var scroll = $(window).scrollTop();

        checkNavOffset();

        position = scroll;
    });

    /*
     * On Scroll (debounce)
     */ 
    $(window).scroll($.debounce(250, true, function () {
        $('body > header').addClass('drop-shadow');
    }));
    $(window).scroll($.debounce(1000, function () {
        $('body > header').removeClass('drop-shadow');
    }));

    $(window).on('hashchange', function (e) {
        updateNavHash();
    });  

    $(window).on('resize', function () {
        checkNavOffset();
    });

    $(function () {
        checkNavOffset();
        updateNavHash();
    });

    // Debounce for Navbar 
    //var stickyScrollFunc = debounce(checkNavOffset, 100);
    //var stickyResizeFunc = debounce(checkNavOffset, 0);
    //window.addEventListener('scroll', stickyScrollFunc);
    //window.addEventListener('resize', stickyResizeFunc);   
});;
$(function () {
    const uap = UAParser();

    /*
     * Add Listeners
     */

    // FocusTrapper
    document.addEventListener('ftKipsu', function _listener() {
        // ADDITIONAL CODE HERE
        document.removeEventListener("ftKipsu", _listener, true);
    }, false);

    // Footer Events
    document.addEventListener('footerEvent', function (e) {
        switch (e.detail.name) {
            case "enter":
                $('.kipsu-icon-container').removeClass('stuck');
                break;
            case "exited":
                $('.kipsu-icon-container').addClass('stuck');
                break;
        }
    });

    // Chat (Kipsu) Event
    document.addEventListener('chatEvent', function (e) {
        switch (e.detail.action) {
            case "widget":
                switch (e.detail.value) {
                    case "maximized":
                        maximizeChat();

                        break;
                    case "minimized":
                        minimizeChat();

                        break;
                    case "close":
                        $(".kipsu-icon-container").removeClass("hide");
                        $(".kipsu-icon-container").attr('aria-expanded', false);

                        closeChat();
                        break;
                }

                dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'kipsu_click', 'dynev.p1_name': e.detail.action + '_action', 'dynev.p1_value': e.detail.value });

                break;
            case "kipsu":
                switch (e.detail.value) {
                    case "Phone":
                    case "cta_sms":

                        break;
                    case "Chat":
                    case "Top Nav":
                    case "Icon":
                    case "Auto":
                    case "cta_chat":                    
                        // refined to desktop only
                        if (window.matchMedia(_MEDIAQUERY["min-xl"]).matches) {
                            $(".kipsu-icon-container").attr('aria-expanded', true);
                            $(".kipsu-icon-container").addClass("hide");
                        }

                        openChat(e.detail);
                        break;
                }

                dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'kipsu_click', 'dynev.p1_name': e.detail.action + '_action', 'dynev.p1_value': e.detail.value });

                break;
            case "data":
                updateChatDOM(e.detail);
                break;
            default:
                switch (e.detail.value) {
                    case "close":
                        closeChat();
                        break;
                }

        }
    });

    // Mutation Observer
    document.addEventListener('observerEvent', function (e) {
        switch (e.detail.name) {
            case "body":
                // refine to attr-style
                if (e.detail.attr === "style") {
                    // mobile nav adds a right padding when disabling scroll. need to capture this value and add to the hamburger nav and mobile pencile nav.
                    $('.kipsu-chat-container').css('margin-right', $('body').css('padding-right'));
                }

                break;
        }
    });


    /*
     * Kipsu Click and Keyboard Listeners
     */
    $(".kipsu-chat-container div.close").on('click keydown', function (e) {
        // only accept Enter for keydown
        if (e.type === "keydown") { if (e.key !== "Enter") { return; } }

        // Dispatch Close Event
        document.dispatchEvent(chatCloseEvent);
    });
    $(".kipsu-chat-container div.minimize").on('click keydown', function (e) {
        // only accept Enter for keydown
        if (e.type === "keydown") { if (e.key !== "Enter") { return; } }

        // Dispatch Minimize Event
        document.dispatchEvent(chatMinimizeEvent);
    });

    $(".kipsu-chat-container div.expand").on('click keydown', function (e) {
        // only accept Enter for keydown
        if (e.type === "keydown") { if (e.key !== "Enter") { return; } }

        // Dispatch Maximize Event
        document.dispatchEvent(chatMaximizeEvent);
    });

    $(".kipsu-icon-container").on('click keydown', function (e) {
        // only accept Enter for keydown
        if (e.type === "keydown") { if (e.key !== "Enter") { return; } }

        // Dispatch Icon Open Event
        document.dispatchEvent(chatIconEvent);
    });


    /*
     * Kipsu DOM Clicks
     */
    $("a.kipsu_chat_link, a.kipsu-cta.kipsu-chat-link").on('click keydown', function (e) {
        // prevents default behavior of <a> tag. Issue when link is clicked, 2 browser windows open
        // When this linked is clicked, only javascript will open the chat window
        e.preventDefault();
        // only accept Enter for keydown
        if (e.type === "keydown") { if (e.key !== "Enter") { return; } }

        var existingDetails = {};

        if ($(e.target).hasClass('kipsu_chat_link')) {
            existingDetails = chatLinkEvent ? chatLinkEvent.detail : {};
        }
        else if ($(e.target).hasClass('kipsu-cta')) {
            existingDetails = chatCTALinkEvent ? chatCTALinkEvent.detail : {};
        }

        // Get existing details if the event already exists
        //const existingDetails = chatLinkEvent ? chatLinkEvent.detail : {};

        // Merge existing details with new details
        const newDetails = {
            ...existingDetails,
            origin: e.target,
        };
        
        // adding origin to event
        const updatedEvent = new CustomEvent('chatEvent', {
            detail: newDetails
        });

        // Dispatch Open Event
        document.dispatchEvent(updatedEvent);
    });

    $("a.kipsu_phone_link").on('click keydown', function (e) {
        // only accept Enter for keydown
        if (e.type === "keydown") { if (e.key !== "Enter") { return; } }

        // Dispatch Open Event
        document.dispatchEvent(chatPhoneEvent);
    });

    $("a.kipsu-cta.kipsu-phone-link").on('click keydown', function (e) {
        // only accept Enter for keydown
        if (e.type === "keydown") { if (e.key !== "Enter") { return; } }

        // Dispatch Open Event
        document.dispatchEvent(chatCTAsmsEvent);
    });


    /*
     * Close Chat
     */
    function closeChat() {
        $(".kipsu-chat-container").removeClass("active");
        $(".kipsu-chat-container").removeClass("min");
        $(".kipsu-chat-container").find('[role="button"]').attr('tabindex', '-1');
        $(".kipsu-chat-container").find('iframe').attr('tabindex', '-1');
        $(".kipsu-chat-container .minimize").show();

        localStorage.removeItem('chat_modal');
    }

    /*
     * Minimize (Collapse) Chat
     */
    function minimizeChat() {
        $(".kipsu-chat-container").addClass("min");
        $(".kipsu-chat-container .minimize").hide().removeAttr('tabindex').removeAttr('role');
        $(".kipsu-chat-container .expand").show().attr('tabindex', '0').attr('role', 'button').focus();
        $(".kipsu-chat-container .kipsu-chat-iframe-holder iframe").css('display', 'none');

        localStorage.setItem('chat_modal', 'minimized');
    }

    /*
     * Maximize (Expand) Chat
     */
    function maximizeChat() {
        $(".kipsu-chat-container").removeClass("min");
        $(".kipsu-chat-container .minimize").show().attr('tabindex', '0').attr('role', 'button').focus();
        $(".kipsu-chat-container .expand").hide().removeAttr('tabindex', '0').removeAttr('role');
        $(".kipsu-chat-container .kipsu-chat-iframe-holder iframe").css('display', 'block');

        localStorage.setItem('chat_modal', 'open');

        new FTWrapper('.kipsu-icon-container', { initFocus: '.kipsu-chat-header-bar .minimize', iframeSupport: true, ariaHide: '#footer,.skipnav,#homepage-nav,#offcanvas', dispatchEnabledEvent: 'ftKipsu' });
    }

    /*
     * Open Chat
     */
    function openChat(data) {
        // trigger widget new window if mobile size and less
        if (window.matchMedia(_MEDIAQUERY["max-sm"]).matches) {
            var kipsuURL;

            if (data) {                
                // get kipsu url from origin if href is not set
                if (kipsuURL !== '' && kipsuURL !== '#') {
                    // get kipsu url from origin
                    if ($(data.origin).attr('data-kipsu-url')) {
                        kipsuURL = $(data.origin).attr('data-kipsu-url');
                    }
                    // else get kipsu web url from kipsu icon container
                    else {
                        kipsuURL = $('.kipsu-icon-container').attr('data-kipsu-url');
                    }

                    window.open(kipsuURL, "_blank");
                } 
            }
        }
        else {
            var widgetURL = $('.kipsu-chat-container').attr('data-widget-url');
            $(".kipsu-chat-iframe-holder > iframe").attr('src', widgetURL);
            // 500ms delay matches the css animation speed
            $(".kipsu-chat-container").removeClass('d-none').delay(500).queue(function () {
                $(".kipsu-chat-container").addClass("active").dequeue();
            });
            //$(".kipsu-chat-container").find('[role="button"]').attr('tabindex', '0');
            $(".kipsu-chat-container .close").attr('tabindex', '0');
            $(".kipsu-chat-container .expand").hide().removeAttr('role').removeAttr('tabindex', '0');
            $(".kipsu-chat-container .minimize").show().attr('tabindex', '0').attr('role', 'button').focus();
            $(".kipsu-chat-container .kipsu-chat-iframe-holder iframe").css('display', 'block');
            $(".kipsu-chat-container").find('iframe').removeAttr('tabindex');

            localStorage.setItem('chat_modal', 'open');

            new FTWrapper('.kipsu-chat-container', { initFocus: '.kipsu-chat-header-bar .close', lastFocus: true, iframeSupport: true, ariaHide: '#footer,.skipnav,#homepage-nav,#offcanvas', dispatchEnabledEvent: 'ftKipsu' });
        }
    }

    /*
     * Check Chat Icon
     */
    function checkChatIcon() {
        // toggle tabindex if present on stage
        if (window.matchMedia(_MEDIAQUERY["max-xl"]).matches) {
            $('.kipsu-icon-container').removeAttr('tabindex')
        }
        else if (window.matchMedia(_MEDIAQUERY["min-xl"]).matches) {
            $('.kipsu-icon-container').attr('tabindex', '0')

            // simple check to see if a data-kipsu-align is present anywhere in the DOM
            if ($('.custom-block[data-kipsu-align="left"]').length > 0) {
                $('.kipsu-icon-container').addClass('kipsu-icon-left')
            }
        }
    }


    /*
     * Check Chat Links
     */
    function checkChatLinks() {
        // refine to tablet and up
        // add role to kipsu-cta
        if (window.matchMedia(_MEDIAQUERY["min-sm"]).matches) {
            $('.kipsu-cta, .kipsu_chat_link').attr('role', 'button');
        } else {
            $('.kipsu-cta, .kipsu_chat_link').removeAttr('role');
        }

        // refine to mobile and down
        // update aria-label and target
        $("a.kipsu_chat_link, a.kipsu-cta.kipsu-chat-link").each(function () {
            var link = $(this).attr('data-kipsu-url');
            if (window.matchMedia(_MEDIAQUERY["max-sm"]).matches) {
                // update href with data-kipsu-url            
                if (link) {
                    $(this).attr('href', link);
                }

                $(this).attr('aria-label', 'Open Chat in New Window').attr('target', '_blank');
            } else {
                $(this).attr('aria-label', 'Open Chat Window').removeAttr('target');

                // remove href if data-kipsu-url is present
                if (link) {
                    $(this).removeAttr('href');
                }
            }
        });

    }


    /*
     * Update Chat DOM
     */

    function updateChatDOM(data) {

        // Update Kipsu SMS information
        $("a.kipsu_phone_link, a.kipsu-cta.kipsu-phone-link").each(function () {
            // check if data is present
            if (data.sms.trim() !== "") {
                // update href with data-kipsu-sms
                $(this).attr('href', 'sms:' + data.sms);
                $(this).attr('data-kipsu-sms', data.sms);
            }
            $(this).attr('aria-label', 'Send SMS Message');
        });

        function updateAttr(selector, attribute, dataValue) {
            $(selector).each(function () {
                const href = $(this).attr('href') || '';
                const value = dataValue && dataValue.trim() !== "" ? dataValue : href.replace("sms:", "");
                // check if attribute is not present and value is not empty
                if (!$(this).attr(attribute) && value !== "") {
                    // add attribute if not present
                     $(this).attr(attribute, value);
                }
            });
        }

        updateAttr("a.kipsu_phone_link, a.kipsu-cta.kipsu-phone-link", 'data-kipsu-sms', data.sms);
        updateAttr("a.kipsu_chat_link, a.kipsu-cta.kipsu-chat-link", 'data-kipsu-url', data.url);   

        checkChatLinks();
    }


    /*
     * On Resize
     */

    $(window).on('resize', $.debounce(250, function () {
        // Chat Auto Close Event
        // Dispatched when chat is resized in mobile view
        var chatOpen = localStorage.getItem('chat_modal');

        // limit dispatch if chat is of any state except closed
        if (chatOpen) {
            // refine to mobile and down
            if (window.matchMedia(_MEDIAQUERY["max-sm"]).matches) {
                // Dispatch Close Event
                document.dispatchEvent(chatAutoCloseEvent);

                checkChatIcon();
            }
        }

        checkChatLinks();
    }));


    /*
     * DOM Load
     */

    $(function () {
        // Chat Auto Open Event
        // Dispatched on DOM load and chat was previously open via localStorage
        var chatOpen = localStorage.getItem('chat_modal');

        if (chatOpen === 'open') {
            // refine to tablet and up
            if (window.matchMedia(_MEDIAQUERY["min-sm"]).matches) {
                // Dispatch Close Event
                document.dispatchEvent(chatAutoOpenEvent);
            }
        }

        checkChatIcon();
    });

});;
let searchInputFields, currentInputField, currentSuggestionBox;

$(function () {
    function checkSearchSubNav() {
        var buffer = 2;

        if (Math.round($('.alphaSearchWrap .search-scrollbar').width()) < $('.alphaSearchWrap .search-scrollbar')[0].scrollWidth) {
            $('.alphaSearchWrap .search-scrollbar-icon').removeClass('d-none');
        } else {
            $('.alphaSearchWrap .search-scrollbar-icon').addClass('d-none');
        }
    }

    if ($('.alphaSearchWrap').length > 0) {
        $(window).on('resize', function () {
            checkSearchSubNav();
        });

        checkSearchSubNav();
    }
});

// FUNCTIONALITY FOR AUTOCOMPLETE SEARCH BOX SUGGESTIONS 
function getKeywordLink(element) {
    var searchForm = currentInputField.parent().parent();
    let suggestedValue = $(element).text();
    currentInputField.val(suggestedValue);
    currentSuggestionBox.addClass('d-none').attr('aria-hidden', true); // Hides suggestion box 
    searchForm.submit();
}


// FUNCTIONALITY FOR SEARCH SUGGESTIONS
function suggestionSearchLink(element) {
    var searchString = $(element).text();
    var searchBox = $('.search-container input.form-control');
    var searchForm = $('.search-container form');
    searchBox.val(searchString);
    if (currentSuggestionBox != null || currentSuggestionBox != undefined) {
        currentSuggestionBox.addClass('d-none').attr('aria-hidden', true); // Hides suggestion box
    } 
    searchForm.submit();
}


// FUNCTIONALITY FOR SEARCH ICON INSIDE SEARCH BOXES 
$('.uk-icon-search, .input-group-text').on('click', function () {
    var searchForm = $(this).parentsUntil('form');
    currentSuggestionBox.addClass('d-none').attr('aria-hidden', true); // Hide suggestion box
    searchForm.parent().submit();
});



$(document).ready(function () {
    let autocompleteEndpoint = sessionStorage.getItem("autocompleteEndpoint"); // Gets autocompleteEndpoint URL from session storage (saved in _MaterLayout.cshtml)
    let generalSuggestionBox = $('.suggestionBox.general');
    let directorySuggestionBox = $('.suggestionBox.directory');
    let mobileSuggestionBox = $('.suggestionBox.mobile');

    searchInputFields = $('form').find('input[type="text"].form-control, input[type="text"].directory.search'); // Selects all input text fields with .form-control or .directory.search class within forms on the current page

    
    $(searchInputFields).on('focus', function () {
        searchSuggestions('keydown', this);
    });

    // Removes suggestion box when search input field goes out of focus
    $(searchInputFields).on('blur', function () {
        if (currentSuggestionBox == undefined) { return; }
        setTimeout(function () {
            mobileSuggestionBox.addClass('d-none').attr('aria-hidden', true); // Hides mobile suggestion box 
        }, 200);

        if ($(this).hasClass('form-control')) {
            if (!generalSuggestionBox.hasClass('d-none')) {
                setTimeout(function () {
                    generalSuggestionBox.addClass('d-none').attr('aria-hidden', true); // Hides general suggestion box 
                }, 200);
                
            }
        } else {
            if (!directorySuggestionBox.hasClass('d-none')) {
                setTimeout(function () {
                    directorySuggestionBox.addClass('d-none').attr('aria-hidden', true); // Hides directory suggestion box 
                }, 200);
            }
        }
    });
    $(searchInputFields).on('keyup', function (e) { searchSuggestions(e, this); }); // Every time content inside search box changes, calls searchSuggestions function
    $(searchInputFields).on('keydown', function (e) {
        if (e.which == 9) {
            e.preventDefault();
            return;
        }
        // Checking if keys UP, DOWN, ENTER or TAB are pressed
        if (e.which === 38 || e.which == 40 || e.which == 13) {
            if (currentSuggestionBox.hasClass('d-none')) {
                return; // Return if selection box is not showing
            } else {
                keyboardNavigation(e);
            }
        }
    });

    
    function searchSuggestions(e, element) {
        if (e.which === 38 || e.which == 40 || e.which == 13 || e.which == 9) {
            return; // Ignore cursor keys, ENTER and TAB - those are covered by "keydown" event
        }
        currentInputField = $(element);
        currentSuggestionBox = currentInputField.parent().find('.suggestionBox');
        var searchKeyword = $(element).val(); // gets current search term
        if (searchKeyword.length > 2) { // If the typed keyword is minimum 3 character long, wait 200 miliseconds before calling getSuggestionKeywords function
            getSuggestionKeywords(element, searchKeyword);
        }
        else {
            currentSuggestionBox.addClass('d-none').attr('aria-hidden', true); // Hide suggestion box
        }
    }


    function getSuggestionKeywords(element, keyword) {  
        let endpoint;
        if ( $(element).hasClass('directory') ) {
            endpoint = autocompleteEndpoint + keyword + "&d=true"; // Endpoint for directory search
        } else {
            endpoint = autocompleteEndpoint + keyword + "&d=false"; // Endpoint for "standard" search
        }
        
        $.ajax({
            type: 'GET',
            url: endpoint,
            success: function (response) {
                populateSuggestionBox(response);
            },
            error: function (error) {
                console.log(error);
            }
        });
    }


    // POPULATES AND DISPLAYS SUGGESTION BOX
    function populateSuggestionBox(keywords) {
        let keyword = "";
        currentSuggestionBox.html(''); // Clear suggestion box        
        for (let i = 0; i < keywords.length; i++) {
            keyword = keyword + '<li><a href="javascript:void(0);" role="button" onclick="getKeywordLink(this)">' + keywords[i] + '</a></li>';
        }
        if (keywords.length == 0) {
            currentSuggestionBox.addClass('d-none').attr('aria-hidden', true); // Hide suggestion box            
        } else {
            currentSuggestionBox.append('<ul>' + keyword + '</ul>'); // Inject suggestions into suggestion box
            currentSuggestionBox.removeClass('d-none').attr('aria-hidden', false); // Display suggestion box 
        }       
    }


    // HANDLES SELECTING KEYWORDS WITH CURSOR KEYS
    function keyboardNavigation(event) {
        if (event.which === 9) {
            return; // TAB key pressed, return
        }
        let focusIndex, noKeywords = currentSuggestionBox.find('a').length;

        // Finding current selected keyword
        currentSuggestionBox.find('a').each(function (index) {
            if ($(this).hasClass('selected')) {
                focusIndex = index;
            }
        });

        if (focusIndex == null) {
            // Nothing is selected, selecting first keyword from the list
            currentSuggestionBox.find('a:first').addClass('selected');
            return;
        } else {
            if (event.which === 40) { // Pressed arrow DOWN, remove current selection and select one keyword after
                if (focusIndex == noKeywords - 1) {
                    return; // Do nothing if the last keyword is already selected
                }
                focusIndex = focusIndex + 1;
            }
            if (event.which === 38) { // Pressed arrow UP, remove current selection and select one keyword after
                if (focusIndex == 0) {
                    return; // Do nothing if the first keyword is already selected
                }
                focusIndex = focusIndex - 1;
            }
            if (event.which === 13) { // Pressed ENTER key, selects currently keyword
                var selectedKeyword = currentSuggestionBox.find('a.selected');
                currentSuggestionBox.addClass('d-none').attr('aria-hidden', true); // Hides suggestion box 
                getKeywordLink(selectedKeyword);
            }
            currentSuggestionBox.find('a.selected').removeClass('selected');
            currentSuggestionBox.find('a').eq(focusIndex).addClass('selected');
        }
    }
});







;
$(function () {
    /*
     * Driven by Cookie Consent and Takeover Presence
     * suppress if either are
     */

    const uap = UAParser();
    var suppress = false;
    var initLoad = false;

    /*
     * TrustArc Listeners
     */
    document.addEventListener('trustarcUpdate', function (e) {
        // cookie consent is not present
        if (e.detail.name === "cookie" && e.detail.status === 'closed') {
            suppress = false;
        }
        // cookie consent is present
        else if (e.detail.name === "cookie" && e.detail.status === 'open') {
            suppress = true;
        }
    });

    /*
     * Takeover Listeners
     */
    document.addEventListener('takeoverEvent', function (e) {
        // cookie consent is not present
        if (e.detail.name === "open") {
            suppress = true;
        }
        // cookie consent is present
        else if (e.detail.name === "cookie" && e.detail.status === 'open') {
            // do nothing (for now);
        }
    });

    /*
     * HotJar DOM Listener
     */
    const bodyObserver = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            if (mutation.target.className.includes('_hj-widget-container')) {
                if (!initLoad) {
                    initLoad = true;
                    init();
                }
                if (suppress) {
                    $('._hj-widget-container').empty();
                }
            }
        });
    });

    bodyObserver.observe(document, {
        childList: true,
        attributes: true,
        subtree: true
    });

    function init() {
        // refined to mobile only
        if (uap.device.type === 'mobile' || uap.device.type === 'tablet') {
            $('._hj-widget-container').attr('data-loaded-as', 'mobile');
        } else {
            $('._hj-widget-container').attr('data-loaded-as', 'desktop');
        }
    }
});;
$(function () {
    /*
     * Apple Business Chat
     */

    const uap = UAParser();

    // limit to iOS and Mac OS
    if (uap.os.name === "iOS" | uap.os.name === "Mac OS") {
        $('.apple-business-chat-banner-container iframe').attr('title', 'Apple Business Chat');
    }
    // else remove from DOM
    else {
        $('.apple-business-chat-banner-wrapper').remove();
    }

});;
$(function () {
    if ($('.custom-block.alert-block').length === 0) return;

    var _customBlock = $('.custom-block.alert-block');

    for (var i = 0; i < _customBlock.length; i++) {
    
    }

    $(document).ready(function () {
        // TODO. Dismissal Cookie is an option in previous code, but there are no close-button.

        // Hide the modal if closed within last 24 hours / cookie
        //if (readCookie('homeAlertClosed')) {
        //    $('#emergency-bar').hide();
        //}
        // Close the modal and set the cookie
        //$('.uk-alert-close.uk-close').click(function () {
        //    createCookie('homeAlertClosed', true, 1);
        //});
    });

});;
$(function () {
    if ($('.custom-block.carousel-block').length === 0) return;

    var _customBlock = $('.custom-block.carousel-block');
    var _splideCollection = {};


    /*
     * Setup Waypoint
     */
    function setupWaypoint(carouselID) {
        _waypoint = new Waypoint.Inview({
            element: $('*[data-id="' + carouselID + '"]')[0],
            enter: function (direction) {
                _splideCollection[carouselID]['waypoint'] = 'enter';

                // block if manually paused
                if (_splideCollection[carouselID]['manualPlayback']) return;

                const { Autoplay } = _splideCollection[carouselID].splide.Components;
                Autoplay.play();
            },
            exited: function (direction) {
                // TODO. Only Pause if Player is actiely playing.

                const { Autoplay } = _splideCollection[carouselID].splide.Components;
                Autoplay.pause();

                _splideCollection[carouselID]['waypoint'] = 'exited';
            }
        });
    }

    for (var i = 0; i < _customBlock.length; i++) {

        var carouselID = $(_customBlock[i]).attr('data-id');
        var toPaginate = $(_customBlock[i]).find('.splide__slide').length > 1 ? true : false;
        var toAutoplay = $(_customBlock[i]).find('.splide__slide').length > 1 ? 'play' : 'pause';

        // store new splide
        _splideCollection[carouselID] =
        {
            splide: new Splide($(_customBlock[i]).find('.splide')[0], {
                type: 'fade',
                rewind: true,
                speed: 1000,
                arrows: false,
                autoplay: toAutoplay,
                pagination: toPaginate,
            })
        };

        _splideCollection[carouselID].splide.on('mounted', function () {
            setupWaypoint(carouselID);
        });

        // init manual playbacks
        _splideCollection[carouselID]['manualPlayback'] = false;


        // disable and hide pause-play track
        if (!toPaginate) {
            $(_customBlock[i]).find('.splide__toggle').prop("disabled", true);
            $(_customBlock[i]).find('.splide__controls ').addClass('d-none');
        }
        // play+pause toggle listener
        else {
            $(_splideCollection[carouselID].splide.root.children[0]).on('click', { carouselID: carouselID }, function (e) {
                // log manual status
                _splideCollection[carouselID]['manualPlayback'] = !$(e.target).hasClass('is-active');
            });
        }

        _splideCollection[carouselID].splide.mount();
    }

    /*
     * Setup Hamburger Listeners
     */
    document.addEventListener('hamburgerNavEvent', function (e) {
        switch (e.detail.name) {
            case "hide":
                $.each(_splideCollection, function (i, item) {
                    // if manually paused prior, do not resume.
                    if (!item.manualPlayback) {
                        const { Autoplay } = item.splide.Components;
                        Autoplay.play();
                    }
                });

                break;
            case "show":
                // pause carousel 

                $.each(_splideCollection, function (i, item) {
                    const { Autoplay } = item.splide.Components;
                    Autoplay.pause();
                });
                break;
        }
    });
});;
$(function () {
    if ($('.custom-block.carousel-promotion-block').length === 0) return;

    var _customBlock = $('.custom-block.carousel-promotion-block');
    var _splideCollection = {};
    var _responsive = {
        "small": {
            perPage: 3,
            drag: true,
            drag_fb: false,
            gap: 24,
            gap_fb: 0,
            arrows: true,
            arrows_fb: false,
            breakpoints: {
                992: {
                    perPage: 2
                },
                768: {
                    perPage: 1
                },
                576: {
                    //type: "loop",
                    perPage: 1,
                    arrows: false,
                    padding: {
                        right: 50,
                    },
                    gap: 0,
                }
            },
            breakpoints_fb: {
                992: {
                    perPage: 2
                },
                768: {
                    perPage: 1
                },
                576: {
                    type: "slide",
                    arrows: false,
                    gap: 15,
                }
            },
        },
        "medium": {
            perPage: 2,
            drag: true,
            drag_fb: false,
            gap: 24,
            gap_fb: 0,
            arrows: true,
            arrows_fb: false,
            breakpoints: {
                768: {
                    perPage: 1
                },
                576: {
                    //type: "loop",
                    perPage: 1,
                    arrows: false,
                    padding: {
                        right: 50,
                    },
                    gap: 0,
                }
            },
            breakpoints_fb: {
                768: {
                    perPage: 1
                },
                576: {
                    type: "slide",
                    arrows: false,
                    gap: 15,
                }
            },
        },
        "large": {
            perPage: 1,
            drag: true,
            drag_fb: false,
            gap: 24,
            gap_fb: 0,
            arrows: true,
            arrows_fb: false,
            breakpoints: {
                576: {
                    //type: "loop",
                    perPage: 1,
                    arrows: false,
                    padding: {
                        right: 50,
                    },
                    gap: 0,
                }
            },
            breakpoints_fb: {
                576: {
                    type: "slide",
                    arrows: false,
                    gap: 15,
                }
            },
        }
    }

    for (var i = 0; i < _customBlock.length; i++) {

        var carouselSize = $(_customBlock[i]).attr('data-carousel-size');
        var carouselID = $(_customBlock[i]).attr('data-id');
        //var toPaginate = $(_customBlock[i]).find('.splide__slide').length > 1 ? true : false;
        var toPerPage = _responsive[carouselSize].perPage;
        var toArrows = $(_customBlock[i]).find('.splide__slide').length > 1 ? _responsive[carouselSize].arrows : _responsive[carouselSize].arrows_fb;
        //var toBreakpoint = _responsive[carouselSize].breakpoints;
        var toBreakpoint = $(_customBlock[i]).find('.splide__slide').length > 1 ? _responsive[carouselSize].breakpoints : _responsive[carouselSize].breakpoints_fb;
        var toGap = $(_customBlock[i]).find('.splide__slide').length > 1 ? _responsive[carouselSize].gap : _responsive[carouselSize].gap_fb;
        var toDrag = $(_customBlock[i]).find('.splide__slide').length > 1 ? _responsive[carouselSize].drag : _responsive[carouselSize].drag_fb;

        // store new splide
        _splideCollection[carouselID] =
        {
            splide: new Splide($(_customBlock[i]).find('.splide')[0], {
                type: 'slide',
                drag: toDrag,
                speed: 500,
                arrows: toArrows,
                pagination: true,
                perPage: toPerPage,
                gap: toGap,
                focus: 0,
                omitEnd: true,
                breakpoints: toBreakpoint,
            })
        };

        /*
         *
         * On Arrow Update
         * splide's native disabling of arrow does not work. adding a listener to manage this.
         * 
         */
        _splideCollection[carouselID].splide.on('arrows:updated', function (e) {
            const _carouselID = $(e).closest('.custom-block.carousel-promotion-block').attr('data-id');
            const { Pagination } = _splideCollection[_carouselID].splide.Components;
            const { Arrows } = _splideCollection[_carouselID].splide.Components;
            const index = _splideCollection[_carouselID].splide.index + 1;

            // if active on first pagination
            if (index === 1) {
                // disable prev
                $(Arrows.arrows.prev).attr('disabled', true);
            } else {
                // remove disabled on prev
                $(Arrows.arrows.prev).removeAttr('disabled');
            }
            // if active on last pagination
            if (index === Pagination.items.length || Pagination.items.length === 0) {
                // disable next
                $(Arrows.arrows.next).attr('disabled', true);
            } else {
                // remove disabled on next
                $(Arrows.arrows.next).removeAttr('disabled');
            }

        });

        //_splideCollection[carouselID].splide.on('mounted', function () {
        //    console.log('mounted ' + carouselID);
        //});

        _splideCollection[carouselID].splide.mount();
    }
});;
$(function () {
    if ($('.custom-block.gallery-block').length === 0) return;

    var _customBlock = $('.custom-block.gallery-block .gallery-block-container');

    _customBlock.each(function (i) {
        $(this).gallery({
            height: 500,
            items: 6,
            thmbHeight: 300,
            200: {
                items: 4,
                height: 250
            },
            768: {
                items: 8
            },
            992: {
                items: 10
            }
        });
    });
     
});;
$(function () {
    if ($('.custom-block.major-tenant-carousel-block').length === 0) return;

    var _customBlock = $('.custom-block.major-tenant-carousel-block');
    var _splideCollection = {};


    /*
     * Setup Waypoint
     */
    function setupWaypoint(carouselID) {
        _waypoint = new Waypoint.Inview({
            element: $('*[data-id="' + carouselID + '"]')[0],
            enter: function (direction) {
                _splideCollection[carouselID]['waypoint'] = 'enter';

                // block if manually paused
                if (_splideCollection[carouselID]['manualPlayback']) return;

                const { AutoScroll } = _splideCollection[carouselID].splide.Components;
                AutoScroll.play();
            },
            exited: function (direction) {
                // TODO. Only Pause if Player is actiely playing.

                const { AutoScroll } = _splideCollection[carouselID].splide.Components;
                AutoScroll.pause();

                _splideCollection[carouselID]['waypoint'] = 'exited';
            }
        });
    }

    for (var i = 0; i < _customBlock.length; i++) {

        var carouselID = $(_customBlock[i]).attr('data-id');

        // store new splide
        _splideCollection[carouselID] =
        {
            splide: new Splide($(_customBlock[i]).find('.splide')[0], {
                type: 'loop',
                drag: 'free',
                focus: 'center',
                keyboard: 'focused',
                perPage: 7,
                //gap: '80px',
                breakpoints: {
                    //1400: {
                    //    perPage: 8,
                    //    gap: '4em'
                    //},
                    1200: {
                        perPage: 6,
                    },
                    992: {
                        perPage: 5,
                    },
                    768: {
                        perPage: 4,
                    },
                    576: {
                        perPage: 5,
                        gap: '40px',
                    }
                },
                arrows: false,
                pagination: false,
                autoScroll: {
                    speed: 1,
                    useToggleButton: true,
                },
            })
        }

        _splideCollection[carouselID].splide.on('mounted', function (e) {
            setupWaypoint(carouselID);
        });

        // init manual playbacks
        _splideCollection[carouselID]['manualPlayback'] = false;

        // play+pause toggle listener
        $(_splideCollection[carouselID].splide.root.children[0]).on('click', { carouselID: carouselID }, function (e) {
            // log manual status
            _splideCollection[carouselID]['manualPlayback'] = $(e.currentTarget).hasClass('is-active');
        });

        _splideCollection[carouselID].splide.mount(window.splide.Extensions);
    }

    /*
     * Setup Hamburger Listeners
     */
    document.addEventListener('hamburgerNavEvent', function (e) {
        switch (e.detail.name) {
            case "hide":
                $.each(_splideCollection, function (i, item) {
                    // if manually paused prior, do not resume.
                    if (!item.manualPlayback) {
                        const { AutoScroll } = item.splide.Components;
                        AutoScroll.play();
                    }
                });

                break;
            case "show":
                // pause carousel 
                $.each(_splideCollection, function (i, item) {
                    const { AutoScroll } = item.splide.Components;
                    AutoScroll.pause();
                });
                break;
        }
    });
});;
$(function () {
    if ($('.custom-block.seo-block').length === 0) return;

    var _customBlock = $('.custom-block.seo-block');

    for (var i = 0; i < _customBlock.length; i++) {
        // attach bottom margin if no p-tag is present in the rte
        if ($(_customBlock[i]).find('.rich-text > p').length > 0) {
            $(_customBlock[i]).find('.rich-text').addClass('mb-3');
        }
    }

});;
$(function () {
    /*
     * Driven by Cookie Consent Presence
     * If cookie banner is not present via dispatch event, we proceed with setup
     */

    if ($('.custom-block.takeover-block').length === 0) return;

    var _customBlock = $('.custom-block.takeover-block');

    document.addEventListener('trustarcUpdate', function (e) {
        // cookie consent is not present
        if (e.detail.name === "cookie" && e.detail.status === 'closed') {
            setupTakeover();
            setupContactModal();
        }
        // cookie consent is present
        else if (e.detail.name === "cookie" && e.detail.status === 'open') {
            // do nothing (for now);
        }
    });

    function setupTakeover() {
        for (var i = 0; i < _customBlock.length; i++) {
            var takeoverID = $(_customBlock[i]).attr('data-id');

            if (readCookie('hpTakeover_' + takeoverID)) {
                $('#homepageTakeover').remove();
            } else {

                // TEMP CONDITIONAL DUE TO setupContactModal CONFLICT
                if ($('#homepageTakeover').length > 0) {
                    // TODO: Need to Convert this to BS

                    $.UIkit.modal("#homepageTakeover").show();
                    new FTWrapper('#homepageTakeover', { initFocus: 'a.uk-modal-close', lastFocus: true, ariaHide: '#footer,.skipnav,#homepage-nav,#offcanvas' });
                    impressionTracking('#homepageTakeover', 'takeover');

                    // Dispatch Opened Event
                    document.dispatchEvent(trustarcTakeoverOpenEvent);

                    // Create Close Cookie on Homepage Takeover Exit
                    $(_customBlock[i]).find('.uk-modal-close').on('click keydown', function (e) {
                        if (e.key === "Enter" || e.type === "click") {
                            e.preventDefault();

                            // distinguish between a successful form or not
                            var expire = $(_customBlock[i]).find('.form-success').hasClass('uk-hidden') ? 1 : 365;

                            createCookie('hpTakeover_' + takeoverID, true, expire);
                            $.UIkit.modal("#homepageTakeover").hide();
                            $(this).off();

                            // Dispatch Closed Event
                            document.dispatchEvent(trustarcTakeoverClosedEvent);
                        }

                        //if (e.type === "keyup") {
                        //    if (e.key === "Enter") {
                        //        // distinguish between a successful form or not
                        //        var expire = $('#homepageTakeover .form-success').hasClass('uk-hidden') ? 1 : 365;
                        //        createCookie('hpTakeover_' + @Model.Takeover.Id, true, expire);
                        //        $.UIkit.modal("#homepageTakeover").hide();
                        //        $(this).off();
                        //    }
                        //}
                        //else {
                        //    // distinguish between a successful form or not
                        //    var expire = $('#homepageTakeover .form-success').hasClass('uk-hidden') ? 1 : 365;
                        //    createCookie('hpTakeover_' + @Model.Takeover.Id, true, expire);
                        //    $(this).off();
                        //}
                    });

                    // Prevent clicking the ad from creating close cookie
                    $(_customBlock[i]).find('.result-hover').on('click', function (e) {
                        e.stopPropagation();
                    });
                }
            }

        }        
    }

    // C O N T A C T - M O D A L
    // TODO. This needs to be merged into setupTakeover func
    function setupContactModal() {
        if (typeof displayContactModal !== 'undefined') {
            var contactModalCookie = "contactModalClosed"; // normal
            if (!readCookie(contactModalCookie) && displayContactModal) {
                var modal = $.UIkit.modal(".contact-modal.secondary");

                setTimeout(
                    function () {
                        modal.show();

                        new FTWrapper('#contactModal', { initFocus: 'a.uk-modal-close', lastFocus: true });
                    }, 15000);
            }
        }
    }

    $(document).ready(function () {
        // TODO. Dismissal Cookie is an option in previous code, but there are no close-button.

        // Hide the modal if closed within last 24 hours / cookie
        //if (readCookie('homeAlertClosed')) {
        //    $('#emergency-bar').hide();
        //}
        // Close the modal and set the cookie
        //$('.uk-alert-close.uk-close').click(function () {
        //    createCookie('homeAlertClosed', true, 1);
        //});
    });

});;
/*
 * V I D E O - P R O M O T I O N  |  B L O C K 
 */
$(function () {
    if ($('.custom-block.video-promotion-block').length === 0) return;

    var _customBlock = $('.custom-block.video-promotion-block');
    //var ccCond = false;

    var _playBackCondCollection = [];
    var _manualPlaybackCondCollection = [];
    var _controllerCollection = [];
    var _playerCollection = [];
    var _waypointStatusCollection = [];

    /*
     * Set Min-Height
     * Currently not utilized. Initialized at bottom and maintained by debounce.
     */ 
    function setMinHeight() {
        var minHeight = _customBlock.find('.overlay-content-container > div').outerHeight();
        var activeStyle = _customBlock.attr('style');
        var newStyle = '';
        var newStyleArr = [];
        var styleFound = false;

        if (activeStyle !== undefined) {
            // remove last semicolon if present
            newStyle = activeStyle.charAt(activeStyle.length - 1) === ';' ? activeStyle.slice(0, -1) : activeStyle;
            // convert to array
            newStyleArr = newStyle.split(';');
            // new min-height style
            newStyle = 'min-height:' + Math.round(minHeight) + 'px';
            // search for existing min-height and replace
            for (var i = 0; i < newStyleArr.length; i++) {
                if (newStyleArr[i].includes('min-height')) {
                    newStyleArr[i] = newStyle;
                    styleFound = true;
                }
            }
            // if style does not exist. push to array
            if (!styleFound) {
                newStyleArr.push(newStyle);
            }
            // new inline style
            newStyle = newStyleArr.join(';') + ';';

            _customBlock.attr('style', newStyle);
        }
    }

    /*
     * Setup Video Player
     */

    function setupVideoPlayer(videoID, count) {
        _playerCollection[videoID].on('play', function () {
            // block if manually paused
            if (_manualPlaybackCondCollection[videoID]) return;

            _playBackCondCollection[videoID] = true;
            _controllerCollection[videoID].find('.pause-play').removeClass('paused').removeAttr('disabled').text('Pause video.');
        });

        _playerCollection[videoID].on('pause', function () {
            _playBackCondCollection[videoID] = false;
            _controllerCollection[videoID].find('.pause-play').addClass('paused').text('Play video.');
        });

        _playerCollection[videoID].ready().then(function () {
            setupWaypoint(videoID);
        });
    }

    /*
     * Setup Video Listeners
     */

    function setupVideoListeners(videoID) {
        // Pause + Play
        _controllerCollection[videoID].find('.pause-play').on('click', function () {
            if (!_playBackCondCollection[videoID]) {
                _manualPlaybackCondCollection[videoID] = false;
                _playerCollection[videoID].play();
            } else {
                _manualPlaybackCondCollection[videoID] = true;
                _playerCollection[videoID].pause();
            }
        });

        //// Closed Caption
        //_controllerCollection[videoID].find('.closed-caption').on('click', function () {
        //    if (ccCond) {
        //        _playerCollection[videoID].disableTextTrack();
        //        ccCond = false;
        //        $(this).addClass('off');
        //    } else {
        //        _playerCollection[videoID].enableTextTrack('en');
        //        ccCond = true;
        //        $(this).removeClass('off');
        //    }
        //});

        // Impression Tracking
        //impressionTracking($('.promotional-video'), 'generic');

        // Listen to Hamburger
        document.addEventListener('hamburgerNavEvent', function (e) {
            switch (e.detail.name) {
                case "hide":
                    if (_waypointStatusCollection[videoID] === 'enter') {
                        // block if manually paused
                        if (_manualPlaybackCondCollection[videoID]) return;

                        _playerCollection[videoID].play();
                    }
                    break;
                case "show":
                    if (_waypointStatusCollection[videoID] === 'enter') {
                        _playerCollection[videoID].pause();
                    }
                    break;
            }
        });
        //document.addEventListener('hamburgerNavEvent', function () {
        //    if (_waypointStatusCollection[videoID] === 'enter') {
        //        console.log('hamburger show');
        //        //player.pause();
        //    }
        //});

        // Handle WCAG Pause Video option in Header
        // Only supports first video
        if (i === 0) {
            $('body > header .visually-hidden-focusable.video-promotion').removeClass('d-none');
            $('body > header .visually-hidden-focusable.video-promotion').on('click', function (e) {
                e.preventDefault();
                _playerCollection[videoID].pause();
            })
        }
    }

    //var blockResizeFunc = debounce(setMinHeight, 250);
    //window.addEventListener('resize', blockResizeFunc);

    /*
     * Setup Waypoint
     */
    function setupWaypoint(videoID) {
        _waypoint = new Waypoint.Inview({
            element: $('*[data-id="' + videoID + '"]').find('.video-container')[0],
            enter: function (direction) {
                _waypointStatusCollection[videoID] = 'enter';

                // block if manually paused
                if (_manualPlaybackCondCollection[videoID]) return;

                _playerCollection[videoID].play();
            },
            exited: function (direction) {
                // only pause if player is actively playing
                _playerCollection[videoID].getPaused().then(function (paused) {
                    if (!paused) {
                        _playerCollection[videoID].pause();
                    }
                })

                _waypointStatusCollection[videoID] = 'exited';
            }
        });
    }


    // I N I T

    //setMinHeight();

    for (var i = 0; i < _customBlock.length; i++) {
        var videoID = $(_customBlock[i]).attr('data-id');
        var iframe = $(_customBlock[i]).find('iframe');
        var controller = $(_customBlock[i]).find('.controller');
        var player = new Vimeo.Player(iframe);

        _playBackCondCollection[videoID] = false;
        _manualPlaybackCondCollection[videoID] = false;
        _controllerCollection[videoID] = controller;
        _playerCollection[videoID] = player

        setupVideoPlayer(videoID, i);
        setupVideoListeners(videoID, i);
    }
});;
$(function () {
    // TODO.
    // Need to tidy up this code and isolate the targeting

    if ($('.custom-block.video-pushdown-block').length === 0) return;

    console.log('video pushdown...');

    var _iframe = $('.video-pushdown').find('iframe');
    var _controller = $('.video-pushdown .controller');
    var _player = new Vimeo.Player(_iframe);
    var _waypoint;

    var ccCond = false;
    var playbackCond = false;
    var playbackManualCond = false;
    var volCond = false;
    var volManualCond = false;
    var replayInterval;
    var volInterval;
    var pauseReplayFlag = false;
    var replayCount;


    /*
    * Setup Video Player
    */
    function setupPlayer() {
        _player.on('play', function () {
            playbackCond = true;
            _controller.find('.pause-play').addClass('paused');
            clearInterval(replayInterval);
            replayInterval = undefined;
        });

        _player.on('pause', function () {
            playbackCond = false;
            _controller.find('.pause-play').removeClass('paused');
        });

        _player.on('ended', function () {
            // countdown
            replayCount = 5;
            replayInterval = setInterval(function () {
                // prevent countdown to proceed if not in view
                if (pauseReplayFlag) return;

                // expose aria-live
                $('[role="timer"]').removeClass('hidden');

                _controller.find('.timer').html(' ' + replayCount);
                if (replayCount === 5) $('button.replay').removeClass('hidden').prop('disabled', false);
                replayCount--;

                if (replayCount < 0) {
                    // Session Storage
                    sessionStorage.setItem('promotionalVideo', true);
                    collapseVideo();
                }
            }, 1000);
        });

        _player.ready().then(function () {
            _controller.find('.pause-play').prop('disabled', false);
            _controller.find('.volume').prop('disabled', false);
            _controller.find('.closed-caption').prop('disabled', false);
            _player.disableTextTrack();

            // need to flip the play-pause if pausing up front
            if (playbackManualCond) {
                playbackCond = false;
                _controller.find('.pause-play').removeClass('paused');
            }

            setupWaypoint();
        });
    }


    /*
    * Setup Listeners
    */
    function setupListeners() {
        // Pause + Play
        _controller.find('.pause-play').on('click', function () {
            if (!playbackCond) {
                _player.play();
                playbackManualCond = false;
            } else {
                _player.pause();
                playbackManualCond = true;
            }

            // Hide Replay Button
            _controller.find('.replay').addClass('hidden').prop('disabled', true);
        });

        // Closed Caption
        _controller.find('.closed-caption').on('click', function () {
            if (ccCond) {
                _player.disableTextTrack();
                ccCond = false;
                $(this).addClass('off');play
            } else {
                _player.enableTextTrack('en');
                ccCond = true;
                $(this).removeClass('off');
            }
        });

        // Mute
        _controller.find('.volume').on('click', function (event, cond = true) {
            if (!volCond && cond) {
                fadeVolumeUp();
                volCond = true;
                volManualCond = true;
                $(this).removeClass('muted');
            } else {
                mute();
                volCond = false;
                if (cond) volManualCond = false;
                $(this).addClass('muted');
            }
        });

        // Replay
        _controller.find('.replay').on('click', function () {
            _player.play();
            $(this).addClass('hidden').prop('disabled', true);
        });

        // Impression Tracking
        impressionTracking($('.video-pushdown'), 'generic');
    }


    /*
    * Setup Waypoint
    */
    function setupWaypoint() {
        console.log('setupWaypoint');


        _waypoint = new Waypoint.Inview({
            element: $('.video-pushdown-block')[0],
            enter: function (direction) {
                pauseReplayFlag = false;

                console.log('playbackManualCond: ' + playbackManualCond);

                // play if not in no countdown
                if (replayInterval === undefined && playbackManualCond === false) {
                    _player.play();
                }

                if (volManualCond) {
                    _controller.find('.volume').trigger('click');
                }
            },
            exited: function (direction) {
                // pause-flag if countdown is present
                if (replayInterval !== undefined) {
                    pauseReplayFlag = true;
                }

                _player.pause();
                _controller.find('.volume').trigger('click', [false]);
            }
        });
    }

    /*
    * Collapse Video
    */
    function collapseVideo() {
        clearInterval(replayInterval);
        _controller.find('button').addClass('hidden').prop('disabled', true);
        var videoHeight = $('.video-pushdown-block').height();

        // Collapse
        $('.video-pushdown-block').animate({
            height: "-=" + videoHeight
        }, 2000, function () {
            _player.destroy();
            // Remove Listeners
            _controller.find('.pause-play').off();
            _controller.find('.closed-caption').off();
            _controller.find('.volume').off();
            _waypoint.destroy();
            $('.video-pushdown-block').remove();
            $('.skipnav .skip-promo-video').remove();
        });
    }


    /*
    * Fade Volume Up
    */
    function fadeVolumeUp() {
        var variance = 0.1;
        var newVolume = variance;

        clearInterval(volInterval);
        volInterval = setInterval(function () {
            _player.setVolume(newVolume);
            newVolume = newVolume + variance;

            if (newVolume > 1 || newVolume < 0) {
                clearInterval(volInterval);
            }
        }, 100);
    }


    /*
    * Mute
    */
    function mute() {
        clearInterval(volInterval);
        _player.setVolume(0);
    }

    /*
     * Setup
     */
    function setup() {
        var videoOverride;

        // Pull URL Params
        const params = new URLSearchParams(window.location.search);
        for (const param of params) {
            if (param[0] === "promoVideo" && param[1] === "true")
                videoOverride = true;
        }

        // Remove From DOM
        if (sessionStorage.getItem("promotionalVideo") && !videoOverride) {
            _player.destroy();
            $('.video-pushdown-block').remove();
            $('.skipnav .skip-promo-video').remove();
        }
        // Proceed
        else {
            setupPlayer();
            setupListeners();
        }
    }

    document.addEventListener('trustarcUpdate', function (e) {
        // cookie consent is not present
        if (e.detail.name === "cookie" && e.detail.status === 'closed') {
            setup();
        }
        // cookie consent is present
        else if (e.detail.name === "cookie" && e.detail.status === 'open') {
            // manually pause until cookie is dismissed
            playbackManualCond = true;
            setup();
        }
        // cookie consent dismissed
        else if (e.detail.name === "cookie" && e.detail.status === 'closing') {
            // manually pause until cookie is dismissed
            _player.play();
        }
    });
});;
(function ($) {
    // Attach Listener
    function attachFilterCollapseListener($targ) {
        //console.log("attachFilter");
        // Detect ESC and DOM (Outside Filter popup) Clicks
        $(window).on('click keyup', function (e) {
            // Restrict to Mouse Click and Esc
            if (e.which === 1 || e.which === 27) {
                detachFilterCollapseListener($(this), $targ);
            }        
        });

        // Update Aria-Expand Attr
        $targ.attr('aria-expanded', 'true');

        return $(this);
    }

    // Remove Listeners and Collapse Filter
    function detachFilterCollapseListener($collapse, $targ) {
        //console.log("detachFilter");
        $collapse.off('click keyup');
        $targ.removeClass('uk-open');
        $targ.focus();

        // Update Aria-Expand Attr
        $targ.attr('aria-expanded', 'false');

        $targ.find('[class*="-drop-down-selector"]').removeClass('active');
        $targ.find('.drop-down').removeClass('active').attr('aria-expanded', 'false');

    }

    $(document).ready(function () {
        var $collapseListener;   

        $('.sales-events-filter-bar .drop-container').on('click', function (e) {
            var $local = $(this);
            // e.stopPropagation();
            e.preventDefault();

            setTimeout(function () {
                if ($local.hasClass('uk-open')) {
                     // Update ARIA
                    $local.attr('aria-expanded', true);
                    attachFilterCollapseListener($local);
                } else {
                     // Update ARIA
                    $local.attr('aria-expanded', false);
                }
            }, 100);        
        });

        $('.sales-events-filter-bar .drop-container').on('keydown', function (e) {
            var $local = $(this);

            //e.stopPropagation();

            /*
             *  Arrow Listeners
             */

            // Up and Left Arrows and Tab-Backwards
            if ($(this).hasClass('uk-open') && (e.which === 38 || e.which === 37 || (e.shiftKey && e.key === 'Tab'))) {
                // Jump to drop container
                if ($(":focus").hasClass('drop-container')) {
                    $local.find('.filter-item:last').focus();
                }
                // If top of ordered list and first, jump to the last item
                else if ($(":focus").is('li[tabindex="-1"]:first-child') && $(":focus").closest('ul')[0] === $(":focus").closest('.level-1').find('ul').first()[0]) {
                    $(":focus").closest('.level-1').find('.filter-item:last').focus();
                }
                // If top of ordered list, jump out into previous group if header has no focus
                else if ($(":focus").is('li[tabindex="-1"]') && $(":focus")[0] === $(":focus").closest('ul').find('.filter-item').first()[0]) {
                    $(":focus").closest('div').prev().find('.filter-item:last').focus();
                }
                // If top of ordered list, jump out and back into the header
                //else if ($(":focus").is('li[tabindex="-1"]:first-child')) {
                //    console.log("jump2?");
                //    $(":focus").closest('div').find('.filter-item:first').focus();
                //}
                else if (!$(":focus").is('li') && $(":focus").closest('div').prev().is('div')) {
                    $(":focus").closest('div').prev().find('.filter-item:last').focus();
                }
                // Previous list item
                else if ($(":focus").prev().is('li')) {
                    $(":focus").prev().focus();
                }
                // Identify nested parent is expanded then Jump back down
                else if ($(':focus').parent().find('.filter-item').length === 1 && $(':focus').attr('aria-expanded') === "true") {
                    $(':focus').next().find('.drop-down-item:last').focus();  
                }
                // Assumes nested single element and not last item
                else if ($(':focus').parent().find('.filter-item').length === 1 && $(':focus').parent().prev().find('.filter-item').length > 0) {
                    $(':focus').parent().prev().find('.filter-item:first').focus();
                }
                // Jump back up into 1st Tier
                else if ($(':focus').hasClass('drop-down-item') && $local.find('.a-z-drop-down-selector').hasClass('active') && $(':focus').parent().prev().find('.drop-down-item').length === 0) {
                    $local.find('.a-z-drop-down-selector').prev().focus();
                }
                // Cycle through the 2nd Tier
                else if ($(':focus').hasClass('drop-down-item') && $(':focus').parent().prev().find('.drop-down-item').length > 0) {
                    $(':focus').parent().prev().find('.drop-down-item:first').focus();
                }
                // Traps keyboard via js
                else {
                    //// If 2nd Tier present, jump to last item of 2nd Tier
                    //if ($local.find('.a-z-drop-down-selector').hasClass('active')) {
                    //    $local.find('.a-z-drop-down-selector .drop-down-item:last').focus();
                    //}
                    // Jump to last item of 1st Tier
                    //else {
                    $local.find('.filter-item:last').focus();
                    //}
                }

                e.preventDefault();
            }
            // Down and Right Arrows and Tab-Forward
            else if ($(this).hasClass('uk-open') && (e.which === 40 || e.which === 39 || e.which === 9)) {
                // Jump to drop container
                if ($(":focus").hasClass('drop-container')) {
                    $local.find('.filter-item:first').focus();
                }
                // If an unodered list, drill down
                else if ($(":focus").next().is('ul')) {
                    $(":focus").next().children()[0].focus();
                }
                // If an current focus is LI, next is an LI and next element group contains a (filter) item
                else if ($(":focus").is('li') && !$(":focus").next().is('li') && $(":focus").closest('div').next().find('.filter-item').length > 0) {
                    $(":focus").closest('div').next().find('.filter-item')[0].focus();
                }
                // Identify if next item is hidden, then find next item that's not
                // For Hidden on Mobile
                else if ($(":focus").next().css('display') === 'none' && $(":focus").attr('aria-expanded') !== "true" && !$(":focus").hasClass('drop-down')) {
                    var _displayNone = false;
                    $filterItem = $(":focus").closest('ul').find('.filter-item');

                    // go through the FilterItem list and identify any that are not hidden
                    // make sure it's not itself
                    for (var i = 0; i < $filterItem.length; i++) {
                        if ($($filterItem[i]).css('display') !== 'none' && $(":focus")[0] !== $filterItem[i]) {
                            $($filterItem[i]).focus();
                            _displayNone = true;
                            break;
                        }
                    }

                    // If no FilterItem were found, we'll jump it to the next DIV
                    if (!_displayNone) {
                        $(":focus").closest('div').next().find('.filter-item')[0].focus();
                    }

                }
                // Next list item
                else if ($(":focus").next().is('li')) {
                    $(":focus").next().focus();
                }
                // Assumes nested single element and not last item
                else if ($(':focus').parent().find('.filter-item').length === 1 && $(':focus').parent().next().find('.filter-item').length > 0) {
                    $(':focus').parent().next().find('.filter-item:first').focus();
                }
                // Support 2nd Tier Drop-Down. Checks if expanded and focus is on the parent drop-down
                else if ($(':focus').next().hasClass('a-z-drop-down-selector active') && $(':focus').hasClass('filter-item')) {
                    $(':focus').next().find('.drop-down-item:first').focus();  
                }
                // Cycle through the 2nd Tier
                else if ($(':focus').hasClass('drop-down-item') && $(':focus').parent().next().find('.drop-down-item').length > 0) {
                    $(':focus').parent().next().find('.drop-down-item:first').focus();
                }
                // Jump to Parent of 2nd Tier
                else if ($(':focus').hasClass('drop-down-item')) {
                    $local.find('.filter-item[aria-expanded="true"]').focus();
                }
                // Traps keyboard via js
                else {
                    $local.find('.filter-item:first').focus();
                }
            
                e.preventDefault();
            }
            

            /*
             *  Keyboard Listeners
             */

            // Expand via 'Enter' and 'Spacebar' only
            if (!$(this).hasClass('uk-open') && (e.which === 13 || e.which === 32)) {
                e.preventDefault();

                // Add UIkit open 
                $(this).addClass('uk-open');
                // Center Dropdown | Mimic UIkit's Click
                $(this).find('.directory.level-1').css('minWidth', $('.sales-events-main').css('width'));
                console.log(window.matchMedia("only screen and (max-width: 959px)"));
                if (!window.matchMedia("only screen and (max-width: 959px)").matches) {
                    $(this).find('.directory.level-1').css('left', $('.sales-events-main').offset().left - $(this).offset().left);
                }
                

                // Attach Collapse Click Listener
                $collapseListener = attachFilterCollapseListener($local);
            }
            // Collapse via 'Enter' and 'Spacebar' only
            else if ($(this).hasClass('uk-open') && (e.which === 13 || e.which === 32) && !$(":focus").hasClass('filter-item')) {
                e.preventDefault();
                
                // Detach Collapse Click Listener
                detachFilterCollapseListener($collapseListener, $local);
            }
            // Listen To 'Enter' key and must be focused on (filter) item
            else if ($(this).hasClass('uk-open') && $(':focus').hasClass('filter-item') && e.which === 13) {
                // Identify if there is filter-item has a drop-down-item. 
                // Only collapse if drop-down-item isn't present
                if ($(':focus').parent().find('.drop-down-item').length === 0) {
                    detachFilterCollapseListener($collapseListener, $local);
                }
            }
            // Listen To 'Enter' key and must be focused on (drop-down) item
            else if ($(this).hasClass('uk-open') && $(':focus').hasClass('drop-down-item') && e.which === 13) {
                detachFilterCollapseListener($collapseListener, $local);
            }
            // Stop all other key actions besides Tabbing
            else if (e.which !== 9 && (e.shiftKey && e.key === 'Tab')) {
                e.preventDefault();
            }
        });
    });

})(jQuery);;
/*!
 * This is a holdover from the old custom.js file
 * Only adding things as needed and need to move eventually clean this up.
 * 
 * need to do away with these functions being exposed publicly.
 */

/*!
 * F O R M  |  F U N C T I O N S
 */

/*!
 * Setup Multiple Select
 */
function setupMultipleSelect(id) {
    var group = $($('select[multiple="multiple"]')[id]).find('optgroup').length;
    //var label = $($('select[multiple="multiple"]')[id]).closest('label').find('.wcag-label');
    var placeholder = $($('select[multiple="multiple"]')[id]).attr('data-placeholder') !== undefined ? $($('select[multiple="multiple"]')[id]).attr('data-placeholder') : "Select One or More";
    var placeholderMobile = $($('select[multiple="multiple"]')[id]).attr('data-placeholder-mobile') !== undefined ? $($('select[multiple="multiple"]')[id]).attr('data-placeholder-mobile') : "Select One or More";
    var local = $($('select[multiple="multiple"]')[id]);
    var isMobile = window.matchMedia("only screen and (max-width: 767px)");

    local.multipleSelect({
        selectAll: false,
        placeholder: isMobile.matches ? placeholderMobile : placeholder,
        width: '100%',
        styler: function (value) {
            // Overwrite Styles if Group not present
            if (group === 0) {
                return 'margin-left: 0;';
            }
        },
        onOpen: function () {
            // WCAG. Force collapse of dropdown if focus leaves the dropdown
            $('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]').on('focus', function (e) {
                if ($(e.currentTarget).closest('.ms-drop').length === 0 && $(e.currentTarget !== 'button.ms-choice') && $(e.currentTarget).attr('id') !== 'maincontent') {
                    local.multipleSelect('close');
                    // unbind when closed
                    $('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]').off('focus');
                }
            });
        },
        onAfterCreate: function () {
            $(local).attr('tabindex', '-1');
        }
    });

    // checkMultipleSelect(id);
    $($('select[multiple="multiple"]')[id]).attr('data-empty', 'true');

    $(window).on('resize', $.debounce(250, function () {
        if (isMobile.matches) {
            local.multipleSelect('refreshOptions', { placeholder: placeholderMobile });
        } else {
            local.multipleSelect('refreshOptions', { placeholder: placeholder });
        }
    }));
}
/*!
 * Check Multiple Select
 */
function checkMultipleSelect() {
    $select = $('select[multiple="multiple"]');

    for (var i = 0; i < $select.length; i++) {
        if ($($select[i]).multipleSelect('getSelects').length > 0) {
            $($select[i]).attr('data-empty', 'false');
        } else {
            $($select[i]).attr('data-empty', 'true');
        }
    }
}
/*!
 * Check Required Multiple Select
 */
function checkRequiredMultipleSelect(local) {
    $select = $(local).find('select[multiple="multiple"]');
    var found = false;

    for (var i = 0; i < $select.length; i++) {
        if ($($select[i]).attr('select-required') === "true" && $($select[i]).attr('data-empty') === "true" && $($select[i]).hasClass('.two-stepper') === false) {
            found = $select[i];
        }
    }

    return found;
}
/*!
 * Check Required Checkbox
 */
function checkRequiredCheckbox() {
    $checkbox = $('.checkbox-container.required input[name^="list"]');
    var found = $checkbox.length > 0 ? $checkbox[0] : false;

    for (var i = 0; i < $checkbox.length; i++) {
        if ($checkbox[i].checked === true) {
            found = false;
        }
    }

    return found;
}

/*!
 * Impression Tracking
 */
function impressionTracking(el, type) {
    var label = '';

    switch (type) {
        case 'takeover':
            label = $($(el).find('.uk-modal-dialog')).attr('data-impression-label');
            break;
        case 'accordion':
        case 'generic':
            label = $(el).attr('data-impression-label');
            break;
    }

    if (label !== '') {
        label = label.split('||');

        // data retrieved will like like the following...
        // UAcategory || UAaction || UAlabel || GA4objectType || GA4impressionLabel

        // GA4 Tracking 
        dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'impression', 'dynev.p1_name': 'object_type', 'dynev.p1_value': label[3], 'dynev.p2_name': 'impression_label', 'dynev.p2_value': label[4] });
    }
}

/*!
 * S A L E S - E V E N T S - F I L T E R  |  F U N C T I O N S
 */

/* function for filtering events and sales */
function filterSalesEvents(filter, el, e, displayVal) {
    // console.log('filterSalesEvents');

    var keyboard = e.type === 'keydown' ? false : true;
    // WCAG Keydown - Only 'Enter' Key    
    if (e.type === 'keydown') {
        if (e.which !== 13) return;
    }

    showSelectedFilter(displayVal, keyboard);
    showHideFeaturedSalesEvents(false);

    $('.sales-events-filter-bar .filter-item.a-z .group').text("a - z"); // Reset A-Z filter
    $('.sales-events-filter-bar .a-z-drop-down-selector').removeClass("active");
    $('.sales-events-filter-bar .a-z-drop-down-selector .drop-down-item').removeClass("active");
    $('.date-selected-display').removeClass("active");
    $('.sales-events-filter-bar').toggleClass("disabled");

    if ($('.sales-events-filter-bar').hasClass('disabled')) {
        $('.sales-events-filter-bar .drop-container').attr('tabindex', '-1').attr('aria-disabled', 'true');

    } else {
        $('.sales-events-filter-bar .drop-container').attr('tabindex', '0').attr('aria-disabled', 'false');
    }

    $('.disable-filter').toggleClass("disabled");

    if (history.replaceState) {
        var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?filter=' + filter.split(' ').join('');
        window.history.replaceState({ path: newurl }, '', newurl);
    }

    $('.sales-events-filter-bar .filter-item').removeClass("active");
    var selectedFilter = $(el).data("filter");
    $('.sales-events-filter-bar .filter-item[data-filter="' + selectedFilter + '"]').addClass("active");


    if (filter === "all" || filter === "reset") {
        $(".sales-events-container").removeClass("filter-hide");
        //$(".results-container-inner").find('.stuff-container').removeClass('filter-hide');
        $(".results-container-inner").find('.custom-block.primary-promotion-block').removeClass('d-none');
        $(".results-container-inner").find('hr').removeClass('filter-hide');
        clearSelectedFilter();
        var isDirectory = false;
        if ($('.sales-events-filter-bar').hasClass('directory')) isDirectory = true;
        if (isDirectory) {
            $("#directorySearchForm")[0].reset();
            $("input.search").focus();
            $("input.search").submit();
            $('.sales-events-filter-bar.directory').removeClass("disabled");
        }

        // Hide No-Results
        $('.no-results').addClass('uk-hidden');
    }
    else {
        var theFilterCounter = 0;
        $(".sales-events-container").each(function () {
            var theFilter = $(this).data("filter");
            if (theFilter.indexOf(filter) > -1) {
                $(this).removeClass("filter-hide");
                theFilterCounter++;
            }
            else {
                $(this).addClass("filter-hide");
            }
        });

        // Display No-Results if none returned
        showNoResults(theFilterCounter);

        //$(".results-container-inner").find('.stuff-container').addClass('filter-hide');
        $(".results-container-inner").find('.custom-block.primary-promotion-block').addClass('d-none');
    }

    $('.show-all-event-sales').addClass("uk-hidden");
    toggleShowAll(filter);
}
/* Function for filtering if querystring found on page load */
function filterSalesEventsOnLoad() {
    var dataFilterVal;

    // Only Init if Filter Bar is present
    if ($('.sales-events-filter-bar.sales-and-events').length > 0) {
        // console.log('filterSalesEventsOnLoad');
        var filter = getParameterByName("filter");
        var customFilterName = getParameterByName("n"); // Custom Gift Guide Filter Name
        var formattedFilterName = $('.sales-events-filter-bar .filter-item[data-filter="' + filter + '"]').html();
        var theFilterCounter;

        if (customFilterName !== "") formattedFilterName = customFilterName;
        showSelectedFilter(formattedFilterName, true);
        $('.sales-events-filter-bar .filter-item').removeClass("active");

        // All but Date
        if (filter.split('date_').length === 1) {
            //formattedFilterName = $('.sales-events-filter-bar .filter-item[data-filter="' + filter + '"]').html();
            //showSelectedFilter(formattedFilterName);
            $('.sales-events-filter-bar .filter-item').removeClass("active");

            if (filter === "other" || filter === "a-f" || filter === "g-l" || filter === "m-s" || filter === "t-z") {
                if (filter === "other") filter = "#";
                showHideFeaturedSalesEvents(false);
                azFilterFunction(filter);
                $('.sales-events-filter-bar .filter-item.a-z').addClass("active");
                dataFilterVal = filter.replace("-", " - ");
                $('.sales-events-filter-bar .drop-down-item[data-filter="' + dataFilterVal + '"]').addClass("active");
                $('.sales-events-filter-bar .a-z-drop-down-selector').addClass("active");
                $('.sales-events-filter-bar').toggleClass("disabled");
            }
            else if (filter === "custom") {
                // CUSTOM FILTER FOR GIFT GUIDE
                showHideFeaturedSalesEvents(true);
                var customFilterIDs = getParameterByName("x").split(",");

                $('.sales-events-filter-bar .filter-item.a-z').addClass("active");
                dataFilterVal = filter.replace("-", " - ");
                $('.sales-events-filter-bar .drop-down-item[data-filter="' + dataFilterVal + '"]').addClass("active");
                $('.sales-events-filter-bar .a-z-drop-down-selector').addClass("active");
                $('.sales-events-filter-bar').addClass("disabled");

                theFilterCounter = 0;
                $('.filter-item[data-filter="all"]').addClass("active");

                // TODO: MICHELLE MAKE SURE I'M PICKING UP ALL THE APPROPRIATE RETAILERS HERE
                customFilterIDs.forEach(function (entry) {
                    filter = entry;

                    $('.sales-events-filter-bar .filter-item').each(function () {
                        if ($(this).data("filter") === filter || $(this).data("filter-sub") === filter) {
                            $(this).addClass("active");
                            $('.sales-events-filter-bar').addClass("disabled");
                        }
                    });
                    $(".sales-events-container").each(function () {
                        // Show found store if matches IDs in query
                        var theFilter = $(this).data("filter");
                        if (theFilter.indexOf(filter) > -1 || filter === "all" || filter === "" || filter === "reset") {
                            $(this).removeClass("filter-hide");
                            $(this).parent().parent().removeClass("filter-hide");
                            $(this).next('hr').removeClass("filter-hide");
                            $(this).addClass("custom-filter");
                            theFilterCounter++;
                        }
                        else {
                            // If the store has already been found, don't hide it again
                            if (!$(this).hasClass("custom-filter")) {
                                $(this).addClass("filter-hide");
                                $(this).next('hr').addClass("filter-hide");
                                $('.alpha-container').each(function () {
                                    var visibleElements = $(this).find('.result-item').not('.filter-hide').length;
                                    if (visibleElements === 0) $(this).addClass("filter-hide");
                                });
                            }
                        }
                    });
                });

                $('.show-all-event-sales').addClass("uk-hidden");
                toggleShowAll(filter);

                // Display No-Results if none returned
                showNoResults(theFilterCounter);
            }
            else {
                showHideFeaturedSalesEvents(false);
                if (filter === "all" || filter === "" || filter === "reset") {
                    $('.filter-item[data-filter="all"]').addClass("active");
                    clearSelectedFilter();
                    showSeeAll();
                }
                else {
                    $('.sales-events-filter-bar .filter-item').each(function () {
                        if ($(this).data("filter") === filter) {
                            $(this).addClass("active");
                            $('.sales-events-filter-bar').toggleClass("disabled");
                        }
                    });

                    //$(".results-container-inner").find('.stuff-container').addClass('filter-hide');
                    $(".results-container-inner").find('.custom-block.primary-promotion-block').addClass('d-none');
                }

                theFilterCounter = 0;
                $(".sales-events-container").each(function () {
                    var theFilter = $(this).data("filter");
                    if (theFilter.indexOf(filter) > -1 || filter === "all" || filter === "" || filter === "reset") {
                        $(this).removeClass("filter-hide");
                        theFilterCounter++;
                    }
                    else {
                        $(this).addClass("filter-hide");
                    }
                });

                $('.show-all-event-sales').addClass("uk-hidden");
                toggleShowAll(filter);

                // Display No-Results if none returned
                showNoResults(theFilterCounter);
            }

            if ($('.sales-events-filter-bar').hasClass('disabled')) {
                $('.sales-events-filter-bar .drop-container').attr('tabindex', '-1').attr('aria-disabled', 'true');
            } else {
                $('.sales-events-filter-bar .drop-container').attr('tabindex', '0').attr('aria-disabled', 'false');
            }
        }
        // Date Only
        else if (filter.split('date_').length === 2) {
            var dateSelected = filter.split('date_')[1];

            $(".sales-events-container").each(function () {
                var startDate = $(this).data("date-start");
                var endDate = $(this).data("date-end");
                var isDateMatch = checkDate(dateSelected, startDate, endDate);

                if (isDateMatch) {
                    $(this).removeClass("filter-hide");
                }
                else {
                    $(this).addClass("filter-hide");
                }
            });

            $('.selected-filter-container').addClass("active");
            $('.selected-filter-container .selected-filter-item span').html(formatDate(dateSelected) + '<span class="reset-filter theme-color events" role="button" tabindex="0" style="margin-left:25px;cursor:pointer;text-decoration:underline;" aria-label="Clear Filter" onclick="filterSalesEvents(\'all\', this, event);" onkeydown="filterSalesEvents(\'all\', this, event);">RESET FILTER</span>');
            $('.sales-events-filter-bar').toggleClass("disabled");

            $('.show-all-event-sales').addClass("uk-hidden");
            toggleShowAll(filter);
        }

        //$('.show-all-event-sales').addClass("uk-hidden");
        //toggleShowAll(filter);

    }

    // Support Events with NO Filter Bar
    else if ($('.no-sales-events-filter-bar').length > 0) {
        toggleShowAll("");
    }
}

/* Function for filtering directory if querystring found on page load */
function filterDirectoryResultsOnLoad() {
    if ($('.sales-events-filter-bar.directory').length > 0) {
        var filter = getParameterByName("filter").toLowerCase();
        var customFilterName = getParameterByName("n"); // Custom Gift Guide Filter Name
        var formattedFilterName = $('.sales-events-filter-bar .filter-item[data-filter="' + filter + '"]').html();
        var theFilterCounter;
        var dataFilterVal;

        if (customFilterName !== "") formattedFilterName = customFilterName;
        showSelectedFilter(formattedFilterName, true);
        $('.sales-events-filter-bar .filter-item').removeClass("active");

        if (filter != "reset" && filter != "" && filter != "clear") {
            disableFilter();
            $('.suggestionBox').addClass('d-none').attr('aria-hidden', true); // Hide suggestion box
        }

        if (filter === "other" || filter === "a-f" || filter === "g-l" || filter === "m-s" || filter === "t-z") {
            if (filter === "other") filter = "#";
            showHideFeaturedSalesEvents(false);
            azFilterFunction(filter);
            $('.sales-events-filter-bar .filter-item.a-z').addClass("active");
            dataFilterVal = filter.replace("-", " - ");
            $('.sales-events-filter-bar .drop-down-item[data-filter="' + dataFilterVal + '"]').addClass("active");
            $('.sales-events-filter-bar .a-z-drop-down-selector').addClass("active");
            $('.sales-events-filter-bar').addClass("disabled");
        }
        else if (filter === "custom") {
            // CUSTOM FILTER FOR GIFT GUIDE
            showHideFeaturedSalesEvents(true);
            var customFilterIDs = getParameterByName("x").split(",");

            azFilterFunction(formattedFilterName, undefined, false);
            $('.sales-events-filter-bar .filter-item.a-z').addClass("active");
            dataFilterVal = filter.replace("-", " - ");
            $('.sales-events-filter-bar .drop-down-item[data-filter="' + dataFilterVal + '"]').addClass("active");
            $('.sales-events-filter-bar .a-z-drop-down-selector').addClass("active");
            $('.sales-events-filter-bar').addClass("disabled");

            theFilterCounter = 0;
            $('.filter-item[data-filter="all"]').addClass("active");

            // TODO: MICHELLE MAKE SURE I'M PICKING UP ALL THE APPROPRIATE RETAILERS HERE
            customFilterIDs.forEach(function (entry) {
                filter = entry;

                $('.sales-events-filter-bar .filter-item').each(function () {
                    if ($(this).data("filter") === filter || $(this).data("filter-sub") === filter) {
                        $(this).addClass("active");
                        $('.sales-events-filter-bar').addClass("disabled");
                    }
                });
                $(".result-item").each(function () {
                    // Show found store if matches IDs in query
                    var theFilter = $(this).data("filter");
                    var theFilterSub = $(this).data("filter-sub");
                    if (theFilterSub.indexOf(filter) > -1 || filter === "all" || filter === "") {
                        $(this).removeClass("filter-hide");
                        $(this).parent().parent().removeClass("filter-hide");
                        $(this).next('hr').removeClass("filter-hide");
                        $(this).addClass("custom-filter");
                        theFilterCounter++;
                    }
                    else {
                        // If the store has already been found, don't hide it again
                        if (!$(this).hasClass("custom-filter")) {
                            $(this).addClass("filter-hide");
                            $(this).next('hr').addClass("filter-hide");
                            $('.alpha-container').each(function () {
                                var visibleElements = $(this).find('.result-item').not('.filter-hide').length;
                                if (visibleElements === 0) $(this).addClass("filter-hide");
                            });
                        }
                    }
                });
            });

            // Display No-Results if none returned
            showNoResults(theFilterCounter);
        }
        else {
            showHideFeaturedSalesEvents(false);
            if (filter === "all" || filter === "clear" || filter === "reset") {
                $('.filter-item[data-filter="all"]').addClass("active");
                clearSelectedFilter();
                showSeeAll();
 

                //if (filter === "clear") {
                //    $("input.search").submit();
                //}
            }
            else {
                $('.sales-events-filter-bar .filter-item').each(function () {
                    if ($(this).data("filter") === filter || $(this).data("filter-sub") === filter) {
                        $(this).addClass("active");
                        $('.sales-events-filter-bar').addClass("disabled");
                    }
                });

                if (filter !== "") {
                    //$(".results-container-inner").find('.stuff-container').addClass('filter-hide');
                    $(".results-container-inner").find('.custom-block.primary-promotion-block').addClass('d-none');
                }

            }

            theFilterCounter = 0;
            $(".result-item").each(function () {
                var theFilter = $(this).data("filter");
                var theFilterSub = $(this).data("filter-sub");
                if (theFilter.indexOf(filter) > -1 || filter === "all" || filter === "clear" || filter === "reset") {
                    $(this).removeClass("filter-hide");
                    $(this).next('hr').removeClass("filter-hide");
                    theFilterCounter++;
                }
                else if (theFilterSub.indexOf(filter) > -1 || filter === "all" || filter === "clear" || filter === "reset") {
                    $(this).removeClass("filter-hide");
                    $(this).next('hr').removeClass("filter-hide");
                    theFilterCounter++;
                }
                else {
                    $(this).addClass("filter-hide");
                    $(this).next('hr').addClass("filter-hide");
                    $('.alpha-container').each(function () {
                        var visibleElements = $(this).find('.result-item').not('.filter-hide').length;
                        if (visibleElements === 0) $(this).addClass("filter-hide");
                    });
                }
            });

            // Display No-Results if none returned
            showNoResults(theFilterCounter);
        }

        if ($('.sales-events-filter-bar').hasClass('disabled')) {
            $('.sales-events-filter-bar .drop-container').attr('tabindex', '-1').attr('aria-disabled', 'true');
        } else {
            $('.sales-events-filter-bar .drop-container').attr('tabindex', '0').attr('aria-disabled', 'false');
        }

        toggleShowAll(filter);
    }
}
/* Function for filtering directory if querystring found on page load */
function filterDirectoryResultsOnClick(filter, el, e, displayVal) {
    var keyboard = e.type === 'keydown' ? false : true;
    // WCAG Keydown - Only 'Enter' Key    
    if (e.type === 'keydown') {
        if (e.which !== 13) return;
    }

    showHideFeaturedSalesEvents(false);
    showSelectedFilter(displayVal, keyboard);

    $('.sales-events-filter-bar .filter-item.a-z .group').text("a - z"); // Reset A-Z filter
    $('.sales-events-filter-bar .a-z-drop-down-selector').removeClass("active");
    $('.sales-events-filter-bar .a-z-drop-down-selector .drop-down-item').removeClass("active");
    $('.date-selected-display').removeClass("active");
    $('.sales-events-filter-bar').toggleClass("disabled");
    $('.disable-filter').toggleClass("disabled");
    $('input.search.wcag-input').removeClass('disabled');
    $('.suggestionBox').addClass('d-none').attr('aria-hidden', true); // Hide suggestion box

    if ($('.sales-events-filter-bar').hasClass('disabled')) {
        $('.sales-events-filter-bar .drop-container').attr('tabindex', '-1').attr('aria-disabled', 'true');

    } else {
        $('.sales-events-filter-bar .drop-container').attr('tabindex', '0').attr('aria-disabled', 'false');
    }

    if (history.replaceState) {
        var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?filter=' + filter.split(' ').join('');
        window.history.replaceState({ path: newurl }, '', newurl);
    }

    $('.sales-events-filter-bar .filter-item').removeClass("active");
    var selectedFilter = $(el).data("filter");
    $('.sales-events-filter-bar .filter-item[data-filter="' + selectedFilter + '"]').addClass("active");

    if (filter === "all" || filter === "clear" || filter === "reset") {
        $(".result-item").removeClass("filter-hide");
        $(".alpha-container").removeClass("filter-hide");
        //$(".results-container-inner").find('.stuff-container').removeClass('filter-hide');
        $(".results-container-inner").find('.custom-block.primary-promotion-block').removeClass('d-none');
        $(".results-container-inner").find('hr').removeClass('filter-hide');

        clearSelectedFilter();
        $("#directorySearchForm")[0].reset();

        if (!keyboard) {
            if (filter === "clear") {
                $("#directorySearchForm input.search").focus();
            } else {
                $('.sales-events-filter-bar .drop-container').focus();
            }

        } else {
            $(':focus').blur();
        }

        $('.disable-filter').removeClass("disabled");

        if (filter === "clear") {
            $("#directorySearchForm").submit();
        }

    }
    else {
        var theFilterCounter = 0;
        $(".result-item").each(function () {
            var theFilter = $(this).data("filter");
            var theFilterSub = $(this).data("filter-sub");
            if (theFilter.indexOf(filter) > -1 || filter === "all" || filter === "") {
                $(this).removeClass("filter-hide");
                $(this).next('hr').removeClass("filter-hide");
                theFilterCounter++;
            }
            else if (theFilterSub.indexOf(filter) > -1 || filter === "all" || filter === "") {
                $(this).removeClass("filter-hide");
                $(this).next('hr').removeClass("filter-hide");
                theFilterCounter++;
            }
            else {
                $(this).addClass("filter-hide");
                $(this).next('hr').addClass("filter-hide");
                $('.alpha-container').each(function () {
                    var visibleElements = $(this).find('.result-item').not('.filter-hide').length;
                    if (visibleElements === 0) $(this).addClass("filter-hide");
                });
            }
        });
        //$(".results-container-inner").find('.stuff-container').addClass('filter-hide');
        $(".results-container-inner").find('.custom-block.primary-promotion-block').addClass('d-none');

        // Display No-Results if none returned
        showNoResults(theFilterCounter);

    }

    $('.show-all-event-sales').addClass("uk-hidden");
    toggleShowAll(filter);
}


// HIDE FILTERED FEATURE AREA PER FOFO REQUEST.
function showHideFeaturedSalesEvents(hide) {
    if (hide) {
        $('.featured-bar').addClass("uk-hidden");
        $('.featured-sales-events-module').addClass("uk-hidden");
    }
    else {
        $('.featured-bar').removeClass("uk-hidden");
        $('.featured-sales-events-module').removeClass("uk-hidden");
    }
}

/* Click function for A-Z Filter */
function filtersSalesEventsByAZ(e) {
    // WCAG Keydown - Only 'Enter', 'spacebar' and Click

    if (e.which === 13 || e.which === 32 || e.type === "click") {
        $('.sales-events-filter-bar .a-z-drop-down-selector').toggleClass('active');
        $('.sales-events-filter-bar .filter-item.a-z').toggleClass("active");
        if (e.type === "click") {
            // no bubbling
            e.stopPropagation();
        }
        if ($('.sales-events-filter-bar .filter-item.a-z').hasClass('active')) {
            $('.sales-events-filter-bar .filter-item.a-z').attr('aria-expanded', true);
        } else {
            $('.sales-events-filter-bar .filter-item.a-z').attr('aria-expanded', false);
        }
    }
}
// Filter by A-Z Select
function filtersSalesEventsByAZSelect(el, e) {
    // console.log('filtersSalesEventsByAZSelect');

    var isDirectory = false;
    isDirectory = $('.sales-events-filter-bar').hasClass("directory");
    var filter = $(el).data("filter").replace(" - ", "-");

    // WCAG Keydown - Only 'Enter' Key    
    if (e.type === 'keydown') {
        if (e.which !== 13) return;
    }

    $('.sales-events-filter-bar .a-z-drop-down-selector .drop-down-item').removeClass("active");
    $('.sales-events-filter-bar').toggleClass("disabled");
    $(el).addClass("active");
    azFilterFunction(filter, isDirectory);
}
// Filter by A-Z
// @ urlUpdate {boolean} allow url vanity redirect
function azFilterFunction(filter, isDirectory, urlUpdate) {
    // console.log('azFilterFunction');
    var theFilterCounter = 0;
    filter = filter.replace("-", " - ");
    urlUpdate = urlUpdate === undefined ? true : urlUpdate;
    if (filter === "#") filter = "other";

    if (history.replaceState && urlUpdate === true) {
        var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?filter=' + filter.split(' ').join('');
        window.history.replaceState({ path: newurl }, '', newurl);
    }

    var selection = "";
    if (filter === "other" || filter === "#") selection = /^[0-9*#+]+$/;
    if (filter === "a - f") selection = /^[a-fA-F]+$/;
    if (filter === "g - l") selection = /^[g-lG-L]+$/;
    if (filter === "m - s") selection = /^[m-sM-S]+$/;
    if (filter === "t - z") selection = /^[t-zT-Z]+$/;

    $(".sales-events-container").each(function () {
        var theTitle = $(this).find('.store').text().charAt(0);
        if (theTitle.match(selection)) {
            $(this).removeClass("filter-hide");
            $(this).removeClass("hide");
            theFilterCounter++;
        }
        else {
            $(this).addClass("filter-hide");
        }
    });

    $(".result-item").each(function () {
        var theTitle = $(this).find('.result-description').text().replace(/^The\s/i, '').replace(/^the\s/i, '');
        theTitle = theTitle.charAt(0);
        if (theTitle.match(selection)) {
            $(this).removeClass("filter-hide");
            $(this).next('hr').removeClass("filter-hide");
            theFilterCounter++;
        }
        else {
            $(this).addClass("filter-hide");
            $(this).next('hr').addClass("filter-hide");
            $('.alpha-container').each(function () {
                var visibleElements = $(this).find('.result-item').not('.filter-hide').length;
                if (visibleElements === 0) $(this).addClass("filter-hide");
            });
        }
    });

    //$(".results-container-inner").find('.stuff-container').addClass('filter-hide');
    $(".results-container-inner").find('.custom-block.primary-promotion-block').addClass('d-none');

    showSelectedFilter(filter);
    toggleShowAll(filter);
    // Display No-Results if none returned
    showNoResults(theFilterCounter);
    $('.show-all-event-sales').addClass("uk-hidden");
}
// Show selected filter items
function showSelectedFilter(theFilter, bypass) {
    // console.log("showSelectedFilter");
    $('.selected-filter-container').addClass("active");

    if (theFilter !== undefined) {
        if ($('.sales-events-filter-bar').hasClass("directory")) {
            $('.selected-filter-container .selected-filter-item span').html(theFilter + '<span class="reset-filter theme-color" role="button" tabindex="0" aria-label="Reset Filter" onclick="filterDirectoryResultsOnClick(\'reset\', this, event);" onkeydown="filterDirectoryResultsOnClick(\'reset\', this, event);">RESET FILTER</span>');
        } else {
            $('.selected-filter-container .selected-filter-item span').html(theFilter + '<span class="reset-filter theme-color" role="button" tabindex="0" aria-label="Reset Filter" onclick="filterSalesEvents(\'reset\', this, event);" onkeydown="filterSalesEvents(\'reset\', this, event);">RESET FILTER</span>');
        }

        if (!bypass) {
            // Give DOM time to add above before focus
            setTimeout(function () {
                $('.selected-filter-container .reset-filter').focus();
            }, 0);
        } else {
            setTimeout(function () {
                $(':focus').blur();
            }, 0);
        }
    } else {
        if (!bypass) {
            $('.sales-events-filter-bar .drop-container').focus();
        } else {
            $(':focus').blur();
        }
    }
}
// Clear filter selection and reset
function clearSelectedFilter() {
    // console.log('clearSelectedFilter');
    $('.selected-filter-container').removeClass("active");
    $('.selected-filter-container .selected-filter-item span').html("");
    $('.sales-events-filter-bar .drop-down-item').removeClass("active");
    $('.sales-events-filter-bar h4, .sales-events-filter-bar li').removeClass("active");
    toggleShowAll("all");
    if (history.replaceState) {
        var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?filter=all';
        // window.history.replaceState({ path: newurl }, '', newurl);
    }
}
// Toggle the show all button based on filter selection
function toggleShowAll(filter) {
    // console.log('toggleShowAll |' + filter);
    var count = 0;

    if (filter === "all" || filter === "" || filter === "reset") {
        $('.show-all-event-sales').addClass("active");
        count = 0;

        $('.sales-events-container').each(function () {
            /* Always show all items, "See All" buton is removed
            if (count > 3) {
                $(this).addClass("hide");
            }
            */
            count++;
        });


        /* Always show all items, "See All" buton is removed
        if (count < 5) {
            $('.show-all-event-sales').addClass("uk-hidden");
        }
        */
    }
    else {
        $('.show-all-event-sales').removeClass("active");
        $('.sales-events-container').each(function () {
            $('.sales-events-container').removeClass("hide");
        });
    }

    var isThereMoreToSee = false;
    count = 0;
    $('.sales-events-container.hide').each(function () {
        count++;
    });
    if (count > 0) {
        $('.show-all-event-sales').addClass("active");
        $('.show-all-event-sales').removeClass("uk-hidden");
    }
}
/* Show All Events/Sales List button */
function showAllItems(element, itemClass, e) {

    if (e.which === 13 || e.which === 1 || e.which === 40 || e.which === 32) {
        e.preventDefault();
        // identify last element in list for focus
        $lastFocus = $("." + itemClass).parent().find('.sales-events-container:not(.hide):last')[0];

        $("." + itemClass).removeClass("hide");
        $('.show-all-event-sales').removeClass("active").addClass('uk-hidden');
        $('.show-all-event-sales span').attr('tabindex', '-1');

        // add a quick delay for transition before focus
        setTimeout(function () {
            $($lastFocus).next('.' + itemClass).focus();
            // help reposition any content due to height change
            $(window).trigger('resize');
        }, 0);
    }

}
function showSeeAll() {
    $('.show-all-event-sales').removeClass("uk-hidden");
}
// Display No-Results if none returned
function showNoResults(count) {
    // console.log('showNoResults: ' + count);
    if (count === 0) {
        $('.no-results').removeClass('uk-hidden');
    } else {
        $('.no-results').addClass('uk-hidden');
    }
}

/*!
 * F O S P - M O D A L
 * Currently set at 30sec. This needs to follow the trustarc hierarchy.
 */
$(function () {
    var isMobile = window.matchMedia("only screen and (max-width: 767px)");

    // FOSP Notification (Modal)
    var _triggerFospModal;
    function checkFospCookie() {
        var fospCookie = "fospClosed";

        if (!readCookie(fospCookie)) {
            setTimeout(function () {
                $("#fospModal").fadeIn();
            }, 30000);

            // Cookie Modal Click function and Create Cookie
            $("#fospModal .uk-modal-close").on('click keydown', function (e) {
                e.preventDefault();
                $("#fospModal").fadeOut();
            });

            $("#fospModal a").on('click keydown', function (e) {
                e.preventDefault();
                window.open(e.currentTarget.origin, e.currentTarget.target);
                createCookie(fospCookie, true, 1);
                $("#fospModal").fadeOut();
            });

        }
    }

    try {
        _triggerFospModal = triggerFospModal;
    } catch (err) {
        _triggerFospModal = false;
    }
    if (_triggerFospModal && isMobile.matches) checkFospCookie();
});


$(function () {
    /*!
     * S A L E S - E V E N T S - F I L T E R
     */

    // Collapsing for filter bars
    $('.sales-events-filter-bar.mobile').addClass("collapse");
    $('.sales-events-filter-bar.mobile .filter-item').click(function () {
        if ($(this).hasClass("active")) {
            $('.sales-events-filter-bar.mobile').toggleClass("collapse");
        }
    });
    $('.sales-events-filter-bar.mobile .drop-down-item').click(function () {
        $('.sales-events-filter-bar.mobile').addClass("collapse");
    });


    // I N I T

    // Filter sales events, only show top on load
    filterSalesEventsOnLoad();
    filterDirectoryResultsOnLoad();
    $('.suggestionBox').addClass('d-none').attr('aria-hidden', true); // Hide suggestion box
});;
/* 
 * FORMS
 * 
 * Supports Campaigner and Charity
 */


var emailregex = /^([\w\.\-]+)@([\w\-]+)((\.(\w){2,63}){1,3})$/;
// phone regex
// allows 1, +1, "no country code",
// allows dashes, periods, "no delimeters" and combination of all
var phoneregex = /^(\+?1 ?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;
var checkCheckbox = checkRequiredCheckbox();

/*!
 * Setup Custom Form
 */
function setupCustomForms() {
    // Only Setup if supported form is present
    var formPresent = 0;
    formPresent = $('form.form-campaigner').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-charity').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-select').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-fashionafare').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-holiday-sweepstakes').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.takeover-newsletter').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-popup-store').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-foc-recycling').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-foc-kidscraft').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-kp-recyclerunway').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-af-inside-track').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-filming').length > 0 ? formPresent + 1 : formPresent;
    formPresent = $('form.form-el-nonprofit').length > 0 ? formPresent + 1 : formPresent;
    if (formPresent === 0) return;    

    // identify select multiples
    $('form').find('select[multiple="multiple"]').each(function (e) {
        setupMultipleSelect(e);
    });

    // identify select with custom data-placeholders
    $('form').find('select:not([multiple="multiple"])').each(function (e) {
        var local = $(this);
        var isMobile = window.matchMedia("only screen and (max-width: 767px)");
        var placeholder = local.attr('data-placeholder') !== "" && local.attr('data-placeholder') !== undefined ? local.attr('data-placeholder') : undefined;
        var placeholderMobile = local.attr('data-placeholder-mobile') !== "" && local.attr('data-placeholder-mobile') ? local.attr('data-placeholder-mobile') : undefined;
        var placeholderOriginal = $(local[0][0]).attr('hidden') === "hidden" ? $(local[0][0]).text() : "Select One";

        if (placeholder !== undefined || placeholderMobile !== undefined) {
            placeholder = placeholder === undefined ? placeholderOriginal : placeholder;
            placeholderMobile = placeholderMobile === undefined ? placeholderOriginal : placeholderMobile;
            // attach listener
            $(window).on('resize', $.debounce(250, updatePlaceholder));
            updatePlaceholder();
        }

        function updatePlaceholder() {
            if (isMobile.matches) {
                // only procede if the first option is hidden
                if ($(local[0][0]).attr('hidden') === "hidden") {
                    $(local[0][0]).text(placeholderMobile);
                }
            }
            else {
                // only procede if the first option is hidden
                if ($(local[0][0]).attr('hidden') === "hidden") {
                    $(local[0][0]).text(placeholder);
                }
            }
        }
    });

    // Toggle form if tied to Verify Age
    $('form.generic input[name="verifyAge"]').on('click', function (e) {
        if (e.currentTarget.value === "no") {
            $('form.generic .toggle-disable').prop('disabled', true);
        } else {
            $('form.generic .toggle-disable').prop('disabled', false);
        }
    });

    // Handling of Email Pref Multi-Toggling
    $('form.generic input[name^="list"]').on('click', function (e) {
        var i;
        switch (e.currentTarget.name.split('list')[1].toLowerCase()) {
            case 'all':
                for (i = 0; i < $('form.form-campaigner input[name^="list"]').length; i++) {
                    $('form.form-campaigner input[name^="list"]')[i].checked = e.currentTarget.checked;
                }
                // Trigger Change Event on Stepper 1 & 2
                $('form.form-campaigner input.toggle-stepper-1').trigger('change');
                break;
            default:
                var allChecked = true;
                for (i = 0; i < $('form.form-campaigner input[name^="list"]').length; i++) {
                    if ($('form.form-campaigner input[name^="list"]')[i].checked === false && $('form.form-campaigner input[name^="list"]')[i].name !== 'listAll') {
                        allChecked = false;
                    }
                }

                if (allChecked) $('form.form-campaigner input[name="listAll"]')[0].checked = true;
                else $('form.form-campaigner input[name="listAll"]')[0].checked = false;

                break;
        }

        // Remove required that may have been set to trigger HTML5 alert
        $($('form.form-campaigner input[name="listAll"]')[0]).prop('required', false);
        $('form.form-campaigner input[name="listAll"]')[0].setCustomValidity('');
    });

    // Handling of Phone Number Auto-format
    //$('form.generic input[name="phone"]').bind("change keyup input", function (e) {
    //    console.log("called");
    //    if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
    //        return false;
    //    }
    //    var curchr = this.value.length;
    //    var curval = $(this).val();
    //    if (curchr == 3 && e.which != 8 && e.which != 0) {
    //        $(this).val(curval + "-");
    //    } else if (curchr == 7 && e.which != 8 && e.which != 0) {
    //        $(this).val(curval + "-");
    //    }
    //    $(this).attr('maxlength', '12');
    //});
    
    // Handling of birthday (mm/dd)
    $('form.generic input[name="birthMonthDay"]').bind('change keyup', function (e) {        
        var val = $(this).val();

        if (val.split('/').length >= 3) {
            val = val.replace(/\//g, '');
            $(this).val(val.substring(0, 2) + '/' + val.substring(2));
        }
        else if (val.length < 3 && val.split('/').length >= 2) {
            val = val.replace(/\//g, '');
            $(this).val(val);
        }        
        else if (val.length === 2 && this.prevLength < 2) {
            $(this).val(val + '/');
        }
        else if (val.length >= 3 && (val.split('/').length !== 2 || val.split('/').length === 0)) {
            $(this).val(val.substring(0, 2) + '/' + val.substring(2));
        }

        // keep track of last input
        this.prevLength = val.length;
    });

    // Handling of birthday (mm/yyyy)
    $('form.generic input[name="birthMonthYear"]').bind('change keyup', function (e) {
        var val = $(this).val();

        if (val.split('/').length >= 3) {
            val = val.replace(/\//g, '');
            $(this).val(val.substring(0, 2) + '/' + val.substring(2));
        }
        else if (val.length < 3 && val.split('/').length >= 2) {
            val = val.replace(/\//g, '');
            $(this).val(val);
        }
        else if (val.length === 2 && this.prevLength < 2) {
            $(this).val(val + '/');
        }
        else if (val.length >= 3 && (val.split('/').length !== 2 || val.split('/').length === 0)) {
            $(this).val(val.substring(0, 2) + '/' + val.substring(2));
        }

        // keep track of last input
        this.prevLength = val.length;
    });

    // Handling of US + CAN PhoneNumber
    $('form.generic input[name="USCANnumber"]').bind('change keyup', function (e) {
        var ph = $(this).val().replace(/\D/g, '');

        if (ph.slice(0, 1) === '1') {
            ph = ph.substring(1, 11);
        }

        var deleteKey = e.keyCode === 8 || e.keyCode === 46;
        var len = ph.length;

        if (len === 0) {
            ph = ph;
        } else if (len < 3) {
            ph = '+1 (' + ph;
        } else if (len === 3) {
            ph = '+1 (' + ph + (deleteKey ? '' : ') ');
        } else if (len < 6) {
            ph = '+1 (' + ph.substring(0, 3) + ') ' + ph.substring(3, 6);
        } else if (len === 6) {
            ph = '+1 (' + ph.substring(0, 3) + ') ' + ph.substring(3, 6) + (deleteKey ? '' : '-');
        } else {
            ph = '+1 (' + ph.substring(0, 3) + ') ' + ph.substring(3, 6) + '-' + ph.substring(6, 10);
        }

        // Toggle checkbox if present
        // attributes considred: aria-hidden, disabled, required
        if (len === 10) {
            $('.uscannnumber-toggle-container').removeClass('uk-hidden').attr('aria-hidden', 'false');
            $('.uscannnumber-toggle-container').find('input').prop('disabled', false).prop('required', true);
        } else {
            $('.uscannnumber-toggle-container').addClass('uk-hidden').attr('aria-hidden', 'true');
            $('.uscannnumber-toggle-container').find('input').prop('disabled', true).prop('required', false);
        }

        $(this).val(ph);
    });

    // If VerifyAge is present, disable forms with .toggle-disable class
    if ($('form.generic input[name="verifyAge"]').length > 0) {
        $('form.generic .toggle-disable').prop('disabled', true);
    }

    // Toggle Stepper for secondary fields
    $('form.generic input.toggle-stepper-1').on('change', function (e) {
        switch (e.currentTarget.type) {
            case "checkbox":
                if (e.currentTarget.checked === true) {
                    $($(e.currentTarget).closest('[class^="uk-width-1-"]').find('.toggle-stepper-2')).prop('disabled', false).prop('required', true);
                } else {
                    $($(e.currentTarget).closest('[class^="uk-width-1-"]').find('.toggle-stepper-2')).prop('disabled', true).prop('required', false);
                }
                break;
            case "radio":
                var radioName = e.currentTarget.name;

                // Disable all stepper-2
                $($('form.form-campaigner input[name="' + radioName + '"]').closest('[class^="uk-width-1-"]').find('.toggle-stepper-2')).prop('disabled', true).prop('required', false);
                $($(e.currentTarget).closest('[class^="uk-width-1-"]').find('.toggle-stepper-2')).prop('disabled', false).prop('required', true);
                break;
        }
    });

    // Campaigner Only
    if ($('form.form-campaigner').length > 0) {
        $('form.form-campaigner').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();
            
            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }

    // Charity Only
    if ($('form.form-charity').length > 0) {
        var _local = 'form.form-charity';
        var postUrl = $(_local).attr('data-posturl');
        var getUrl = $(_local).attr('data-geturl');
        var serverIdentity = $(_local).attr('data-identity');

        $('form.form-charity').submit(function (e) {
            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    $.ajax({
                        url: postUrl,
                        crossDomain: true,
                        secure: true,
                        type: "POST",
                        data: JSON.stringify({
                            'firstName': $(_local).find('input[name="firstName"]').val() + serverIdentity,
                            'lastName': $(_local).find('input[name="lastName"]').val(),
                            'email': $(_local).find('input[name="email"]').val(),
                            'mobileNumber': $(_local).find('input[name="phone"]').val(),
                            'charityId': $(_local).find('select[name="charityId"]').val()
                        }),
                        dataType: "json",
                        processData: true,
                        contentType: "application/json"
                    }).done(function (data) {
                        // Output Legacy Number
                        $($('.form-success').find('.legacy-number')).html(data.legacyNumber);
                        formPostSuccess(_local);                        
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });

        // Load data for form
        $.ajax({
            type: 'GET',
            crossDomain: true,
            url: getUrl,
            secure: true,
            timeout: 5000,
            success: function (data, textStatus, jqXHR) {
                var _retailersHTML = "";
                var _charitiesHTML = "";
                var _charities2HTML = "";

                var _customClass = "";
                var j = 0;

                for (j = 0; j < data.retailers.length; j++) {
                    _customClass = j === 0 ? " uk-margin-top" : "";

                    _retailersHTML += "<div class=\"uk-width-medium-1-2 uk-margin" + _customClass + "\">";
                    _retailersHTML += "<a href=\"/Directory/Details/" + data.retailers[j].tenantId + "\" target=\"_blank\" class=\"theme-link-hover uppercase\">" + data.retailers[j].name +  " <span class=\"wcag\"> (open in new window)</span></a>";
                    _retailersHTML += "</div>";
                }

                for (j = 0; j < data.charities.length; j++) {
                    _customClass = j === 0 ? " uk-margin-top" : "";

                    _charitiesHTML += "<div class=\"uk-width-medium-1-2 uk-margin" + _customClass + "\">";
                    _charitiesHTML += "<a href=\"" + data.charities[j].websiteUrl + "\" target=\"_blank\" class=\"theme-link-hover uppercase\">" + data.charities[j].name + " <span class=\"wcag\"> (open in new window)</span></a>";
                    _charitiesHTML += "</div>";

                    _charities2HTML += "<option value=\"" + data.charities[j].id + "\">" + data.charities[j].name + "</option>"
                }

                //$('.accordion-module .retailer-container .uk-grid').append(_retailersHTML);
                $('.accordion-module .nonprofit-container .uk-grid').append(_charitiesHTML);
                $(_local).find('select[name="charityId"]').append(_charities2HTML);
            }
        }).fail(function () {
            console.log("ERROR loading data");
        })
        .always(function () {});
    }

    // Select Only
    if ($('form.form-select').length > 0) {
        $('form.form-select').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }

    // Fashion Fare
    if ($('form.form-fashionafare').length > 0) {
        $('form.form-fashionafare').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }

    // Holiday Sweepstakes Only
    if ($('form.form-holiday-sweepstakes').length > 0) {
        $('form.form-holiday-sweepstakes').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }

    // Takeover Newsletter Only
    if ($('form.takeover-newsletter').length > 0) {
        $('form.takeover-newsletter').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }

    // Popup Only
    if ($('form.form-popup-store').length > 0) {
        $('form.form-popup-store').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local, false);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local, false);
                    });
                }
            }
        });
    }
    
    if ($('form.form-foc-recycling').length > 0) {
        $('form.form-foc-recycling').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }

    if ($('form.form-foc-kidscraft').length > 0) {
        $('form.form-foc-kidscraft').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }

    if ($('form.form-kp-recyclerunway').length > 0) {
        $('form.form-kp-recyclerunway').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }

    if ($('form.form-af-inside-track').length > 0) {
        $('form.form-af-inside-track').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }

    if ($('form.form-filming').length > 0) {
        $('form.form-filming').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }

    if ($('form.form-el-nonprofit').length > 0) {
        $('form.form-el-nonprofit').submit(function (e) {
            var _local = e.currentTarget;

            e.preventDefault();

            if (validateForm(_local)) {
                // Submit test
                if ($(_local).find('input[name="submitTest"]').val() === "true") {
                    console.log("%cSerialized\n==========", "color: red");
                    console.log($(_local).serialize());

                    formPostSuccess(_local);
                    formPostAlways(_local);
                } else {
                    formPostReset(_local);

                    var postUrl = $(_local).attr('data-posturl');

                    $.post(postUrl, $(this).serialize(), function () {
                        formPostSuccess(_local);
                    }).fail(function (xhr) {
                        formPostErrors(_local, xhr);
                    }).always(function () {
                        formPostAlways(_local);
                    });
                }
            }
        });
    }
}

/*!
 * Validate Form
 */
function validateForm(scope) {
    var _local = scope;
    var checkMultipleSelect = checkRequiredMultipleSelect(_local);
    var error;

    $(_local).find('.errors').empty().addClass('uk-hidden');
    $(_local).find('.required').first().removeClass('uk-hidden');

    // Compare Emails
    if ($(_local).find('input[name="emailConfirm"]').length > 0 && $(_local).find('input[name="email"]').val() !== $(_local).find('input[name="emailConfirm"]').val()) {
        $(_local).find('input[name="emailConfirm"]')[0].setCustomValidity('Email address does not match above');
        $(_local).find('input[name="emailConfirm"]')[0].reportValidity();

        // Listen for change before resetting error
        $(_local).find('input[name="emailConfirm"]').on('input', function () {
            $(_local).find('input[name="emailConfirm"]')[0].setCustomValidity('');
            $(this).off('input');
        });

        return false;
    }

    // Validate Email Format
    else if (($(_local).find('input[name="email"]').length > 0 && $(_local).find('input[name="email"]').val().length > 0) &&
        !$(_local).find('input[name="email"]').val().match(emailregex)) {

        $(_local).find('input[name="email"]')[0].setCustomValidity('Please enter a valid email');
        $(_local).find('input[name="email"]')[0].reportValidity();

        // Listen for change before resetting error
        $(_local).find('input[name="email"]').on('input', function () {
            $(_local).find('input[name="email"]')[0].setCustomValidity('');
            $(this).off('input');
        });

        return false;
    }

    // Support Multi-Select if required
    //else if (checkMultipleSelect !== false) {
    //    $(checkMultipleSelect).next().find('.ms-choice-wcag').removeAttr('disabled').removeClass('uk-hidden').prop('required', true);
    //    $(checkMultipleSelect).next().find('.ms-choice-wcag')[0].setCustomValidity('Please select one or more items in this list.');
    //    $(checkMultipleSelect).next().find('.ms-choice-wcag')[0].reportValidity();
    //    $(checkMultipleSelect).next().find('.ms-choice').addClass('focus');

    //    $(checkMultipleSelect).next().find('.ms-choice').on('click', function () {
    //        $(this).removeClass('focus');
    //        $(checkMultipleSelect).next().find('.ms-choice-wcag').prop('disabled', true).addClass('uk-hidden').prop('required', false);
    //        $(checkMultipleSelect).next().find('.ms-choice-wcag')[0].setCustomValidity('');
    //        // $(this).off('click');
    //    });

    //    return false;
    //}

    // Support Checkbox List if required
    else if (checkCheckbox !== false) {
        $(checkCheckbox).prop('required', true);
        $(checkCheckbox)[0].setCustomValidity('Please check one or more options.');
        $(checkCheckbox)[0].reportValidity();

        return false;
    }
    // Select's Membership Number
    else if ($(_local).find('input[name="membershipNumber"]').length > 0 && ($(_local).find('input[name="membershipNumber"]').val().length !== 4 || $(_local).find('input[name="membershipNumber"]').val() > 1000)) {
        $(_local).find('input[name="membershipNumber"]')[0].setCustomValidity('Please enter a valid membership number');
        $(_local).find('input[name="membershipNumber"]')[0].reportValidity();

        // Listen for change before resetting error
        $(_local).find('input[name="membershipNumber"]').on('input', function () {
            $(_local).find('input[name="membershipNumber"]')[0].setCustomValidity('');
            $(this).off('input');
        });

        return false;
    }
    // Birth-Month-Day Check 
    else if ($(_local).find('input[name="birthMonthDay"]').length > 0 && $(_local).find('input[name="birthMonthDay"]').val().length > 0 && validateMonthDay($(_local).find('input[name="birthMonthDay"]').val()).status === "Error") {
        //validateMonthDay($(_local).find('input[name="birthMonthDay"]').val());
        error = validateMonthDay($(_local).find('input[name="birthMonthDay"]').val());

        $(_local).find('input[name="birthMonthDay"]')[0].setCustomValidity('Please enter a valid ' + error.msg);
        $(_local).find('input[name="birthMonthDay"]')[0].reportValidity();

        // Listen for change before resetting error
        $(_local).find('input[name="birthMonthDay"]').on('input', function () {
            $(_local).find('input[name="birthMonthDay"]')[0].setCustomValidity('');
            $(this).off('input');
        });
        return false;
    }
    // Birth-Month-Year Check 
    else if ($(_local).find('input[name="birthMonthYear"]').length > 0 && $(_local).find('input[name="birthMonthYear"]').val().length > 0 && validateMonthYear($(_local).find('input[name="birthMonthYear"]').val(), $($(_local).find('input[name="birthMonthYear"]')[0]).attr('data-validate-age')).status === "Error") {
        error = validateMonthYear($(_local).find('input[name="birthMonthYear"]').val(), $($(_local).find('input[name="birthMonthYear"]')[0]).attr('data-validate-age'));        

        $(_local).find('input[name="birthMonthYear"]')[0].setCustomValidity('Please enter a valid ' + error.msg);
        $(_local).find('input[name="birthMonthYear"]')[0].reportValidity();

        // Listen for change before resetting error
        $(_local).find('input[name="birthMonthYear"]').on('input', function () {
            $(_local).find('input[name="birthMonthYear"]')[0].setCustomValidity('');
            $(this).off('input');
        });
        return false;
    }
    // Basic Telelphone
    else if ($(_local).find('input[type="tel"]').length > 0 && $(_local).find('input[type="tel"]').val().length > 0 && !$(_local).find('input[type="tel"]').val().match(phoneregex) ) {
        $(_local).find('input[type="tel"]')[0].setCustomValidity('Please enter a valid phone number');
        $(_local).find('input[type="tel"]')[0].reportValidity();

        // Listen for change before resetting error
        $(_local).find('input[type="tel"]').on('input', function () {
            $(_local).find('input[type="tel"]')[0].setCustomValidity('');
            $(this).off('input');
        });
        return false;
    }
    // US + CAN Telphone
    else if ($(_local).find('input[name="USCANnumber"]').length > 0 && $(_local).find('input[name="USCANnumber"]').val().length > 0 && !$(_local).find('input[name="USCANnumber"]').val().match(phoneregex)) {
        $(_local).find('input[name="USCANnumber"]')[0].setCustomValidity('Please enter a valid phone number.');
        $(_local).find('input[name="USCANnumber"]')[0].reportValidity();

        // Listen for change before resetting error
        $(_local).find('input[name="USCANnumber"]').on('input', function () {
            $(_local).find('input[name="USCANnumber"]')[0].setCustomValidity('');
            $(this).off('input');
        });
        return false;
    }
    else {
        return true;
    }
}

/*!
 * Form Post Success
 */
function formPostSuccess(scope) {
    var _local = scope;
    var propertyName;

    // Successful
    $(_local).addClass('uk-hidden').attr('aria-hidden', 'true');
    $(_local).closest('.form-container').find('.form-outside').addClass('uk-hidden').attr('aria-hidden', 'true');
    // Find .form-sucess (if available)
    $(_local).closest('.form-container').find('.form-success').removeClass('uk-hidden').attr('aria-hidden', 'false');

    // Analytics
    switch ($(_local).attr('data-form')) {
        case 'newsletter':
            propertyName = $($(_local).find('input[name="propertyName"]')).val();
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'Newsletter' });
            break;
        case 'popup':
            propertyName = $($(_local).find('input[name="propertyName"]')).val();
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'Pop-Up Entrepreneurship' });
            break;
        case 'propertySweeps':
            propertyName = $($(_local).find('input[name="propertyName"]')).val();
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'Holiday Sweepstakes 2019' });
            break;
        case 'propertySweeps2020':
            propertyName = $($(_local).find('input[name="propertyName"]')).val();
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'Holiday Sweepstakes 2020' });
            break;
        case 'takeoverNewsletter':
            propertyName = $($(_local).find('input[name="propertyName"]')).val();
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'Newsletter Takeover' });
            break;
        case 'sfsredev': //SFS only
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'SFS Redev' });
            break;
        case 'select': //SFS only
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'SFS Select' });
            break;
        case 'fashionafare': //SFS only
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'SFS Fashion AFare' });
            break;
        case 'focrecycling': //FOC only
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'FOC Recycling' });
            break;
        case 'fockidscraft': //FOC only
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'FOC Kids Craft Giveaway' });
            break;
        case 'kpHoliday2021Event': //KP only
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'KP Holiday 2021 Event' });
            break;
        case 'kprecyclerunway': //KP only
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'KP Recycle the Runway' });
            break;
        case 'tccdreamstart': //TCC only
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'TCC DreamStart Competition' });
            break;
        case 'insideTrack': //AF only
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'AF Inside Track' });
            break;
        case 'kidsClub':
            propertyName = $($(_local).find('input[name="propertyName"]')).val();
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'Kids Club' });
            break;
        case 'filming':
            propertyName = $($(_local).find('input[name="propertyName"]')).val();
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'Filming' });
            break;
        case 'elnonprofit': //EL only
            dataLayer.push({ 'event': 'dynamicEvent', 'dynev.ev_name': 'form_submission', 'dynev.p1_name': 'form_id', 'dynev.p1_value': 'EL Nonprofit of the Month' });
            break;
        // NOTE: Cayton Rewards and Visitor Rewards logins in separate cshtml files
    }
}

/*!
 * Form Post Reset
 */
function formPostReset(scope) {
    var _local = scope;

    // Disable button
    $(_local).find('button.submit').attr('disabled', true);
    // Reset Errors
    $(_local).find('.errors').addClass('uk-hidden');
    $(_local).find('.required').first().removeClass('uk-hidden');
    // Reset Indicator
    $(_local).find('.loader').removeClass('uk-hidden');
}

/*!
 * Form Post Errors
 */
function formPostErrors(scope, xhr) {
    var _local = scope;

    switch (xhr.status) {
        case 412:
            // Exclsuve for Select Form
            if ($(_local).attr('data-form') === "select") {
                // Member ID Used
                $(_local).find('.errors').html('This membership number is invalid. Please contact Guest Services for additional help.').removeClass('uk-hidden');                
            }
            else if ($(_local).attr('data-form') === "popup") {
                // reCaptcha validation
                $(_local).find('.errors').html('Please validate reCAPTCHA.').removeClass('uk-hidden');
            }
            else {
                // API connection failed
                $(_local).find('.errors').html('Sorry, this form cannot be submitted at this time.').removeClass('uk-hidden');
            }
            $(_local).find('.required').first().addClass('uk-hidden');
            
            break;
        case 500:
            // Server Error
            $(_local).find('.errors').html('Sorry, server is not responding. Please try again shortly.').removeClass('uk-hidden');
            //$(_local).find('.required').first().addClass('uk-hidden');
            break;
        default:
            // Catch-all
            $(_local).find('.errors').html('Sorry, server is not responding. Please try again shortly.').removeClass('uk-hidden');
            //$(_local).find('.required').first().addClass('uk-hidden');
            break;
    }

}

/*!
 * Form Post Always
 */
function formPostAlways(scope, scrollUp) {
    var _local = scope;
    var _scrollUp = scrollUp === undefined ? true : scrollUp;

    // Scroll Up
    if (_scrollUp) {
        $([document.documentElement, document.body]).animate({
            scrollTop: $(".form-success").offset().top - 200
        }, 500);
    }
    // Activate button
    $(_local).find('button.submit').attr('disabled', false);
    // Hide Indicator
    $(_local).find('.loader').addClass('uk-hidden');
}

/*
 * Get Days In MOnth
 */ 
function getDaysInMonth(m, y) { 
    m -= 1; //indexed: 0-11
    switch (m) {
        case 1:
            return (y % 4 === 0 && y % 100) || y % 400 === 0 ? 29 : 28;
        case 8: case 3: case 5: case 10:
            return 30;
        default:
            return 31;
    }
}

function validateMonthDay(date) {
    var month = date.split('/')[0].replace(/^0+/, '');
    var days = date.split('/')[1].replace(/^0+/, '');
    var year = 2000;
    var response = {
        status: 'Success',
        msg: ''
    };

    if (isNaN(month) || isNaN(days)) {
        response.status = "Error";
        response.msg = "format (mm/dd).";
    }
    else if (date.length < 5) {
        response.status = "Error";
        response.msg = "format (mm/dd).";
    }
    else if (month > 12 || month < 1) {
        response.status = "Error";
        response.msg = "month.";
    }
    else if (days > getDaysInMonth(month, year)) {
        response.status = "Error";
        response.msg = "day based on the month.";
    }
    else if (days.length === 0) {
        response.status = "Error";
        response.msg = "day.";
    }

    return response;  
}

function validateMonthYear(date, ageLimit) {
    var month = date.split('/')[0].replace(/^0+/, '');
    var year = date.split('/')[1].replace(/^0+/, '');
    var yearNow = new Date().getFullYear();
    var age = getAge(('0' + month).slice(-2) + '/01/' + year);

    var response = {
        status: 'Success',
        msg: ''
    };

    if (isNaN(month) || isNaN(year)) {
        response.status = "Error";
        response.msg = "format (mm/yyyy).";
    }
    else if (date.length < 7) {
        response.status = "Error";
        response.msg = "format (mm/yyyy).";
    }
    else if (month > 12 || month < 1) {
        response.status = "Error";
        response.msg = "month.";
    }
    else if (year.length === 0 || year < 1900 || year > yearNow) {
        response.status = "Error";
        response.msg = "year.";
    }
    else if (age.years < ageLimit) {
        response.status = "Error";
        response.msg = "age.";
    }

    return response;
}


// Get Age
// @dateString mm/dd/yyy
// returns {month, days, years}

function getAge(dateString) {
    var now = new Date();
    var yearNow = now.getYear();
    var monthNow = now.getMonth();
    var dateNow = now.getDate();

    var dob = new Date(dateString.substring(6, 10),
        dateString.substring(0, 2) - 1,
        dateString.substring(3, 5)
    );

    var yearDob = dob.getYear();
    var monthDob = dob.getMonth();
    var dateDob = dob.getDate();
    var dateAge = "";
    var monthAge = "";

    yearAge = yearNow - yearDob;

    if (monthNow >= monthDob)
        monthAge = monthNow - monthDob;
    else {
        yearAge--;
        monthAge = 12 + monthNow - monthDob;
    }

    if (dateNow >= dateDob)
        dateAge = dateNow - dateDob;
    else {
        monthAge--;
        dateAge = 31 + dateNow - dateDob;

        if (monthAge < 0) {
            monthAge = 11;
            yearAge--;
        }
    }

    return {
        months: monthAge,
        days: dateAge,
        years: yearAge
    };
}

// I N I T

setupCustomForms();;
$(function () {
    var multipleClosingFirePrevent = false;
    /*
     * Trustarc DOM Listener
     */
    const bodyObserver = new MutationObserver((mutations) => {
        mutations.forEach((mutation) => {
            // mobile nav adds a right padding when disabling scroll. need to capture this value and add to the hamburger nav and mobile pencile nav.
            if (mutation.attributeName === 'style' && mutation.target.id === 'truste-consent-track') {
                // filter down
                if ($('#truste-consent-track').css('opacity') === '0') {
                    // reduce multiple dispatch
                    if (!multipleClosingFirePrevent) {
                        multipleClosingFirePrevent = true;
                        //Dispatch Closing Event
                        document.dispatchEvent(trustarcCookieClosingEvent);
                    }
                }

                if ($('#truste-consent-track').css('opacity') === '1') {
                    //console.log('cookie opened');
                }   
            }
        });
    });

    bodyObserver.observe(document, {
        childList: true,
        attributes: true,
        subtree: true
    });


    // I N I T


    // this means cookie has been interacted (or dismissed)
    if (readCookie('cmapi_cookie_privacy')) {
        //Dispatch Closing Event
        document.dispatchEvent(trustarcCookieClosedEvent);
    } else {
        // Dispatch Opened Event
        document.dispatchEvent(trustarcCookieOpenEvent);
    }
});;
$(function () {
        // I N I T

});;
