"use strict";

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

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

(function (global, undefined) {
    "use strict";

    if (global.setImmediate) {
        return;
    }

    var nextHandle = 1; // Spec says greater than zero
    var tasksByHandle = {};
    var currentlyRunningATask = false;
    var doc = global.document;
    var registerImmediate;

    function setImmediate(callback) {
        // Callback can either be a function or a string
        if (typeof callback !== "function") {
            callback = new Function("" + callback);
        }
        // Copy function arguments
        var args = new Array(arguments.length - 1);
        for (var i = 0; i < args.length; i++) {
            args[i] = arguments[i + 1];
        }
        // Store and register the task
        var task = { callback: callback, args: args };
        tasksByHandle[nextHandle] = task;
        registerImmediate(nextHandle);
        return nextHandle++;
    }

    function clearImmediate(handle) {
        delete tasksByHandle[handle];
    }

    function run(task) {
        var callback = task.callback;
        var args = task.args;
        switch (args.length) {
            case 0:
                callback();
                break;
            case 1:
                callback(args[0]);
                break;
            case 2:
                callback(args[0], args[1]);
                break;
            case 3:
                callback(args[0], args[1], args[2]);
                break;
            default:
                callback.apply(undefined, args);
                break;
        }
    }

    function runIfPresent(handle) {
        // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
        // So if we're currently running a task, we'll need to delay this invocation.
        if (currentlyRunningATask) {
            // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
            // "too much recursion" error.
            setTimeout(runIfPresent, 0, handle);
        } else {
            var task = tasksByHandle[handle];
            if (task) {
                currentlyRunningATask = true;
                try {
                    run(task);
                } finally {
                    clearImmediate(handle);
                    currentlyRunningATask = false;
                }
            }
        }
    }

    function installNextTickImplementation() {
        registerImmediate = function registerImmediate(handle) {
            process.nextTick(function () {
                runIfPresent(handle);
            });
        };
    }

    function canUsePostMessage() {
        // The test against `importScripts` prevents this implementation from being installed inside a web worker,
        // where `global.postMessage` means something completely different and can't be used for this purpose.
        if (global.postMessage && !global.importScripts) {
            var postMessageIsAsynchronous = true;
            var oldOnMessage = global.onmessage;
            global.onmessage = function () {
                postMessageIsAsynchronous = false;
            };
            global.postMessage("", "*");
            global.onmessage = oldOnMessage;
            return postMessageIsAsynchronous;
        }
    }

    function installPostMessageImplementation() {
        // Installs an event handler on `global` for the `message` event: see
        // * https://developer.mozilla.org/en/DOM/window.postMessage
        // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages

        var messagePrefix = "setImmediate$" + Math.random() + "$";
        var onGlobalMessage = function onGlobalMessage(event) {
            if (event.source === global && typeof event.data === "string" && event.data.indexOf(messagePrefix) === 0) {
                runIfPresent(+event.data.slice(messagePrefix.length));
            }
        };

        if (global.addEventListener) {
            global.addEventListener("message", onGlobalMessage, false);
        } else {
            global.attachEvent("onmessage", onGlobalMessage);
        }

        registerImmediate = function registerImmediate(handle) {
            global.postMessage(messagePrefix + handle, "*");
        };
    }

    function installMessageChannelImplementation() {
        var channel = new MessageChannel();
        channel.port1.onmessage = function (event) {
            var handle = event.data;
            runIfPresent(handle);
        };

        registerImmediate = function registerImmediate(handle) {
            channel.port2.postMessage(handle);
        };
    }

    function installReadyStateChangeImplementation() {
        var html = doc.documentElement;
        registerImmediate = function registerImmediate(handle) {
            // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
            // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
            var script = doc.createElement("script");
            script.onreadystatechange = function () {
                runIfPresent(handle);
                script.onreadystatechange = null;
                html.removeChild(script);
                script = null;
            };
            html.appendChild(script);
        };
    }

    function installSetTimeoutImplementation() {
        registerImmediate = function registerImmediate(handle) {
            setTimeout(runIfPresent, 0, handle);
        };
    }

    // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
    var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
    attachTo = attachTo && attachTo.setTimeout ? attachTo : global;

    // Don't get fooled by e.g. browserify environments.
    if ({}.toString.call(global.process) === "[object process]") {
        // For Node.js before 0.9
        installNextTickImplementation();
    } else if (canUsePostMessage()) {
        // For non-IE10 modern browsers
        installPostMessageImplementation();
    } else if (global.MessageChannel) {
        // For web workers, where supported
        installMessageChannelImplementation();
    } else if (doc && "onreadystatechange" in doc.createElement("script")) {
        // For IE 6–8
        installReadyStateChangeImplementation();
    } else {
        // For older browsers
        installSetTimeoutImplementation();
    }

    attachTo.setImmediate = setImmediate;
    attachTo.clearImmediate = clearImmediate;
})(typeof self === "undefined" ? typeof global === "undefined" ? undefined : global : self);
(function (t) {
    function z() {
        for (var a = 0; a < g.length; a++) {
            g[a][0](g[a][1]);
        }g = [];m = !1;
    }function n(a, b) {
        g.push([a, b]);m || (m = !0, A(z, 0));
    }function B(a, b) {
        function c(a) {
            p(b, a);
        }function h(a) {
            k(b, a);
        }try {
            a(c, h);
        } catch (d) {
            h(d);
        }
    }function u(a) {
        var b = a.owner,
            c = b.state_,
            b = b.data_,
            h = a[c];a = a.then;if ("function" === typeof h) {
            c = l;try {
                b = h(b);
            } catch (d) {
                k(a, d);
            }
        }v(a, b) || (c === l && p(a, b), c === q && k(a, b));
    }function v(a, b) {
        var c;try {
            if (a === b) throw new TypeError("A promises callback cannot return that same promise.");if (b && ("function" === typeof b || "object" === (typeof b === "undefined" ? "undefined" : _typeof(b)))) {
                var h = b.then;if ("function" === typeof h) return h.call(b, function (d) {
                    c || (c = !0, b !== d ? p(a, d) : w(a, d));
                }, function (b) {
                    c || (c = !0, k(a, b));
                }), !0;
            }
        } catch (d) {
            return c || k(a, d), !0;
        }return !1;
    }function p(a, b) {
        a !== b && v(a, b) || w(a, b);
    }function w(a, b) {
        a.state_ === r && (a.state_ = x, a.data_ = b, n(C, a));
    }function k(a, b) {
        a.state_ === r && (a.state_ = x, a.data_ = b, n(D, a));
    }function y(a) {
        var b = a.then_;a.then_ = void 0;for (a = 0; a < b.length; a++) {
            u(b[a]);
        }
    }function C(a) {
        a.state_ = l;y(a);
    }function D(a) {
        a.state_ = q;y(a);
    }function e(a) {
        if ("function" !== typeof a) throw new TypeError("Promise constructor takes a function argument");if (!1 === this instanceof e) throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");this.then_ = [];B(a, this);
    }var f = t.Promise,
        s = f && "resolve" in f && "reject" in f && "all" in f && "race" in f && function () {
        var a;new f(function (b) {
            a = b;
        });return "function" === typeof a;
    }();"undefined" !== typeof exports && exports ? (exports.Promise = s ? f : e, exports.Polyfill = e) : "function" == typeof define && define.amd ? define(function () {
        return s ? f : e;
    }) : s || (t.Promise = e);var r = "pending",
        x = "sealed",
        l = "fulfilled",
        q = "rejected",
        E = function E() {},
        A = "undefined" !== typeof setImmediate ? setImmediate : setTimeout,
        g = [],
        m;e.prototype = { constructor: e, state_: r, then_: null, data_: void 0, then: function then(a, b) {
            var c = { owner: this, then: new this.constructor(E), fulfilled: a, rejected: b };this.state_ === l || this.state_ === q ? n(u, c) : this.then_.push(c);return c.then;
        }, "catch": function _catch(a) {
            return this.then(null, a);
        } };e.all = function (a) {
        if ("[object Array]" !== Object.prototype.toString.call(a)) throw new TypeError("You must pass an array to Promise.all().");return new this(function (b, c) {
            function h(a) {
                e++;return function (c) {
                    d[a] = c;--e || b(d);
                };
            }for (var d = [], e = 0, f = 0, g; f < a.length; f++) {
                (g = a[f]) && "function" === typeof g.then ? g.then(h(f), c) : d[f] = g;
            }e || b(d);
        });
    };e.race = function (a) {
        if ("[object Array]" !== Object.prototype.toString.call(a)) throw new TypeError("You must pass an array to Promise.race().");return new this(function (b, c) {
            for (var e = 0, d; e < a.length; e++) {
                (d = a[e]) && "function" === typeof d.then ? d.then(b, c) : b(d);
            }
        });
    };e.resolve = function (a) {
        return a && "object" === (typeof a === "undefined" ? "undefined" : _typeof(a)) && a.constructor === this ? a : new this(function (b) {
            b(a);
        });
    };e.reject = function (a) {
        return new this(function (b, c) {
            c(a);
        });
    };
})("undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : undefined);
/*
 * classList.js: Cross-browser full element.classList implementation.
 * 1.2.20171210
 *
 * By Eli Grey, http://eligrey.com
 * License: Dedicated to the public domain.
 *   See https://github.com/eligrey/classList.js/blob/master/LICENSE.md
 */

/*global self, document, DOMException */

/*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js */

if ("document" in self) {

    // Full polyfill for browsers with no classList support
    // Including IE < Edge missing SVGElement.classList
    if (!("classList" in document.createElement("_")) || document.createElementNS && !("classList" in document.createElementNS("http://www.w3.org/2000/svg", "g"))) {

        (function (view) {

            "use strict";

            if (!('Element' in view)) return;

            var classListProp = "classList",
                protoProp = "prototype",
                elemCtrProto = view.Element[protoProp],
                objCtr = Object,
                strTrim = String[protoProp].trim || function () {
                return this.replace(/^\s+|\s+$/g, "");
            },
                arrIndexOf = Array[protoProp].indexOf || function (item) {
                var i = 0,
                    len = this.length;
                for (; i < len; i++) {
                    if (i in this && this[i] === item) {
                        return i;
                    }
                }
                return -1;
            }
            // Vendors: please allow content code to instantiate DOMExceptions
            ,
                DOMEx = function DOMEx(type, message) {
                this.name = type;
                this.code = DOMException[type];
                this.message = message;
            },
                checkTokenAndGetIndex = function checkTokenAndGetIndex(classList, token) {
                if (token === "") {
                    throw new DOMEx("SYNTAX_ERR", "The token must not be empty.");
                }
                if (/\s/.test(token)) {
                    throw new DOMEx("INVALID_CHARACTER_ERR", "The token must not contain space characters.");
                }
                return arrIndexOf.call(classList, token);
            },
                ClassList = function ClassList(elem) {
                var trimmedClasses = strTrim.call(elem.getAttribute("class") || ""),
                    classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [],
                    i = 0,
                    len = classes.length;
                for (; i < len; i++) {
                    this.push(classes[i]);
                }
                this._updateClassName = function () {
                    elem.setAttribute("class", this.toString());
                };
            },
                classListProto = ClassList[protoProp] = [],
                classListGetter = function classListGetter() {
                return new ClassList(this);
            };
            // Most DOMException implementations don't allow calling DOMException's toString()
            // on non-DOMExceptions. Error's toString() is sufficient here.
            DOMEx[protoProp] = Error[protoProp];
            classListProto.item = function (i) {
                return this[i] || null;
            };
            classListProto.contains = function (token) {
                return ~checkTokenAndGetIndex(this, token + "");
            };
            classListProto.add = function () {
                var tokens = arguments,
                    i = 0,
                    l = tokens.length,
                    token,
                    updated = false;
                do {
                    token = tokens[i] + "";
                    if (!~checkTokenAndGetIndex(this, token)) {
                        this.push(token);
                        updated = true;
                    }
                } while (++i < l);

                if (updated) {
                    this._updateClassName();
                }
            };
            classListProto.remove = function () {
                var tokens = arguments,
                    i = 0,
                    l = tokens.length,
                    token,
                    updated = false,
                    index;
                do {
                    token = tokens[i] + "";
                    index = checkTokenAndGetIndex(this, token);
                    while (~index) {
                        this.splice(index, 1);
                        updated = true;
                        index = checkTokenAndGetIndex(this, token);
                    }
                } while (++i < l);

                if (updated) {
                    this._updateClassName();
                }
            };
            classListProto.toggle = function (token, force) {
                var result = this.contains(token),
                    method = result ? force !== true && "remove" : force !== false && "add";

                if (method) {
                    this[method](token);
                }

                if (force === true || force === false) {
                    return force;
                } else {
                    return !result;
                }
            };
            classListProto.replace = function (token, replacement_token) {
                var index = checkTokenAndGetIndex(token + "");
                if (~index) {
                    this.splice(index, 1, replacement_token);
                    this._updateClassName();
                }
            };
            classListProto.toString = function () {
                return this.join(" ");
            };

            if (objCtr.defineProperty) {
                var classListPropDesc = {
                    get: classListGetter,
                    enumerable: true,
                    configurable: true
                };
                try {
                    objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
                } catch (ex) {
                    // IE 8 doesn't support enumerable:true
                    // adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36
                    // modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected
                    if (ex.number === undefined || ex.number === -0x7FF5EC54) {
                        classListPropDesc.enumerable = false;
                        objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
                    }
                }
            } else if (objCtr[protoProp].__defineGetter__) {
                elemCtrProto.__defineGetter__(classListProp, classListGetter);
            }
        })(self);
    }

    // There is full or partial native classList support, so just check if we need
    // to normalize the add/remove and toggle APIs.

    (function () {
        "use strict";

        var testElement = document.createElement("_");

        testElement.classList.add("c1", "c2");

        // Polyfill for IE 10/11 and Firefox <26, where classList.add and
        // classList.remove exist but support only one argument at a time.
        if (!testElement.classList.contains("c2")) {
            var createMethod = function createMethod(method) {
                var original = DOMTokenList.prototype[method];

                DOMTokenList.prototype[method] = function (token) {
                    var i,
                        len = arguments.length;

                    for (i = 0; i < len; i++) {
                        token = arguments[i];
                        original.call(this, token);
                    }
                };
            };
            createMethod('add');
            createMethod('remove');
        }

        testElement.classList.toggle("c3", false);

        // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
        // support the second argument.
        if (testElement.classList.contains("c3")) {
            var _toggle = DOMTokenList.prototype.toggle;

            DOMTokenList.prototype.toggle = function (token, force) {
                if (1 in arguments && !this.contains(token) === !force) {
                    return force;
                } else {
                    return _toggle.call(this, token);
                }
            };
        }

        // replace() polyfill
        if (!("replace" in document.createElement("_").classList)) {
            DOMTokenList.prototype.replace = function (token, replacement_token) {
                var tokens = this.toString().split(" "),
                    index = tokens.indexOf(token + "");
                if (~index) {
                    tokens = tokens.slice(index);
                    this.remove.apply(this, tokens);
                    this.add(replacement_token);
                    this.add.apply(this, tokens.slice(1));
                }
            };
        }

        testElement = null;
    })();
}
"use strict";

if (!Element.prototype.matches) Element.prototype.matches = Element.prototype.msMatchesSelector || Element.prototype.webkitMatchesSelector;

if (!Element.prototype.closest) Element.prototype.closest = function (s) {
    var el = this;
    if (!document.documentElement.contains(el)) return null;
    do {
        if (el.matches(s)) return el;
        el = el.parentElement || el.parentNode;
    } while (el !== null);
    return null;
};
(function (self) {
    'use strict';

    if (self.fetch) {
        return;
    }

    var support = {
        searchParams: 'URLSearchParams' in self,
        iterable: 'Symbol' in self && 'iterator' in Symbol,
        blob: 'FileReader' in self && 'Blob' in self && function () {
            try {
                new Blob();
                return true;
            } catch (e) {
                return false;
            }
        }(),
        formData: 'FormData' in self,
        arrayBuffer: 'ArrayBuffer' in self
    };

    if (support.arrayBuffer) {
        var viewClasses = ['[object Int8Array]', '[object Uint8Array]', '[object Uint8ClampedArray]', '[object Int16Array]', '[object Uint16Array]', '[object Int32Array]', '[object Uint32Array]', '[object Float32Array]', '[object Float64Array]'];

        var isDataView = function isDataView(obj) {
            return obj && DataView.prototype.isPrototypeOf(obj);
        };

        var isArrayBufferView = ArrayBuffer.isView || function (obj) {
            return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1;
        };
    }

    function normalizeName(name) {
        if (typeof name !== 'string') {
            name = String(name);
        }
        if (/[^a-z0-9\-#$%&'*+.\^_`|~]/i.test(name)) {
            throw new TypeError('Invalid character in header field name');
        }
        return name.toLowerCase();
    }

    function normalizeValue(value) {
        if (typeof value !== 'string') {
            value = String(value);
        }
        return value;
    }

    // Build a destructive iterator for the value list
    function iteratorFor(items) {
        var iterator = {
            next: function next() {
                var value = items.shift();
                return { done: value === undefined, value: value };
            }
        };

        if (support.iterable) {
            iterator[Symbol.iterator] = function () {
                return iterator;
            };
        }

        return iterator;
    }

    function Headers(headers) {
        this.map = {};

        if (headers instanceof Headers) {
            headers.forEach(function (value, name) {
                this.append(name, value);
            }, this);
        } else if (Array.isArray(headers)) {
            headers.forEach(function (header) {
                this.append(header[0], header[1]);
            }, this);
        } else if (headers) {
            Object.getOwnPropertyNames(headers).forEach(function (name) {
                this.append(name, headers[name]);
            }, this);
        }
    }

    Headers.prototype.append = function (name, value) {
        name = normalizeName(name);
        value = normalizeValue(value);
        var oldValue = this.map[name];
        this.map[name] = oldValue ? oldValue + ',' + value : value;
    };

    Headers.prototype['delete'] = function (name) {
        delete this.map[normalizeName(name)];
    };

    Headers.prototype.get = function (name) {
        name = normalizeName(name);
        return this.has(name) ? this.map[name] : null;
    };

    Headers.prototype.has = function (name) {
        return this.map.hasOwnProperty(normalizeName(name));
    };

    Headers.prototype.set = function (name, value) {
        this.map[normalizeName(name)] = normalizeValue(value);
    };

    Headers.prototype.forEach = function (callback, thisArg) {
        for (var name in this.map) {
            if (this.map.hasOwnProperty(name)) {
                callback.call(thisArg, this.map[name], name, this);
            }
        }
    };

    Headers.prototype.keys = function () {
        var items = [];
        this.forEach(function (value, name) {
            items.push(name);
        });
        return iteratorFor(items);
    };

    Headers.prototype.values = function () {
        var items = [];
        this.forEach(function (value) {
            items.push(value);
        });
        return iteratorFor(items);
    };

    Headers.prototype.entries = function () {
        var items = [];
        this.forEach(function (value, name) {
            items.push([name, value]);
        });
        return iteratorFor(items);
    };

    if (support.iterable) {
        Headers.prototype[Symbol.iterator] = Headers.prototype.entries;
    }

    function consumed(body) {
        if (body.bodyUsed) {
            return Promise.reject(new TypeError('Already read'));
        }
        body.bodyUsed = true;
    }

    function fileReaderReady(reader) {
        return new Promise(function (resolve, reject) {
            reader.onload = function () {
                resolve(reader.result);
            };
            reader.onerror = function () {
                reject(reader.error);
            };
        });
    }

    function readBlobAsArrayBuffer(blob) {
        var reader = new FileReader();
        var promise = fileReaderReady(reader);
        reader.readAsArrayBuffer(blob);
        return promise;
    }

    function readBlobAsText(blob) {
        var reader = new FileReader();
        var promise = fileReaderReady(reader);
        reader.readAsText(blob);
        return promise;
    }

    function readArrayBufferAsText(buf) {
        var view = new Uint8Array(buf);
        var chars = new Array(view.length);

        for (var i = 0; i < view.length; i++) {
            chars[i] = String.fromCharCode(view[i]);
        }
        return chars.join('');
    }

    function bufferClone(buf) {
        if (buf.slice) {
            return buf.slice(0);
        } else {
            var view = new Uint8Array(buf.byteLength);
            view.set(new Uint8Array(buf));
            return view.buffer;
        }
    }

    function Body() {
        this.bodyUsed = false;

        this._initBody = function (body) {
            this._bodyInit = body;
            if (!body) {
                this._bodyText = '';
            } else if (typeof body === 'string') {
                this._bodyText = body;
            } else if (support.blob && Blob.prototype.isPrototypeOf(body)) {
                this._bodyBlob = body;
            } else if (support.formData && FormData.prototype.isPrototypeOf(body)) {
                this._bodyFormData = body;
            } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
                this._bodyText = body.toString();
            } else if (support.arrayBuffer && support.blob && isDataView(body)) {
                this._bodyArrayBuffer = bufferClone(body.buffer);
                // IE 10-11 can't handle a DataView body.
                this._bodyInit = new Blob([this._bodyArrayBuffer]);
            } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView(body))) {
                this._bodyArrayBuffer = bufferClone(body);
            } else {
                throw new Error('unsupported BodyInit type');
            }

            if (!this.headers.get('content-type')) {
                if (typeof body === 'string') {
                    this.headers.set('content-type', 'text/plain;charset=UTF-8');
                } else if (this._bodyBlob && this._bodyBlob.type) {
                    this.headers.set('content-type', this._bodyBlob.type);
                } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) {
                    this.headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');
                }
            }
        };

        if (support.blob) {
            this.blob = function () {
                var rejected = consumed(this);
                if (rejected) {
                    return rejected;
                }

                if (this._bodyBlob) {
                    return Promise.resolve(this._bodyBlob);
                } else if (this._bodyArrayBuffer) {
                    return Promise.resolve(new Blob([this._bodyArrayBuffer]));
                } else if (this._bodyFormData) {
                    throw new Error('could not read FormData body as blob');
                } else {
                    return Promise.resolve(new Blob([this._bodyText]));
                }
            };

            this.arrayBuffer = function () {
                if (this._bodyArrayBuffer) {
                    return consumed(this) || Promise.resolve(this._bodyArrayBuffer);
                } else {
                    return this.blob().then(readBlobAsArrayBuffer);
                }
            };
        }

        this.text = function () {
            var rejected = consumed(this);
            if (rejected) {
                return rejected;
            }

            if (this._bodyBlob) {
                return readBlobAsText(this._bodyBlob);
            } else if (this._bodyArrayBuffer) {
                return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer));
            } else if (this._bodyFormData) {
                throw new Error('could not read FormData body as text');
            } else {
                return Promise.resolve(this._bodyText);
            }
        };

        if (support.formData) {
            this.formData = function () {
                return this.text().then(decode);
            };
        }

        this.json = function () {
            return this.text().then(JSON.parse);
        };

        return this;
    }

    // HTTP methods whose capitalization should be normalized
    var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT'];

    function normalizeMethod(method) {
        var upcased = method.toUpperCase();
        return methods.indexOf(upcased) > -1 ? upcased : method;
    }

    function Request(input, options) {
        options = options || {};
        var body = options.body;

        if (input instanceof Request) {
            if (input.bodyUsed) {
                throw new TypeError('Already read');
            }
            this.url = input.url;
            this.credentials = input.credentials;
            if (!options.headers) {
                this.headers = new Headers(input.headers);
            }
            this.method = input.method;
            this.mode = input.mode;
            if (!body && input._bodyInit != null) {
                body = input._bodyInit;
                input.bodyUsed = true;
            }
        } else {
            this.url = String(input);
        }

        this.credentials = options.credentials || this.credentials || 'omit';
        if (options.headers || !this.headers) {
            this.headers = new Headers(options.headers);
        }
        this.method = normalizeMethod(options.method || this.method || 'GET');
        this.mode = options.mode || this.mode || null;
        this.referrer = null;

        if ((this.method === 'GET' || this.method === 'HEAD') && body) {
            throw new TypeError('Body not allowed for GET or HEAD requests');
        }
        this._initBody(body);
    }

    Request.prototype.clone = function () {
        return new Request(this, { body: this._bodyInit });
    };

    function decode(body) {
        var form = new FormData();
        body.trim().split('&').forEach(function (bytes) {
            if (bytes) {
                var split = bytes.split('=');
                var name = split.shift().replace(/\+/g, ' ');
                var value = split.join('=').replace(/\+/g, ' ');
                form.append(decodeURIComponent(name), decodeURIComponent(value));
            }
        });
        return form;
    }

    function parseHeaders(rawHeaders) {
        var headers = new Headers();
        // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space
        // https://tools.ietf.org/html/rfc7230#section-3.2
        var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, ' ');
        preProcessedHeaders.split(/\r?\n/).forEach(function (line) {
            var parts = line.split(':');
            var key = parts.shift().trim();
            if (key) {
                var value = parts.join(':').trim();
                headers.append(key, value);
            }
        });
        return headers;
    }

    Body.call(Request.prototype);

    function Response(bodyInit, options) {
        if (!options) {
            options = {};
        }

        this.type = 'default';
        this.status = options.status === undefined ? 200 : options.status;
        this.ok = this.status >= 200 && this.status < 300;
        this.statusText = 'statusText' in options ? options.statusText : 'OK';
        this.headers = new Headers(options.headers);
        this.url = options.url || '';
        this._initBody(bodyInit);
    }

    Body.call(Response.prototype);

    Response.prototype.clone = function () {
        return new Response(this._bodyInit, {
            status: this.status,
            statusText: this.statusText,
            headers: new Headers(this.headers),
            url: this.url
        });
    };

    Response.error = function () {
        var response = new Response(null, { status: 0, statusText: '' });
        response.type = 'error';
        return response;
    };

    var redirectStatuses = [301, 302, 303, 307, 308];

    Response.redirect = function (url, status) {
        if (redirectStatuses.indexOf(status) === -1) {
            throw new RangeError('Invalid status code');
        }

        return new Response(null, { status: status, headers: { location: url } });
    };

    self.Headers = Headers;
    self.Request = Request;
    self.Response = Response;

    self.fetch = function (input, init) {
        return new Promise(function (resolve, reject) {
            var request = new Request(input, init);
            var xhr = new XMLHttpRequest();

            xhr.onload = function () {
                var options = {
                    status: xhr.status,
                    statusText: xhr.statusText,
                    headers: parseHeaders(xhr.getAllResponseHeaders() || '')
                };
                options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL');
                var body = 'response' in xhr ? xhr.response : xhr.responseText;
                resolve(new Response(body, options));
            };

            xhr.onerror = function () {
                reject(new TypeError('Network request failed'));
            };

            xhr.ontimeout = function () {
                reject(new TypeError('Network request failed'));
            };

            xhr.open(request.method, request.url, true);

            if (request.credentials === 'include') {
                xhr.withCredentials = true;
            } else if (request.credentials === 'omit') {
                xhr.withCredentials = false;
            }

            if ('responseType' in xhr && support.blob) {
                xhr.responseType = 'blob';
            }

            request.headers.forEach(function (value, name) {
                xhr.setRequestHeader(name, value);
            });

            xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit);
        });
    };
    self.fetch.polyfill = true;
})(typeof self !== 'undefined' ? self : undefined);
/** Version 1.2-AZ */
(function (window, document, grecaptcha, undefined) {
    "use strict";

    function obformsSubmit(element) {
        this.$element = element;
        this.elementID = this.$element.getAttribute("id");
        this.url = this.$element.getAttribute("action");
        this.$message = this.$element.querySelector('.form__message');
        this.hasCaptcha = grecaptcha ? true : false;
        this.$captcha = this.$element.querySelector(".g-recaptcha");
        this.$submitButton = this.$element.querySelector("button[type='submit']");
        this.callback = this.$element.querySelector('input[name="obcb"]').value ? atob(this.$element.querySelector('input[name="obcb"]').value) : false;

        // conditional testing
        this.$form_conditions = this.$element.querySelector('.form__conditions');
        this.$rows = this.$element.querySelectorAll('.form__row');
        this.$noMatchFields = this.$element.querySelector('.form__input--no-match');
        this.$inputs = this.$element.querySelectorAll('.form__input');
        this.compareFields = JSON.parse(this.$form_conditions.getAttribute("data-compare-fields"));
        this.validationFields = JSON.parse(this.$form_conditions.getAttribute("data-validation-fields"));
        this.watchedFields = JSON.parse(this.$form_conditions.getAttribute("data-watch-fields"));
        // required fields
        this.$required = this.$element.querySelector('.form__required');
        this.requiredArray = window.atob(this.$required.getAttribute("value")).split(",");
        // notification recipients
        this.recipientConditions = JSON.parse(this.$form_conditions.getAttribute("data-recipient-conditions"));
        this.$recipients = this.$element.querySelector('.form__recipients');
        this.recipientsArray = window.atob(this.$recipients.getAttribute("value")).split(",");

        // form responses
        this.defaultFormResponse = JSON.parse(this.$form_conditions.getAttribute("data-default-response"));
        this.responseConditions = JSON.parse(this.$form_conditions.getAttribute("data-response-conditions"));
        this.responseConditionalField = JSON.parse(this.$form_conditions.getAttribute("data-response-conditional-field"));
        this.$response = this.$element.querySelector('.form__response');

        this.init();
    }

    // INIT
    obformsSubmit.prototype.init = function () {
        var self = this;
        // conditional checks
        var inputsToCheck = self.getInputsToCheck(self.watchedFields);
        var rowsToValidate = self.getRowsToValidate(self.validationFields);
        self.validateByConditions(rowsToValidate, inputsToCheck);
        self.addConditionalListeners(self.watchedFields, rowsToValidate, inputsToCheck);
        // recipient checking
        if (self.recipientConditions) {
            self.addRecipientsListener();
            self.updateRecipientsArray();
        }
        // comparison checks
        if (self.compareFields) {
            self.validateByComparison(self.compareFields);
        }
        // disable submit if captcha
        if (self.hasCaptcha) {
            self.$submitButton.disabled = true;
        }
        // base
        self.addListeners();
    };

    // LISTENERS
    obformsSubmit.prototype.addListeners = function () {
        var self = this;
        self.$inputs.forEach(function (elem) {
            elem.addEventListener("input", function () {
                if (this.value) {
                    this.closest('.form__row').querySelector('.form__label').classList.remove('form__label--empty');
                }
            });
        });
        self.$element.addEventListener('submit', function (e) {
            e.preventDefault();
            self.updateRecipientsArray();
            self.updateFormResponse();
            if (self.requiredArray) {
                self.requiredArray.forEach(function (name) {
                    var $elems = self.$element.querySelectorAll('[name="' + name + '"]');
                    $elems.forEach(function (elem) {
                        if (!elem.value) {
                            elem.closest('.form__row').querySelector('.form__label').classList.add('form__label--empty');
                        }
                    });
                });
            }
            var $unmatchedFields = self.$element.querySelector('.form__label--no-match');

            if ($unmatchedFields) {
                self.setStatus('error');
                var message = 'Form cannot be submitted - please check your submission for errors';
                self.setMessage(message);
            } else {
                self.setStatus('loading');
                self.submitForm();
            }
        });
    };

    obformsSubmit.prototype.addConditionalListeners = function (watchedFields, rowsToValidate, inputsToCheck) {
        var self = this;
        var uniqueFieldNames = [].concat(_toConsumableArray(new Set(watchedFields)));
        var arrayLength = self.$inputs.length;
        var fieldsLength = uniqueFieldNames.length;
        // add listener if input matches watched fields
        for (var ind = 0; ind < arrayLength; ind++) {
            for (var i = 0; i < fieldsLength; i++) {
                if (self.$inputs[ind] && self.$inputs[ind].getAttribute("name") === uniqueFieldNames[i]) {
                    self.$inputs[ind].addEventListener('change', function () {
                        self.validateByConditions(rowsToValidate, inputsToCheck);
                        self.updateRecipientsArray();
                        self.updateResponseMessage();
                    });
                }
            }
        }
    };

    obformsSubmit.prototype.addRecipientsListener = function () {
        var self = this;
        var recipientConditions = self.recipientConditions;
        var recipientElements = [];

        //Find all elements that recipient list is based on
        for (var i = 0; i < recipientConditions.length; i++) {
            var conditionArray = recipientConditions[i].split('&|&');
            recipientElements.push(conditionArray[0]);
        }

        //Reduce duplicate elements
        recipientElements = [].concat(_toConsumableArray(new Set(recipientElements)));

        //Add listener to each element
        for (var i = 0; i < recipientElements.length; i++) {
            self.$element.querySelectorAll('[name="' + recipientElements[i] + '"]').forEach(function (element) {
                return element.addEventListener('change', function (e) {
                    return self.updateRecipientsArray(e);
                });
            });
        }
    };

    // CHECK CONDITIONS:

    // validate recipient by condition
    obformsSubmit.prototype.updateRecipientsArray = function () {
        var self = this;
        var recipientConditions = self.recipientConditions;
        // add email to recipients array when condition is met
        for (var i = 0; i < recipientConditions.length; i++) {
            var conditionArray = recipientConditions[i].split('&|&');
            if (self.$element.querySelectorAll('[name="' + conditionArray[0] + '"]')[0].value === conditionArray[1]) {
                if (!self.recipientsArray.includes(conditionArray[2])) {
                    self.recipientsArray.push(conditionArray[2]);
                }
            } else {
                if (self.recipientsArray.includes(conditionArray[2])) {
                    var indexOfElem = this.recipientsArray.indexOf(conditionArray[2]);
                    if (indexOfElem > -1) {
                        this.recipientsArray.splice(indexOfElem, 1);
                    }
                }
            }
        }
        self.updateRecipientsList();
    };

    // update response by condition
    obformsSubmit.prototype.updateResponseMessage = function () {
        var self = this;
        var responseConditions = self.responseConditions;
        var formResponse = "";
        // change to correct response message
        for (var i = 0; i < responseConditions.length; i++) {
            var conditionArray = responseConditions[i].split('&|&');
            // 1. if field value matches condition value then output the condition response
            if (self.$element.querySelectorAll('[name="' + self.responseConditionalField + '"]')[0].value === conditionArray[0]) {
                formResponse = conditionArray[1];
            }
        }
        if (formResponse) {
            // if there is a conditional form response
            self.formResponse = formResponse;
        } else if (!formResponse && self.defaultFormResponse) {
            // if there is no conditional response but there is a custom default response
            self.formResponse = self.defaultFormResponse;
        } else if (!formResponse && !self.defaultFormResponse) {
            // if there is no conditional response and no custom default response (defaults to message hardcoded in obforms_rest.php)
            self.formResponse = "";
        }
    };

    // get inputs to check
    obformsSubmit.prototype.getInputsToCheck = function (watchedFields) {
        var self = this;
        var uniqueFieldNames = [].concat(_toConsumableArray(new Set(watchedFields)));
        var arrayLength = self.$inputs.length;
        var fieldsLength = uniqueFieldNames.length;
        var inputsToCheck = [];
        // add listener if input matches watched fields
        for (var ind = 0; ind < arrayLength; ind++) {
            for (var i = 0; i < fieldsLength; i++) {
                if (self.$inputs[ind].getAttribute("name") === uniqueFieldNames[i]) {
                    inputsToCheck.push(self.$inputs[ind]);
                }
            }
        }
        return inputsToCheck;
    };

    // get rows to validate
    obformsSubmit.prototype.getRowsToValidate = function (validationFields) {
        var self = this;
        var arrayLength = self.$rows.length;
        var fieldsLength = validationFields.length;
        var rowsToValidate = [];
        // add listener if input matches watched fields
        for (var ind = 0; ind < arrayLength; ind++) {
            var rowConditions = JSON.parse(self.$rows[ind].getAttribute("data-conditions"));
            if (rowConditions != undefined) {
                rowsToValidate.push(self.$rows[ind]);
            }
        }
        return rowsToValidate;
    };

    // validation by conditional fields
    obformsSubmit.prototype.validateByConditions = function (rowsToValidate, inputsToCheck) {
        var self = this;
        var rowsLength = rowsToValidate.length;
        var inputsToCheckLength = inputsToCheck.length;
        for (var ind = 0; ind < rowsLength; ind++) {
            // foreach row get the row conditions
            var rowConditions = JSON.parse(rowsToValidate[ind].getAttribute("data-conditions"));
            var conditionsMet = [];

            for (var i = 0; i < rowConditions.length; i++) {
                // foreach condition get the field_name of the condition
                var split = rowConditions[i].split("&|&");
                for (var index = 0; index < inputsToCheckLength; index++) {
                    // foreach input field check if input value matches condition value
                    if (inputsToCheck[index].value === split[1]) {
                        conditionsMet.push(rowsToValidate[ind]);
                    } else if (split[1] === "*" && inputsToCheck[index].value) {
                        // check for * value
                        conditionsMet.push(rowsToValidate[ind]);
                    } else if (split[1] === "1" && inputsToCheck[index].checked) {
                        // check for checkbox input
                        conditionsMet.push(rowsToValidate[ind]);
                    }
                }
            }

            // check if all conditions are met...
            if (conditionsMet.length === rowConditions.length) {
                rowsToValidate[ind].classList.remove("form__row--conditions-not-met");
                rowsToValidate[ind].classList.add("form__row--conditions-met");
                var requiredInput = rowsToValidate[ind].querySelectorAll(".form__input");
                if (!this.requiredArray.includes(requiredInput[0].name) && rowsToValidate[ind].hasAttribute('required')) {
                    this.requiredArray.push(requiredInput[0].name);
                }
                conditionsMet.push(rowsToValidate[ind]);
            } else {
                rowsToValidate[ind].classList.remove("form__row--conditions-met");
                rowsToValidate[ind].classList.add("form__row--conditions-not-met");
                // rowsToValidate[ind].querySelectorAll(".form__input")[0].value = "";
                // rowsToValidate[ind].querySelectorAll(".form__input--select")[0].selectedIndex = 0;
                var requiredInput = rowsToValidate[ind].querySelectorAll(".form__input");
                if (this.requiredArray.includes(requiredInput[0].name)) {
                    var indexOfElem = this.requiredArray.indexOf(requiredInput[0].name);
                    if (indexOfElem > -1) {
                        this.requiredArray.splice(indexOfElem, 1);
                    }
                }
            }
        }

        self.updateRequiredFields();
    };

    // validate by matching fields
    obformsSubmit.prototype.validateByComparison = function (compareFields) {
        var self = this;
        var comparePairs = compareFields.split(",");

        var _loop = function _loop() {
            var compareInputs = [];
            compareFields = comparePairs[ind].split("&|&");

            for (i = 0; i < self.$inputs.length; i++) {
                if (self.$inputs[i].getAttribute("name") === compareFields[0] || self.$inputs[i].getAttribute("name") === compareFields[1]) {
                    compareInputs.push(self.$inputs[i]);
                    self.$inputs[i].addEventListener('change', function () {
                        checkForMatch();
                    });
                }
            }
            function checkForMatch() {
                self.setNoMatchFields(compareInputs);
            }
        };

        for (var ind = 0; ind < comparePairs.length; ind++) {
            var compareFields;
            var i;

            _loop();
        }
    };

    // ACTIONS
    // update required list
    obformsSubmit.prototype.updateRequiredFields = function () {
        var self = this;
        if (self.requiredArray) {
            var encodedRequiredFields = window.btoa(self.requiredArray.toString());
            this.$required.value = encodedRequiredFields;
        }
    };

    // update recipients list
    obformsSubmit.prototype.updateRecipientsList = function () {
        if (this.recipientsArray) {
            var recipientsString = this.recipientsArray.toString();
            // remove initial , if there is an empty first element
            while (recipientsString.charAt(0) === ',') {
                recipientsString = recipientsString.substr(1);
            }
            var encodedRecipientsFields = window.btoa(recipientsString);
            this.$recipients.value = encodedRecipientsFields;
        }
    };

    // update form response
    obformsSubmit.prototype.updateFormResponse = function () {
        var self = this;
        if (self.formResponse) {
            var encodedResponseMessage = window.btoa(self.formResponse);
            this.$response.value = encodedResponseMessage;
        }
    };

    // set no match fields
    obformsSubmit.prototype.setNoMatchFields = function (fields) {
        var $current_noMatches = this.$element.querySelectorAll('.form__label--no-match');
        Array.prototype.forEach.call($current_noMatches, function ($current_noMatch) {
            $current_noMatch.classList.remove('form__label--no-match');
        });
        if (fields[0].value != fields[1].value) {
            var _iteratorNormalCompletion = true;
            var _didIteratorError = false;
            var _iteratorError = undefined;

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

                    var $fields = this.$element.querySelectorAll('[name="' + field.name + '"]');
                    Array.prototype.forEach.call($fields, function ($field) {
                        $field.closest('.form__row').querySelector('.form__label').classList.add('form__label--no-match');
                    });
                }
            } catch (err) {
                _didIteratorError = true;
                _iteratorError = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion && _iterator.return) {
                        _iterator.return();
                    }
                } finally {
                    if (_didIteratorError) {
                        throw _iteratorError;
                    }
                }
            }

            ;
        }
    };

    // set conditions not met fields
    obformsSubmit.prototype.setConditionsNotMetFields = function (fields) {
        var $current_unmetFields = this.$element.querySelectorAll('.form__label--conditions-not-met');
        Array.prototype.forEach.call($current_unmetFields, function ($current_unmetField) {
            $current_unmetField.classList.remove('form__label--conditions-not-met');
        });
        if (fields[0].value != fields[1].value) {
            var _iteratorNormalCompletion2 = true;
            var _didIteratorError2 = false;
            var _iteratorError2 = undefined;

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

                    var $fields = this.$element.querySelectorAll('[name="' + field.name + '"]');
                    Array.prototype.forEach.call($fields, function ($field) {
                        $field.closest('.form__row').querySelector('.form__label').classList.add('form__label--conditions-not-met');
                    });
                }
            } catch (err) {
                _didIteratorError2 = true;
                _iteratorError2 = err;
            } finally {
                try {
                    if (!_iteratorNormalCompletion2 && _iterator2.return) {
                        _iterator2.return();
                    }
                } finally {
                    if (_didIteratorError2) {
                        throw _iteratorError2;
                    }
                }
            }

            ;
        }
    };

    // SUBMIT FORM
    obformsSubmit.prototype.submitForm = function () {
        var self = this;

        var form = new FormData(this.$element);
        var formRequest = new Request(this.url, {
            'method': 'POST',
            'body': form
        });

        fetch(formRequest).then(function (response) {
            return response.json();
        }).then(function (json) {
            if (!json.status) {
                self.setStatus('error');
                if (self.hasCaptcha) {
                    grecaptcha.reset();
                }
            } else {
                self.setStatus('success');
                if (self.hasCaptcha) {
                    self.$captcha.style.display = 'none';
                }
                if (self.callback) {
                    // This is very hacky code, but the only way to make this extensible
                    if (self.callback === 'azure.gaCustomEvent') {
                        eval("window." + self.callback + "('Form Submission','" + self.elementID + "','page" + document.location.pathname + "')");
                    } else {
                        eval("window." + self.callback + "()");
                    }
                }
            }
            if (json.empty_fields) {
                self.setEmptyFields(json.empty_fields);
            }
            self.setMessage(json.message);
        });
    };

    // ACTIONS AFTER SUBMIT
    // set empty fields
    obformsSubmit.prototype.setEmptyFields = function (fields) {
        var $current_empties = this.$element.querySelectorAll('.form__label--empty');

        Array.prototype.forEach.call($current_empties, function ($current_empty) {
            $current_empty.classList.remove('form__label--empty');
        });
        var _iteratorNormalCompletion3 = true;
        var _didIteratorError3 = false;
        var _iteratorError3 = undefined;

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

                var $fields = this.$element.querySelectorAll('[name="' + field + '"]');
                Array.prototype.forEach.call($fields, function ($field) {
                    $field.closest('.form__row').querySelector('.form__label').classList.add('form__label--empty');
                });
            }
        } catch (err) {
            _didIteratorError3 = true;
            _iteratorError3 = err;
        } finally {
            try {
                if (!_iteratorNormalCompletion3 && _iterator3.return) {
                    _iterator3.return();
                }
            } finally {
                if (_didIteratorError3) {
                    throw _iteratorError3;
                }
            }
        }

        ;
    };

    // set message
    obformsSubmit.prototype.setMessage = function (message) {
        this.$message.innerHTML = message;
    };

    // set status
    obformsSubmit.prototype.setStatus = function (status) {
        this.$element.classList.remove('form--success', 'form--error', 'form--loading');
        this.$element.classList.add('form--' + status);
    };

    // GET ELEMENTS AND EXECUTE FUNCTION
    var elements = document.querySelectorAll('.obform');

    Array.prototype.forEach.call(elements, function (element) {
        new obformsSubmit(element);
    });
})(window, document, grecaptcha);
//# sourceMappingURL=ob-forms.min.js.map
