/* Minification failed. Returning unminified contents.
(548,6297-6298): run-time error JS1014: Invalid character: \
(548,6298-6299): run-time error JS1014: Invalid character: \
(548,6301): run-time error JS1004: Expected ';'
(548,6301-6302): run-time error JS1195: Expected expression: ]
(548,8057-8058): run-time error JS1195: Expected expression: )
(548,8105-8106): run-time error JS1195: Expected expression: )
(548,8051-8052): run-time error JS1013: Syntax error in regular expression: (
(548,6296-6297): run-time error JS1013: Syntax error in regular expression: |
 */
angular.module("JSV", [])
    .service("JsvHttpParamSerializer", function () {

        function isWindow(obj) {
            return obj && obj.window === obj;
        }

        function isScope(obj) {
            return obj && obj.$evalAsync && obj.$watch;
        }

        function toJsvReplacer(key, value) {
            var val = value;

            if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
                val = undefined;
            } else if (isWindow(value)) {
                val = '$WINDOW';
            } else if (value && document === value) {
                val = '$DOCUMENT';
            } else if (isScope(value)) {
                val = '$SCOPE';
            }

            return val;
        }

        function toJsv(obj, pretty) {
            if (typeof obj === 'undefined') return undefined;
            if (!angular.isNumber(pretty)) {
                pretty = pretty ? 2 : null;
            }
            return JSV.stringify(obj, toJsvReplacer, pretty);
        }

        function serializeValue(v) {
            if (angular.isObject(v)) {
                return angular.isDate(v) ? v.toISOString() : toJsv(v);
            }
            return v;
        }


        function forEachSorted(obj, iterator, context) {
            var keys = Object.keys(obj).sort();
            for (var i = 0; i < keys.length; i++) {
                iterator.call(context, obj[keys[i]], keys[i]);
            }
            return keys;
        }

        function encodeUriQuery(val, pctEncodeSpaces) {
            return encodeURIComponent(val).
                       replace(/%40/gi, '@').
                       replace(/%3A/gi, ':').
                       replace(/%24/g, '$').
                       replace(/%2C/gi, ',').
                       replace(/%3B/gi, ';').
                       replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
        }

        return function (params) {
            if (!params) return '';
            var parts = [];
            forEachSorted(params, function (value, key) {
                if (value === null || angular.isUndefined(value)) return;
                if (angular.isArray(value)) {
                    angular.forEach(value, function (v, k) {
                        parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
                    });
                } else {
                    parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
                }
            });

            return parts.join('&');
        }
    });

/**
 * Created by IntelliJ IDEA.
 * User: mythz
 * Date: 16-Jun-2010
 * Time: 00:51:17
 * To change this template use File | Settings | File Templates.
 */

(function () {

    if (typeof window !== "undefined" && window !== null) {
        window.JSV = JSV = {};
    } else if (typeof module !== "undefined" && module !== null) {
        module.exports = JSV = {};
    }

    /**
     * parses JSV text into a JavaScript type
     * @param str
     */
    JSV.parse = function (str) {
        if (!str) return str;
        if (str[0] == '{') {
            return JSV.parseObject_(str);
        }
        else if (str[0] == '[') {
            return JSV.parseArray_(str);
        }
        else {
            return JSV.parseString(str);
        }
    }

    JSV.ESCAPE_CHARS = ['"', ',', '{', '}', '[', ']'];

    JSV.parseArray_ = function (str) {
        var to = [], value = JSV.stripList_(str);
        if (!value) return to;

        if (value[0] == '{') {
            var ref = { i: 0 };
            do {
                var itemValue = JSV.eatMapValue_(value, ref);
                to.push(JSV.parse(itemValue));
            } while (++ref.i < value.length);
        }
        else {
            for (var ref = { i: 0 }; ref.i < value.length; ref.i++) {
                var elementValue = JSV.eatElementValue_(value, ref);
                to.push(JSV.parse(elementValue));
            }
        }
        return to;
    };

    JSV.parseObject_ = function (str) {
        if (str[0] != '{') {
            throw "Type definitions should start with a '{', got string starting with: "
                + str.substr(0, str.length < 50 ? str.length : 50);
        }

        var name, obj = {};

        if (str == '{}') return null;
        for (var ref = { i: 1 }, strTypeLength = str.length; ref.i < strTypeLength; ref.i++) {
            name = JSV.eatMapKey_(str, ref);
            ref.i++;
            var value = JSV.eatMapValue_(str, ref);
            obj[name] = JSV.parse(value);
        }
        return obj;
    }

    JSV.eatElementValue_ = function (value, ref) {
        return JSV.eatUntilCharFound_(value, ref, ',');
    }

    JSV.containsAny_ = function (str, tests) {
        if (!is.String(str)) return;
        for (var i = 0, len = tests.length; i < len; i++) {
            if (str.indexOf(tests[i]) != -1) return true;
        }
        return false;
    };

    JSV.toCsvField = function (text) {
        return !text || JSV.containsAny_(JSV.ESCAPE_CHARS)
            ? text
            : '"' + text.replace(/"/g, '""') + '"';
    }

    JSV.parseString = JSV.fromCsvField = function (text) {
        return !text || text[0] != '"'
            ? text
            : text.substr(1, text.length - 2).replace(/""/g, '"');
    }

    JSV.stripList_ = function (value) {
        if (!value) return null;
        return value[0] == '['
            ? value.substr(1, value.length - 2)
            : value;
    };

    /**
     * @param value {string}
     * @param ref {ref int}
     * @param findChar {char}
     */
    JSV.eatUntilCharFound_ = function (value, ref, findChar) {
        var tokenStartPos = ref.i;
        var valueLength = value.length;
        if (value[tokenStartPos] != '"') {
            ref.i = value.indexOf(findChar, tokenStartPos);
            if (ref.i == -1) ref.i = valueLength;
            return value.substr(tokenStartPos, ref.i - tokenStartPos);
        }

        while (++ref.i < valueLength) {
            if (value[ref.i] == '"') {
                if (ref.i + 1 >= valueLength) {
                    return value.substr(tokenStartPos, ++ref.i - tokenStartPos);
                }
                if (value[ref.i + 1] == '"') {
                    ref.i++;
                }
                else if (value[ref.i + 1] == findChar) {
                    return value.substr(tokenStartPos, ++ref.i - tokenStartPos);
                }
            }
        }

        throw "Could not find ending quote";
    }

    /**
     *
     * @param value {string}
     * @param i {ref int}
     */
    JSV.eatMapKey_ = function (value, ref) {
        var tokenStartPos = ref.i;
        while (value[++ref.i] != ':' && ref.i < value.length) { }
        return value.substr(tokenStartPos, ref.i - tokenStartPos);
    }

    /**
     *
     * @param value {string}
     * @param ref {ref int}
     */
    JSV.eatMapValue_ = function (value, ref) {
        var tokenStartPos = ref.i;
        var valueLength = value.length;
        if (ref.i == valueLength) return null;

        var valueChar = value[ref.i];

        //If we are at the end, return.
        if (valueChar == ',' || valueChar == '}') {
            return null;
        }

        //Is List, i.e. [...]
        var withinQuotes = false;
        if (valueChar == '[') {
            var endsToEat = 1;
            while (++ref.i < valueLength && endsToEat > 0) {
                valueChar = value[ref.i];
                if (valueChar == '"')
                    withinQuotes = !withinQuotes;
                if (withinQuotes)
                    continue;
                if (valueChar == '[')
                    endsToEat++;
                if (valueChar == ']')
                    endsToEat--;
            }
            return value.substr(tokenStartPos, ref.i - tokenStartPos);
        }

        //Is Type/Map, i.e. {...}
        if (valueChar == '{') {
            var endsToEat = 1;
            while (++ref.i < valueLength && endsToEat > 0) {
                valueChar = value[ref.i];

                if (valueChar == '"')
                    withinQuotes = !withinQuotes;
                if (withinQuotes)
                    continue;
                if (valueChar == '{')
                    endsToEat++;
                if (valueChar == '}')
                    endsToEat--;
            }
            return value.substr(tokenStartPos, ref.i - tokenStartPos);
        }

        //Is Within Quotes, i.e. "..."
        if (valueChar == '"') {
            while (++ref.i < valueLength) {
                valueChar = value[ref.i];
                if (valueChar != '"') continue;
                var isLiteralQuote = ref.i + 1 < valueLength && value[ref.i + 1] == '"';
                ref.i++; //skip quote
                if (!isLiteralQuote)
                    break;
            }
            return value.substr(tokenStartPos, ref.i - tokenStartPos);
        }

        //Is Value
        while (++ref.i < valueLength) {
            valueChar = value[ref.i];
            if (valueChar == ',' || valueChar == '}')
                break;
        }

        return value.substr(tokenStartPos, ref.i - tokenStartPos);
    }

    JSV.isEmpty_ = function (a) {
        return (a === null || a === undefined || a === "");
    }
    JSV.isFunction_ = function (a) {
        return (typeof (a) === 'function') ? a.constructor.toString().match(/Function/) !== null : false;
    };
    JSV.isString_ = function (a) {
        if (a === null || a === undefined) return false;
        return (typeof (a) === 'string') ? true : (typeof (a) === 'object') ? a.constructor.toString().match(/string/i) !== null : false;
    };
    JSV.isDate_ = function (a) {
        if (JSV.isEmpty_(a)) return false;
        return (typeof (a) === 'date') ? true : (typeof (a) === 'object') ? a.constructor.toString().match(/date/i) !== null : false;
    };

    JSV.isArray_ = function (a) {
        if (a === null || a === undefined || a === "") return false;
        return (typeof (a) === 'object') ? a.constructor.toString().match(/array/i) !== null || a.length !== undefined : false;
    };
    JSV.toXsdDateTime = function (date) {
        function pad(n) {
            var s = n.toString();
            return s.length < 2 ? '0' + s : s;
        };
        var yyyy = date.getUTCFullYear();
        var MM = pad(date.getUTCMonth() + 1);
        var dd = pad(date.getUTCDate());
        var hh = pad(date.getUTCHours());
        var mm = pad(date.getUTCMinutes());
        var ss = pad(date.getUTCSeconds());
        var ms = pad(date.getUTCMilliseconds());

        return yyyy + '-' + MM + '-' + dd + 'T' + hh + ':' + mm + ':' + ss + '.' + ms + 'Z';
    }
    JSV.serialize = JSV.stringify = function (obj) {
        if (obj === null || obj === undefined) return null;

        var typeOf = typeof (obj);
        if (obj === 'function') return null;

        if (typeOf === 'object') {
            var ctorStr = obj.constructor.toString().toLowerCase();
            if (ctorStr.indexOf('string') != -1)
                return JSV.escapeString(obj);
            if (ctorStr.indexOf('boolean') != -1)
                return obj ? "True" : "False";
            if (ctorStr.indexOf('number') != -1)
                return obj;
            if (ctorStr.indexOf('date') != -1)
                return JSV.escapeString(JSV.toXsdDateTime(obj));
            if (ctorStr.indexOf('array') != -1)
                return JSV.serializeArray(obj);

            return JSV.serializeObject(obj);
        }
        else {
            switch (typeOf) {
                case 'string':
                    return JSV.escapeString(obj);
                    break;
                case 'boolean':
                    return obj ? "True" : "False";
                    break;
                case 'date':
                    return JSV.escapeString(JSV.toXsdDateTime(obj));
                    break;
                case 'array':
                    return JSV.serializeArray(obj);
                    break;
                case 'number':
                default:
                    return obj;
            }
        }
    };
    JSV.serializeObject = function (obj) {
        var value, sb = new StringBuffer();
        for (var key in obj) {
            value = obj[key];
            if (!obj.hasOwnProperty(key) || JSV.isEmpty_(value) || JSV.isFunction_(value)) continue;

            if (sb.getLength() > 0)
                sb.append(',');

            sb.append(JSV.escapeString(key));
            sb.append(':');
            sb.append(JSV.serialize(value));
        }
        return '{' + sb.toString() + '}';
    };
    JSV.serializeArray = function (array) {
        var value, sb = new StringBuffer();
        for (var i = 0, len = array.length; i < len; i++) {
            value = array[i];
            if (JSV.isEmpty_(value) || JSV.isFunction_(value)) continue;

            if (sb.getLength() > 0)
                sb.append(',');

            sb.append(JSV.serialize(value));
        }
        return '[' + sb.toString() + ']';
    };
    JSV.escapeString = function (str) {
        if (str === undefined || str === null) return null;
        if (str === '') return '""';

        if (str.indexOf('"')) {
            str = str.replace(/"/g, '""');
        }
        if (JSV.containsAny_(str, JSV.ESCAPE_CHARS)) {
            return '"' + str + '"';
        }
        return str;
    };
    JSV.containsAny_ = function (str, tests) {
        if (!JSV.isString_(str)) return;
        for (var i = 0, len = tests.length; i < len; i++) {
            if (str.indexOf(tests[i]) != -1) return true;
        }
        return false;
    };

    /* Closure Library StringBuffer for efficient string concatenation */
    var hasScriptEngine = 'ScriptEngine' in window;
    var HAS_JSCRIPT = hasScriptEngine && window['ScriptEngine']() == 'JScript';

    StringBuffer = function (opt_a1, var_args) {
        this.buffer_ = HAS_JSCRIPT ? [] : '';

        if (opt_a1 != null) {
            this.append.apply(this, arguments);
        }
    };
    StringBuffer.prototype.set = function (s) {
        this.clear();
        this.append(s);
    };
    if (HAS_JSCRIPT) {
        StringBuffer.prototype.bufferLength_ = 0;
        StringBuffer.prototype.append = function (a1, opt_a2, var_args) {
            // IE version.
            if (opt_a2 == null) { // second argument is undefined (null == undefined)
                // Array assignment is 2x faster than Array push.  Also, use a1
                // directly to avoid arguments instantiation, another 2x improvement.
                this.buffer_[this.bufferLength_++] = a1;
            } else {
                this.buffer_.push.apply(/** @type {Array} */(this.buffer_), arguments);
                this.bufferLength_ = this.buffer_.length;
            }
            return this;
        };
    } else {
        StringBuffer.prototype.append = function (a1, opt_a2, var_args) {
            // W3 version.
            this.buffer_ += a1;
            if (opt_a2 != null) { // second argument is undefined (null == undefined)
                for (var i = 1; i < arguments.length; i++) {
                    this.buffer_ += arguments[i];
                }
            }
            return this;
        };
    }
    StringBuffer.prototype.clear = function () {
        if (HAS_JSCRIPT) {
            this.buffer_.length = 0;  // Reuse the array to avoid creating new object.
            this.bufferLength_ = 0;
        } else {
            this.buffer_ = '';
        }
    };
    StringBuffer.prototype.getLength = function () {
        return this.toString().length;
    };
    StringBuffer.prototype.toString = function () {
        if (HAS_JSCRIPT) {
            var str = this.buffer_.join('');
            this.clear();
            if (str) {
                this.append(str);
            }
            return str;
        } else {
            return /** @type {string} */ (this.buffer_);
        }
    };
})();;
/**
 * bootbox.js 5.4.0
 *
 * http://bootboxjs.com/license.txt
 */
!function (t, e) { 'use strict'; 'function' == typeof define && define.amd ? define(['jquery'], e) : 'object' == typeof exports ? module.exports = e(require('jquery')) : t.bootbox = e(t.jQuery) }(this, function e(p, u) { 'use strict'; var r, n, i, l; Object.keys || (Object.keys = (r = Object.prototype.hasOwnProperty, n = !{ toString: null }.propertyIsEnumerable('toString'), l = (i = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor']).length, function (t) { if ('function' != typeof t && ('object' != typeof t || null === t)) throw new TypeError('Object.keys called on non-object'); var e, o, a = []; for (e in t) r.call(t, e) && a.push(e); if (n) for (o = 0; o < l; o++)r.call(t, i[o]) && a.push(i[o]); return a })); var d = {}; d.VERSION = '5.0.0'; var b = { en: { OK: 'OK', CANCEL: 'Cancel', CONFIRM: 'OK' } }, f = { dialog: "<div class=\"bootbox modal\" tabindex=\"-1\" role=\"dialog\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-body\"><div class=\"bootbox-body\"></div></div></div></div></div>", header: "<div class=\"modal-header\"><h5 class=\"modal-title\"></h5></div>", footer: '<div class="modal-footer"></div>', closeButton: '<button type="button" class="bootbox-close-button close" aria-hidden="true">&times;</button>', form: '<form class="bootbox-form"></form>', button: '<button type="button" class="btn"></button>', option: '<option></option>', promptMessage: '<div class="bootbox-prompt-message"></div>', inputs: { text: '<input class="bootbox-input bootbox-input-text form-control" autocomplete="off" type="text" />', textarea: '<textarea class="bootbox-input bootbox-input-textarea form-control"></textarea>', email: '<input class="bootbox-input bootbox-input-email form-control" autocomplete="off" type="email" />', select: '<select class="bootbox-input bootbox-input-select form-control"></select>', checkbox: '<div class="form-check checkbox"><label class="form-check-label"><input class="form-check-input bootbox-input bootbox-input-checkbox" type="checkbox" /></label></div>', radio: '<div class="form-check radio"><label class="form-check-label"><input class="form-check-input bootbox-input bootbox-input-radio" type="radio" name="bootbox-radio" /></label></div>', date: '<input class="bootbox-input bootbox-input-date form-control" autocomplete="off" type="date" />', time: '<input class="bootbox-input bootbox-input-time form-control" autocomplete="off" type="time" />', number: '<input class="bootbox-input bootbox-input-number form-control" autocomplete="off" type="number" />', password: '<input class="bootbox-input bootbox-input-password form-control" autocomplete="off" type="password" />', range: '<input class="bootbox-input bootbox-input-range form-control-range" autocomplete="off" type="range" />' } }, m = { locale: 'en', backdrop: 'static', animate: !0, className: null, closeButton: !0, show: !0, container: 'body', value: '', inputType: 'text', swapButtonOrder: !1, centerVertical: !1, multiple: !1, scrollable: !1 }; function c(t, e, o) { return p.extend(!0, {}, t, function (t, e) { var o = t.length, a = {}; if (o < 1 || 2 < o) throw new Error('Invalid argument length'); return 2 === o || 'string' == typeof t[0] ? (a[e[0]] = t[0], a[e[1]] = t[1]) : a = t[0], a }(e, o)) } function h(t, e, o, a) { var r; a && a[0] && (r = a[0].locale || m.locale, (a[0].swapButtonOrder || m.swapButtonOrder) && (e = e.reverse())); var n, i, l, s = { className: 'bootbox-' + t, buttons: function (t, e) { for (var o = {}, a = 0, r = t.length; a < r; a++) { var n = t[a], i = n.toLowerCase(), l = n.toUpperCase(); o[i] = { label: (s = l, c = e, p = b[c], p ? p[s] : b.en[s]) } } var s, c, p; return o }(e, r) }; return n = c(s, a, o), l = {}, v(i = e, function (t, e) { l[e] = !0 }), v(n.buttons, function (t) { if (l[t] === u) throw new Error('button key "' + t + '" is not allowed (options are ' + i.join(' ') + ')') }), n } function w(t) { return Object.keys(t).length } function v(t, o) { var a = 0; p.each(t, function (t, e) { o(t, e, a++) }) } function g(t) { t.data.dialog.find('.bootbox-accept').first().trigger('focus') } function y(t) { t.target === t.data.dialog[0] && t.data.dialog.remove() } function x(t) { t.target === t.data.dialog[0] && (t.data.dialog.off('escape.close.bb'), t.data.dialog.off('click')) } function k(t, e, o) { t.stopPropagation(), t.preventDefault(), p.isFunction(o) && !1 === o.call(e, t) || e.modal('hide') } function E(t) { return /([01][0-9]|2[0-3]):[0-5][0-9]?:[0-5][0-9]/.test(t) } function O(t) { return /(\d{4})-(\d{2})-(\d{2})/.test(t) } return d.locales = function (t) { return t ? b[t] : b }, d.addLocale = function (t, o) { return p.each(['OK', 'CANCEL', 'CONFIRM'], function (t, e) { if (!o[e]) throw new Error('Please supply a translation for "' + e + '"') }), b[t] = { OK: o.OK, CANCEL: o.CANCEL, CONFIRM: o.CONFIRM }, d }, d.removeLocale = function (t) { if ('en' === t) throw new Error('"en" is used as the default and fallback locale and cannot be removed.'); return delete b[t], d }, d.setLocale = function (t) { return d.setDefaults('locale', t) }, d.setDefaults = function () { var t = {}; return 2 === arguments.length ? t[arguments[0]] = arguments[1] : t = arguments[0], p.extend(m, t), d }, d.hideAll = function () { return p('.bootbox').modal('hide'), d }, d.init = function (t) { return e(t || p) }, d.dialog = function (t) { if (p.fn.modal === u) throw new Error("\"$.fn.modal\" is not defined; please double check you have included the Bootstrap JavaScript library. See https://getbootstrap.com/docs/4.4/getting-started/javascript/ for more details."); if (t = function (r) { var n, i; if ('object' != typeof r) throw new Error('Please supply an object of options'); if (!r.message) throw new Error('"message" option must not be null or an empty string.'); (r = p.extend({}, m, r)).buttons || (r.buttons = {}); return n = r.buttons, i = w(n), v(n, function (t, e, o) { if (p.isFunction(e) && (e = n[t] = { callback: e }), 'object' !== p.type(e)) throw new Error('button with key "' + t + '" must be an object'); if (e.label || (e.label = t), !e.className) { var a = !1; a = r.swapButtonOrder ? 0 === o : o === i - 1, e.className = i <= 2 && a ? 'btn-primary' : 'btn-secondary btn-default' } }), r }(t), p.fn.modal.Constructor.VERSION) { t.fullBootstrapVersion = p.fn.modal.Constructor.VERSION; var e = t.fullBootstrapVersion.indexOf('.'); t.bootstrap = t.fullBootstrapVersion.substring(0, e) } else t.bootstrap = '2', t.fullBootstrapVersion = '2.3.2', console.warn('Bootbox will *mostly* work with Bootstrap 2, but we do not officially support it. Please upgrade, if possible.'); var o = p(f.dialog), a = o.find('.modal-dialog'), r = o.find('.modal-body'), n = p(f.header), i = p(f.footer), l = t.buttons, s = { onEscape: t.onEscape }; if (r.find('.bootbox-body').html(t.message), 0 < w(t.buttons) && (v(l, function (t, e) { var o = p(f.button); switch (o.data('bb-handler', t), o.addClass(e.className), t) { case 'ok': case 'confirm': o.addClass('bootbox-accept'); break; case 'cancel': o.addClass('bootbox-cancel') }o.html(e.label), i.append(o), s[t] = e.callback }), r.after(i)), !0 === t.animate && o.addClass('fade'), t.className && o.addClass(t.className), t.size) switch (t.fullBootstrapVersion.substring(0, 3) < '3.1' && console.warn('"size" requires Bootstrap 3.1.0 or higher. You appear to be using ' + t.fullBootstrapVersion + '. Please upgrade to use this option.'), t.size) { case 'small': case 'sm': a.addClass('modal-sm'); break; case 'large': case 'lg': a.addClass('modal-lg'); break; case 'extra-large': case 'xl': a.addClass('modal-xl'), t.fullBootstrapVersion.substring(0, 3) < '4.2' && console.warn('Using size "xl"/"extra-large" requires Bootstrap 4.2.0 or higher. You appear to be using ' + t.fullBootstrapVersion + '. Please upgrade to use this option.') }if (t.scrollable && (a.addClass('modal-dialog-scrollable'), t.fullBootstrapVersion.substring(0, 3) < '4.3' && console.warn('Using "scrollable" requires Bootstrap 4.3.0 or higher. You appear to be using ' + t.fullBootstrapVersion + '. Please upgrade to use this option.')), t.title && (r.before(n), o.find('.modal-title').html(t.title)), t.closeButton) { var c = p(f.closeButton); t.title ? 3 < t.bootstrap ? o.find('.modal-header').append(c) : o.find('.modal-header').prepend(c) : c.prependTo(r) } if (t.centerVertical && (a.addClass('modal-dialog-centered'), t.fullBootstrapVersion < '4.0.0' && console.warn('"centerVertical" requires Bootstrap 4.0.0-beta.3 or higher. You appear to be using ' + t.fullBootstrapVersion + '. Please upgrade to use this option.')), o.one('hide.bs.modal', { dialog: o }, x), t.onHide) { if (!p.isFunction(t.onHide)) throw new Error('Argument supplied to "onHide" must be a function'); o.on('hide.bs.modal', t.onHide) } if (o.one('hidden.bs.modal', { dialog: o }, y), t.onHidden) { if (!p.isFunction(t.onHidden)) throw new Error('Argument supplied to "onHidden" must be a function'); o.on('hidden.bs.modal', t.onHidden) } if (t.onShow) { if (!p.isFunction(t.onShow)) throw new Error('Argument supplied to "onShow" must be a function'); o.on('show.bs.modal', t.onShow) } if (o.one('shown.bs.modal', { dialog: o }, g), t.onShown) { if (!p.isFunction(t.onShown)) throw new Error('Argument supplied to "onShown" must be a function'); o.on('shown.bs.modal', t.onShown) } return 'static' !== t.backdrop && o.on('click.dismiss.bs.modal', function (t) { o.children('.modal-backdrop').length && (t.currentTarget = o.children('.modal-backdrop').get(0)), t.target === t.currentTarget && o.trigger('escape.close.bb') }), o.on('escape.close.bb', function (t) { s.onEscape && k(t, o, s.onEscape) }), o.on('click', '.modal-footer button:not(.disabled)', function (t) { var e = p(this).data('bb-handler'); e !== u && k(t, o, s[e]) }), o.on('click', '.bootbox-close-button', function (t) { k(t, o, s.onEscape) }), o.on('keyup', function (t) { 27 === t.which && o.trigger('escape.close.bb') }), p(t.container).append(o), o.modal({ backdrop: !!t.backdrop && 'static', keyboard: !1, show: !1 }), t.show && o.modal('show'), o }, d.alert = function () { var t; if ((t = h('alert', ['ok'], ['message', 'callback'], arguments)).callback && !p.isFunction(t.callback)) throw new Error('alert requires the "callback" property to be a function when provided'); return t.buttons.ok.callback = t.onEscape = function () { return !p.isFunction(t.callback) || t.callback.call(this) }, d.dialog(t) }, d.confirm = function () { var t; if (t = h('confirm', ['cancel', 'confirm'], ['message', 'callback'], arguments), !p.isFunction(t.callback)) throw new Error('confirm requires a callback'); return t.buttons.cancel.callback = t.onEscape = function () { return t.callback.call(this, !1) }, t.buttons.confirm.callback = function () { return t.callback.call(this, !0) }, d.dialog(t) }, d.prompt = function () { var r, e, t, n, o, a; if (t = p(f.form), (r = h('prompt', ['cancel', 'confirm'], ['title', 'callback'], arguments)).value || (r.value = m.value), r.inputType || (r.inputType = m.inputType), o = r.show === u ? m.show : r.show, r.show = !1, r.buttons.cancel.callback = r.onEscape = function () { return r.callback.call(this, null) }, r.buttons.confirm.callback = function () { var t; if ('checkbox' === r.inputType) t = n.find('input:checked').map(function () { return p(this).val() }).get(); else if ('radio' === r.inputType) t = n.find('input:checked').val(); else { if (n[0].checkValidity && !n[0].checkValidity()) return !1; t = 'select' === r.inputType && !0 === r.multiple ? n.find('option:selected').map(function () { return p(this).val() }).get() : n.val() } return r.callback.call(this, t) }, !r.title) throw new Error('prompt requires a title'); if (!p.isFunction(r.callback)) throw new Error('prompt requires a callback'); if (!f.inputs[r.inputType]) throw new Error('Invalid prompt type'); switch (n = p(f.inputs[r.inputType]), r.inputType) { case 'text': case 'textarea': case 'email': case 'password': n.val(r.value), r.placeholder && n.attr('placeholder', r.placeholder), r.pattern && n.attr('pattern', r.pattern), r.maxlength && n.attr('maxlength', r.maxlength), r.required && n.prop({ required: !0 }), r.rows && !isNaN(parseInt(r.rows)) && 'textarea' === r.inputType && n.attr({ rows: r.rows }); break; case 'date': case 'time': case 'number': case 'range': if (n.val(r.value), r.placeholder && n.attr('placeholder', r.placeholder), r.pattern && n.attr('pattern', r.pattern), r.required && n.prop({ required: !0 }), 'date' !== r.inputType && r.step) { if (!('any' === r.step || !isNaN(r.step) && 0 < parseFloat(r.step))) throw new Error('"step" must be a valid positive number or the value "any". See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-step for more information.'); n.attr('step', r.step) } !function (t, e, o) { var a = !1, r = !0, n = !0; if ('date' === t) e === u || (r = O(e)) ? o === u || (n = O(o)) || console.warn('Browsers which natively support the "date" input type expect date values to be of the form "YYYY-MM-DD" (see ISO-8601 https://www.iso.org/iso-8601-date-and-time-format.html). Bootbox does not enforce this rule, but your max value may not be enforced by this browser.') : console.warn('Browsers which natively support the "date" input type expect date values to be of the form "YYYY-MM-DD" (see ISO-8601 https://www.iso.org/iso-8601-date-and-time-format.html). Bootbox does not enforce this rule, but your min value may not be enforced by this browser.'); else if ('time' === t) { if (e !== u && !(r = E(e))) throw new Error('"min" is not a valid time. See https://www.w3.org/TR/2012/WD-html-markup-20120315/datatypes.html#form.data.time for more information.'); if (o !== u && !(n = E(o))) throw new Error('"max" is not a valid time. See https://www.w3.org/TR/2012/WD-html-markup-20120315/datatypes.html#form.data.time for more information.') } else { if (e !== u && isNaN(e)) throw r = !1, new Error('"min" must be a valid number. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-min for more information.'); if (o !== u && isNaN(o)) throw n = !1, new Error('"max" must be a valid number. See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-max for more information.') } if (r && n) { if (o <= e) throw new Error('"max" must be greater than "min". See https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-max for more information.'); a = !0 } return a }(r.inputType, r.min, r.max) || (r.min !== u && n.attr('min', r.min), r.max !== u && n.attr('max', r.max)); break; case 'select': var i = {}; if (a = r.inputOptions || [], !p.isArray(a)) throw new Error('Please pass an array of input options'); if (!a.length) throw new Error('prompt with "inputType" set to "select" requires at least one option'); r.placeholder && n.attr('placeholder', r.placeholder), r.required && n.prop({ required: !0 }), r.multiple && n.prop({ multiple: !0 }), v(a, function (t, e) { var o = n; if (e.value === u || e.text === u) throw new Error('each option needs a "value" property and a "text" property'); e.group && (i[e.group] || (i[e.group] = p('<optgroup />').attr('label', e.group)), o = i[e.group]); var a = p(f.option); a.attr('value', e.value).text(e.text), o.append(a) }), v(i, function (t, e) { n.append(e) }), n.val(r.value); break; case 'checkbox': var l = p.isArray(r.value) ? r.value : [r.value]; if (!(a = r.inputOptions || []).length) throw new Error('prompt with "inputType" set to "checkbox" requires at least one option'); n = p('<div class="bootbox-checkbox-list"></div>'), v(a, function (t, o) { if (o.value === u || o.text === u) throw new Error('each option needs a "value" property and a "text" property'); var a = p(f.inputs[r.inputType]); a.find('input').attr('value', o.value), a.find('label').append('\n' + o.text), v(l, function (t, e) { e === o.value && a.find('input').prop('checked', !0) }), n.append(a) }); break; case 'radio': if (r.value !== u && p.isArray(r.value)) throw new Error('prompt with "inputType" set to "radio" requires a single, non-array value for "value"'); if (!(a = r.inputOptions || []).length) throw new Error('prompt with "inputType" set to "radio" requires at least one option'); n = p('<div class="bootbox-radiobutton-list"></div>'); var s = !0; v(a, function (t, e) { if (e.value === u || e.text === u) throw new Error('each option needs a "value" property and a "text" property'); var o = p(f.inputs[r.inputType]); o.find('input').attr('value', e.value), o.find('label').append('\n' + e.text), r.value !== u && e.value === r.value && (o.find('input').prop('checked', !0), s = !1), n.append(o) }), s && n.find('input[type="radio"]').first().prop('checked', !0) }if (t.append(n), t.on('submit', function (t) { t.preventDefault(), t.stopPropagation(), e.find('.bootbox-accept').trigger('click') }), '' !== p.trim(r.message)) { var c = p(f.promptMessage).html(r.message); t.prepend(c), r.message = t } else r.message = t; return (e = d.dialog(r)).off('shown.bs.modal', g), e.on('shown.bs.modal', function () { n.focus() }), !0 === o && e.modal('show'), e }, d });;
/*!
 * Datepicker for Bootstrap v1.6.4 (https://github.com/eternicode/bootstrap-datepicker)
 *
 * Copyright 2012 Stefan Petre
 * Improvements by Andrew Rowls
 * Licensed under the Apache License v2.0 (http://www.apache.org/licenses/LICENSE-2.0)
 */
!function (a) { "function" == typeof define && define.amd ? define(["jquery"], a) : a("object" == typeof exports ? require("jquery") : jQuery) }(function (a, b) {
    function c() { return new Date(Date.UTC.apply(Date, arguments)) } function d() { var a = new Date; return c(a.getFullYear(), a.getMonth(), a.getDate()) } function e(a, b) { return a.getUTCFullYear() === b.getUTCFullYear() && a.getUTCMonth() === b.getUTCMonth() && a.getUTCDate() === b.getUTCDate() } function f(a) { return function () { return this[a].apply(this, arguments) } } function g(a) { return a && !isNaN(a.getTime()) } function h(b, c) { function d(a, b) { return b.toLowerCase() } var e, f = a(b).data(), g = {}, h = new RegExp("^" + c.toLowerCase() + "([A-Z])"); c = new RegExp("^" + c.toLowerCase()); for (var i in f) c.test(i) && (e = i.replace(h, d), g[e] = f[i]); return g } function i(b) { var c = {}; if (q[b] || (b = b.split("-")[0], q[b])) { var d = q[b]; return a.each(p, function (a, b) { b in d && (c[b] = d[b]) }), c } } var j = function () { var b = { get: function (a) { return this.slice(a)[0] }, contains: function (a) { for (var b = a && a.valueOf(), c = 0, d = this.length; d > c; c++) if (this[c].valueOf() === b) return c; return -1 }, remove: function (a) { this.splice(a, 1) }, replace: function (b) { b && (a.isArray(b) || (b = [b]), this.clear(), this.push.apply(this, b)) }, clear: function () { this.length = 0 }, copy: function () { var a = new j; return a.replace(this), a } }; return function () { var c = []; return c.push.apply(c, arguments), a.extend(c, b), c } }(), k = function (b, c) { a(b).data("datepicker", this), this._process_options(c), this.dates = new j, this.viewDate = this.o.defaultViewDate, this.focusDate = null, this.element = a(b), this.isInput = this.element.is("input"), this.inputField = this.isInput ? this.element : this.element.find("input"), this.component = this.element.hasClass("date") ? this.element.find(".add-on, .input-group-addon, .btn") : !1, this.hasInput = this.component && this.inputField.length, this.component && 0 === this.component.length && (this.component = !1), this.isInline = !this.component && this.element.is("div"), this.picker = a(r.template), this._check_template(this.o.templates.leftArrow) && this.picker.find(".prev").html(this.o.templates.leftArrow), this._check_template(this.o.templates.rightArrow) && this.picker.find(".next").html(this.o.templates.rightArrow), this._buildEvents(), this._attachEvents(), this.isInline ? this.picker.addClass("datepicker-inline").appendTo(this.element) : this.picker.addClass("datepicker-dropdown dropdown-menu"), this.o.rtl && this.picker.addClass("datepicker-rtl"), this.viewMode = this.o.startView, this.o.calendarWeeks && this.picker.find("thead .datepicker-title, tfoot .today, tfoot .clear").attr("colspan", function (a, b) { return parseInt(b) + 1 }), this._allow_update = !1, this.setStartDate(this._o.startDate), this.setEndDate(this._o.endDate), this.setDaysOfWeekDisabled(this.o.daysOfWeekDisabled), this.setDaysOfWeekHighlighted(this.o.daysOfWeekHighlighted), this.setDatesDisabled(this.o.datesDisabled), this.fillDow(), this.fillMonths(), this._allow_update = !0, this.update(), this.showMode(), this.isInline && this.show() }; k.prototype = { constructor: k, _resolveViewName: function (a, c) { return 0 === a || "days" === a || "month" === a ? 0 : 1 === a || "months" === a || "year" === a ? 1 : 2 === a || "years" === a || "decade" === a ? 2 : 3 === a || "decades" === a || "century" === a ? 3 : 4 === a || "centuries" === a || "millennium" === a ? 4 : c === b ? !1 : c }, _check_template: function (c) { try { if (c === b || "" === c) return !1; if ((c.match(/[<>]/g) || []).length <= 0) return !0; var d = a(c); return d.length > 0 } catch (e) { return !1 } }, _process_options: function (b) { this._o = a.extend({}, this._o, b); var e = this.o = a.extend({}, this._o), f = e.language; q[f] || (f = f.split("-")[0], q[f] || (f = o.language)), e.language = f, e.startView = this._resolveViewName(e.startView, 0), e.minViewMode = this._resolveViewName(e.minViewMode, 0), e.maxViewMode = this._resolveViewName(e.maxViewMode, 4), e.startView = Math.min(e.startView, e.maxViewMode), e.startView = Math.max(e.startView, e.minViewMode), e.multidate !== !0 && (e.multidate = Number(e.multidate) || !1, e.multidate !== !1 && (e.multidate = Math.max(0, e.multidate))), e.multidateSeparator = String(e.multidateSeparator), e.weekStart %= 7, e.weekEnd = (e.weekStart + 6) % 7; var g = r.parseFormat(e.format); e.startDate !== -(1 / 0) && (e.startDate ? e.startDate instanceof Date ? e.startDate = this._local_to_utc(this._zero_time(e.startDate)) : e.startDate = r.parseDate(e.startDate, g, e.language, e.assumeNearbyYear) : e.startDate = -(1 / 0)), e.endDate !== 1 / 0 && (e.endDate ? e.endDate instanceof Date ? e.endDate = this._local_to_utc(this._zero_time(e.endDate)) : e.endDate = r.parseDate(e.endDate, g, e.language, e.assumeNearbyYear) : e.endDate = 1 / 0), e.daysOfWeekDisabled = e.daysOfWeekDisabled || [], a.isArray(e.daysOfWeekDisabled) || (e.daysOfWeekDisabled = e.daysOfWeekDisabled.split(/[,\s]*/)), e.daysOfWeekDisabled = a.map(e.daysOfWeekDisabled, function (a) { return parseInt(a, 10) }), e.daysOfWeekHighlighted = e.daysOfWeekHighlighted || [], a.isArray(e.daysOfWeekHighlighted) || (e.daysOfWeekHighlighted = e.daysOfWeekHighlighted.split(/[,\s]*/)), e.daysOfWeekHighlighted = a.map(e.daysOfWeekHighlighted, function (a) { return parseInt(a, 10) }), e.datesDisabled = e.datesDisabled || [], a.isArray(e.datesDisabled) || (e.datesDisabled = [e.datesDisabled]), e.datesDisabled = a.map(e.datesDisabled, function (a) { return r.parseDate(a, g, e.language, e.assumeNearbyYear) }); var h = String(e.orientation).toLowerCase().split(/\s+/g), i = e.orientation.toLowerCase(); if (h = a.grep(h, function (a) { return /^auto|left|right|top|bottom$/.test(a) }), e.orientation = { x: "auto", y: "auto" }, i && "auto" !== i) if (1 === h.length) switch (h[0]) { case "top": case "bottom": e.orientation.y = h[0]; break; case "left": case "right": e.orientation.x = h[0] } else i = a.grep(h, function (a) { return /^left|right$/.test(a) }), e.orientation.x = i[0] || "auto", i = a.grep(h, function (a) { return /^top|bottom$/.test(a) }), e.orientation.y = i[0] || "auto"; else; if (e.defaultViewDate) { var j = e.defaultViewDate.year || (new Date).getFullYear(), k = e.defaultViewDate.month || 0, l = e.defaultViewDate.day || 1; e.defaultViewDate = c(j, k, l) } else e.defaultViewDate = d() }, _events: [], _secondaryEvents: [], _applyEvents: function (a) { for (var c, d, e, f = 0; f < a.length; f++) c = a[f][0], 2 === a[f].length ? (d = b, e = a[f][1]) : 3 === a[f].length && (d = a[f][1], e = a[f][2]), c.on(e, d) }, _unapplyEvents: function (a) { for (var c, d, e, f = 0; f < a.length; f++) c = a[f][0], 2 === a[f].length ? (e = b, d = a[f][1]) : 3 === a[f].length && (e = a[f][1], d = a[f][2]), c.off(d, e) }, _buildEvents: function () { var b = { keyup: a.proxy(function (b) { -1 === a.inArray(b.keyCode, [27, 37, 39, 38, 40, 32, 13, 9]) && this.update() }, this), keydown: a.proxy(this.keydown, this), paste: a.proxy(this.paste, this) }; this.o.showOnFocus === !0 && (b.focus = a.proxy(this.show, this)), this.isInput ? this._events = [[this.element, b]] : this.component && this.hasInput ? this._events = [[this.inputField, b], [this.component, { click: a.proxy(this.show, this) }]] : this._events = [[this.element, { click: a.proxy(this.show, this), keydown: a.proxy(this.keydown, this) }]], this._events.push([this.element, "*", { blur: a.proxy(function (a) { this._focused_from = a.target }, this) }], [this.element, { blur: a.proxy(function (a) { this._focused_from = a.target }, this) }]), this.o.immediateUpdates && this._events.push([this.element, { "changeYear changeMonth": a.proxy(function (a) { this.update(a.date) }, this) }]), this._secondaryEvents = [[this.picker, { click: a.proxy(this.click, this) }], [a(window), { resize: a.proxy(this.place, this) }], [a(document), { mousedown: a.proxy(function (a) { this.element.is(a.target) || this.element.find(a.target).length || this.picker.is(a.target) || this.picker.find(a.target).length || this.isInline || this.hide() }, this) }]] }, _attachEvents: function () { this._detachEvents(), this._applyEvents(this._events) }, _detachEvents: function () { this._unapplyEvents(this._events) }, _attachSecondaryEvents: function () { this._detachSecondaryEvents(), this._applyEvents(this._secondaryEvents) }, _detachSecondaryEvents: function () { this._unapplyEvents(this._secondaryEvents) }, _trigger: function (b, c) { var d = c || this.dates.get(-1), e = this._utc_to_local(d); this.element.trigger({ type: b, date: e, dates: a.map(this.dates, this._utc_to_local), format: a.proxy(function (a, b) { 0 === arguments.length ? (a = this.dates.length - 1, b = this.o.format) : "string" == typeof a && (b = a, a = this.dates.length - 1), b = b || this.o.format; var c = this.dates.get(a); return r.formatDate(c, b, this.o.language) }, this) }) }, show: function () { return this.inputField.prop("disabled") || this.inputField.prop("readonly") && this.o.enableOnReadonly === !1 ? void 0 : (this.isInline || this.picker.appendTo(this.o.container), this.place(), this.picker.show(), this._attachSecondaryEvents(), this._trigger("show"), (window.navigator.msMaxTouchPoints || "ontouchstart" in document) && this.o.disableTouchKeyboard && a(this.element).blur(), this) }, hide: function () { return this.isInline || !this.picker.is(":visible") ? this : (this.focusDate = null, this.picker.hide().detach(), this._detachSecondaryEvents(), this.viewMode = this.o.startView, this.showMode(), this.o.forceParse && this.inputField.val() && this.setValue(), this._trigger("hide"), this) }, destroy: function () { return this.hide(), this._detachEvents(), this._detachSecondaryEvents(), this.picker.remove(), delete this.element.data().datepicker, this.isInput || delete this.element.data().date, this }, paste: function (b) { var c; if (b.originalEvent.clipboardData && b.originalEvent.clipboardData.types && -1 !== a.inArray("text/plain", b.originalEvent.clipboardData.types)) c = b.originalEvent.clipboardData.getData("text/plain"); else { if (!window.clipboardData) return; c = window.clipboardData.getData("Text") } this.setDate(c), this.update(), b.preventDefault() }, _utc_to_local: function (a) { return a && new Date(a.getTime() + 6e4 * a.getTimezoneOffset()) }, _local_to_utc: function (a) { return a && new Date(a.getTime() - 6e4 * a.getTimezoneOffset()) }, _zero_time: function (a) { return a && new Date(a.getFullYear(), a.getMonth(), a.getDate()) }, _zero_utc_time: function (a) { return a && new Date(Date.UTC(a.getUTCFullYear(), a.getUTCMonth(), a.getUTCDate())) }, getDates: function () { return a.map(this.dates, this._utc_to_local) }, getUTCDates: function () { return a.map(this.dates, function (a) { return new Date(a) }) }, getDate: function () { return this._utc_to_local(this.getUTCDate()) }, getUTCDate: function () { var a = this.dates.get(-1); return "undefined" != typeof a ? new Date(a) : null }, clearDates: function () { this.inputField && this.inputField.val(""), this.update(), this._trigger("changeDate"), this.o.autoclose && this.hide() }, setDates: function () { var b = a.isArray(arguments[0]) ? arguments[0] : arguments; return this.update.apply(this, b), this._trigger("changeDate"), this.setValue(), this }, setUTCDates: function () { var b = a.isArray(arguments[0]) ? arguments[0] : arguments; return this.update.apply(this, a.map(b, this._utc_to_local)), this._trigger("changeDate"), this.setValue(), this }, setDate: f("setDates"), setUTCDate: f("setUTCDates"), remove: f("destroy"), setValue: function () { var a = this.getFormattedDate(); return this.inputField.val(a), this }, getFormattedDate: function (c) { c === b && (c = this.o.format); var d = this.o.language; return a.map(this.dates, function (a) { return r.formatDate(a, c, d) }).join(this.o.multidateSeparator) }, getStartDate: function () { return this.o.startDate }, setStartDate: function (a) { return this._process_options({ startDate: a }), this.update(), this.updateNavArrows(), this }, getEndDate: function () { return this.o.endDate }, setEndDate: function (a) { return this._process_options({ endDate: a }), this.update(), this.updateNavArrows(), this }, setDaysOfWeekDisabled: function (a) { return this._process_options({ daysOfWeekDisabled: a }), this.update(), this.updateNavArrows(), this }, setDaysOfWeekHighlighted: function (a) { return this._process_options({ daysOfWeekHighlighted: a }), this.update(), this }, setDatesDisabled: function (a) { this._process_options({ datesDisabled: a }), this.update(), this.updateNavArrows() }, place: function () { if (this.isInline) return this; var b = this.picker.outerWidth(), c = this.picker.outerHeight(), d = 10, e = a(this.o.container), f = e.width(), g = "body" === this.o.container ? a(document).scrollTop() : e.scrollTop(), h = e.offset(), i = []; this.element.parents().each(function () { var b = a(this).css("z-index"); "auto" !== b && 0 !== b && i.push(parseInt(b)) }); var j = Math.max.apply(Math, i) + this.o.zIndexOffset, k = this.component ? this.component.parent().offset() : this.element.offset(), l = this.component ? this.component.outerHeight(!0) : this.element.outerHeight(!1), m = this.component ? this.component.outerWidth(!0) : this.element.outerWidth(!1), n = k.left - h.left, o = k.top - h.top; "body" !== this.o.container && (o += g), this.picker.removeClass("datepicker-orient-top datepicker-orient-bottom datepicker-orient-right datepicker-orient-left"), "auto" !== this.o.orientation.x ? (this.picker.addClass("datepicker-orient-" + this.o.orientation.x), "right" === this.o.orientation.x && (n -= b - m)) : k.left < 0 ? (this.picker.addClass("datepicker-orient-left"), n -= k.left - d) : n + b > f ? (this.picker.addClass("datepicker-orient-right"), n += m - b) : this.picker.addClass("datepicker-orient-left"); var p, q = this.o.orientation.y; if ("auto" === q && (p = -g + o - c, q = 0 > p ? "bottom" : "top"), this.picker.addClass("datepicker-orient-" + q), "top" === q ? o -= c + parseInt(this.picker.css("padding-top")) : o += l, this.o.rtl) { var r = f - (n + m); this.picker.css({ top: o, right: r, zIndex: j }) } else this.picker.css({ top: o, left: n, zIndex: j }); return this }, _allow_update: !0, update: function () { if (!this._allow_update) return this; var b = this.dates.copy(), c = [], d = !1; return arguments.length ? (a.each(arguments, a.proxy(function (a, b) { b instanceof Date && (b = this._local_to_utc(b)), c.push(b) }, this)), d = !0) : (c = this.isInput ? this.element.val() : this.element.data("date") || this.inputField.val(), c = c && this.o.multidate ? c.split(this.o.multidateSeparator) : [c], delete this.element.data().date), c = a.map(c, a.proxy(function (a) { return r.parseDate(a, this.o.format, this.o.language, this.o.assumeNearbyYear) }, this)), c = a.grep(c, a.proxy(function (a) { return !this.dateWithinRange(a) || !a }, this), !0), this.dates.replace(c), this.dates.length ? this.viewDate = new Date(this.dates.get(-1)) : this.viewDate < this.o.startDate ? this.viewDate = new Date(this.o.startDate) : this.viewDate > this.o.endDate ? this.viewDate = new Date(this.o.endDate) : this.viewDate = this.o.defaultViewDate, d ? this.setValue() : c.length && String(b) !== String(this.dates) && this._trigger("changeDate"), !this.dates.length && b.length && this._trigger("clearDate"), this.fill(), this.element.change(), this }, fillDow: function () { var b = this.o.weekStart, c = "<tr>"; for (this.o.calendarWeeks && (this.picker.find(".datepicker-days .datepicker-switch").attr("colspan", function (a, b) { return parseInt(b) + 1 }), c += '<th class="cw">&#160;</th>') ; b < this.o.weekStart + 7;) c += '<th class="dow', a.inArray(b, this.o.daysOfWeekDisabled) > -1 && (c += " disabled"), c += '">' + q[this.o.language].daysMin[b++ % 7] + "</th>"; c += "</tr>", this.picker.find(".datepicker-days thead").append(c) }, fillMonths: function () { for (var a = this._utc_to_local(this.viewDate), b = "", c = 0; 12 > c;) { var d = a && a.getMonth() === c ? " focused" : ""; b += '<span class="month' + d + '">' + q[this.o.language].monthsShort[c++] + "</span>" } this.picker.find(".datepicker-months td").html(b) }, setRange: function (b) { b && b.length ? this.range = a.map(b, function (a) { return a.valueOf() }) : delete this.range, this.fill() }, getClassNames: function (b) { var c = [], d = this.viewDate.getUTCFullYear(), e = this.viewDate.getUTCMonth(), f = new Date; return b.getUTCFullYear() < d || b.getUTCFullYear() === d && b.getUTCMonth() < e ? c.push("old") : (b.getUTCFullYear() > d || b.getUTCFullYear() === d && b.getUTCMonth() > e) && c.push("new"), this.focusDate && b.valueOf() === this.focusDate.valueOf() && c.push("focused"), this.o.todayHighlight && b.getUTCFullYear() === f.getFullYear() && b.getUTCMonth() === f.getMonth() && b.getUTCDate() === f.getDate() && c.push("today"), -1 !== this.dates.contains(b) && c.push("active"), this.dateWithinRange(b) || c.push("disabled"), this.dateIsDisabled(b) && c.push("disabled", "disabled-date"), -1 !== a.inArray(b.getUTCDay(), this.o.daysOfWeekHighlighted) && c.push("highlighted"), this.range && (b > this.range[0] && b < this.range[this.range.length - 1] && c.push("range"), -1 !== a.inArray(b.valueOf(), this.range) && c.push("selected"), b.valueOf() === this.range[0] && c.push("range-start"), b.valueOf() === this.range[this.range.length - 1] && c.push("range-end")), c }, _fill_yearsView: function (c, d, e, f, g, h, i, j) { var k, l, m, n, o, p, q, r, s, t, u; for (k = "", l = this.picker.find(c), m = parseInt(g / e, 10) * e, o = parseInt(h / f, 10) * f, p = parseInt(i / f, 10) * f, n = a.map(this.dates, function (a) { return parseInt(a.getUTCFullYear() / f, 10) * f }), l.find(".datepicker-switch").text(m + "-" + (m + 9 * f)), q = m - f, r = -1; 11 > r; r += 1) s = [d], t = null, -1 === r ? s.push("old") : 10 === r && s.push("new"), -1 !== a.inArray(q, n) && s.push("active"), (o > q || q > p) && s.push("disabled"), q === this.viewDate.getFullYear() && s.push("focused"), j !== a.noop && (u = j(new Date(q, 0, 1)), u === b ? u = {} : "boolean" == typeof u ? u = { enabled: u } : "string" == typeof u && (u = { classes: u }), u.enabled === !1 && s.push("disabled"), u.classes && (s = s.concat(u.classes.split(/\s+/))), u.tooltip && (t = u.tooltip)), k += '<span class="' + s.join(" ") + '"' + (t ? ' title="' + t + '"' : "") + ">" + q + "</span>", q += f; l.find("td").html(k) }, fill: function () { var d, e, f = new Date(this.viewDate), g = f.getUTCFullYear(), h = f.getUTCMonth(), i = this.o.startDate !== -(1 / 0) ? this.o.startDate.getUTCFullYear() : -(1 / 0), j = this.o.startDate !== -(1 / 0) ? this.o.startDate.getUTCMonth() : -(1 / 0), k = this.o.endDate !== 1 / 0 ? this.o.endDate.getUTCFullYear() : 1 / 0, l = this.o.endDate !== 1 / 0 ? this.o.endDate.getUTCMonth() : 1 / 0, m = q[this.o.language].today || q.en.today || "", n = q[this.o.language].clear || q.en.clear || "", o = q[this.o.language].titleFormat || q.en.titleFormat; if (!isNaN(g) && !isNaN(h)) { this.picker.find(".datepicker-days .datepicker-switch").text(r.formatDate(f, o, this.o.language)), this.picker.find("tfoot .today").text(m).toggle(this.o.todayBtn !== !1), this.picker.find("tfoot .clear").text(n).toggle(this.o.clearBtn !== !1), this.picker.find("thead .datepicker-title").text(this.o.title).toggle("" !== this.o.title), this.updateNavArrows(), this.fillMonths(); var p = c(g, h - 1, 28), s = r.getDaysInMonth(p.getUTCFullYear(), p.getUTCMonth()); p.setUTCDate(s), p.setUTCDate(s - (p.getUTCDay() - this.o.weekStart + 7) % 7); var t = new Date(p); p.getUTCFullYear() < 100 && t.setUTCFullYear(p.getUTCFullYear()), t.setUTCDate(t.getUTCDate() + 42), t = t.valueOf(); for (var u, v = []; p.valueOf() < t;) { if (p.getUTCDay() === this.o.weekStart && (v.push("<tr>"), this.o.calendarWeeks)) { var w = new Date(+p + (this.o.weekStart - p.getUTCDay() - 7) % 7 * 864e5), x = new Date(Number(w) + (11 - w.getUTCDay()) % 7 * 864e5), y = new Date(Number(y = c(x.getUTCFullYear(), 0, 1)) + (11 - y.getUTCDay()) % 7 * 864e5), z = (x - y) / 864e5 / 7 + 1; v.push('<td class="cw">' + z + "</td>") } u = this.getClassNames(p), u.push("day"), this.o.beforeShowDay !== a.noop && (e = this.o.beforeShowDay(this._utc_to_local(p)), e === b ? e = {} : "boolean" == typeof e ? e = { enabled: e } : "string" == typeof e && (e = { classes: e }), e.enabled === !1 && u.push("disabled"), e.classes && (u = u.concat(e.classes.split(/\s+/))), e.tooltip && (d = e.tooltip)), u = a.isFunction(a.uniqueSort) ? a.uniqueSort(u) : a.unique(u), v.push('<td class="' + u.join(" ") + '"' + (d ? ' title="' + d + '"' : "") + ">" + p.getUTCDate() + "</td>"), d = null, p.getUTCDay() === this.o.weekEnd && v.push("</tr>"), p.setUTCDate(p.getUTCDate() + 1) } this.picker.find(".datepicker-days tbody").empty().append(v.join("")); var A = q[this.o.language].monthsTitle || q.en.monthsTitle || "Months", B = this.picker.find(".datepicker-months").find(".datepicker-switch").text(this.o.maxViewMode < 2 ? A : g).end().find("span").removeClass("active"); if (a.each(this.dates, function (a, b) { b.getUTCFullYear() === g && B.eq(b.getUTCMonth()).addClass("active") }), (i > g || g > k) && B.addClass("disabled"), g === i && B.slice(0, j).addClass("disabled"), g === k && B.slice(l + 1).addClass("disabled"), this.o.beforeShowMonth !== a.noop) { var C = this; a.each(B, function (c, d) { var e = new Date(g, c, 1), f = C.o.beforeShowMonth(e); f === b ? f = {} : "boolean" == typeof f ? f = { enabled: f } : "string" == typeof f && (f = { classes: f }), f.enabled !== !1 || a(d).hasClass("disabled") || a(d).addClass("disabled"), f.classes && a(d).addClass(f.classes), f.tooltip && a(d).prop("title", f.tooltip) }) } this._fill_yearsView(".datepicker-years", "year", 10, 1, g, i, k, this.o.beforeShowYear), this._fill_yearsView(".datepicker-decades", "decade", 100, 10, g, i, k, this.o.beforeShowDecade), this._fill_yearsView(".datepicker-centuries", "century", 1e3, 100, g, i, k, this.o.beforeShowCentury) } }, updateNavArrows: function () { if (this._allow_update) { var a = new Date(this.viewDate), b = a.getUTCFullYear(), c = a.getUTCMonth(); switch (this.viewMode) { case 0: this.o.startDate !== -(1 / 0) && b <= this.o.startDate.getUTCFullYear() && c <= this.o.startDate.getUTCMonth() ? this.picker.find(".prev").css({ visibility: "hidden" }) : this.picker.find(".prev").css({ visibility: "visible" }), this.o.endDate !== 1 / 0 && b >= this.o.endDate.getUTCFullYear() && c >= this.o.endDate.getUTCMonth() ? this.picker.find(".next").css({ visibility: "hidden" }) : this.picker.find(".next").css({ visibility: "visible" }); break; case 1: case 2: case 3: case 4: this.o.startDate !== -(1 / 0) && b <= this.o.startDate.getUTCFullYear() || this.o.maxViewMode < 2 ? this.picker.find(".prev").css({ visibility: "hidden" }) : this.picker.find(".prev").css({ visibility: "visible" }), this.o.endDate !== 1 / 0 && b >= this.o.endDate.getUTCFullYear() || this.o.maxViewMode < 2 ? this.picker.find(".next").css({ visibility: "hidden" }) : this.picker.find(".next").css({ visibility: "visible" }) } } }, click: function (b) { b.preventDefault(), b.stopPropagation(); var e, f, g, h, i, j, k; e = a(b.target), e.hasClass("datepicker-switch") && this.showMode(1); var l = e.closest(".prev, .next"); l.length > 0 && (f = r.modes[this.viewMode].navStep * (l.hasClass("prev") ? -1 : 1), 0 === this.viewMode ? (this.viewDate = this.moveMonth(this.viewDate, f), this._trigger("changeMonth", this.viewDate)) : (this.viewDate = this.moveYear(this.viewDate, f), 1 === this.viewMode && this._trigger("changeYear", this.viewDate)), this.fill()), e.hasClass("today") && !e.hasClass("day") && (this.showMode(-2), this._setDate(d(), "linked" === this.o.todayBtn ? null : "view")), e.hasClass("clear") && this.clearDates(), e.hasClass("disabled") || (e.hasClass("day") && (g = parseInt(e.text(), 10) || 1, h = this.viewDate.getUTCFullYear(), i = this.viewDate.getUTCMonth(), e.hasClass("old") && (0 === i ? (i = 11, h -= 1, j = !0, k = !0) : (i -= 1, j = !0)), e.hasClass("new") && (11 === i ? (i = 0, h += 1, j = !0, k = !0) : (i += 1, j = !0)), this._setDate(c(h, i, g)), k && this._trigger("changeYear", this.viewDate), j && this._trigger("changeMonth", this.viewDate)), e.hasClass("month") && (this.viewDate.setUTCDate(1), g = 1, i = e.parent().find("span").index(e), h = this.viewDate.getUTCFullYear(), this.viewDate.setUTCMonth(i), this._trigger("changeMonth", this.viewDate), 1 === this.o.minViewMode ? (this._setDate(c(h, i, g)), this.showMode()) : this.showMode(-1), this.fill()), (e.hasClass("year") || e.hasClass("decade") || e.hasClass("century")) && (this.viewDate.setUTCDate(1), g = 1, i = 0, h = parseInt(e.text(), 10) || 0, this.viewDate.setUTCFullYear(h), e.hasClass("year") && (this._trigger("changeYear", this.viewDate), 2 === this.o.minViewMode && this._setDate(c(h, i, g))), e.hasClass("decade") && (this._trigger("changeDecade", this.viewDate), 3 === this.o.minViewMode && this._setDate(c(h, i, g))), e.hasClass("century") && (this._trigger("changeCentury", this.viewDate), 4 === this.o.minViewMode && this._setDate(c(h, i, g))), this.showMode(-1), this.fill())), this.picker.is(":visible") && this._focused_from && a(this._focused_from).focus(), delete this._focused_from }, _toggle_multidate: function (a) { var b = this.dates.contains(a); if (a || this.dates.clear(), -1 !== b ? (this.o.multidate === !0 || this.o.multidate > 1 || this.o.toggleActive) && this.dates.remove(b) : this.o.multidate === !1 ? (this.dates.clear(), this.dates.push(a)) : this.dates.push(a), "number" == typeof this.o.multidate) for (; this.dates.length > this.o.multidate;) this.dates.remove(0) }, _setDate: function (a, b) { b && "date" !== b || this._toggle_multidate(a && new Date(a)), b && "view" !== b || (this.viewDate = a && new Date(a)), this.fill(), this.setValue(), b && "view" === b || this._trigger("changeDate"), this.inputField && this.inputField.change(), !this.o.autoclose || b && "date" !== b || this.hide() }, moveDay: function (a, b) { var c = new Date(a); return c.setUTCDate(a.getUTCDate() + b), c }, moveWeek: function (a, b) { return this.moveDay(a, 7 * b) }, moveMonth: function (a, b) { if (!g(a)) return this.o.defaultViewDate; if (!b) return a; var c, d, e = new Date(a.valueOf()), f = e.getUTCDate(), h = e.getUTCMonth(), i = Math.abs(b); if (b = b > 0 ? 1 : -1, 1 === i) d = -1 === b ? function () { return e.getUTCMonth() === h } : function () { return e.getUTCMonth() !== c }, c = h + b, e.setUTCMonth(c), (0 > c || c > 11) && (c = (c + 12) % 12); else { for (var j = 0; i > j; j++) e = this.moveMonth(e, b); c = e.getUTCMonth(), e.setUTCDate(f), d = function () { return c !== e.getUTCMonth() } } for (; d() ;) e.setUTCDate(--f), e.setUTCMonth(c); return e }, moveYear: function (a, b) { return this.moveMonth(a, 12 * b) }, moveAvailableDate: function (a, b, c) { do { if (a = this[c](a, b), !this.dateWithinRange(a)) return !1; c = "moveDay" } while (this.dateIsDisabled(a)); return a }, weekOfDateIsDisabled: function (b) { return -1 !== a.inArray(b.getUTCDay(), this.o.daysOfWeekDisabled) }, dateIsDisabled: function (b) { return this.weekOfDateIsDisabled(b) || a.grep(this.o.datesDisabled, function (a) { return e(b, a) }).length > 0 }, dateWithinRange: function (a) { return a >= this.o.startDate && a <= this.o.endDate }, keydown: function (a) { if (!this.picker.is(":visible")) return void ((40 === a.keyCode || 27 === a.keyCode) && (this.show(), a.stopPropagation())); var b, c, d = !1, e = this.focusDate || this.viewDate; switch (a.keyCode) { case 27: this.focusDate ? (this.focusDate = null, this.viewDate = this.dates.get(-1) || this.viewDate, this.fill()) : this.hide(), a.preventDefault(), a.stopPropagation(); break; case 37: case 38: case 39: case 40: if (!this.o.keyboardNavigation || 7 === this.o.daysOfWeekDisabled.length) break; b = 37 === a.keyCode || 38 === a.keyCode ? -1 : 1, 0 === this.viewMode ? a.ctrlKey ? (c = this.moveAvailableDate(e, b, "moveYear"), c && this._trigger("changeYear", this.viewDate)) : a.shiftKey ? (c = this.moveAvailableDate(e, b, "moveMonth"), c && this._trigger("changeMonth", this.viewDate)) : 37 === a.keyCode || 39 === a.keyCode ? c = this.moveAvailableDate(e, b, "moveDay") : this.weekOfDateIsDisabled(e) || (c = this.moveAvailableDate(e, b, "moveWeek")) : 1 === this.viewMode ? ((38 === a.keyCode || 40 === a.keyCode) && (b = 4 * b), c = this.moveAvailableDate(e, b, "moveMonth")) : 2 === this.viewMode && ((38 === a.keyCode || 40 === a.keyCode) && (b = 4 * b), c = this.moveAvailableDate(e, b, "moveYear")), c && (this.focusDate = this.viewDate = c, this.setValue(), this.fill(), a.preventDefault()); break; case 13: if (!this.o.forceParse) break; e = this.focusDate || this.dates.get(-1) || this.viewDate, this.o.keyboardNavigation && (this._toggle_multidate(e), d = !0), this.focusDate = null, this.viewDate = this.dates.get(-1) || this.viewDate, this.setValue(), this.fill(), this.picker.is(":visible") && (a.preventDefault(), a.stopPropagation(), this.o.autoclose && this.hide()); break; case 9: this.focusDate = null, this.viewDate = this.dates.get(-1) || this.viewDate, this.fill(), this.hide() } d && (this.dates.length ? this._trigger("changeDate") : this._trigger("clearDate"), this.inputField && this.inputField.change()) }, showMode: function (a) { a && (this.viewMode = Math.max(this.o.minViewMode, Math.min(this.o.maxViewMode, this.viewMode + a))), this.picker.children("div").hide().filter(".datepicker-" + r.modes[this.viewMode].clsName).show(), this.updateNavArrows() } }; var l = function (b, c) { a(b).data("datepicker", this), this.element = a(b), this.inputs = a.map(c.inputs, function (a) { return a.jquery ? a[0] : a }), delete c.inputs, n.call(a(this.inputs), c).on("changeDate", a.proxy(this.dateUpdated, this)), this.pickers = a.map(this.inputs, function (b) { return a(b).data("datepicker") }), this.updateDates() }; l.prototype = { updateDates: function () { this.dates = a.map(this.pickers, function (a) { return a.getUTCDate() }), this.updateRanges() }, updateRanges: function () { var b = a.map(this.dates, function (a) { return a.valueOf() }); a.each(this.pickers, function (a, c) { c.setRange(b) }) }, dateUpdated: function (b) { if (!this.updating) { this.updating = !0; var c = a(b.target).data("datepicker"); if ("undefined" != typeof c) { var d = c.getUTCDate(), e = a.inArray(b.target, this.inputs), f = e - 1, g = e + 1, h = this.inputs.length; if (-1 !== e) { if (a.each(this.pickers, function (a, b) { b.getUTCDate() || b.setUTCDate(d) }), d < this.dates[f]) for (; f >= 0 && d < this.dates[f];) this.pickers[f--].setUTCDate(d); else if (d > this.dates[g]) for (; h > g && d > this.dates[g];) this.pickers[g++].setUTCDate(d); this.updateDates(), delete this.updating } } } }, remove: function () { a.map(this.pickers, function (a) { a.remove() }), delete this.element.data().datepicker } }; var m = a.fn.datepicker, n = function (c) { var d = Array.apply(null, arguments); d.shift(); var e; if (this.each(function () { var b = a(this), f = b.data("datepicker"), g = "object" == typeof c && c; if (!f) { var j = h(this, "date"), m = a.extend({}, o, j, g), n = i(m.language), p = a.extend({}, o, n, j, g); b.hasClass("input-daterange") || p.inputs ? (a.extend(p, { inputs: p.inputs || b.find("input").toArray() }), f = new l(this, p)) : f = new k(this, p), b.data("datepicker", f) } "string" == typeof c && "function" == typeof f[c] && (e = f[c].apply(f, d)) }), e === b || e instanceof k || e instanceof l) return this; if (this.length > 1) throw new Error("Using only allowed for the collection of a single element (" + c + " function)"); return e }; a.fn.datepicker = n; var o = a.fn.datepicker.defaults = { assumeNearbyYear: !1, autoclose: !1, beforeShowDay: a.noop, beforeShowMonth: a.noop, beforeShowYear: a.noop, beforeShowDecade: a.noop, beforeShowCentury: a.noop, calendarWeeks: !1, clearBtn: !1, toggleActive: !1, daysOfWeekDisabled: [], daysOfWeekHighlighted: [], datesDisabled: [], endDate: 1 / 0, forceParse: !0, format: "mm/dd/yyyy", keyboardNavigation: !0, language: "en", minViewMode: 0, maxViewMode: 4, multidate: !1, multidateSeparator: ",", orientation: "auto", rtl: !1, startDate: -(1 / 0), startView: 0, todayBtn: !1, todayHighlight: !1, weekStart: 0, disableTouchKeyboard: !1, enableOnReadonly: !0, showOnFocus: !0, zIndexOffset: 10, container: "body", immediateUpdates: !1, title: "", templates: { leftArrow: "&laquo;", rightArrow: "&raquo;" } }, p = a.fn.datepicker.locale_opts = ["format", "rtl", "weekStart"]; a.fn.datepicker.Constructor = k; var q = a.fn.datepicker.dates = { en: { days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], daysShort: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], daysMin: ["Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"], months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], monthsShort: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"], today: "Today", clear: "Clear", titleFormat: "MM yyyy" } }, r = {
        modes: [{ clsName: "days", navFnc: "Month", navStep: 1 }, { clsName: "months", navFnc: "FullYear", navStep: 1 }, { clsName: "years", navFnc: "FullYear", navStep: 10 }, { clsName: "decades", navFnc: "FullDecade", navStep: 100 }, { clsName: "centuries", navFnc: "FullCentury", navStep: 1e3 }], isLeapYear: function (a) { return a % 4 === 0 && a % 100 !== 0 || a % 400 === 0 }, getDaysInMonth: function (a, b) { return [31, r.isLeapYear(a) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][b] }, validParts: /dd?|DD?|mm?|MM?|yy(?:yy)?/g, nonpunctuation: /[^ -\/:-@\u5e74\u6708\u65e5\[-`{-~\t\n\r]+/g, parseFormat: function (a) { if ("function" == typeof a.toValue && "function" == typeof a.toDisplay) return a; var b = a.replace(this.validParts, "\x00").split("\x00"), c = a.match(this.validParts); if (!b || !b.length || !c || 0 === c.length) throw new Error("Invalid date format."); return { separators: b, parts: c } }, parseDate: function (e, f, g, h) { function i(a, b) { return b === !0 && (b = 10), 100 > a && (a += 2e3, a > (new Date).getFullYear() + b && (a -= 100)), a } function j() { var a = this.slice(0, s[n].length), b = s[n].slice(0, a.length); return a.toLowerCase() === b.toLowerCase() } if (!e) return b; if (e instanceof Date) return e; if ("string" == typeof f && (f = r.parseFormat(f)), f.toValue) return f.toValue(e, f, g); var l, m, n, o, p = /([\-+]\d+)([dmwy])/, s = e.match(/([\-+]\d+)([dmwy])/g), t = { d: "moveDay", m: "moveMonth", w: "moveWeek", y: "moveYear" }, u = { yesterday: "-1d", today: "+0d", tomorrow: "+1d" }; if (/^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(e)) { for (e = new Date, n = 0; n < s.length; n++) l = p.exec(s[n]), m = parseInt(l[1]), o = t[l[2]], e = k.prototype[o](e, m); return c(e.getUTCFullYear(), e.getUTCMonth(), e.getUTCDate()) } if ("undefined" != typeof u[e] && (e = u[e], s = e.match(/([\-+]\d+)([dmwy])/g), /^[\-+]\d+[dmwy]([\s,]+[\-+]\d+[dmwy])*$/.test(e))) { for (e = new Date, n = 0; n < s.length; n++) l = p.exec(s[n]), m = parseInt(l[1]), o = t[l[2]], e = k.prototype[o](e, m); return c(e.getUTCFullYear(), e.getUTCMonth(), e.getUTCDate()) } s = e && e.match(this.nonpunctuation) || [], e = new Date; var v, w, x = {}, y = ["yyyy", "yy", "M", "MM", "m", "mm", "d", "dd"], z = { yyyy: function (a, b) { return a.setUTCFullYear(h ? i(b, h) : b) }, yy: function (a, b) { return a.setUTCFullYear(h ? i(b, h) : b) }, m: function (a, b) { if (isNaN(a)) return a; for (b -= 1; 0 > b;) b += 12; for (b %= 12, a.setUTCMonth(b) ; a.getUTCMonth() !== b;) a.setUTCDate(a.getUTCDate() - 1); return a }, d: function (a, b) { return a.setUTCDate(b) } }; z.M = z.MM = z.mm = z.m, z.dd = z.d, e = d(); var A = f.parts.slice(); if (s.length !== A.length && (A = a(A).filter(function (b, c) { return -1 !== a.inArray(c, y) }).toArray()), s.length === A.length) { var B; for (n = 0, B = A.length; B > n; n++) { if (v = parseInt(s[n], 10), l = A[n], isNaN(v)) switch (l) { case "MM": w = a(q[g].months).filter(j), v = a.inArray(w[0], q[g].months) + 1; break; case "M": w = a(q[g].monthsShort).filter(j), v = a.inArray(w[0], q[g].monthsShort) + 1 } x[l] = v } var C, D; for (n = 0; n < y.length; n++) D = y[n], D in x && !isNaN(x[D]) && (C = new Date(e), z[D](C, x[D]), isNaN(C) || (e = C)) } return e }, formatDate: function (b, c, d) {
            if (!b) return ""; if ("string" == typeof c && (c = r.parseFormat(c)),
            c.toDisplay) return c.toDisplay(b, c, d); var e = { d: b.getUTCDate(), D: q[d].daysShort[b.getUTCDay()], DD: q[d].days[b.getUTCDay()], m: b.getUTCMonth() + 1, M: q[d].monthsShort[b.getUTCMonth()], MM: q[d].months[b.getUTCMonth()], yy: b.getUTCFullYear().toString().substring(2), yyyy: b.getUTCFullYear() }; e.dd = (e.d < 10 ? "0" : "") + e.d, e.mm = (e.m < 10 ? "0" : "") + e.m, b = []; for (var f = a.extend([], c.separators), g = 0, h = c.parts.length; h >= g; g++) f.length && b.push(f.shift()), b.push(e[c.parts[g]]); return b.join("")
        }, headTemplate: '<thead><tr><th colspan="7" class="datepicker-title"></th></tr><tr><th class="prev">&laquo;</th><th colspan="5" class="datepicker-switch"></th><th class="next">&raquo;</th></tr></thead>', contTemplate: '<tbody><tr><td colspan="7"></td></tr></tbody>', footTemplate: '<tfoot><tr><th colspan="7" class="today"></th></tr><tr><th colspan="7" class="clear"></th></tr></tfoot>'
    }; r.template = '<div class="datepicker"><div class="datepicker-days"><table class="table-condensed">' + r.headTemplate + "<tbody></tbody>" + r.footTemplate + '</table></div><div class="datepicker-months"><table class="table-condensed">' + r.headTemplate + r.contTemplate + r.footTemplate + '</table></div><div class="datepicker-years"><table class="table-condensed">' + r.headTemplate + r.contTemplate + r.footTemplate + '</table></div><div class="datepicker-decades"><table class="table-condensed">' + r.headTemplate + r.contTemplate + r.footTemplate + '</table></div><div class="datepicker-centuries"><table class="table-condensed">' + r.headTemplate + r.contTemplate + r.footTemplate + "</table></div></div>", a.fn.datepicker.DPGlobal = r, a.fn.datepicker.noConflict = function () { return a.fn.datepicker = m, this }, a.fn.datepicker.version = "1.6.4", a(document).on("focus.datepicker.data-api click.datepicker.data-api", '[data-provide="datepicker"]', function (b) { var c = a(this); c.data("datepicker") || (b.preventDefault(), n.call(c, "show")) }), a(function () { n.call(a('[data-provide="datepicker-inline"]')) })
});;
/*!
 * Bootstrap v3.4.1 (https://getbootstrap.com/)
 * Copyright 2011-2019 Twitter, Inc.
 * Licensed under the MIT license
 */
if ("undefined" == typeof jQuery) throw new Error("Bootstrap's JavaScript requires jQuery"); !function (t) { "use strict"; var e = jQuery.fn.jquery.split(" ")[0].split("."); if (e[0] < 2 && e[1] < 9 || 1 == e[0] && 9 == e[1] && e[2] < 1 || 3 < e[0]) throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4") }(), function (n) { "use strict"; n.fn.emulateTransitionEnd = function (t) { var e = !1, i = this; n(this).one("bsTransitionEnd", function () { e = !0 }); return setTimeout(function () { e || n(i).trigger(n.support.transition.end) }, t), this }, n(function () { n.support.transition = function o() { var t = document.createElement("bootstrap"), e = { WebkitTransition: "webkitTransitionEnd", MozTransition: "transitionend", OTransition: "oTransitionEnd otransitionend", transition: "transitionend" }; for (var i in e) if (t.style[i] !== undefined) return { end: e[i] }; return !1 }(), n.support.transition && (n.event.special.bsTransitionEnd = { bindType: n.support.transition.end, delegateType: n.support.transition.end, handle: function (t) { if (n(t.target).is(this)) return t.handleObj.handler.apply(this, arguments) } }) }) }(jQuery), function (s) { "use strict"; var e = '[data-dismiss="alert"]', a = function (t) { s(t).on("click", e, this.close) }; a.VERSION = "3.4.1", a.TRANSITION_DURATION = 150, a.prototype.close = function (t) { var e = s(this), i = e.attr("data-target"); i || (i = (i = e.attr("href")) && i.replace(/.*(?=#[^\s]*$)/, "")), i = "#" === i ? [] : i; var o = s(document).find(i); function n() { o.detach().trigger("closed.bs.alert").remove() } t && t.preventDefault(), o.length || (o = e.closest(".alert")), o.trigger(t = s.Event("close.bs.alert")), t.isDefaultPrevented() || (o.removeClass("in"), s.support.transition && o.hasClass("fade") ? o.one("bsTransitionEnd", n).emulateTransitionEnd(a.TRANSITION_DURATION) : n()) }; var t = s.fn.alert; s.fn.alert = function o(i) { return this.each(function () { var t = s(this), e = t.data("bs.alert"); e || t.data("bs.alert", e = new a(this)), "string" == typeof i && e[i].call(t) }) }, s.fn.alert.Constructor = a, s.fn.alert.noConflict = function () { return s.fn.alert = t, this }, s(document).on("click.bs.alert.data-api", e, a.prototype.close) }(jQuery), function (s) { "use strict"; var n = function (t, e) { this.$element = s(t), this.options = s.extend({}, n.DEFAULTS, e), this.isLoading = !1 }; function i(o) { return this.each(function () { var t = s(this), e = t.data("bs.button"), i = "object" == typeof o && o; e || t.data("bs.button", e = new n(this, i)), "toggle" == o ? e.toggle() : o && e.setState(o) }) } n.VERSION = "3.4.1", n.DEFAULTS = { loadingText: "loading..." }, n.prototype.setState = function (t) { var e = "disabled", i = this.$element, o = i.is("input") ? "val" : "html", n = i.data(); t += "Text", null == n.resetText && i.data("resetText", i[o]()), setTimeout(s.proxy(function () { i[o](null == n[t] ? this.options[t] : n[t]), "loadingText" == t ? (this.isLoading = !0, i.addClass(e).attr(e, e).prop(e, !0)) : this.isLoading && (this.isLoading = !1, i.removeClass(e).removeAttr(e).prop(e, !1)) }, this), 0) }, n.prototype.toggle = function () { var t = !0, e = this.$element.closest('[data-toggle="buttons"]'); if (e.length) { var i = this.$element.find("input"); "radio" == i.prop("type") ? (i.prop("checked") && (t = !1), e.find(".active").removeClass("active"), this.$element.addClass("active")) : "checkbox" == i.prop("type") && (i.prop("checked") !== this.$element.hasClass("active") && (t = !1), this.$element.toggleClass("active")), i.prop("checked", this.$element.hasClass("active")), t && i.trigger("change") } else this.$element.attr("aria-pressed", !this.$element.hasClass("active")), this.$element.toggleClass("active") }; var t = s.fn.button; s.fn.button = i, s.fn.button.Constructor = n, s.fn.button.noConflict = function () { return s.fn.button = t, this }, s(document).on("click.bs.button.data-api", '[data-toggle^="button"]', function (t) { var e = s(t.target).closest(".btn"); i.call(e, "toggle"), s(t.target).is('input[type="radio"], input[type="checkbox"]') || (t.preventDefault(), e.is("input,button") ? e.trigger("focus") : e.find("input:visible,button:visible").first().trigger("focus")) }).on("focus.bs.button.data-api blur.bs.button.data-api", '[data-toggle^="button"]', function (t) { s(t.target).closest(".btn").toggleClass("focus", /^focus(in)?$/.test(t.type)) }) }(jQuery), function (p) { "use strict"; var c = function (t, e) { this.$element = p(t), this.$indicators = this.$element.find(".carousel-indicators"), this.options = e, this.paused = null, this.sliding = null, this.interval = null, this.$active = null, this.$items = null, this.options.keyboard && this.$element.on("keydown.bs.carousel", p.proxy(this.keydown, this)), "hover" == this.options.pause && !("ontouchstart" in document.documentElement) && this.$element.on("mouseenter.bs.carousel", p.proxy(this.pause, this)).on("mouseleave.bs.carousel", p.proxy(this.cycle, this)) }; function r(n) { return this.each(function () { var t = p(this), e = t.data("bs.carousel"), i = p.extend({}, c.DEFAULTS, t.data(), "object" == typeof n && n), o = "string" == typeof n ? n : i.slide; e || t.data("bs.carousel", e = new c(this, i)), "number" == typeof n ? e.to(n) : o ? e[o]() : i.interval && e.pause().cycle() }) } c.VERSION = "3.4.1", c.TRANSITION_DURATION = 600, c.DEFAULTS = { interval: 5e3, pause: "hover", wrap: !0, keyboard: !0 }, c.prototype.keydown = function (t) { if (!/input|textarea/i.test(t.target.tagName)) { switch (t.which) { case 37: this.prev(); break; case 39: this.next(); break; default: return }t.preventDefault() } }, c.prototype.cycle = function (t) { return t || (this.paused = !1), this.interval && clearInterval(this.interval), this.options.interval && !this.paused && (this.interval = setInterval(p.proxy(this.next, this), this.options.interval)), this }, c.prototype.getItemIndex = function (t) { return this.$items = t.parent().children(".item"), this.$items.index(t || this.$active) }, c.prototype.getItemForDirection = function (t, e) { var i = this.getItemIndex(e); if (("prev" == t && 0 === i || "next" == t && i == this.$items.length - 1) && !this.options.wrap) return e; var o = (i + ("prev" == t ? -1 : 1)) % this.$items.length; return this.$items.eq(o) }, c.prototype.to = function (t) { var e = this, i = this.getItemIndex(this.$active = this.$element.find(".item.active")); if (!(t > this.$items.length - 1 || t < 0)) return this.sliding ? this.$element.one("slid.bs.carousel", function () { e.to(t) }) : i == t ? this.pause().cycle() : this.slide(i < t ? "next" : "prev", this.$items.eq(t)) }, c.prototype.pause = function (t) { return t || (this.paused = !0), this.$element.find(".next, .prev").length && p.support.transition && (this.$element.trigger(p.support.transition.end), this.cycle(!0)), this.interval = clearInterval(this.interval), this }, c.prototype.next = function () { if (!this.sliding) return this.slide("next") }, c.prototype.prev = function () { if (!this.sliding) return this.slide("prev") }, c.prototype.slide = function (t, e) { var i = this.$element.find(".item.active"), o = e || this.getItemForDirection(t, i), n = this.interval, s = "next" == t ? "left" : "right", a = this; if (o.hasClass("active")) return this.sliding = !1; var r = o[0], l = p.Event("slide.bs.carousel", { relatedTarget: r, direction: s }); if (this.$element.trigger(l), !l.isDefaultPrevented()) { if (this.sliding = !0, n && this.pause(), this.$indicators.length) { this.$indicators.find(".active").removeClass("active"); var h = p(this.$indicators.children()[this.getItemIndex(o)]); h && h.addClass("active") } var d = p.Event("slid.bs.carousel", { relatedTarget: r, direction: s }); return p.support.transition && this.$element.hasClass("slide") ? (o.addClass(t), "object" == typeof o && o.length && o[0].offsetWidth, i.addClass(s), o.addClass(s), i.one("bsTransitionEnd", function () { o.removeClass([t, s].join(" ")).addClass("active"), i.removeClass(["active", s].join(" ")), a.sliding = !1, setTimeout(function () { a.$element.trigger(d) }, 0) }).emulateTransitionEnd(c.TRANSITION_DURATION)) : (i.removeClass("active"), o.addClass("active"), this.sliding = !1, this.$element.trigger(d)), n && this.cycle(), this } }; var t = p.fn.carousel; p.fn.carousel = r, p.fn.carousel.Constructor = c, p.fn.carousel.noConflict = function () { return p.fn.carousel = t, this }; var e = function (t) { var e = p(this), i = e.attr("href"); i && (i = i.replace(/.*(?=#[^\s]+$)/, "")); var o = e.attr("data-target") || i, n = p(document).find(o); if (n.hasClass("carousel")) { var s = p.extend({}, n.data(), e.data()), a = e.attr("data-slide-to"); a && (s.interval = !1), r.call(n, s), a && n.data("bs.carousel").to(a), t.preventDefault() } }; p(document).on("click.bs.carousel.data-api", "[data-slide]", e).on("click.bs.carousel.data-api", "[data-slide-to]", e), p(window).on("load", function () { p('[data-ride="carousel"]').each(function () { var t = p(this); r.call(t, t.data()) }) }) }(jQuery), function (a) { "use strict"; var r = function (t, e) { this.$element = a(t), this.options = a.extend({}, r.DEFAULTS, e), this.$trigger = a('[data-toggle="collapse"][href="#' + t.id + '"],[data-toggle="collapse"][data-target="#' + t.id + '"]'), this.transitioning = null, this.options.parent ? this.$parent = this.getParent() : this.addAriaAndCollapsedClass(this.$element, this.$trigger), this.options.toggle && this.toggle() }; function n(t) { var e, i = t.attr("data-target") || (e = t.attr("href")) && e.replace(/.*(?=#[^\s]+$)/, ""); return a(document).find(i) } function l(o) { return this.each(function () { var t = a(this), e = t.data("bs.collapse"), i = a.extend({}, r.DEFAULTS, t.data(), "object" == typeof o && o); !e && i.toggle && /show|hide/.test(o) && (i.toggle = !1), e || t.data("bs.collapse", e = new r(this, i)), "string" == typeof o && e[o]() }) } r.VERSION = "3.4.1", r.TRANSITION_DURATION = 350, r.DEFAULTS = { toggle: !0 }, r.prototype.dimension = function () { return this.$element.hasClass("width") ? "width" : "height" }, r.prototype.show = function () { if (!this.transitioning && !this.$element.hasClass("in")) { var t, e = this.$parent && this.$parent.children(".panel").children(".in, .collapsing"); if (!(e && e.length && (t = e.data("bs.collapse")) && t.transitioning)) { var i = a.Event("show.bs.collapse"); if (this.$element.trigger(i), !i.isDefaultPrevented()) { e && e.length && (l.call(e, "hide"), t || e.data("bs.collapse", null)); var o = this.dimension(); this.$element.removeClass("collapse").addClass("collapsing")[o](0).attr("aria-expanded", !0), this.$trigger.removeClass("collapsed").attr("aria-expanded", !0), this.transitioning = 1; var n = function () { this.$element.removeClass("collapsing").addClass("collapse in")[o](""), this.transitioning = 0, this.$element.trigger("shown.bs.collapse") }; if (!a.support.transition) return n.call(this); var s = a.camelCase(["scroll", o].join("-")); this.$element.one("bsTransitionEnd", a.proxy(n, this)).emulateTransitionEnd(r.TRANSITION_DURATION)[o](this.$element[0][s]) } } } }, r.prototype.hide = function () { if (!this.transitioning && this.$element.hasClass("in")) { var t = a.Event("hide.bs.collapse"); if (this.$element.trigger(t), !t.isDefaultPrevented()) { var e = this.dimension(); this.$element[e](this.$element[e]())[0].offsetHeight, this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded", !1), this.$trigger.addClass("collapsed").attr("aria-expanded", !1), this.transitioning = 1; var i = function () { this.transitioning = 0, this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse") }; if (!a.support.transition) return i.call(this); this.$element[e](0).one("bsTransitionEnd", a.proxy(i, this)).emulateTransitionEnd(r.TRANSITION_DURATION) } } }, r.prototype.toggle = function () { this[this.$element.hasClass("in") ? "hide" : "show"]() }, r.prototype.getParent = function () { return a(document).find(this.options.parent).find('[data-toggle="collapse"][data-parent="' + this.options.parent + '"]').each(a.proxy(function (t, e) { var i = a(e); this.addAriaAndCollapsedClass(n(i), i) }, this)).end() }, r.prototype.addAriaAndCollapsedClass = function (t, e) { var i = t.hasClass("in"); t.attr("aria-expanded", i), e.toggleClass("collapsed", !i).attr("aria-expanded", i) }; var t = a.fn.collapse; a.fn.collapse = l, a.fn.collapse.Constructor = r, a.fn.collapse.noConflict = function () { return a.fn.collapse = t, this }, a(document).on("click.bs.collapse.data-api", '[data-toggle="collapse"]', function (t) { var e = a(this); e.attr("data-target") || t.preventDefault(); var i = n(e), o = i.data("bs.collapse") ? "toggle" : e.data(); l.call(i, o) }) }(jQuery), function (a) { "use strict"; var r = '[data-toggle="dropdown"]', o = function (t) { a(t).on("click.bs.dropdown", this.toggle) }; function l(t) { var e = t.attr("data-target"); e || (e = (e = t.attr("href")) && /#[A-Za-z]/.test(e) && e.replace(/.*(?=#[^\s]*$)/, "")); var i = "#" !== e ? a(document).find(e) : null; return i && i.length ? i : t.parent() } function s(o) { o && 3 === o.which || (a(".dropdown-backdrop").remove(), a(r).each(function () { var t = a(this), e = l(t), i = { relatedTarget: this }; e.hasClass("open") && (o && "click" == o.type && /input|textarea/i.test(o.target.tagName) && a.contains(e[0], o.target) || (e.trigger(o = a.Event("hide.bs.dropdown", i)), o.isDefaultPrevented() || (t.attr("aria-expanded", "false"), e.removeClass("open").trigger(a.Event("hidden.bs.dropdown", i))))) })) } o.VERSION = "3.4.1", o.prototype.toggle = function (t) { var e = a(this); if (!e.is(".disabled, :disabled")) { var i = l(e), o = i.hasClass("open"); if (s(), !o) { "ontouchstart" in document.documentElement && !i.closest(".navbar-nav").length && a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click", s); var n = { relatedTarget: this }; if (i.trigger(t = a.Event("show.bs.dropdown", n)), t.isDefaultPrevented()) return; e.trigger("focus").attr("aria-expanded", "true"), i.toggleClass("open").trigger(a.Event("shown.bs.dropdown", n)) } return !1 } }, o.prototype.keydown = function (t) { if (/(38|40|27|32)/.test(t.which) && !/input|textarea/i.test(t.target.tagName)) { var e = a(this); if (t.preventDefault(), t.stopPropagation(), !e.is(".disabled, :disabled")) { var i = l(e), o = i.hasClass("open"); if (!o && 27 != t.which || o && 27 == t.which) return 27 == t.which && i.find(r).trigger("focus"), e.trigger("click"); var n = i.find(".dropdown-menu li:not(.disabled):visible a"); if (n.length) { var s = n.index(t.target); 38 == t.which && 0 < s && s-- , 40 == t.which && s < n.length - 1 && s++ , ~s || (s = 0), n.eq(s).trigger("focus") } } } }; var t = a.fn.dropdown; a.fn.dropdown = function e(i) { return this.each(function () { var t = a(this), e = t.data("bs.dropdown"); e || t.data("bs.dropdown", e = new o(this)), "string" == typeof i && e[i].call(t) }) }, a.fn.dropdown.Constructor = o, a.fn.dropdown.noConflict = function () { return a.fn.dropdown = t, this }, a(document).on("click.bs.dropdown.data-api", s).on("click.bs.dropdown.data-api", ".dropdown form", function (t) { t.stopPropagation() }).on("click.bs.dropdown.data-api", r, o.prototype.toggle).on("keydown.bs.dropdown.data-api", r, o.prototype.keydown).on("keydown.bs.dropdown.data-api", ".dropdown-menu", o.prototype.keydown) }(jQuery), function (a) { "use strict"; var s = function (t, e) { this.options = e, this.$body = a(document.body), this.$element = a(t), this.$dialog = this.$element.find(".modal-dialog"), this.$backdrop = null, this.isShown = null, this.originalBodyPad = null, this.scrollbarWidth = 0, this.ignoreBackdropClick = !1, this.fixedContent = ".navbar-fixed-top, .navbar-fixed-bottom", this.options.remote && this.$element.find(".modal-content").load(this.options.remote, a.proxy(function () { this.$element.trigger("loaded.bs.modal") }, this)) }; function r(o, n) { return this.each(function () { var t = a(this), e = t.data("bs.modal"), i = a.extend({}, s.DEFAULTS, t.data(), "object" == typeof o && o); e || t.data("bs.modal", e = new s(this, i)), "string" == typeof o ? e[o](n) : i.show && e.show(n) }) } s.VERSION = "3.4.1", s.TRANSITION_DURATION = 300, s.BACKDROP_TRANSITION_DURATION = 150, s.DEFAULTS = { backdrop: !0, keyboard: !0, show: !0 }, s.prototype.toggle = function (t) { return this.isShown ? this.hide() : this.show(t) }, s.prototype.show = function (i) { var o = this, t = a.Event("show.bs.modal", { relatedTarget: i }); this.$element.trigger(t), this.isShown || t.isDefaultPrevented() || (this.isShown = !0, this.checkScrollbar(), this.setScrollbar(), this.$body.addClass("modal-open"), this.escape(), this.resize(), this.$element.on("click.dismiss.bs.modal", '[data-dismiss="modal"]', a.proxy(this.hide, this)), this.$dialog.on("mousedown.dismiss.bs.modal", function () { o.$element.one("mouseup.dismiss.bs.modal", function (t) { a(t.target).is(o.$element) && (o.ignoreBackdropClick = !0) }) }), this.backdrop(function () { var t = a.support.transition && o.$element.hasClass("fade"); o.$element.parent().length || o.$element.appendTo(o.$body), o.$element.show().scrollTop(0), o.adjustDialog(), t && o.$element[0].offsetWidth, o.$element.addClass("in"), o.enforceFocus(); var e = a.Event("shown.bs.modal", { relatedTarget: i }); t ? o.$dialog.one("bsTransitionEnd", function () { o.$element.trigger("focus").trigger(e) }).emulateTransitionEnd(s.TRANSITION_DURATION) : o.$element.trigger("focus").trigger(e) })) }, s.prototype.hide = function (t) { t && t.preventDefault(), t = a.Event("hide.bs.modal"), this.$element.trigger(t), this.isShown && !t.isDefaultPrevented() && (this.isShown = !1, this.escape(), this.resize(), a(document).off("focusin.bs.modal"), this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"), this.$dialog.off("mousedown.dismiss.bs.modal"), a.support.transition && this.$element.hasClass("fade") ? this.$element.one("bsTransitionEnd", a.proxy(this.hideModal, this)).emulateTransitionEnd(s.TRANSITION_DURATION) : this.hideModal()) }, s.prototype.enforceFocus = function () { a(document).off("focusin.bs.modal").on("focusin.bs.modal", a.proxy(function (t) { document === t.target || this.$element[0] === t.target || this.$element.has(t.target).length || this.$element.trigger("focus") }, this)) }, s.prototype.escape = function () { this.isShown && this.options.keyboard ? this.$element.on("keydown.dismiss.bs.modal", a.proxy(function (t) { 27 == t.which && this.hide() }, this)) : this.isShown || this.$element.off("keydown.dismiss.bs.modal") }, s.prototype.resize = function () { this.isShown ? a(window).on("resize.bs.modal", a.proxy(this.handleUpdate, this)) : a(window).off("resize.bs.modal") }, s.prototype.hideModal = function () { var t = this; this.$element.hide(), this.backdrop(function () { t.$body.removeClass("modal-open"), t.resetAdjustments(), t.resetScrollbar(), t.$element.trigger("hidden.bs.modal") }) }, s.prototype.removeBackdrop = function () { this.$backdrop && this.$backdrop.remove(), this.$backdrop = null }, s.prototype.backdrop = function (t) { var e = this, i = this.$element.hasClass("fade") ? "fade" : ""; if (this.isShown && this.options.backdrop) { var o = a.support.transition && i; if (this.$backdrop = a(document.createElement("div")).addClass("modal-backdrop " + i).appendTo(this.$body), this.$element.on("click.dismiss.bs.modal", a.proxy(function (t) { this.ignoreBackdropClick ? this.ignoreBackdropClick = !1 : t.target === t.currentTarget && ("static" == this.options.backdrop ? this.$element[0].focus() : this.hide()) }, this)), o && this.$backdrop[0].offsetWidth, this.$backdrop.addClass("in"), !t) return; o ? this.$backdrop.one("bsTransitionEnd", t).emulateTransitionEnd(s.BACKDROP_TRANSITION_DURATION) : t() } else if (!this.isShown && this.$backdrop) { this.$backdrop.removeClass("in"); var n = function () { e.removeBackdrop(), t && t() }; a.support.transition && this.$element.hasClass("fade") ? this.$backdrop.one("bsTransitionEnd", n).emulateTransitionEnd(s.BACKDROP_TRANSITION_DURATION) : n() } else t && t() }, s.prototype.handleUpdate = function () { this.adjustDialog() }, s.prototype.adjustDialog = function () { var t = this.$element[0].scrollHeight > document.documentElement.clientHeight; this.$element.css({ paddingLeft: !this.bodyIsOverflowing && t ? this.scrollbarWidth : "", paddingRight: this.bodyIsOverflowing && !t ? this.scrollbarWidth : "" }) }, s.prototype.resetAdjustments = function () { this.$element.css({ paddingLeft: "", paddingRight: "" }) }, s.prototype.checkScrollbar = function () { var t = window.innerWidth; if (!t) { var e = document.documentElement.getBoundingClientRect(); t = e.right - Math.abs(e.left) } this.bodyIsOverflowing = document.body.clientWidth < t, this.scrollbarWidth = this.measureScrollbar() }, s.prototype.setScrollbar = function () { var t = parseInt(this.$body.css("padding-right") || 0, 10); this.originalBodyPad = document.body.style.paddingRight || ""; var n = this.scrollbarWidth; this.bodyIsOverflowing && (this.$body.css("padding-right", t + n), a(this.fixedContent).each(function (t, e) { var i = e.style.paddingRight, o = a(e).css("padding-right"); a(e).data("padding-right", i).css("padding-right", parseFloat(o) + n + "px") })) }, s.prototype.resetScrollbar = function () { this.$body.css("padding-right", this.originalBodyPad), a(this.fixedContent).each(function (t, e) { var i = a(e).data("padding-right"); a(e).removeData("padding-right"), e.style.paddingRight = i || "" }) }, s.prototype.measureScrollbar = function () { var t = document.createElement("div"); t.className = "modal-scrollbar-measure", this.$body.append(t); var e = t.offsetWidth - t.clientWidth; return this.$body[0].removeChild(t), e }; var t = a.fn.modal; a.fn.modal = r, a.fn.modal.Constructor = s, a.fn.modal.noConflict = function () { return a.fn.modal = t, this }, a(document).on("click.bs.modal.data-api", '[data-toggle="modal"]', function (t) { var e = a(this), i = e.attr("href"), o = e.attr("data-target") || i && i.replace(/.*(?=#[^\s]+$)/, ""), n = a(document).find(o), s = n.data("bs.modal") ? "toggle" : a.extend({ remote: !/#/.test(i) && i }, n.data(), e.data()); e.is("a") && t.preventDefault(), n.one("show.bs.modal", function (t) { t.isDefaultPrevented() || n.one("hidden.bs.modal", function () { e.is(":visible") && e.trigger("focus") }) }), r.call(n, s, this) }) }(jQuery), function (g) { "use strict"; var o = ["sanitize", "whiteList", "sanitizeFn"], a = ["background", "cite", "href", "itemtype", "longdesc", "poster", "src", "xlink:href"], t = { "*": ["class", "dir", "id", "lang", "role", /^aria-[\w-]*$/i], a: ["target", "href", "title", "rel"], area: [], b: [], br: [], col: [], code: [], div: [], em: [], hr: [], h1: [], h2: [], h3: [], h4: [], h5: [], h6: [], i: [], img: ["src", "alt", "title", "width", "height"], li: [], ol: [], p: [], pre: [], s: [], small: [], span: [], sub: [], sup: [], strong: [], u: [], ul: [] }, r = /^(?:(?:https?|mailto|ftp|tel|file):|[^&:/?#]*(?:[/?#]|$))/gi, l = /^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[a-z0-9+/]+=*$/i; function u(t, e) { var i = t.nodeName.toLowerCase(); if (-1 !== g.inArray(i, e)) return -1 === g.inArray(i, a) || Boolean(t.nodeValue.match(r) || t.nodeValue.match(l)); for (var o = g(e).filter(function (t, e) { return e instanceof RegExp }), n = 0, s = o.length; n < s; n++)if (i.match(o[n])) return !0; return !1 } function n(t, e, i) { if (0 === t.length) return t; if (i && "function" == typeof i) return i(t); if (!document.implementation || !document.implementation.createHTMLDocument) return t; var o = document.implementation.createHTMLDocument("sanitization"); o.body.innerHTML = t; for (var n = g.map(e, function (t, e) { return e }), s = g(o.body).find("*"), a = 0, r = s.length; a < r; a++) { var l = s[a], h = l.nodeName.toLowerCase(); if (-1 !== g.inArray(h, n)) for (var d = g.map(l.attributes, function (t) { return t }), p = [].concat(e["*"] || [], e[h] || []), c = 0, f = d.length; c < f; c++)u(d[c], p) || l.removeAttribute(d[c].nodeName); else l.parentNode.removeChild(l) } return o.body.innerHTML } var m = function (t, e) { this.type = null, this.options = null, this.enabled = null, this.timeout = null, this.hoverState = null, this.$element = null, this.inState = null, this.init("tooltip", t, e) }; m.VERSION = "3.4.1", m.TRANSITION_DURATION = 150, m.DEFAULTS = { animation: !0, placement: "top", selector: !1, template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>', trigger: "hover focus", title: "", delay: 0, html: !1, container: !1, viewport: { selector: "body", padding: 0 }, sanitize: !0, sanitizeFn: null, whiteList: t }, m.prototype.init = function (t, e, i) { if (this.enabled = !0, this.type = t, this.$element = g(e), this.options = this.getOptions(i), this.$viewport = this.options.viewport && g(document).find(g.isFunction(this.options.viewport) ? this.options.viewport.call(this, this.$element) : this.options.viewport.selector || this.options.viewport), this.inState = { click: !1, hover: !1, focus: !1 }, this.$element[0] instanceof document.constructor && !this.options.selector) throw new Error("`selector` option must be specified when initializing " + this.type + " on the window.document object!"); for (var o = this.options.trigger.split(" "), n = o.length; n--;) { var s = o[n]; if ("click" == s) this.$element.on("click." + this.type, this.options.selector, g.proxy(this.toggle, this)); else if ("manual" != s) { var a = "hover" == s ? "mouseenter" : "focusin", r = "hover" == s ? "mouseleave" : "focusout"; this.$element.on(a + "." + this.type, this.options.selector, g.proxy(this.enter, this)), this.$element.on(r + "." + this.type, this.options.selector, g.proxy(this.leave, this)) } } this.options.selector ? this._options = g.extend({}, this.options, { trigger: "manual", selector: "" }) : this.fixTitle() }, m.prototype.getDefaults = function () { return m.DEFAULTS }, m.prototype.getOptions = function (t) { var e = this.$element.data(); for (var i in e) e.hasOwnProperty(i) && -1 !== g.inArray(i, o) && delete e[i]; return (t = g.extend({}, this.getDefaults(), e, t)).delay && "number" == typeof t.delay && (t.delay = { show: t.delay, hide: t.delay }), t.sanitize && (t.template = n(t.template, t.whiteList, t.sanitizeFn)), t }, m.prototype.getDelegateOptions = function () { var i = {}, o = this.getDefaults(); return this._options && g.each(this._options, function (t, e) { o[t] != e && (i[t] = e) }), i }, m.prototype.enter = function (t) { var e = t instanceof this.constructor ? t : g(t.currentTarget).data("bs." + this.type); if (e || (e = new this.constructor(t.currentTarget, this.getDelegateOptions()), g(t.currentTarget).data("bs." + this.type, e)), t instanceof g.Event && (e.inState["focusin" == t.type ? "focus" : "hover"] = !0), e.tip().hasClass("in") || "in" == e.hoverState) e.hoverState = "in"; else { if (clearTimeout(e.timeout), e.hoverState = "in", !e.options.delay || !e.options.delay.show) return e.show(); e.timeout = setTimeout(function () { "in" == e.hoverState && e.show() }, e.options.delay.show) } }, m.prototype.isInStateTrue = function () { for (var t in this.inState) if (this.inState[t]) return !0; return !1 }, m.prototype.leave = function (t) { var e = t instanceof this.constructor ? t : g(t.currentTarget).data("bs." + this.type); if (e || (e = new this.constructor(t.currentTarget, this.getDelegateOptions()), g(t.currentTarget).data("bs." + this.type, e)), t instanceof g.Event && (e.inState["focusout" == t.type ? "focus" : "hover"] = !1), !e.isInStateTrue()) { if (clearTimeout(e.timeout), e.hoverState = "out", !e.options.delay || !e.options.delay.hide) return e.hide(); e.timeout = setTimeout(function () { "out" == e.hoverState && e.hide() }, e.options.delay.hide) } }, m.prototype.show = function () { var t = g.Event("show.bs." + this.type); if (this.hasContent() && this.enabled) { this.$element.trigger(t); var e = g.contains(this.$element[0].ownerDocument.documentElement, this.$element[0]); if (t.isDefaultPrevented() || !e) return; var i = this, o = this.tip(), n = this.getUID(this.type); this.setContent(), o.attr("id", n), this.$element.attr("aria-describedby", n), this.options.animation && o.addClass("fade"); var s = "function" == typeof this.options.placement ? this.options.placement.call(this, o[0], this.$element[0]) : this.options.placement, a = /\s?auto?\s?/i, r = a.test(s); r && (s = s.replace(a, "") || "top"), o.detach().css({ top: 0, left: 0, display: "block" }).addClass(s).data("bs." + this.type, this), this.options.container ? o.appendTo(g(document).find(this.options.container)) : o.insertAfter(this.$element), this.$element.trigger("inserted.bs." + this.type); var l = this.getPosition(), h = o[0].offsetWidth, d = o[0].offsetHeight; if (r) { var p = s, c = this.getPosition(this.$viewport); s = "bottom" == s && l.bottom + d > c.bottom ? "top" : "top" == s && l.top - d < c.top ? "bottom" : "right" == s && l.right + h > c.width ? "left" : "left" == s && l.left - h < c.left ? "right" : s, o.removeClass(p).addClass(s) } var f = this.getCalculatedOffset(s, l, h, d); this.applyPlacement(f, s); var u = function () { var t = i.hoverState; i.$element.trigger("shown.bs." + i.type), i.hoverState = null, "out" == t && i.leave(i) }; g.support.transition && this.$tip.hasClass("fade") ? o.one("bsTransitionEnd", u).emulateTransitionEnd(m.TRANSITION_DURATION) : u() } }, m.prototype.applyPlacement = function (t, e) { var i = this.tip(), o = i[0].offsetWidth, n = i[0].offsetHeight, s = parseInt(i.css("margin-top"), 10), a = parseInt(i.css("margin-left"), 10); isNaN(s) && (s = 0), isNaN(a) && (a = 0), t.top += s, t.left += a, g.offset.setOffset(i[0], g.extend({ using: function (t) { i.css({ top: Math.round(t.top), left: Math.round(t.left) }) } }, t), 0), i.addClass("in"); var r = i[0].offsetWidth, l = i[0].offsetHeight; "top" == e && l != n && (t.top = t.top + n - l); var h = this.getViewportAdjustedDelta(e, t, r, l); h.left ? t.left += h.left : t.top += h.top; var d = /top|bottom/.test(e), p = d ? 2 * h.left - o + r : 2 * h.top - n + l, c = d ? "offsetWidth" : "offsetHeight"; i.offset(t), this.replaceArrow(p, i[0][c], d) }, m.prototype.replaceArrow = function (t, e, i) { this.arrow().css(i ? "left" : "top", 50 * (1 - t / e) + "%").css(i ? "top" : "left", "") }, m.prototype.setContent = function () { var t = this.tip(), e = this.getTitle(); this.options.html ? (this.options.sanitize && (e = n(e, this.options.whiteList, this.options.sanitizeFn)), t.find(".tooltip-inner").html(e)) : t.find(".tooltip-inner").text(e), t.removeClass("fade in top bottom left right") }, m.prototype.hide = function (t) { var e = this, i = g(this.$tip), o = g.Event("hide.bs." + this.type); function n() { "in" != e.hoverState && i.detach(), e.$element && e.$element.removeAttr("aria-describedby").trigger("hidden.bs." + e.type), t && t() } if (this.$element.trigger(o), !o.isDefaultPrevented()) return i.removeClass("in"), g.support.transition && i.hasClass("fade") ? i.one("bsTransitionEnd", n).emulateTransitionEnd(m.TRANSITION_DURATION) : n(), this.hoverState = null, this }, m.prototype.fixTitle = function () { var t = this.$element; (t.attr("title") || "string" != typeof t.attr("data-original-title")) && t.attr("data-original-title", t.attr("title") || "").attr("title", "") }, m.prototype.hasContent = function () { return this.getTitle() }, m.prototype.getPosition = function (t) { var e = (t = t || this.$element)[0], i = "BODY" == e.tagName, o = e.getBoundingClientRect(); null == o.width && (o = g.extend({}, o, { width: o.right - o.left, height: o.bottom - o.top })); var n = window.SVGElement && e instanceof window.SVGElement, s = i ? { top: 0, left: 0 } : n ? null : t.offset(), a = { scroll: i ? document.documentElement.scrollTop || document.body.scrollTop : t.scrollTop() }, r = i ? { width: g(window).width(), height: g(window).height() } : null; return g.extend({}, o, a, r, s) }, m.prototype.getCalculatedOffset = function (t, e, i, o) { return "bottom" == t ? { top: e.top + e.height, left: e.left + e.width / 2 - i / 2 } : "top" == t ? { top: e.top - o, left: e.left + e.width / 2 - i / 2 } : "left" == t ? { top: e.top + e.height / 2 - o / 2, left: e.left - i } : { top: e.top + e.height / 2 - o / 2, left: e.left + e.width } }, m.prototype.getViewportAdjustedDelta = function (t, e, i, o) { var n = { top: 0, left: 0 }; if (!this.$viewport) return n; var s = this.options.viewport && this.options.viewport.padding || 0, a = this.getPosition(this.$viewport); if (/right|left/.test(t)) { var r = e.top - s - a.scroll, l = e.top + s - a.scroll + o; r < a.top ? n.top = a.top - r : l > a.top + a.height && (n.top = a.top + a.height - l) } else { var h = e.left - s, d = e.left + s + i; h < a.left ? n.left = a.left - h : d > a.right && (n.left = a.left + a.width - d) } return n }, m.prototype.getTitle = function () { var t = this.$element, e = this.options; return t.attr("data-original-title") || ("function" == typeof e.title ? e.title.call(t[0]) : e.title) }, m.prototype.getUID = function (t) { for (; t += ~~(1e6 * Math.random()), document.getElementById(t);); return t }, m.prototype.tip = function () { if (!this.$tip && (this.$tip = g(this.options.template), 1 != this.$tip.length)) throw new Error(this.type + " `template` option must consist of exactly 1 top-level element!"); return this.$tip }, m.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find(".tooltip-arrow") }, m.prototype.enable = function () { this.enabled = !0 }, m.prototype.disable = function () { this.enabled = !1 }, m.prototype.toggleEnabled = function () { this.enabled = !this.enabled }, m.prototype.toggle = function (t) { var e = this; t && ((e = g(t.currentTarget).data("bs." + this.type)) || (e = new this.constructor(t.currentTarget, this.getDelegateOptions()), g(t.currentTarget).data("bs." + this.type, e))), t ? (e.inState.click = !e.inState.click, e.isInStateTrue() ? e.enter(e) : e.leave(e)) : e.tip().hasClass("in") ? e.leave(e) : e.enter(e) }, m.prototype.destroy = function () { var t = this; clearTimeout(this.timeout), this.hide(function () { t.$element.off("." + t.type).removeData("bs." + t.type), t.$tip && t.$tip.detach(), t.$tip = null, t.$arrow = null, t.$viewport = null, t.$element = null }) }, m.prototype.sanitizeHtml = function (t) { return n(t, this.options.whiteList, this.options.sanitizeFn) }; var e = g.fn.tooltip; g.fn.tooltip = function i(o) { return this.each(function () { var t = g(this), e = t.data("bs.tooltip"), i = "object" == typeof o && o; !e && /destroy|hide/.test(o) || (e || t.data("bs.tooltip", e = new m(this, i)), "string" == typeof o && e[o]()) }) }, g.fn.tooltip.Constructor = m, g.fn.tooltip.noConflict = function () { return g.fn.tooltip = e, this } }(jQuery), function (n) { "use strict"; var s = function (t, e) { this.init("popover", t, e) }; if (!n.fn.tooltip) throw new Error("Popover requires tooltip.js"); s.VERSION = "3.4.1", s.DEFAULTS = n.extend({}, n.fn.tooltip.Constructor.DEFAULTS, { placement: "right", trigger: "click", content: "", template: '<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>' }), ((s.prototype = n.extend({}, n.fn.tooltip.Constructor.prototype)).constructor = s).prototype.getDefaults = function () { return s.DEFAULTS }, s.prototype.setContent = function () { var t = this.tip(), e = this.getTitle(), i = this.getContent(); if (this.options.html) { var o = typeof i; this.options.sanitize && (e = this.sanitizeHtml(e), "string" === o && (i = this.sanitizeHtml(i))), t.find(".popover-title").html(e), t.find(".popover-content").children().detach().end()["string" === o ? "html" : "append"](i) } else t.find(".popover-title").text(e), t.find(".popover-content").children().detach().end().text(i); t.removeClass("fade top bottom left right in"), t.find(".popover-title").html() || t.find(".popover-title").hide() }, s.prototype.hasContent = function () { return this.getTitle() || this.getContent() }, s.prototype.getContent = function () { var t = this.$element, e = this.options; return t.attr("data-content") || ("function" == typeof e.content ? e.content.call(t[0]) : e.content) }, s.prototype.arrow = function () { return this.$arrow = this.$arrow || this.tip().find(".arrow") }; var t = n.fn.popover; n.fn.popover = function e(o) { return this.each(function () { var t = n(this), e = t.data("bs.popover"), i = "object" == typeof o && o; !e && /destroy|hide/.test(o) || (e || t.data("bs.popover", e = new s(this, i)), "string" == typeof o && e[o]()) }) }, n.fn.popover.Constructor = s, n.fn.popover.noConflict = function () { return n.fn.popover = t, this } }(jQuery), function (s) { "use strict"; function n(t, e) { this.$body = s(document.body), this.$scrollElement = s(t).is(document.body) ? s(window) : s(t), this.options = s.extend({}, n.DEFAULTS, e), this.selector = (this.options.target || "") + " .nav li > a", this.offsets = [], this.targets = [], this.activeTarget = null, this.scrollHeight = 0, this.$scrollElement.on("scroll.bs.scrollspy", s.proxy(this.process, this)), this.refresh(), this.process() } function e(o) { return this.each(function () { var t = s(this), e = t.data("bs.scrollspy"), i = "object" == typeof o && o; e || t.data("bs.scrollspy", e = new n(this, i)), "string" == typeof o && e[o]() }) } n.VERSION = "3.4.1", n.DEFAULTS = { offset: 10 }, n.prototype.getScrollHeight = function () { return this.$scrollElement[0].scrollHeight || Math.max(this.$body[0].scrollHeight, document.documentElement.scrollHeight) }, n.prototype.refresh = function () { var t = this, o = "offset", n = 0; this.offsets = [], this.targets = [], this.scrollHeight = this.getScrollHeight(), s.isWindow(this.$scrollElement[0]) || (o = "position", n = this.$scrollElement.scrollTop()), this.$body.find(this.selector).map(function () { var t = s(this), e = t.data("target") || t.attr("href"), i = /^#./.test(e) && s(e); return i && i.length && i.is(":visible") && [[i[o]().top + n, e]] || null }).sort(function (t, e) { return t[0] - e[0] }).each(function () { t.offsets.push(this[0]), t.targets.push(this[1]) }) }, n.prototype.process = function () { var t, e = this.$scrollElement.scrollTop() + this.options.offset, i = this.getScrollHeight(), o = this.options.offset + i - this.$scrollElement.height(), n = this.offsets, s = this.targets, a = this.activeTarget; if (this.scrollHeight != i && this.refresh(), o <= e) return a != (t = s[s.length - 1]) && this.activate(t); if (a && e < n[0]) return this.activeTarget = null, this.clear(); for (t = n.length; t--;)a != s[t] && e >= n[t] && (n[t + 1] === undefined || e < n[t + 1]) && this.activate(s[t]) }, n.prototype.activate = function (t) { this.activeTarget = t, this.clear(); var e = this.selector + '[data-target="' + t + '"],' + this.selector + '[href="' + t + '"]', i = s(e).parents("li").addClass("active"); i.parent(".dropdown-menu").length && (i = i.closest("li.dropdown").addClass("active")), i.trigger("activate.bs.scrollspy") }, n.prototype.clear = function () { s(this.selector).parentsUntil(this.options.target, ".active").removeClass("active") }; var t = s.fn.scrollspy; s.fn.scrollspy = e, s.fn.scrollspy.Constructor = n, s.fn.scrollspy.noConflict = function () { return s.fn.scrollspy = t, this }, s(window).on("load.bs.scrollspy.data-api", function () { s('[data-spy="scroll"]').each(function () { var t = s(this); e.call(t, t.data()) }) }) }(jQuery), function (r) { "use strict"; var a = function (t) { this.element = r(t) }; function e(i) { return this.each(function () { var t = r(this), e = t.data("bs.tab"); e || t.data("bs.tab", e = new a(this)), "string" == typeof i && e[i]() }) } a.VERSION = "3.4.1", a.TRANSITION_DURATION = 150, a.prototype.show = function () { var t = this.element, e = t.closest("ul:not(.dropdown-menu)"), i = t.data("target"); if (i || (i = (i = t.attr("href")) && i.replace(/.*(?=#[^\s]*$)/, "")), !t.parent("li").hasClass("active")) { var o = e.find(".active:last a"), n = r.Event("hide.bs.tab", { relatedTarget: t[0] }), s = r.Event("show.bs.tab", { relatedTarget: o[0] }); if (o.trigger(n), t.trigger(s), !s.isDefaultPrevented() && !n.isDefaultPrevented()) { var a = r(document).find(i); this.activate(t.closest("li"), e), this.activate(a, a.parent(), function () { o.trigger({ type: "hidden.bs.tab", relatedTarget: t[0] }), t.trigger({ type: "shown.bs.tab", relatedTarget: o[0] }) }) } } }, a.prototype.activate = function (t, e, i) { var o = e.find("> .active"), n = i && r.support.transition && (o.length && o.hasClass("fade") || !!e.find("> .fade").length); function s() { o.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded", !1), t.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded", !0), n ? (t[0].offsetWidth, t.addClass("in")) : t.removeClass("fade"), t.parent(".dropdown-menu").length && t.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded", !0), i && i() } o.length && n ? o.one("bsTransitionEnd", s).emulateTransitionEnd(a.TRANSITION_DURATION) : s(), o.removeClass("in") }; var t = r.fn.tab; r.fn.tab = e, r.fn.tab.Constructor = a, r.fn.tab.noConflict = function () { return r.fn.tab = t, this }; var i = function (t) { t.preventDefault(), e.call(r(this), "show") }; r(document).on("click.bs.tab.data-api", '[data-toggle="tab"]', i).on("click.bs.tab.data-api", '[data-toggle="pill"]', i) }(jQuery), function (l) { "use strict"; var h = function (t, e) { this.options = l.extend({}, h.DEFAULTS, e); var i = this.options.target === h.DEFAULTS.target ? l(this.options.target) : l(document).find(this.options.target); this.$target = i.on("scroll.bs.affix.data-api", l.proxy(this.checkPosition, this)).on("click.bs.affix.data-api", l.proxy(this.checkPositionWithEventLoop, this)), this.$element = l(t), this.affixed = null, this.unpin = null, this.pinnedOffset = null, this.checkPosition() }; function i(o) { return this.each(function () { var t = l(this), e = t.data("bs.affix"), i = "object" == typeof o && o; e || t.data("bs.affix", e = new h(this, i)), "string" == typeof o && e[o]() }) } h.VERSION = "3.4.1", h.RESET = "affix affix-top affix-bottom", h.DEFAULTS = { offset: 0, target: window }, h.prototype.getState = function (t, e, i, o) { var n = this.$target.scrollTop(), s = this.$element.offset(), a = this.$target.height(); if (null != i && "top" == this.affixed) return n < i && "top"; if ("bottom" == this.affixed) return null != i ? !(n + this.unpin <= s.top) && "bottom" : !(n + a <= t - o) && "bottom"; var r = null == this.affixed, l = r ? n : s.top; return null != i && n <= i ? "top" : null != o && t - o <= l + (r ? a : e) && "bottom" }, h.prototype.getPinnedOffset = function () { if (this.pinnedOffset) return this.pinnedOffset; this.$element.removeClass(h.RESET).addClass("affix"); var t = this.$target.scrollTop(), e = this.$element.offset(); return this.pinnedOffset = e.top - t }, h.prototype.checkPositionWithEventLoop = function () { setTimeout(l.proxy(this.checkPosition, this), 1) }, h.prototype.checkPosition = function () { if (this.$element.is(":visible")) { var t = this.$element.height(), e = this.options.offset, i = e.top, o = e.bottom, n = Math.max(l(document).height(), l(document.body).height()); "object" != typeof e && (o = i = e), "function" == typeof i && (i = e.top(this.$element)), "function" == typeof o && (o = e.bottom(this.$element)); var s = this.getState(n, t, i, o); if (this.affixed != s) { null != this.unpin && this.$element.css("top", ""); var a = "affix" + (s ? "-" + s : ""), r = l.Event(a + ".bs.affix"); if (this.$element.trigger(r), r.isDefaultPrevented()) return; this.affixed = s, this.unpin = "bottom" == s ? this.getPinnedOffset() : null, this.$element.removeClass(h.RESET).addClass(a).trigger(a.replace("affix", "affixed") + ".bs.affix") } "bottom" == s && this.$element.offset({ top: n - t - o }) } }; var t = l.fn.affix; l.fn.affix = i, l.fn.affix.Constructor = h, l.fn.affix.noConflict = function () { return l.fn.affix = t, this }, l(window).on("load", function () { l('[data-spy="affix"]').each(function () { var t = l(this), e = t.data(); e.offset = e.offset || {}, null != e.offsetBottom && (e.offset.bottom = e.offsetBottom), null != e.offsetTop && (e.offset.top = e.offsetTop), i.call(t, e) }) }) }(jQuery);;
"use strict";!function(){function keydown(e){var id,k=e?e.keyCode:event.keyCode;if(!held[k]){held[k]=!0;for(id in sequences)sequences[id].keydown(k)}}function keyup(e){var k=e?e.keyCode:event.keyCode;held[k]=!1}function reset(){var k;for(k in held)held[k]=!1}function on(obj,type,fn){obj.addEventListener?obj.addEventListener(type,fn,!1):obj.attachEvent&&(obj["e"+type+fn]=fn,obj[type+fn]=function(){obj["e"+type+fn](window.event)},obj.attachEvent("on"+type,obj[type+fn]))}var cheet,Sequence,sequences={},keys={backspace:8,tab:9,enter:13,"return":13,shift:16,"⇧":16,control:17,ctrl:17,"⌃":17,alt:18,option:18,"⌥":18,pause:19,capslock:20,esc:27,space:32,pageup:33,pagedown:34,end:35,home:36,left:37,L:37,"←":37,up:38,U:38,"↑":38,right:39,R:39,"→":39,down:40,D:40,"↓":40,insert:45,"delete":46,0:48,1:49,2:50,3:51,4:52,5:53,6:54,7:55,8:56,9:57,a:65,b:66,c:67,d:68,e:69,f:70,g:71,h:72,i:73,j:74,k:75,l:76,m:77,n:78,o:79,p:80,q:81,r:82,s:83,t:84,u:85,v:86,w:87,x:88,y:89,z:90,"⌘":91,command:91,kp_0:96,kp_1:97,kp_2:98,kp_3:99,kp_4:100,kp_5:101,kp_6:102,kp_7:103,kp_8:104,kp_9:105,kp_multiply:106,kp_plus:107,kp_minus:109,kp_decimal:110,kp_divide:111,f1:112,f2:113,f3:114,f4:115,f5:116,f6:117,f7:118,f8:119,f9:120,f10:121,f11:122,f12:123,equal:187,"=":187,comma:188,",":188,minus:189,"-":189,period:190,".":190},NOOP=function(){},held={};Sequence=function(str,next,fail,done){var i;for(this.str=str,this.next=next?next:NOOP,this.fail=fail?fail:NOOP,this.done=done?done:NOOP,this.seq=str.split(" "),this.keys=[],i=0;i<this.seq.length;++i)this.keys.push(keys[this.seq[i]]);this.idx=0},Sequence.prototype.keydown=function(keyCode){var i=this.idx;return keyCode!==this.keys[i]?(i>0&&(this.idx=0,this.fail(this.str),cheet.__fail(this.str)),void 0):(this.next(this.str,this.seq[i],i,this.seq),cheet.__next(this.str,this.seq[i],i,this.seq),++this.idx===this.keys.length&&(this.done(this.str),cheet.__done(this.str),this.idx=0),void 0)},cheet=function(str,handlers){var next,fail,done;"function"==typeof handlers?done=handlers:null!=handlers&&(next=handlers.next,fail=handlers.fail,done=handlers.done),sequences[str]=new Sequence(str,next,fail,done)},cheet.disable=function(str){delete sequences[str]},on(window,"keydown",keydown),on(window,"keyup",keyup),on(window,"blur",reset),on(window,"focus",reset),cheet.__next=NOOP,cheet.next=function(fn){cheet.__next=null===fn?NOOP:fn},cheet.__fail=NOOP,cheet.fail=function(fn){cheet.__fail=null===fn?NOOP:fn},cheet.__done=NOOP,cheet.done=function(fn){cheet.__done=null===fn?NOOP:fn},window.cheet=cheet,"undefined"!=typeof module&&(module.exports=cheet)}();;
/**!

 @license
 handlebars v4.7.2

Copyright (C) 2011-2019 by Yehuda Katz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

*/
!function(a,b){"object"==typeof exports&&"object"==typeof module?module.exports=b():"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?exports.Handlebars=b():a.Handlebars=b()}(this,function(){return function(a){function b(d){if(c[d])return c[d].exports;var e=c[d]={exports:{},id:d,loaded:!1};return a[d].call(e.exports,e,e.exports,b),e.loaded=!0,e.exports}var c={};return b.m=a,b.c=c,b.p="",b(0)}([function(a,b,c){"use strict";function d(){var a=r();return a.compile=function(b,c){return k.compile(b,c,a)},a.precompile=function(b,c){return k.precompile(b,c,a)},a.AST=i["default"],a.Compiler=k.Compiler,a.JavaScriptCompiler=m["default"],a.Parser=j.parser,a.parse=j.parse,a.parseWithoutProcessing=j.parseWithoutProcessing,a}var e=c(1)["default"];b.__esModule=!0;var f=c(2),g=e(f),h=c(45),i=e(h),j=c(46),k=c(51),l=c(52),m=e(l),n=c(49),o=e(n),p=c(44),q=e(p),r=g["default"].create,s=d();s.create=d,q["default"](s),s.Visitor=o["default"],s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){return a&&a.__esModule?a:{"default":a}},b.__esModule=!0},function(a,b,c){"use strict";function d(){var a=new h.HandlebarsEnvironment;return n.extend(a,h),a.SafeString=j["default"],a.Exception=l["default"],a.Utils=n,a.escapeExpression=n.escapeExpression,a.VM=p,a.template=function(b){return p.template(b,a)},a}var e=c(3)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(4),h=e(g),i=c(37),j=f(i),k=c(6),l=f(k),m=c(5),n=e(m),o=c(38),p=e(o),q=c(44),r=f(q),s=d();s.create=d,r["default"](s),s["default"]=s,b["default"]=s,a.exports=b["default"]},function(a,b){"use strict";b["default"]=function(a){if(a&&a.__esModule)return a;var b={};if(null!=a)for(var c in a)Object.prototype.hasOwnProperty.call(a,c)&&(b[c]=a[c]);return b["default"]=a,b},b.__esModule=!0},function(a,b,c){"use strict";function d(a,b,c){this.helpers=a||{},this.partials=b||{},this.decorators=c||{},i.registerDefaultHelpers(this),j.registerDefaultDecorators(this)}var e=c(1)["default"];b.__esModule=!0,b.HandlebarsEnvironment=d;var f=c(5),g=c(6),h=e(g),i=c(10),j=c(30),k=c(32),l=e(k),m=c(33),n="4.7.2";b.VERSION=n;var o=8;b.COMPILER_REVISION=o;var p=7;b.LAST_COMPATIBLE_COMPILER_REVISION=p;var q={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0 <4.3.0",8:">= 4.3.0"};b.REVISION_CHANGES=q;var r="[object Object]";d.prototype={constructor:d,logger:l["default"],log:l["default"].log,registerHelper:function(a,b){if(f.toString.call(a)===r){if(b)throw new h["default"]("Arg not supported with multiple helpers");f.extend(this.helpers,a)}else this.helpers[a]=b},unregisterHelper:function(a){delete this.helpers[a]},registerPartial:function(a,b){if(f.toString.call(a)===r)f.extend(this.partials,a);else{if("undefined"==typeof b)throw new h["default"]('Attempting to register a partial called "'+a+'" as undefined');this.partials[a]=b}},unregisterPartial:function(a){delete this.partials[a]},registerDecorator:function(a,b){if(f.toString.call(a)===r){if(b)throw new h["default"]("Arg not supported with multiple decorators");f.extend(this.decorators,a)}else this.decorators[a]=b},unregisterDecorator:function(a){delete this.decorators[a]},resetLoggedPropertyAccesses:function(){m.resetLoggedProperties()}};var s=l["default"].log;b.log=s,b.createFrame=f.createFrame,b.logger=l["default"]},function(a,b){"use strict";function c(a){return k[a]}function d(a){for(var b=1;b<arguments.length;b++)for(var c in arguments[b])Object.prototype.hasOwnProperty.call(arguments[b],c)&&(a[c]=arguments[b][c]);return a}function e(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1}function f(a){if("string"!=typeof a){if(a&&a.toHTML)return a.toHTML();if(null==a)return"";if(!a)return a+"";a=""+a}return m.test(a)?a.replace(l,c):a}function g(a){return!a&&0!==a||!(!p(a)||0!==a.length)}function h(a){var b=d({},a);return b._parent=a,b}function i(a,b){return a.path=b,a}function j(a,b){return(a?a+".":"")+b}b.__esModule=!0,b.extend=d,b.indexOf=e,b.escapeExpression=f,b.isEmpty=g,b.createFrame=h,b.blockParams=i,b.appendContextPath=j;var k={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},l=/[&<>"'`=]/g,m=/[&<>"'`=]/,n=Object.prototype.toString;b.toString=n;var o=function(a){return"function"==typeof a};o(/x/)&&(b.isFunction=o=function(a){return"function"==typeof a&&"[object Function]"===n.call(a)}),b.isFunction=o;var p=Array.isArray||function(a){return!(!a||"object"!=typeof a)&&"[object Array]"===n.call(a)};b.isArray=p},function(a,b,c){"use strict";function d(a,b){var c=b&&b.loc,g=void 0,h=void 0,i=void 0,j=void 0;c&&(g=c.start.line,h=c.end.line,i=c.start.column,j=c.end.column,a+=" - "+g+":"+i);for(var k=Error.prototype.constructor.call(this,a),l=0;l<f.length;l++)this[f[l]]=k[f[l]];Error.captureStackTrace&&Error.captureStackTrace(this,d);try{c&&(this.lineNumber=g,this.endLineNumber=h,e?(Object.defineProperty(this,"column",{value:i,enumerable:!0}),Object.defineProperty(this,"endColumn",{value:j,enumerable:!0})):(this.column=i,this.endColumn=j))}catch(m){}}var e=c(7)["default"];b.__esModule=!0;var f=["description","fileName","lineNumber","endLineNumber","message","name","number","stack"];d.prototype=new Error,b["default"]=d,a.exports=b["default"]},function(a,b,c){a.exports={"default":c(8),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b,c){return d.setDesc(a,b,c)}},function(a,b){var c=Object;a.exports={create:c.create,getProto:c.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:c.getOwnPropertyDescriptor,setDesc:c.defineProperty,setDescs:c.defineProperties,getKeys:c.keys,getNames:c.getOwnPropertyNames,getSymbols:c.getOwnPropertySymbols,each:[].forEach}},function(a,b,c){"use strict";function d(a){h["default"](a),j["default"](a),l["default"](a),n["default"](a),p["default"](a),r["default"](a),t["default"](a)}function e(a,b,c){a.helpers[b]&&(a.hooks[b]=a.helpers[b],c||delete a.helpers[b])}var f=c(1)["default"];b.__esModule=!0,b.registerDefaultHelpers=d,b.moveHelperToHooks=e;var g=c(11),h=f(g),i=c(12),j=f(i),k=c(25),l=f(k),m=c(26),n=f(m),o=c(27),p=f(o),q=c(28),r=f(q),s=c(29),t=f(s)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerHelper("blockHelperMissing",function(b,c){var e=c.inverse,f=c.fn;if(b===!0)return f(this);if(b===!1||null==b)return e(this);if(d.isArray(b))return b.length>0?(c.ids&&(c.ids=[c.name]),a.helpers.each(b,c)):e(this);if(c.data&&c.ids){var g=d.createFrame(c.data);g.contextPath=d.appendContextPath(c.data.contextPath,c.name),c={data:g}}return f(b,c)})},a.exports=b["default"]},function(a,b,c){(function(d){"use strict";var e=c(13)["default"],f=c(1)["default"];b.__esModule=!0;var g=c(5),h=c(6),i=f(h);b["default"]=function(a){a.registerHelper("each",function(a,b){function c(b,c,d){l&&(l.key=b,l.index=c,l.first=0===c,l.last=!!d,m&&(l.contextPath=m+b)),k+=f(a[b],{data:l,blockParams:g.blockParams([a[b],b],[m+b,null])})}if(!b)throw new i["default"]("Must pass iterator to #each");var f=b.fn,h=b.inverse,j=0,k="",l=void 0,m=void 0;if(b.data&&b.ids&&(m=g.appendContextPath(b.data.contextPath,b.ids[0])+"."),g.isFunction(a)&&(a=a.call(this)),b.data&&(l=g.createFrame(b.data)),a&&"object"==typeof a)if(g.isArray(a))for(var n=a.length;j<n;j++)j in a&&c(j,j,j===a.length-1);else if(d.Symbol&&a[d.Symbol.iterator]){for(var o=[],p=a[d.Symbol.iterator](),q=p.next();!q.done;q=p.next())o.push(q.value);a=o;for(var n=a.length;j<n;j++)c(j,j,j===a.length-1)}else!function(){var b=void 0;e(a).forEach(function(a){void 0!==b&&c(b,j-1),b=a,j++}),void 0!==b&&c(b,j-1,!0)}();return 0===j&&(k=h(this)),k})},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b,c){a.exports={"default":c(14),__esModule:!0}},function(a,b,c){c(15),a.exports=c(21).Object.keys},function(a,b,c){var d=c(16);c(18)("keys",function(a){return function(b){return a(d(b))}})},function(a,b,c){var d=c(17);a.exports=function(a){return Object(d(a))}},function(a,b){a.exports=function(a){if(void 0==a)throw TypeError("Can't call method on  "+a);return a}},function(a,b,c){var d=c(19),e=c(21),f=c(24);a.exports=function(a,b){var c=(e.Object||{})[a]||Object[a],g={};g[a]=b(c),d(d.S+d.F*f(function(){c(1)}),"Object",g)}},function(a,b,c){var d=c(20),e=c(21),f=c(22),g="prototype",h=function(a,b,c){var i,j,k,l=a&h.F,m=a&h.G,n=a&h.S,o=a&h.P,p=a&h.B,q=a&h.W,r=m?e:e[b]||(e[b]={}),s=m?d:n?d[b]:(d[b]||{})[g];m&&(c=b);for(i in c)j=!l&&s&&i in s,j&&i in r||(k=j?s[i]:c[i],r[i]=m&&"function"!=typeof s[i]?c[i]:p&&j?f(k,d):q&&s[i]==k?function(a){var b=function(b){return this instanceof a?new a(b):a(b)};return b[g]=a[g],b}(k):o&&"function"==typeof k?f(Function.call,k):k,o&&((r[g]||(r[g]={}))[i]=k))};h.F=1,h.G=2,h.S=4,h.P=8,h.B=16,h.W=32,a.exports=h},function(a,b){var c=a.exports="undefined"!=typeof window&&window.Math==Math?window:"undefined"!=typeof self&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=c)},function(a,b){var c=a.exports={version:"1.2.6"};"number"==typeof __e&&(__e=c)},function(a,b,c){var d=c(23);a.exports=function(a,b,c){if(d(a),void 0===b)return a;switch(c){case 1:return function(c){return a.call(b,c)};case 2:return function(c,d){return a.call(b,c,d)};case 3:return function(c,d,e){return a.call(b,c,d,e)}}return function(){return a.apply(b,arguments)}}},function(a,b){a.exports=function(a){if("function"!=typeof a)throw TypeError(a+" is not a function!");return a}},function(a,b){a.exports=function(a){try{return!!a()}catch(b){return!0}}},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(6),f=d(e);b["default"]=function(a){a.registerHelper("helperMissing",function(){if(1!==arguments.length)throw new f["default"]('Missing helper: "'+arguments[arguments.length-1].name+'"')})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("if",function(a,b){if(2!=arguments.length)throw new g["default"]("#if requires exactly one argument");return e.isFunction(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||e.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){if(2!=arguments.length)throw new g["default"]("#unless requires exactly one argument");return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("log",function(){for(var b=[void 0],c=arguments[arguments.length-1],d=0;d<arguments.length-1;d++)b.push(arguments[d]);var e=1;null!=c.hash.level?e=c.hash.level:c.data&&null!=c.data.level&&(e=c.data.level),b[0]=e,a.log.apply(a,b)})},a.exports=b["default"]},function(a,b){"use strict";b.__esModule=!0,b["default"]=function(a){a.registerHelper("lookup",function(a,b,c){return a?c.lookupProperty(a,b):a})},a.exports=b["default"]},function(a,b,c){"use strict";var d=c(1)["default"];b.__esModule=!0;var e=c(5),f=c(6),g=d(f);b["default"]=function(a){a.registerHelper("with",function(a,b){if(2!=arguments.length)throw new g["default"]("#with requires exactly one argument");e.isFunction(a)&&(a=a.call(this));var c=b.fn;if(e.isEmpty(a))return b.inverse(this);var d=b.data;return b.data&&b.ids&&(d=e.createFrame(b.data),d.contextPath=e.appendContextPath(b.data.contextPath,b.ids[0])),c(a,{data:d,blockParams:e.blockParams([a],[d&&d.contextPath])})})},a.exports=b["default"]},function(a,b,c){"use strict";function d(a){g["default"](a)}var e=c(1)["default"];b.__esModule=!0,b.registerDefaultDecorators=d;var f=c(31),g=e(f)},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5);b["default"]=function(a){a.registerDecorator("inline",function(a,b,c,e){var f=a;return b.partials||(b.partials={},f=function(e,f){var g=c.partials;c.partials=d.extend({},g,b.partials);var h=a(e,f);return c.partials=g,h}),b.partials[e.args[0]]=e.fn,f})},a.exports=b["default"]},function(a,b,c){"use strict";b.__esModule=!0;var d=c(5),e={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(a){if("string"==typeof a){var b=d.indexOf(e.methodMap,a.toLowerCase());a=b>=0?b:parseInt(a,10)}return a},log:function(a){if(a=e.lookupLevel(a),"undefined"!=typeof console&&e.lookupLevel(e.level)<=a){var b=e.methodMap[a];console[b]||(b="log");for(var c=arguments.length,d=Array(c>1?c-1:0),f=1;f<c;f++)d[f-1]=arguments[f];console[b].apply(console,d)}}};b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=i(null);b.constructor=!1,b.__defineGetter__=!1,b.__defineSetter__=!1,b.__lookupGetter__=!1;var c=i(null);return c.__proto__=!1,{properties:{whitelist:l.createNewLookupObject(c,a.allowedProtoProperties),defaultValue:a.allowProtoPropertiesByDefault},methods:{whitelist:l.createNewLookupObject(b,a.allowedProtoMethods),defaultValue:a.allowProtoMethodsByDefault}}}function e(a,b,c){return"function"==typeof a?f(b.methods,c):f(b.properties,c)}function f(a,b){return void 0!==a.whitelist[b]?a.whitelist[b]===!0:void 0!==a.defaultValue?a.defaultValue:(g(b),!1)}function g(a){o[a]!==!0&&(o[a]=!0,n.log("error",'Handlebars: Access has been denied to resolve the property "'+a+'" because it is not an "own property" of its parent.\nYou can add a runtime option to disable the check or this warning:\nSee https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details'))}function h(){j(o).forEach(function(a){delete o[a]})}var i=c(34)["default"],j=c(13)["default"],k=c(3)["default"];b.__esModule=!0,b.createProtoAccessControl=d,b.resultIsAllowed=e,b.resetLoggedProperties=h;var l=c(36),m=c(32),n=k(m),o=i(null)},function(a,b,c){a.exports={"default":c(35),__esModule:!0}},function(a,b,c){var d=c(9);a.exports=function(a,b){return d.create(a,b)}},function(a,b,c){"use strict";function d(){for(var a=arguments.length,b=Array(a),c=0;c<a;c++)b[c]=arguments[c];return f.extend.apply(void 0,[e(null)].concat(b))}var e=c(34)["default"];b.__esModule=!0,b.createNewLookupObject=d;var f=c(5)},function(a,b){"use strict";function c(a){this.string=a}b.__esModule=!0,c.prototype.toString=c.prototype.toHTML=function(){return""+this.string},b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a){var b=a&&a[0]||1,c=v.COMPILER_REVISION;if(!(b>=v.LAST_COMPATIBLE_COMPILER_REVISION&&b<=v.COMPILER_REVISION)){if(b<v.LAST_COMPATIBLE_COMPILER_REVISION){var d=v.REVISION_CHANGES[c],e=v.REVISION_CHANGES[b];throw new u["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+d+") or downgrade your runtime to an older version ("+e+").")}throw new u["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){function c(c,d,e){e.hash&&(d=s.extend({},d,e.hash),e.ids&&(e.ids[0]=!0)),c=b.VM.resolvePartial.call(this,c,d,e);var f=s.extend({},e,{hooks:this.hooks,protoAccessControl:this.protoAccessControl}),g=b.VM.invokePartial.call(this,c,d,f);if(null==g&&b.compile&&(e.partials[e.name]=b.compile(c,a.compilerOptions,b),g=e.partials[e.name](d,f)),null!=g){if(e.indent){for(var h=g.split("\n"),i=0,j=h.length;i<j&&(h[i]||i+1!==j);i++)h[i]=e.indent+h[i];g=h.join("\n")}return g}throw new u["default"]("The partial "+e.name+" could not be compiled when running in runtime-only mode")}function d(b){function c(b){return""+a.main(g,b,g.helpers,g.partials,f,i,h)}var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],f=e.data;d._setup(e),!e.partial&&a.useData&&(f=j(b,f));var h=void 0,i=a.useBlockParams?[]:void 0;return a.useDepths&&(h=e.depths?b!=e.depths[0]?[b].concat(e.depths):e.depths:[b]),(c=k(a.main,c,g,e.depths||[],f,i))(b,e)}if(!b)throw new u["default"]("No environment passed to template");if(!a||!a.main)throw new u["default"]("Unknown template object: "+typeof a);a.main.decorator=a.main_d,b.VM.checkRevision(a.compiler);var e=a.compiler&&7===a.compiler[0],g={strict:function(a,b,c){if(!(a&&b in a))throw new u["default"]('"'+b+'" not defined in '+a,{loc:c});return a[b]},lookupProperty:function(a,b){var c=a[b];return null==c?c:Object.prototype.hasOwnProperty.call(a,b)?c:y.resultIsAllowed(c,g.protoAccessControl,b)?c:void 0},lookup:function(a,b){for(var c=a.length,d=0;d<c;d++){var e=a[d]&&g.lookupProperty(a[d],b);if(null!=e)return a[d][b]}},lambda:function(a,b){return"function"==typeof a?a.call(b):a},escapeExpression:s.escapeExpression,invokePartial:c,fn:function(b){var c=a[b];return c.decorator=a[b+"_d"],c},programs:[],program:function(a,b,c,d,e){var g=this.programs[a],h=this.fn(a);return b||e||d||c?g=f(this,a,h,b,c,d,e):g||(g=this.programs[a]=f(this,a,h)),g},data:function(a,b){for(;a&&b--;)a=a._parent;return a},mergeIfNeeded:function(a,b){var c=a||b;return a&&b&&a!==b&&(c=s.extend({},b,a)),c},nullContext:n({}),noop:b.VM.noop,compilerInfo:a.compiler};return d.isTop=!0,d._setup=function(c){if(c.partial)g.protoAccessControl=c.protoAccessControl,g.helpers=c.helpers,g.partials=c.partials,g.decorators=c.decorators,g.hooks=c.hooks;else{var d=s.extend({},b.helpers,c.helpers);l(d,g),g.helpers=d,a.usePartial&&(g.partials=g.mergeIfNeeded(c.partials,b.partials)),(a.usePartial||a.useDecorators)&&(g.decorators=s.extend({},b.decorators,c.decorators)),g.hooks={},g.protoAccessControl=y.createProtoAccessControl(c);var f=c.allowCallsToHelperMissing||e;w.moveHelperToHooks(g,"helperMissing",f),w.moveHelperToHooks(g,"blockHelperMissing",f)}},d._child=function(b,c,d,e){if(a.useBlockParams&&!d)throw new u["default"]("must pass block params");if(a.useDepths&&!e)throw new u["default"]("must pass parent depths");return f(g,b,a[b],c,0,d,e)},d}function f(a,b,c,d,e,f,g){function h(b){var e=arguments.length<=1||void 0===arguments[1]?{}:arguments[1],h=g;return!g||b==g[0]||b===a.nullContext&&null===g[0]||(h=[b].concat(g)),c(a,b,a.helpers,a.partials,e.data||d,f&&[e.blockParams].concat(f),h)}return h=k(c,h,a,g,d,f),h.program=b,h.depth=g?g.length:0,h.blockParams=e||0,h}function g(a,b,c){return a?a.call||c.name||(c.name=a,a=c.partials[a]):a="@partial-block"===c.name?c.data["partial-block"]:c.partials[c.name],a}function h(a,b,c){var d=c.data&&c.data["partial-block"];c.partial=!0,c.ids&&(c.data.contextPath=c.ids[0]||c.data.contextPath);var e=void 0;if(c.fn&&c.fn!==i&&!function(){c.data=v.createFrame(c.data);var a=c.fn;e=c.data["partial-block"]=function(b){var c=arguments.length<=1||void 0===arguments[1]?{}:arguments[1];return c.data=v.createFrame(c.data),c.data["partial-block"]=d,a(b,c)},a.partials&&(c.partials=s.extend({},c.partials,a.partials))}(),void 0===a&&e&&(a=e),void 0===a)throw new u["default"]("The partial "+c.name+" could not be found");if(a instanceof Function)return a(b,c)}function i(){return""}function j(a,b){return b&&"root"in b||(b=b?v.createFrame(b):{},b.root=a),b}function k(a,b,c,d,e,f){if(a.decorator){var g={};b=a.decorator(b,g,c,d&&d[0],e,f,d),s.extend(b,g)}return b}function l(a,b){o(a).forEach(function(c){var d=a[c];a[c]=m(d,b)})}function m(a,b){var c=b.lookupProperty;return x.wrapHelper(a,function(a){return s.extend({lookupProperty:c},a)})}var n=c(39)["default"],o=c(13)["default"],p=c(3)["default"],q=c(1)["default"];b.__esModule=!0,b.checkRevision=d,b.template=e,b.wrapProgram=f,b.resolvePartial=g,b.invokePartial=h,b.noop=i;var r=c(5),s=p(r),t=c(6),u=q(t),v=c(4),w=c(10),x=c(43),y=c(33)},function(a,b,c){a.exports={"default":c(40),__esModule:!0}},function(a,b,c){c(41),a.exports=c(21).Object.seal},function(a,b,c){var d=c(42);c(18)("seal",function(a){return function(b){return a&&d(b)?a(b):b}})},function(a,b){a.exports=function(a){return"object"==typeof a?null!==a:"function"==typeof a}},function(a,b){"use strict";function c(a,b){if("function"!=typeof a)return a;var c=function(){var c=arguments[arguments.length-1];return arguments[arguments.length-1]=b(c),a.apply(this,arguments)};return c}b.__esModule=!0,b.wrapHelper=c},function(a,b){(function(c){"use strict";b.__esModule=!0,b["default"]=function(a){var b="undefined"!=typeof c?c:window,d=b.Handlebars;a.noConflict=function(){return b.Handlebars===a&&(b.Handlebars=d),a}},a.exports=b["default"]}).call(b,function(){return this}())},function(a,b){"use strict";b.__esModule=!0;var c={helpers:{helperExpression:function(a){return"SubExpression"===a.type||("MustacheStatement"===a.type||"BlockStatement"===a.type)&&!!(a.params&&a.params.length||a.hash)},scopedId:function(a){return/^\.|this\b/.test(a.original)},simpleId:function(a){return 1===a.parts.length&&!c.helpers.scopedId(a)&&!a.depth}}};b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if("Program"===a.type)return a;i["default"].yy=o,o.locInfo=function(a){return new o.SourceLocation(b&&b.srcName,a)};var c=i["default"].parse(a);return c}function e(a,b){var c=d(a,b),e=new k["default"](b);return e.accept(c)}var f=c(1)["default"],g=c(3)["default"];b.__esModule=!0,b.parseWithoutProcessing=d,b.parse=e;var h=c(47),i=f(h),j=c(48),k=f(j),l=c(50),m=g(l),n=c(5);b.parser=i["default"];var o={};n.extend(o,m)},function(a,b){"use strict";b.__esModule=!0;var c=function(){function a(){this.yy={}}var b={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,0],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(a,b,c,d,e,f,g){var h=f.length-1;switch(e){case 1:return f[h-1];case 2:this.$=d.prepareProgram(f[h]);break;case 3:this.$=f[h];break;case 4:this.$=f[h];break;case 5:this.$=f[h];break;case 6:this.$=f[h];break;case 7:this.$=f[h];break;case 8:this.$=f[h];break;case 9:this.$={type:"CommentStatement",value:d.stripComment(f[h]),strip:d.stripFlags(f[h],f[h]),loc:d.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:f[h],value:f[h],loc:d.locInfo(this._$)};break;case 11:this.$=d.prepareRawBlock(f[h-2],f[h-1],f[h],this._$);break;case 12:this.$={path:f[h-3],params:f[h-2],hash:f[h-1]};break;case 13:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!1,this._$);break;case 14:this.$=d.prepareBlock(f[h-3],f[h-2],f[h-1],f[h],!0,this._$);break;case 15:this.$={open:f[h-5],path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 16:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 17:this.$={path:f[h-4],params:f[h-3],hash:f[h-2],blockParams:f[h-1],strip:d.stripFlags(f[h-5],f[h])};break;case 18:this.$={strip:d.stripFlags(f[h-1],f[h-1]),program:f[h]};break;case 19:var i=d.prepareBlock(f[h-2],f[h-1],f[h],f[h],!1,this._$),j=d.prepareProgram([i],f[h-1].loc);j.chained=!0,this.$={strip:f[h-2].strip,program:j,chain:!0};break;case 20:this.$=f[h];break;case 21:this.$={path:f[h-1],strip:d.stripFlags(f[h-2],f[h])};break;case 22:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 23:this.$=d.prepareMustache(f[h-3],f[h-2],f[h-1],f[h-4],d.stripFlags(f[h-4],f[h]),this._$);break;case 24:this.$={type:"PartialStatement",name:f[h-3],params:f[h-2],hash:f[h-1],indent:"",strip:d.stripFlags(f[h-4],f[h]),loc:d.locInfo(this._$)};break;case 25:this.$=d.preparePartialBlock(f[h-2],f[h-1],f[h],this._$);break;case 26:this.$={path:f[h-3],params:f[h-2],hash:f[h-1],strip:d.stripFlags(f[h-4],f[h])};break;case 27:this.$=f[h];break;case 28:this.$=f[h];break;case 29:this.$={type:"SubExpression",path:f[h-3],params:f[h-2],hash:f[h-1],loc:d.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:f[h],loc:d.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:d.id(f[h-2]),value:f[h],loc:d.locInfo(this._$)};break;case 32:this.$=d.id(f[h-1]);break;case 33:this.$=f[h];break;case 34:this.$=f[h];break;case 35:this.$={type:"StringLiteral",value:f[h],original:f[h],loc:d.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(f[h]),original:Number(f[h]),loc:d.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:"true"===f[h],original:"true"===f[h],loc:d.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:d.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:d.locInfo(this._$)};break;case 40:this.$=f[h];break;case 41:this.$=f[h];break;case 42:this.$=d.preparePath(!0,f[h],this._$);break;case 43:this.$=d.preparePath(!1,f[h],this._$);break;case 44:f[h-2].push({part:d.id(f[h]),original:f[h],separator:f[h-1]}),this.$=f[h-2];break;case 45:this.$=[{part:d.id(f[h]),original:f[h]}];break;case 46:this.$=[];break;case 47:f[h-1].push(f[h]);break;case 48:this.$=[];break;case 49:f[h-1].push(f[h]);break;case 50:this.$=[];break;case 51:f[h-1].push(f[h]);break;case 58:this.$=[];break;case 59:f[h-1].push(f[h]);break;case 64:this.$=[];break;case 65:f[h-1].push(f[h]);break;case 70:this.$=[];break;case 71:f[h-1].push(f[h]);break;case 78:this.$=[];break;case 79:f[h-1].push(f[h]);break;case 82:this.$=[];break;case 83:f[h-1].push(f[h]);break;case 86:this.$=[];break;case 87:f[h-1].push(f[h]);break;case 90:this.$=[];break;case 91:f[h-1].push(f[h]);break;case 94:this.$=[];break;case 95:f[h-1].push(f[h]);break;case 98:this.$=[f[h]];break;case 99:f[h-1].push(f[h]);break;case 100:this.$=[f[h]];break;case 101:f[h-1].push(f[h])}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{15:[2,48],17:39,18:[2,48]},{20:41,56:40,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:44,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:45,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:41,56:48,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:49,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,50]},{72:[1,35],86:51},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:52,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:53,38:55,39:[1,57],43:56,44:[1,58],45:54,47:[2,54]},{28:59,43:60,44:[1,58],47:[2,56]},{13:62,15:[1,20],18:[1,61]},{33:[2,86],57:63,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],
72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:64,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:65,47:[1,66]},{30:67,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:68,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:69,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:70,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:74,33:[2,80],50:71,63:72,64:75,65:[1,43],69:73,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,79]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,50]},{20:74,53:80,54:[2,84],63:81,64:75,65:[1,43],69:82,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:83,47:[1,66]},{47:[2,55]},{4:84,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:85,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:86,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:87,47:[1,66]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:74,33:[2,88],58:88,63:89,64:75,65:[1,43],69:90,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:91,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:92,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,31:93,33:[2,60],63:94,64:75,65:[1,43],69:95,70:76,71:77,72:[1,78],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,66],36:96,63:97,64:75,65:[1,43],69:98,70:76,71:77,72:[1,78],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,22:99,23:[2,52],63:100,64:75,65:[1,43],69:101,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,92],62:102,63:103,64:75,65:[1,43],69:104,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,105]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:106,72:[1,107],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,108],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,109]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:55,39:[1,57],43:56,44:[1,58],45:111,46:110,47:[2,76]},{33:[2,70],40:112,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,113]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],85:[2,87]},{33:[2,89]},{20:74,63:115,64:75,65:[1,43],67:114,68:[2,96],69:116,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,117]},{32:118,33:[2,62],74:119,75:[1,120]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:121,74:122,75:[1,120]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,123]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,124]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,108]},{20:74,63:125,64:75,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:74,33:[2,72],41:126,63:127,64:75,65:[1,43],69:128,70:76,71:77,72:[1,78],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,129]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,130]},{33:[2,63]},{72:[1,132],76:131},{33:[1,133]},{33:[2,69]},{15:[2,12],18:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:134,74:135,75:[1,120]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,137],77:[1,136]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,138]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],54:[2,55],56:[2,20],60:[2,57],73:[2,81],82:[2,85],86:[2,18],90:[2,89],101:[2,53],104:[2,93],110:[2,19],111:[2,77],116:[2,97],119:[2,63],122:[2,69],135:[2,75],136:[2,32]},parseError:function(a,b){throw new Error(a)},parse:function(a){function b(){var a;return a=c.lexer.lex()||1,"number"!=typeof a&&(a=c.symbols_[a]||a),a}var c=this,d=[0],e=[null],f=[],g=this.table,h="",i=0,j=0,k=0;this.lexer.setInput(a),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,"undefined"==typeof this.lexer.yylloc&&(this.lexer.yylloc={});var l=this.lexer.yylloc;f.push(l);var m=this.lexer.options&&this.lexer.options.ranges;"function"==typeof this.yy.parseError&&(this.parseError=this.yy.parseError);for(var n,o,p,q,r,s,t,u,v,w={};;){if(p=d[d.length-1],this.defaultActions[p]?q=this.defaultActions[p]:(null!==n&&"undefined"!=typeof n||(n=b()),q=g[p]&&g[p][n]),"undefined"==typeof q||!q.length||!q[0]){var x="";if(!k){v=[];for(s in g[p])this.terminals_[s]&&s>2&&v.push("'"+this.terminals_[s]+"'");x=this.lexer.showPosition?"Parse error on line "+(i+1)+":\n"+this.lexer.showPosition()+"\nExpecting "+v.join(", ")+", got '"+(this.terminals_[n]||n)+"'":"Parse error on line "+(i+1)+": Unexpected "+(1==n?"end of input":"'"+(this.terminals_[n]||n)+"'"),this.parseError(x,{text:this.lexer.match,token:this.terminals_[n]||n,line:this.lexer.yylineno,loc:l,expected:v})}}if(q[0]instanceof Array&&q.length>1)throw new Error("Parse Error: multiple actions possible at state: "+p+", token: "+n);switch(q[0]){case 1:d.push(n),e.push(this.lexer.yytext),f.push(this.lexer.yylloc),d.push(q[1]),n=null,o?(n=o,o=null):(j=this.lexer.yyleng,h=this.lexer.yytext,i=this.lexer.yylineno,l=this.lexer.yylloc,k>0&&k--);break;case 2:if(t=this.productions_[q[1]][1],w.$=e[e.length-t],w._$={first_line:f[f.length-(t||1)].first_line,last_line:f[f.length-1].last_line,first_column:f[f.length-(t||1)].first_column,last_column:f[f.length-1].last_column},m&&(w._$.range=[f[f.length-(t||1)].range[0],f[f.length-1].range[1]]),r=this.performAction.call(w,h,j,i,this.yy,q[1],e,f),"undefined"!=typeof r)return r;t&&(d=d.slice(0,-1*t*2),e=e.slice(0,-1*t),f=f.slice(0,-1*t)),d.push(this.productions_[q[1]][0]),e.push(w.$),f.push(w._$),u=g[d[d.length-2]][d[d.length-1]],d.push(u);break;case 3:return!0}}return!0}},c=function(){var a={EOF:1,parseError:function(a,b){if(!this.yy.parser)throw new Error(a);this.yy.parser.parseError(a,b)},setInput:function(a){return this._input=a,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var a=this._input[0];this.yytext+=a,this.yyleng++,this.offset++,this.match+=a,this.matched+=a;var b=a.match(/(?:\r\n?|\n).*/g);return b?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),a},unput:function(a){var b=a.length,c=a.split(/(?:\r\n?|\n)/g);this._input=a+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-b-1),this.offset-=b;var d=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),c.length-1&&(this.yylineno-=c.length-1);var e=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:c?(c.length===d.length?this.yylloc.first_column:0)+d[d.length-c.length].length-c[0].length:this.yylloc.first_column-b},this.options.ranges&&(this.yylloc.range=[e[0],e[0]+this.yyleng-b]),this},more:function(){return this._more=!0,this},less:function(a){this.unput(this.match.slice(a))},pastInput:function(){var a=this.matched.substr(0,this.matched.length-this.match.length);return(a.length>20?"...":"")+a.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var a=this.match;return a.length<20&&(a+=this._input.substr(0,20-a.length)),(a.substr(0,20)+(a.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var a=this.pastInput(),b=new Array(a.length+1).join("-");return a+this.upcomingInput()+"\n"+b+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var a,b,c,d,e;this._more||(this.yytext="",this.match="");for(var f=this._currentRules(),g=0;g<f.length&&(c=this._input.match(this.rules[f[g]]),!c||b&&!(c[0].length>b[0].length)||(b=c,d=g,this.options.flex));g++);return b?(e=b[0].match(/(?:\r\n?|\n).*/g),e&&(this.yylineno+=e.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:e?e[e.length-1].length-e[e.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+b[0].length},this.yytext+=b[0],this.match+=b[0],this.matches=b,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(b[0].length),this.matched+=b[0],a=this.performAction.call(this,this.yy,this,f[d],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),a?a:void 0):""===this._input?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+". Unrecognized text.\n"+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var a=this.next();return"undefined"!=typeof a?a:this.lex()},begin:function(a){this.conditionStack.push(a)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(a){this.begin(a)}};return a.options={},a.performAction=function(a,b,c,d){function e(a,c){return b.yytext=b.yytext.substring(a,b.yyleng-c+a)}switch(c){case 0:if("\\\\"===b.yytext.slice(-2)?(e(0,1),this.begin("mu")):"\\"===b.yytext.slice(-1)?(e(0,1),this.begin("emu")):this.begin("mu"),b.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;case 3:return this.begin("raw"),15;case 4:return this.popState(),"raw"===this.conditionStack[this.conditionStack.length-1]?15:(e(5,9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;case 16:return this.popState(),44;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(b.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;case 30:return this.popState(),33;case 31:return b.yytext=e(1,2).replace(/\\"/g,'"'),80;case 32:return b.yytext=e(1,2).replace(/\\'/g,"'"),80;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return b.yytext=b.yytext.replace(/\\([\\\]])/g,"$1"),72;case 43:return"INVALID";case 44:return 5}},a.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^\/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]+?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],a.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},a}();return b.lexer=c,a.prototype=b,b.Parser=a,new a}();b["default"]=c,a.exports=b["default"]},function(a,b,c){"use strict";function d(){var a=arguments.length<=0||void 0===arguments[0]?{}:arguments[0];this.options=a}function e(a,b,c){void 0===b&&(b=a.length);var d=a[b-1],e=a[b-2];return d?"ContentStatement"===d.type?(e||!c?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(d.original):void 0:c}function f(a,b,c){void 0===b&&(b=-1);var d=a[b+1],e=a[b+2];return d?"ContentStatement"===d.type?(e||!c?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(d.original):void 0:c}function g(a,b,c){var d=a[null==b?0:b+1];if(d&&"ContentStatement"===d.type&&(c||!d.rightStripped)){var e=d.value;d.value=d.value.replace(c?/^\s+/:/^[ \t]*\r?\n?/,""),d.rightStripped=d.value!==e}}function h(a,b,c){var d=a[null==b?a.length-1:b-1];if(d&&"ContentStatement"===d.type&&(c||!d.leftStripped)){var e=d.value;return d.value=d.value.replace(c?/\s+$/:/[ \t]+$/,""),d.leftStripped=d.value!==e,d.leftStripped}}var i=c(1)["default"];b.__esModule=!0;var j=c(49),k=i(j);d.prototype=new k["default"],d.prototype.Program=function(a){var b=!this.options.ignoreStandalone,c=!this.isRootSeen;this.isRootSeen=!0;for(var d=a.body,i=0,j=d.length;i<j;i++){var k=d[i],l=this.accept(k);if(l){var m=e(d,i,c),n=f(d,i,c),o=l.openStandalone&&m,p=l.closeStandalone&&n,q=l.inlineStandalone&&m&&n;l.close&&g(d,i,!0),l.open&&h(d,i,!0),b&&q&&(g(d,i),h(d,i)&&"PartialStatement"===k.type&&(k.indent=/([ \t]+$)/.exec(d[i-1].original)[1])),b&&o&&(g((k.program||k.inverse).body),h(d,i)),b&&p&&(g(d,i),h((k.inverse||k.program).body))}}return a},d.prototype.BlockStatement=d.prototype.DecoratorBlock=d.prototype.PartialBlockStatement=function(a){this.accept(a.program),this.accept(a.inverse);var b=a.program||a.inverse,c=a.program&&a.inverse,d=c,i=c;if(c&&c.chained)for(d=c.body[0].program;i.chained;)i=i.body[i.body.length-1].program;var j={open:a.openStrip.open,close:a.closeStrip.close,openStandalone:f(b.body),closeStandalone:e((d||b).body)};if(a.openStrip.close&&g(b.body,null,!0),c){var k=a.inverseStrip;k.open&&h(b.body,null,!0),k.close&&g(d.body,null,!0),a.closeStrip.open&&h(i.body,null,!0),!this.options.ignoreStandalone&&e(b.body)&&f(d.body)&&(h(b.body),g(d.body))}else a.closeStrip.open&&h(b.body,null,!0);return j},d.prototype.Decorator=d.prototype.MustacheStatement=function(a){return a.strip},d.prototype.PartialStatement=d.prototype.CommentStatement=function(a){var b=a.strip||{};return{inlineStandalone:!0,open:b.open,close:b.close}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(){this.parents=[]}function e(a){this.acceptRequired(a,"path"),this.acceptArray(a.params),this.acceptKey(a,"hash")}function f(a){e.call(this,a),this.acceptKey(a,"program"),this.acceptKey(a,"inverse")}function g(a){this.acceptRequired(a,"name"),this.acceptArray(a.params),this.acceptKey(a,"hash")}var h=c(1)["default"];b.__esModule=!0;var i=c(6),j=h(i);d.prototype={constructor:d,mutating:!1,acceptKey:function(a,b){var c=this.accept(a[b]);if(this.mutating){if(c&&!d.prototype[c.type])throw new j["default"]('Unexpected node type "'+c.type+'" found when accepting '+b+" on "+a.type);a[b]=c}},acceptRequired:function(a,b){if(this.acceptKey(a,b),!a[b])throw new j["default"](a.type+" requires "+b)},acceptArray:function(a){for(var b=0,c=a.length;b<c;b++)this.acceptKey(a,b),a[b]||(a.splice(b,1),b--,c--)},accept:function(a){if(a){if(!this[a.type])throw new j["default"]("Unknown type: "+a.type,a);this.current&&this.parents.unshift(this.current),this.current=a;var b=this[a.type](a);return this.current=this.parents.shift(),!this.mutating||b?b:b!==!1?a:void 0}},Program:function(a){this.acceptArray(a.body)},MustacheStatement:e,Decorator:e,BlockStatement:f,DecoratorBlock:f,PartialStatement:g,PartialBlockStatement:function(a){g.call(this,a),this.acceptKey(a,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:e,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(a){this.acceptArray(a.pairs)},HashPair:function(a){this.acceptRequired(a,"value")}},b["default"]=d,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b){if(b=b.path?b.path.original:b,a.path.original!==b){var c={loc:a.path.loc};throw new q["default"](a.path.original+" doesn't match "+b,c)}}function e(a,b){this.source=a,this.start={line:b.first_line,column:b.first_column},this.end={line:b.last_line,column:b.last_column}}function f(a){return/^\[.*\]$/.test(a)?a.substring(1,a.length-1):a}function g(a,b){return{open:"~"===a.charAt(2),close:"~"===b.charAt(b.length-3)}}function h(a){return a.replace(/^\{\{~?!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function i(a,b,c){c=this.locInfo(c);for(var d=a?"@":"",e=[],f=0,g=0,h=b.length;g<h;g++){var i=b[g].part,j=b[g].original!==i;if(d+=(b[g].separator||"")+i,j||".."!==i&&"."!==i&&"this"!==i)e.push(i);else{if(e.length>0)throw new q["default"]("Invalid path: "+d,{loc:c});".."===i&&f++}}return{type:"PathExpression",data:a,depth:f,parts:e,original:d,loc:c}}function j(a,b,c,d,e,f){var g=d.charAt(3)||d.charAt(2),h="{"!==g&&"&"!==g,i=/\*/.test(d);return{type:i?"Decorator":"MustacheStatement",path:a,params:b,hash:c,escaped:h,strip:e,loc:this.locInfo(f)}}function k(a,b,c,e){d(a,c),e=this.locInfo(e);var f={type:"Program",body:b,strip:{},loc:e};return{type:"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:f,openStrip:{},inverseStrip:{},closeStrip:{},loc:e}}function l(a,b,c,e,f,g){e&&e.path&&d(a,e);var h=/\*/.test(a.open);b.blockParams=a.blockParams;var i=void 0,j=void 0;if(c){if(h)throw new q["default"]("Unexpected inverse block on decorator",c);c.chain&&(c.program.body[0].closeStrip=e.strip),j=c.strip,i=c.program}return f&&(f=i,i=b,b=f),{type:h?"DecoratorBlock":"BlockStatement",path:a.path,params:a.params,hash:a.hash,program:b,inverse:i,openStrip:a.strip,inverseStrip:j,closeStrip:e&&e.strip,loc:this.locInfo(g)}}function m(a,b){if(!b&&a.length){var c=a[0].loc,d=a[a.length-1].loc;c&&d&&(b={source:c.source,start:{line:c.start.line,column:c.start.column},end:{line:d.end.line,column:d.end.column}})}return{type:"Program",body:a,strip:{},loc:b}}function n(a,b,c,e){return d(a,c),{type:"PartialBlockStatement",name:a.path,params:a.params,hash:a.hash,program:b,openStrip:a.strip,closeStrip:c&&c.strip,loc:this.locInfo(e)}}var o=c(1)["default"];b.__esModule=!0,b.SourceLocation=e,b.id=f,b.stripFlags=g,b.stripComment=h,b.preparePath=i,b.prepareMustache=j,b.prepareRawBlock=k,b.prepareBlock=l,b.prepareProgram=m,b.preparePartialBlock=n;var p=c(6),q=o(p)},function(a,b,c){"use strict";function d(){}function e(a,b,c){if(null==a||"string"!=typeof a&&"Program"!==a.type)throw new l["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+a);b=b||{},"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var d=c.parse(a,b),e=(new c.Compiler).compile(d,b);return(new c.JavaScriptCompiler).compile(e,b)}function f(a,b,c){function d(){var d=c.parse(a,b),e=(new c.Compiler).compile(d,b),f=(new c.JavaScriptCompiler).compile(e,b,void 0,!0);return c.template(f)}function e(a,b){return f||(f=d()),f.call(this,a,b)}if(void 0===b&&(b={}),null==a||"string"!=typeof a&&"Program"!==a.type)throw new l["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+a);b=m.extend({},b),"data"in b||(b.data=!0),b.compat&&(b.useDepths=!0);var f=void 0;return e._setup=function(a){return f||(f=d()),f._setup(a)},e._child=function(a,b,c,e){return f||(f=d()),f._child(a,b,c,e)},e}function g(a,b){if(a===b)return!0;if(m.isArray(a)&&m.isArray(b)&&a.length===b.length){for(var c=0;c<a.length;c++)if(!g(a[c],b[c]))return!1;return!0}}function h(a){if(!a.path.parts){var b=a.path;a.path={type:"PathExpression",data:!1,depth:0,parts:[b.original+""],original:b.original+"",loc:b.loc}}}var i=c(34)["default"],j=c(1)["default"];b.__esModule=!0,b.Compiler=d,b.precompile=e,b.compile=f;var k=c(6),l=j(k),m=c(5),n=c(45),o=j(n),p=[].slice;d.prototype={compiler:d,equals:function(a){var b=this.opcodes.length;if(a.opcodes.length!==b)return!1;for(var c=0;c<b;c++){var d=this.opcodes[c],e=a.opcodes[c];if(d.opcode!==e.opcode||!g(d.args,e.args))return!1}b=this.children.length;for(var c=0;c<b;c++)if(!this.children[c].equals(a.children[c]))return!1;return!0},guid:0,compile:function(a,b){return this.sourceNode=[],this.opcodes=[],this.children=[],this.options=b,this.stringParams=b.stringParams,this.trackIds=b.trackIds,b.blockParams=b.blockParams||[],b.knownHelpers=m.extend(i(null),{helperMissing:!0,blockHelperMissing:!0,each:!0,"if":!0,unless:!0,"with":!0,log:!0,lookup:!0},b.knownHelpers),this.accept(a)},compileProgram:function(a){var b=new this.compiler,c=b.compile(a,this.options),d=this.guid++;return this.usePartial=this.usePartial||c.usePartial,this.children[d]=c,this.useDepths=this.useDepths||c.useDepths,d},accept:function(a){if(!this[a.type])throw new l["default"]("Unknown type: "+a.type,a);this.sourceNode.unshift(a);var b=this[a.type](a);return this.sourceNode.shift(),b},Program:function(a){this.options.blockParams.unshift(a.blockParams);for(var b=a.body,c=b.length,d=0;d<c;d++)this.accept(b[d]);return this.options.blockParams.shift(),this.isSimple=1===c,this.blockParams=a.blockParams?a.blockParams.length:0,this},BlockStatement:function(a){h(a);var b=a.program,c=a.inverse;b=b&&this.compileProgram(b),c=c&&this.compileProgram(c);var d=this.classifySexpr(a);"helper"===d?this.helperSexpr(a,b,c):"simple"===d?(this.simpleSexpr(a),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("blockValue",a.path.original)):(this.ambiguousSexpr(a,b,c),this.opcode("pushProgram",b),this.opcode("pushProgram",c),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(a){var b=a.program&&this.compileProgram(a.program),c=this.setupFullMustacheParams(a,b,void 0),d=a.path;this.useDecorators=!0,this.opcode("registerDecorator",c.length,d.original)},PartialStatement:function(a){this.usePartial=!0;var b=a.program;b&&(b=this.compileProgram(a.program));var c=a.params;if(c.length>1)throw new l["default"]("Unsupported number of partial arguments: "+c.length,a);c.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):c.push({type:"PathExpression",parts:[],depth:0}));var d=a.name.original,e="SubExpression"===a.name.type;e&&this.accept(a.name),this.setupFullMustacheParams(a,b,void 0,!0);var f=a.indent||"";this.options.preventIndent&&f&&(this.opcode("appendContent",f),f=""),this.opcode("invokePartial",e,d,f),this.opcode("append")},PartialBlockStatement:function(a){this.PartialStatement(a)},MustacheStatement:function(a){this.SubExpression(a),a.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(a){this.DecoratorBlock(a)},ContentStatement:function(a){a.value&&this.opcode("appendContent",a.value)},CommentStatement:function(){},SubExpression:function(a){h(a);var b=this.classifySexpr(a);"simple"===b?this.simpleSexpr(a):"helper"===b?this.helperSexpr(a):this.ambiguousSexpr(a)},ambiguousSexpr:function(a,b,c){var d=a.path,e=d.parts[0],f=null!=b||null!=c;this.opcode("getContext",d.depth),this.opcode("pushProgram",b),this.opcode("pushProgram",c),d.strict=!0,this.accept(d),this.opcode("invokeAmbiguous",e,f)},simpleSexpr:function(a){var b=a.path;b.strict=!0,this.accept(b),this.opcode("resolvePossibleLambda")},helperSexpr:function(a,b,c){var d=this.setupFullMustacheParams(a,b,c),e=a.path,f=e.parts[0];if(this.options.knownHelpers[f])this.opcode("invokeKnownHelper",d.length,f);else{if(this.options.knownHelpersOnly)throw new l["default"]("You specified knownHelpersOnly, but used the unknown helper "+f,a);e.strict=!0,e.falsy=!0,this.accept(e),this.opcode("invokeHelper",d.length,e.original,o["default"].helpers.simpleId(e))}},PathExpression:function(a){this.addDepth(a.depth),this.opcode("getContext",a.depth);var b=a.parts[0],c=o["default"].helpers.scopedId(a),d=!a.depth&&!c&&this.blockParamIndex(b);d?this.opcode("lookupBlockParam",d,a.parts):b?a.data?(this.options.data=!0,this.opcode("lookupData",a.depth,a.parts,a.strict)):this.opcode("lookupOnContext",a.parts,a.falsy,a.strict,c):this.opcode("pushContext")},StringLiteral:function(a){this.opcode("pushString",a.value)},NumberLiteral:function(a){this.opcode("pushLiteral",a.value)},BooleanLiteral:function(a){this.opcode("pushLiteral",a.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(a){var b=a.pairs,c=0,d=b.length;for(this.opcode("pushHash");c<d;c++)this.pushParam(b[c].value);for(;c--;)this.opcode("assignToHash",b[c].key);this.opcode("popHash")},opcode:function(a){this.opcodes.push({opcode:a,args:p.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(a){a&&(this.useDepths=!0)},classifySexpr:function(a){var b=o["default"].helpers.simpleId(a.path),c=b&&!!this.blockParamIndex(a.path.parts[0]),d=!c&&o["default"].helpers.helperExpression(a),e=!c&&(d||b);if(e&&!d){var f=a.path.parts[0],g=this.options;g.knownHelpers[f]?d=!0:g.knownHelpersOnly&&(e=!1)}return d?"helper":e?"ambiguous":"simple"},pushParams:function(a){for(var b=0,c=a.length;b<c;b++)this.pushParam(a[b])},pushParam:function(a){var b=null!=a.value?a.value:a.original||"";if(this.stringParams)b.replace&&(b=b.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),a.depth&&this.addDepth(a.depth),this.opcode("getContext",a.depth||0),this.opcode("pushStringParam",b,a.type),"SubExpression"===a.type&&this.accept(a);else{if(this.trackIds){var c=void 0;if(!a.parts||o["default"].helpers.scopedId(a)||a.depth||(c=this.blockParamIndex(a.parts[0])),c){var d=a.parts.slice(1).join(".");this.opcode("pushId","BlockParam",c,d)}else b=a.original||b,b.replace&&(b=b.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",a.type,b)}this.accept(a)}},setupFullMustacheParams:function(a,b,c,d){var e=a.params;return this.pushParams(e),this.opcode("pushProgram",b),this.opcode("pushProgram",c),a.hash?this.accept(a.hash):this.opcode("emptyHash",d),e},blockParamIndex:function(a){for(var b=0,c=this.options.blockParams.length;b<c;b++){var d=this.options.blockParams[b],e=d&&m.indexOf(d,a);if(d&&e>=0)return[b,e]}}}},function(a,b,c){"use strict";function d(a){this.value=a}function e(){}function f(a,b,c,d){var e=b.popStack(),f=0,g=c.length;for(a&&g--;f<g;f++)e=b.nameLookup(e,c[f],d);return a?[b.aliasable("container.strict"),"(",e,", ",b.quotedString(c[f]),", ",JSON.stringify(b.source.currentLocation)," )"]:e}var g=c(13)["default"],h=c(1)["default"];b.__esModule=!0;var i=c(4),j=c(6),k=h(j),l=c(5),m=c(53),n=h(m);e.prototype={nameLookup:function(a,b){return this.internalNameLookup(a,b)},depthedLookup:function(a){return[this.aliasable("container.lookup"),'(depths, "',a,'")']},compilerInfo:function(){var a=i.COMPILER_REVISION,b=i.REVISION_CHANGES[a];return[a,b]},appendToBuffer:function(a,b,c){return l.isArray(a)||(a=[a]),a=this.source.wrap(a,b),this.environment.isSimple?["return ",a,";"]:c?["buffer += ",a,";"]:(a.appendToBuffer=!0,a)},initializeBuffer:function(){return this.quotedString("")},internalNameLookup:function(a,b){return this.lookupPropertyFunctionIsUsed=!0,["lookupProperty(",a,",",JSON.stringify(b),")"]},lookupPropertyFunctionIsUsed:!1,compile:function(a,b,c,d){this.environment=a,this.options=b,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!d,this.name=this.environment.name,this.isChild=!!c,this.context=c||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(a,b),this.useDepths=this.useDepths||a.useDepths||a.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||a.useBlockParams;var e=a.opcodes,f=void 0,g=void 0,h=void 0,i=void 0;for(h=0,i=e.length;h<i;h++)f=e[h],this.source.currentLocation=f.loc,g=g||f.loc,this[f.opcode].apply(this,f.args);if(this.source.currentLocation=g,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new k["default"]("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend(["var decorators = container.decorators, ",this.lookupPropertyFunctionVarDeclaration(),";\n"]),
this.decorators.push("return fn;"),d?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"),this.decorators.push("}\n"),this.decorators=this.decorators.merge()));var j=this.createFunctionContext(d);if(this.isChild)return j;var l={compiler:this.compilerInfo(),main:j};this.decorators&&(l.main_d=this.decorators,l.useDecorators=!0);var m=this.context,n=m.programs,o=m.decorators;for(h=0,i=n.length;h<i;h++)n[h]&&(l[h]=n[h],o[h]&&(l[h+"_d"]=o[h],l.useDecorators=!0));return this.environment.usePartial&&(l.usePartial=!0),this.options.data&&(l.useData=!0),this.useDepths&&(l.useDepths=!0),this.useBlockParams&&(l.useBlockParams=!0),this.options.compat&&(l.compat=!0),d?l.compilerOptions=this.options:(l.compiler=JSON.stringify(l.compiler),this.source.currentLocation={start:{line:1,column:0}},l=this.objectLiteral(l),b.srcName?(l=l.toStringWithSourceMap({file:b.destName}),l.map=l.map&&l.map.toString()):l=l.toString()),l},preamble:function(){this.lastContext=0,this.source=new n["default"](this.options.srcName),this.decorators=new n["default"](this.options.srcName)},createFunctionContext:function(a){var b=this,c="",d=this.stackVars.concat(this.registers.list);d.length>0&&(c+=", "+d.join(", "));var e=0;g(this.aliases).forEach(function(a){var d=b.aliases[a];d.children&&d.referenceCount>1&&(c+=", alias"+ ++e+"="+a,d.children[0]="alias"+e)}),this.lookupPropertyFunctionIsUsed&&(c+=", "+this.lookupPropertyFunctionVarDeclaration());var f=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&f.push("blockParams"),this.useDepths&&f.push("depths");var h=this.mergeSource(c);return a?(f.push(h),Function.apply(this,f)):this.source.wrap(["function(",f.join(","),") {\n  ",h,"}"])},mergeSource:function(a){var b=this.environment.isSimple,c=!this.forceBuffer,d=void 0,e=void 0,f=void 0,g=void 0;return this.source.each(function(a){a.appendToBuffer?(f?a.prepend("  + "):f=a,g=a):(f&&(e?f.prepend("buffer += "):d=!0,g.add(";"),f=g=void 0),e=!0,b||(c=!1))}),c?f?(f.prepend("return "),g.add(";")):e||this.source.push('return "";'):(a+=", buffer = "+(d?"":this.initializeBuffer()),f?(f.prepend("return buffer + "),g.add(";")):this.source.push("return buffer;")),a&&this.source.prepend("var "+a.substring(2)+(d?"":";\n")),this.source.merge()},lookupPropertyFunctionVarDeclaration:function(){return"\n      lookupProperty = container.lookupProperty || function(parent, propertyName) {\n        if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {\n          return parent[propertyName];\n        }\n        return undefined\n    }\n    ".trim()},blockValue:function(a){var b=this.aliasable("container.hooks.blockHelperMissing"),c=[this.contextName(0)];this.setupHelperArgs(a,0,c);var d=this.popStack();c.splice(1,0,d),this.push(this.source.functionCall(b,"call",c))},ambiguousBlockValue:function(){var a=this.aliasable("container.hooks.blockHelperMissing"),b=[this.contextName(0)];this.setupHelperArgs("",0,b,!0),this.flushInline();var c=this.topStack();b.splice(1,0,c),this.pushSource(["if (!",this.lastHelper,") { ",c," = ",this.source.functionCall(a,"call",b),"}"])},appendContent:function(a){this.pendingContent?a=this.pendingContent+a:this.pendingLocation=this.source.currentLocation,this.pendingContent=a},append:function(){if(this.isInline())this.replaceStack(function(a){return[" != null ? ",a,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var a=this.popStack();this.pushSource(["if (",a," != null) { ",this.appendToBuffer(a,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(a){this.lastContext=a},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(a,b,c,d){var e=0;d||!this.options.compat||this.lastContext?this.pushContext():this.push(this.depthedLookup(a[e++])),this.resolvePath("context",a,e,b,c)},lookupBlockParam:function(a,b){this.useBlockParams=!0,this.push(["blockParams[",a[0],"][",a[1],"]"]),this.resolvePath("context",b,1)},lookupData:function(a,b,c){a?this.pushStackLiteral("container.data(data, "+a+")"):this.pushStackLiteral("data"),this.resolvePath("data",b,0,!0,c)},resolvePath:function(a,b,c,d,e){var g=this;if(this.options.strict||this.options.assumeObjects)return void this.push(f(this.options.strict&&e,this,b,a));for(var h=b.length;c<h;c++)this.replaceStack(function(e){var f=g.nameLookup(e,b[c],a);return d?[" && ",f]:[" != null ? ",f," : ",e]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(a,b){this.pushContext(),this.pushString(b),"SubExpression"!==b&&("string"==typeof a?this.pushString(a):this.pushStackLiteral(a))},emptyHash:function(a){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(a?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:{},types:[],contexts:[],ids:[]}},popHash:function(){var a=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(a.ids)),this.stringParams&&(this.push(this.objectLiteral(a.contexts)),this.push(this.objectLiteral(a.types))),this.push(this.objectLiteral(a.values))},pushString:function(a){this.pushStackLiteral(this.quotedString(a))},pushLiteral:function(a){this.pushStackLiteral(a)},pushProgram:function(a){null!=a?this.pushStackLiteral(this.programExpression(a)):this.pushStackLiteral(null)},registerDecorator:function(a,b){var c=this.nameLookup("decorators",b,"decorator"),d=this.setupHelperArgs(b,a);this.decorators.push(["fn = ",this.decorators.functionCall(c,"",["fn","props","container",d])," || fn;"])},invokeHelper:function(a,b,c){var d=this.popStack(),e=this.setupHelper(a,b),f=[];c&&f.push(e.name),f.push(d),this.options.strict||f.push(this.aliasable("container.hooks.helperMissing"));var g=["(",this.itemsSeparatedBy(f,"||"),")"],h=this.source.functionCall(g,"call",e.callParams);this.push(h)},itemsSeparatedBy:function(a,b){var c=[];c.push(a[0]);for(var d=1;d<a.length;d++)c.push(b,a[d]);return c},invokeKnownHelper:function(a,b){var c=this.setupHelper(a,b);this.push(this.source.functionCall(c.name,"call",c.callParams))},invokeAmbiguous:function(a,b){this.useRegister("helper");var c=this.popStack();this.emptyHash();var d=this.setupHelper(0,a,b),e=this.lastHelper=this.nameLookup("helpers",a,"helper"),f=["(","(helper = ",e," || ",c,")"];this.options.strict||(f[0]="(helper = ",f.push(" != null ? helper : ",this.aliasable("container.hooks.helperMissing"))),this.push(["(",f,d.paramsInit?["),(",d.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",d.callParams)," : helper))"])},invokePartial:function(a,b,c){var d=[],e=this.setupParams(b,1,d);a&&(b=this.popStack(),delete e.name),c&&(e.indent=JSON.stringify(c)),e.helpers="helpers",e.partials="partials",e.decorators="container.decorators",a?d.unshift(b):d.unshift(this.nameLookup("partials",b,"partial")),this.options.compat&&(e.depths="depths"),e=this.objectLiteral(e),d.push(e),this.push(this.source.functionCall("container.invokePartial","",d))},assignToHash:function(a){var b=this.popStack(),c=void 0,d=void 0,e=void 0;this.trackIds&&(e=this.popStack()),this.stringParams&&(d=this.popStack(),c=this.popStack());var f=this.hash;c&&(f.contexts[a]=c),d&&(f.types[a]=d),e&&(f.ids[a]=e),f.values[a]=b},pushId:function(a,b,c){"BlockParam"===a?this.pushStackLiteral("blockParams["+b[0]+"].path["+b[1]+"]"+(c?" + "+JSON.stringify("."+c):"")):"PathExpression"===a?this.pushString(b):"SubExpression"===a?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:e,compileChildren:function(a,b){for(var c=a.children,d=void 0,e=void 0,f=0,g=c.length;f<g;f++){d=c[f],e=new this.compiler;var h=this.matchExistingProgram(d);if(null==h){this.context.programs.push("");var i=this.context.programs.length;d.index=i,d.name="program"+i,this.context.programs[i]=e.compile(d,b,this.context,!this.precompile),this.context.decorators[i]=e.decorators,this.context.environments[i]=d,this.useDepths=this.useDepths||e.useDepths,this.useBlockParams=this.useBlockParams||e.useBlockParams,d.useDepths=this.useDepths,d.useBlockParams=this.useBlockParams}else d.index=h.index,d.name="program"+h.index,this.useDepths=this.useDepths||h.useDepths,this.useBlockParams=this.useBlockParams||h.useBlockParams}},matchExistingProgram:function(a){for(var b=0,c=this.context.environments.length;b<c;b++){var d=this.context.environments[b];if(d&&d.equals(a))return d}},programExpression:function(a){var b=this.environment.children[a],c=[b.index,"data",b.blockParams];return(this.useBlockParams||this.useDepths)&&c.push("blockParams"),this.useDepths&&c.push("depths"),"container.program("+c.join(", ")+")"},useRegister:function(a){this.registers[a]||(this.registers[a]=!0,this.registers.list.push(a))},push:function(a){return a instanceof d||(a=this.source.wrap(a)),this.inlineStack.push(a),a},pushStackLiteral:function(a){this.push(new d(a))},pushSource:function(a){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),a&&this.source.push(a)},replaceStack:function(a){var b=["("],c=void 0,e=void 0,f=void 0;if(!this.isInline())throw new k["default"]("replaceStack on non-inline");var g=this.popStack(!0);if(g instanceof d)c=[g.value],b=["(",c],f=!0;else{e=!0;var h=this.incrStack();b=["((",this.push(h)," = ",g,")"],c=this.topStack()}var i=a.call(this,c);f||this.popStack(),e&&this.stackSlot--,this.push(b.concat(i,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var a=this.inlineStack;this.inlineStack=[];for(var b=0,c=a.length;b<c;b++){var e=a[b];if(e instanceof d)this.compileStack.push(e);else{var f=this.incrStack();this.pushSource([f," = ",e,";"]),this.compileStack.push(f)}}},isInline:function(){return this.inlineStack.length},popStack:function(a){var b=this.isInline(),c=(b?this.inlineStack:this.compileStack).pop();if(!a&&c instanceof d)return c.value;if(!b){if(!this.stackSlot)throw new k["default"]("Invalid stack pop");this.stackSlot--}return c},topStack:function(){var a=this.isInline()?this.inlineStack:this.compileStack,b=a[a.length-1];return b instanceof d?b.value:b},contextName:function(a){return this.useDepths&&a?"depths["+a+"]":"depth"+a},quotedString:function(a){return this.source.quotedString(a)},objectLiteral:function(a){return this.source.objectLiteral(a)},aliasable:function(a){var b=this.aliases[a];return b?(b.referenceCount++,b):(b=this.aliases[a]=this.source.wrap(a),b.aliasable=!0,b.referenceCount=1,b)},setupHelper:function(a,b,c){var d=[],e=this.setupHelperArgs(b,a,d,c),f=this.nameLookup("helpers",b,"helper"),g=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:d,paramsInit:e,name:f,callParams:[g].concat(d)}},setupParams:function(a,b,c){var d={},e=[],f=[],g=[],h=!c,i=void 0;h&&(c=[]),d.name=this.quotedString(a),d.hash=this.popStack(),this.trackIds&&(d.hashIds=this.popStack()),this.stringParams&&(d.hashTypes=this.popStack(),d.hashContexts=this.popStack());var j=this.popStack(),k=this.popStack();(k||j)&&(d.fn=k||"container.noop",d.inverse=j||"container.noop");for(var l=b;l--;)i=this.popStack(),c[l]=i,this.trackIds&&(g[l]=this.popStack()),this.stringParams&&(f[l]=this.popStack(),e[l]=this.popStack());return h&&(d.args=this.source.generateArray(c)),this.trackIds&&(d.ids=this.source.generateArray(g)),this.stringParams&&(d.types=this.source.generateArray(f),d.contexts=this.source.generateArray(e)),this.options.data&&(d.data="data"),this.useBlockParams&&(d.blockParams="blockParams"),d},setupHelperArgs:function(a,b,c,d){var e=this.setupParams(a,b,c);return e.loc=JSON.stringify(this.source.currentLocation),e=this.objectLiteral(e),d?(this.useRegister("options"),c.push("options"),["options=",e]):c?(c.push(e),""):e}},function(){for(var a="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),b=e.RESERVED_WORDS={},c=0,d=a.length;c<d;c++)b[a[c]]=!0}(),e.isValidJavaScriptVariableName=function(a){return!e.RESERVED_WORDS[a]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(a)},b["default"]=e,a.exports=b["default"]},function(a,b,c){"use strict";function d(a,b,c){if(g.isArray(a)){for(var d=[],e=0,f=a.length;e<f;e++)d.push(b.wrap(a[e],c));return d}return"boolean"==typeof a||"number"==typeof a?a+"":a}function e(a){this.srcFile=a,this.source=[]}var f=c(13)["default"];b.__esModule=!0;var g=c(5),h=void 0;try{}catch(i){}h||(h=function(a,b,c,d){this.src="",d&&this.add(d)},h.prototype={add:function(a){g.isArray(a)&&(a=a.join("")),this.src+=a},prepend:function(a){g.isArray(a)&&(a=a.join("")),this.src=a+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}}),e.prototype={isEmpty:function(){return!this.source.length},prepend:function(a,b){this.source.unshift(this.wrap(a,b))},push:function(a,b){this.source.push(this.wrap(a,b))},merge:function(){var a=this.empty();return this.each(function(b){a.add(["  ",b,"\n"])}),a},each:function(a){for(var b=0,c=this.source.length;b<c;b++)a(this.source[b])},empty:function(){var a=this.currentLocation||{start:{}};return new h(a.start.line,a.start.column,this.srcFile)},wrap:function(a){var b=arguments.length<=1||void 0===arguments[1]?this.currentLocation||{start:{}}:arguments[1];return a instanceof h?a:(a=d(a,this,b),new h(b.start.line,b.start.column,this.srcFile,a))},functionCall:function(a,b,c){return c=this.generateList(c),this.wrap([a,b?"."+b+"(":"(",c,")"])},quotedString:function(a){return'"'+(a+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(a){var b=this,c=[];f(a).forEach(function(e){var f=d(a[e],b);"undefined"!==f&&c.push([b.quotedString(e),":",f])});var e=this.generateList(c);return e.prepend("{"),e.add("}"),e},generateList:function(a){for(var b=this.empty(),c=0,e=a.length;c<e;c++)c&&b.add(","),b.add(d(a[c],this));return b},generateArray:function(a){var b=this.generateList(a);return b.prepend("["),b.add("]"),b}},b["default"]=e,a.exports=b["default"]}])});;
/* instafeed.js | v2.0.0-rc2 | https://github.com/stevenschobert/instafeed.js | License: MIT */
!function exportInstafeed(e, t) { "function" == typeof define && define.amd ? define([], t) : "object" == typeof exports && "string" != typeof exports.nodeName ? module.exports = t() : e.Instafeed = t() }(this, function defineInstafeed() { function n(e, t) { if (!e) throw new Error(t) } function e(e) { n(!e || "object" == typeof e, "options must be an object, got " + e + " (" + typeof e + ")"); var t = { accessToken: null, accessTokenTimeout: 1e4, after: null, apiTimeout: 1e4, before: null, debug: !1, error: null, filter: null, limit: null, mock: !1, render: null, sort: null, success: null, target: "instafeed", template: '<a href="{{link}}"><img title="{{caption}}" src="{{image}}" /></a>', templateBoundaries: ["{{", "}}"], transform: null }; if (e) for (var o in t) "undefined" != typeof e[o] && (t[o] = e[o]); n("string" == typeof t.target || "object" == typeof t.target, "target must be a string or DOM node, got " + t.target + " (" + typeof t.target + ")"), n("string" == typeof t.accessToken || "function" == typeof t.accessToken, "accessToken must be a string or function, got " + t.accessToken + " (" + typeof t.accessToken + ")"), n("number" == typeof t.accessTokenTimeout, "accessTokenTimeout must be a number, got " + t.accessTokenTimeout + " (" + typeof t.accessTokenTimeout + ")"), n("number" == typeof t.apiTimeout, "apiTimeout must be a number, got " + t.apiTimeout + " (" + typeof t.apiTimeout + ")"), n("boolean" == typeof t.debug, "debug must be true or false, got " + t.debug + " (" + typeof t.debug + ")"), n("boolean" == typeof t.mock, "mock must be true or false, got " + t.mock + " (" + typeof t.mock + ")"), n("object" == typeof t.templateBoundaries && 2 === t.templateBoundaries.length && "string" == typeof t.templateBoundaries[0] && "string" == typeof t.templateBoundaries[1], "templateBoundaries must be an array of 2 strings, got " + t.templateBoundaries + " (" + typeof t.templateBoundaries + ")"), n(!t.template || "string" == typeof t.template, "template must null or string, got " + t.template + " (" + typeof t.template + ")"), n(!t.error || "function" == typeof t.error, "error must be null or function, got " + t.error + " (" + typeof t.error + ")"), n(!t.before || "function" == typeof t.before, "before must be null or function, got " + t.before + " (" + typeof t.before + ")"), n(!t.after || "function" == typeof t.after, "after must be null or function, got " + t.after + " (" + typeof t.after + ")"), n(!t.success || "function" == typeof t.success, "success must be null or function, got " + t.success + " (" + typeof t.success + ")"), n(!t.filter || "function" == typeof t.filter, "filter must be null or function, got " + t.filter + " (" + typeof t.filter + ")"), n(!t.transform || "function" == typeof t.transform, "transform must be null or function, got " + t.transform + " (" + typeof t.transform + ")"), n(!t.sort || "function" == typeof t.sort, "sort must be null or function, got " + t.sort + " (" + typeof t.sort + ")"), n(!t.render || "function" == typeof t.render, "render must be null or function, got " + t.render + " (" + typeof t.render + ")"), n(!t.limit || "number" == typeof t.limit, "limit must be null or number, got " + t.limit + " (" + typeof t.limit + ")"), this._state = { running: !1 }, this._options = t } return e.prototype.run = function () { var r = this, s = null, o = null, i = null, a = null; return this._debug("run", "options", this._options), this._debug("run", "state", this._state), this._state.running ? (this._debug("run", "already running, skipping"), !1) : (this._start(), this._debug("run", "getting dom node"), (s = "string" == typeof this._options.target ? document.getElementById(this._options.target) : this._options.target) ? (this._debug("run", "got dom node", s), this._debug("run", "getting access token"), this._getAccessToken(function (e, t) { if (e) return r._debug("onTokenReceived", "error", e), void r._fail(new Error("error getting access token: " + e.message)); o = "https://graph.instagram.com/me/media?fields=caption,id,media_type,media_url,permalink,thumbnail_url,timestamp,username&access_token=" + t, r._debug("onTokenReceived", "request url", o), r._makeApiRequest(o, function (e, t) { if (e) return r._debug("onResponseReceived", "error", e), void r._fail(new Error("api request error: " + e.message)); r._debug("onResponseReceived", "data", t), r._success(t); try { i = r._processData(t), r._debug("onResponseReceived", "processed data", i) } catch (o) { return void r._fail(o) } if (r._options.mock) r._debug("onResponseReceived", "mock enabled, skipping render"); else { try { a = r._renderData(i), r._debug("onResponseReceived", "html content", a) } catch (n) { return void r._fail(n) } s.innerHTML = a } r._finish() }) }), !0) : (this._fail(new Error("no element found with ID " + this._options.target)), !1)) }, e.prototype._processData = function (e) { var t = "function" == typeof this._options.transform, o = "function" == typeof this._options.filter, n = "function" == typeof this._options.sort, r = "number" == typeof this._options.limit, s = [], i = null, a = null, u = null, c = null; if (this._debug("processData", "hasFilter", o, "hasTransform", t, "hasSort", n, "hasLimit", r), "object" != typeof e || "object" != typeof e.data || e.data.length <= 0) return null; for (var l = 0; l < e.data.length; l++) { if (a = this._getItemData(e.data[l]), t) try { u = this._options.transform(a), this._debug("processData", "transformed item", a, u) } catch (p) { throw this._debug("processData", "error calling transform", p), new Error("error in transform: " + p.message) } else u = a; if (o) { try { c = this._options.filter(u), this._debug("processData", "filter item result", u, c) } catch (p) { throw this._debug("processData", "error calling filter", p), new Error("error in filter: " + p.message) } c && s.push(u) } else s.push(u) } if (n) try { s.sort(this._options.sort) } catch (p) { throw this._debug("processData", "error calling sort", p), new Error("error in sort: " + p.message) } return r && (i = s.length - this._options.limit, this._debug("processData", "checking limit", s.length, this._options.limit, i), 0 < i && s.splice(s.length - i, i)), s }, e.prototype._extractTags = function (e) { var t = /#([^\s]+)/gi, o = /[~`!@#$%^&*\(\)\-\+={}\[\]:;"'<>\?,\./|\\\s]+/i, n = []; if ("string" == typeof e) for (; null !== (match = t.exec(e));)!1 === o.test(match[1]) && n.push(match[1]); return n }, e.prototype._getItemData = function (e) { var t = null, o = null; switch (e.media_type) { case "IMAGE": t = "image", o = e.media_url; break; case "VIDEO": t = "video", o = e.thumbnail_url; break; case "CAROUSEL_ALBUM": t = "album", o = e.media_url }return { caption: e.caption, tags: this._extractTags(e.caption), id: e.id, image: o, link: e.permalink, model: e, timestamp: e.timestamp, type: t, username: e.username } }, e.prototype._renderData = function (e) { var t = "string" == typeof this._options.template, o = "function" == typeof this._options.render, n = null, r = null, s = ""; if (this._debug("renderData", "hasTemplate", t, "hasRender", o), "object" != typeof e || e.length <= 0) return null; for (var i = 0; i < e.length; i++) { if (n = e[i], o) try { r = this._options.render(n, this._options), this._debug("renderData", "custom render result", n, r) } catch (a) { throw this._debug("renderData", "error calling render", a), new Error("error in render: " + a.message) } else t && (r = this._basicRender(n)); r ? s += r : this._debug("renderData", "render item did not return any content", n) } return s }, e.prototype._basicRender = function (e) { for (var t = new RegExp(this._options.templateBoundaries[0] + "([\\s\\w.]+)" + this._options.templateBoundaries[1], "gm"), o = this._options.template, n = null, r = "", s = 0, i = null, a = null; null !== (n = t.exec(o));)i = n[1], r += o.slice(s, n.index), (a = this._valueForKeyPath(i, e)) && (r += a.toString()), s = t.lastIndex; return s < o.length && (r += o.slice(s, o.length)), r }, e.prototype._valueForKeyPath = function (e, t) { for (var o = /([\w]+)/gm, n = null, r = t; null !== (n = o.exec(e));) { if ("object" != typeof r) return null; r = r[n[1]] } return r }, e.prototype._fail = function (e) { !this._runHook("error", e) && console && "function" == typeof console.error && console.error(e), this._state.running = !1 }, e.prototype._start = function () { this._state.running = !0, this._runHook("before") }, e.prototype._finish = function () { this._runHook("after"), this._state.running = !1 }, e.prototype._success = function (e) { this._runHook("success", e), this._state.running = !1 }, e.prototype._makeApiRequest = function (e, o) { var n = !1, r = this, s = null, i = function i(e, t) { n || (n = !0, o(e, t)) }; (s = new XMLHttpRequest).ontimeout = function (e) { i(new Error("api request timed out")) }, s.onerror = function (e) { i(new Error("api connection error")) }, s.onload = function (e) { var t = s.getResponseHeader("Content-Type"), o = null; if (r._debug("apiRequestOnLoad", "loaded", e), r._debug("apiRequestOnLoad", "response status", s.status), r._debug("apiRequestOnLoad", "response content type", t), 0 <= t.indexOf("application/json")) try { o = JSON.parse(s.responseText) } catch (n) { return r._debug("apiRequestOnLoad", "json parsing error", n, s.responseText), void i(new Error("error parsing response json")) } 200 === s.status ? i(null, o) : o && o.error ? i(new Error(o.error.code + " " + o.error.message)) : i(new Error("status code " + s.status)) }, s.open("GET", e, !0), s.timeout = this._options.apiTimeout, s.send() }, e.prototype._getAccessToken = function (o) { var n = !1, r = this, s = null, i = function i(e, t) { n || (n = !0, clearTimeout(s), o(e, t)) }; if ("function" == typeof this._options.accessToken) { this._debug("getAccessToken", "calling accessToken as function"), s = setTimeout(function () { r._debug("getAccessToken", "timeout check", n), i(new Error("accessToken timed out"), null) }, this._options.accessTokenTimeout); try { this._options.accessToken(function (e, t) { r._debug("getAccessToken", "received accessToken callback", n, e, t), i(e, t) }) } catch (e) { this._debug("getAccessToken", "error invoking the accessToken as function", e), i(e, null) } } else this._debug("getAccessToken", "treating accessToken as static", typeof this._options.accessToken), i(null, this._options.accessToken) }, e.prototype._debug = function () { var e = null; this._options.debug && console && "function" == typeof console.log && ((e = [].slice.call(arguments))[0] = "[Instafeed] [" + e[0] + "]", console.log.apply(null, e)) }, e.prototype._runHook = function (e, t) { var o = !1; if ("function" == typeof this._options[e]) try { this._options[e](t), o = !0 } catch (n) { this._debug("runHook", "error calling hook", e, n) } return o }, e });;
(function (e) { if (typeof define === "function" && define.amd) { define(["jquery"], e) } else { e(jQuery) } })(function (e) { function n(e) { return u.raw ? e : encodeURIComponent(e) } function r(e) { return u.raw ? e : decodeURIComponent(e) } function i(e) { return n(u.json ? JSON.stringify(e) : String(e)) } function s(e) { if (e.indexOf('"') === 0) { e = e.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\") } try { e = decodeURIComponent(e.replace(t, " ")); return u.json ? JSON.parse(e) : e } catch (n) { } } function o(t, n) { var r = u.raw ? t : s(t); return e.isFunction(n) ? n(r) : r } var t = /\+/g; var u = e.cookie = function (t, s, a) { if (s !== undefined && !e.isFunction(s)) { a = e.extend({}, u.defaults, a); if (typeof a.expires === "number") { var f = a.expires, l = a.expires = new Date; l.setDate(l.getDate() + f) } return document.cookie = [n(t), "=", i(s), a.expires ? "; expires=" + a.expires.toUTCString() : "", a.path ? "; path=" + a.path : "", a.domain ? "; domain=" + a.domain : "", a.secure ? "; secure" : ""].join("") } var c = t ? undefined : {}; var h = document.cookie ? document.cookie.split("; ") : []; for (var p = 0, d = h.length; p < d; p++) { var v = h[p].split("="); var m = r(v.shift()); var g = v.join("="); if (t && t === m) { c = o(g, s); break } if (!t && (g = o(g)) !== undefined) { c[m] = g } } return c }; u.defaults = {}; e.removeCookie = function (t, n) { if (e.cookie(t) === undefined) { return false } e.cookie(t, "", e.extend({}, n, { expires: -1 })); return !e.cookie(t) } });
/*
 
jquery.draghover.js
 
Emulates draghover event by tracking
dragenter / dragleave events of element + children.
 
https://gist.github.com/gists/3794126
http://stackoverflow.com/a/10310815/4196
 
Example:
 
$(window).draghover().on({
 
'draghoverstart': function() {
console.log('A file has been dragged into the window.');
},
 
'draghoverend': function() {
console.log('A file has been dragged out of the window.');
}
 
});
 
*/

$.fn.draghover = function (options) {

    return this.each(function () {

        // create an empty collection
        var collection = $(),
            self = $(this);

        // dragenter will fire on our original element + all of its children
        self.on('dragenter', function (e) {

            // if collection is empty this must be our original element
            if (collection.length === 0) self.trigger('draghoverstart');

            //CUSTOMIZATION
            //to prevent issues with missed events, we need make sure this element will be the only one in the collection when hovered
            //note to future developer: trying to get rid of this will cause more pain, i promise
            if ($(e.target).hasClass("drag-overlay")) {
                collection = $();
            }

            // add the 'entered' element to the collection
            collection = collection.add(e.target);

        });

        // dragleave will fire on our original element + all of its children
        // drop is equivalent to a dragleave
        self.on('dragleave drop', function (e) {

            // timeout is needed because Firefox 3.6 fires the dragleave event on
            // the previous element before firing dragenter on the next one
            setTimeout(function () {

                // remove 'left' element from the collection
                collection = collection.not(e.target);

                // if collection is empty we have left the original element
                // (dragleave has fired on all 'entered' elements)
                if (collection.length === 0) self.trigger('draghoverend');

            }, 1);

        });

    });
};;
/*! fancyBox v2.1.5 fancyapps.com | fancyapps.com/fancybox/#license */
(function(r,G,f,v){var J=f("html"),n=f(r),p=f(G),b=f.fancybox=function(){b.open.apply(this,arguments)},I=navigator.userAgent.match(/msie/i),B=null,s=G.createTouch!==v,t=function(a){return a&&a.hasOwnProperty&&a instanceof f},q=function(a){return a&&"string"===f.type(a)},E=function(a){return q(a)&&0<a.indexOf("%")},l=function(a,d){var e=parseInt(a,10)||0;d&&E(a)&&(e*=b.getViewport()[d]/100);return Math.ceil(e)},w=function(a,b){return l(a,b)+"px"};f.extend(b,{version:"2.1.5",defaults:{padding:15,margin:20,
width:800,height:600,minWidth:100,minHeight:100,maxWidth:9999,maxHeight:9999,pixelRatio:1,autoSize:!0,autoHeight:!1,autoWidth:!1,autoResize:!0,autoCenter:!s,fitToView:!0,aspectRatio:!1,topRatio:0.5,leftRatio:0.5,scrolling:"auto",wrapCSS:"",arrows:!0,closeBtn:!0,closeClick:!1,nextClick:!1,mouseWheel:!0,autoPlay:!1,playSpeed:3E3,preload:3,modal:!1,loop:!0,ajax:{dataType:"html",headers:{"X-fancyBox":!0}},iframe:{scrolling:"auto",preload:!0},swf:{wmode:"transparent",allowfullscreen:"true",allowscriptaccess:"always"},
keys:{next:{13:"left",34:"up",39:"left",40:"up"},prev:{8:"right",33:"down",37:"right",38:"down"},close:[27],play:[32],toggle:[70]},direction:{next:"left",prev:"right"},scrollOutside:!0,index:0,type:null,href:null,content:null,title:null,tpl:{wrap:'<div class="fancybox-wrap" tabIndex="-1"><div class="fancybox-skin"><div class="fancybox-outer"><div class="fancybox-inner"></div></div></div></div>',image:'<img class="fancybox-image" src="{href}" alt="" />',iframe:'<iframe id="fancybox-frame{rnd}" name="fancybox-frame{rnd}" class="fancybox-iframe" frameborder="0" vspace="0" hspace="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen'+
(I?' allowtransparency="true"':"")+"></iframe>",error:'<p class="fancybox-error">The requested content cannot be loaded.<br/>Please try again later.</p>',closeBtn:'<a title="Close" class="fancybox-item fancybox-close" href="javascript:;"></a>',next:'<a title="Next" class="fancybox-nav fancybox-next" href="javascript:;"><span></span></a>',prev:'<a title="Previous" class="fancybox-nav fancybox-prev" href="javascript:;"><span></span></a>'},openEffect:"fade",openSpeed:250,openEasing:"swing",openOpacity:!0,
openMethod:"zoomIn",closeEffect:"fade",closeSpeed:250,closeEasing:"swing",closeOpacity:!0,closeMethod:"zoomOut",nextEffect:"elastic",nextSpeed:250,nextEasing:"swing",nextMethod:"changeIn",prevEffect:"elastic",prevSpeed:250,prevEasing:"swing",prevMethod:"changeOut",helpers:{overlay:!0,title:!0},onCancel:f.noop,beforeLoad:f.noop,afterLoad:f.noop,beforeShow:f.noop,afterShow:f.noop,beforeChange:f.noop,beforeClose:f.noop,afterClose:f.noop},group:{},opts:{},previous:null,coming:null,current:null,isActive:!1,
isOpen:!1,isOpened:!1,wrap:null,skin:null,outer:null,inner:null,player:{timer:null,isActive:!1},ajaxLoad:null,imgPreload:null,transitions:{},helpers:{},open:function(a,d){if(a&&(f.isPlainObject(d)||(d={}),!1!==b.close(!0)))return f.isArray(a)||(a=t(a)?f(a).get():[a]),f.each(a,function(e,c){var k={},g,h,j,m,l;"object"===f.type(c)&&(c.nodeType&&(c=f(c)),t(c)?(k={href:c.data("fancybox-href")||c.attr("href"),title:c.data("fancybox-title")||c.attr("title"),isDom:!0,element:c},f.metadata&&f.extend(!0,k,
c.metadata())):k=c);g=d.href||k.href||(q(c)?c:null);h=d.title!==v?d.title:k.title||"";m=(j=d.content||k.content)?"html":d.type||k.type;!m&&k.isDom&&(m=c.data("fancybox-type"),m||(m=(m=c.prop("class").match(/fancybox\.(\w+)/))?m[1]:null));q(g)&&(m||(b.isImage(g)?m="image":b.isSWF(g)?m="swf":"#"===g.charAt(0)?m="inline":q(c)&&(m="html",j=c)),"ajax"===m&&(l=g.split(/\s+/,2),g=l.shift(),l=l.shift()));j||("inline"===m?g?j=f(q(g)?g.replace(/.*(?=#[^\s]+$)/,""):g):k.isDom&&(j=c):"html"===m?j=g:!m&&(!g&&
k.isDom)&&(m="inline",j=c));f.extend(k,{href:g,type:m,content:j,title:h,selector:l});a[e]=k}),b.opts=f.extend(!0,{},b.defaults,d),d.keys!==v&&(b.opts.keys=d.keys?f.extend({},b.defaults.keys,d.keys):!1),b.group=a,b._start(b.opts.index)},cancel:function(){var a=b.coming;a&&!1!==b.trigger("onCancel")&&(b.hideLoading(),b.ajaxLoad&&b.ajaxLoad.abort(),b.ajaxLoad=null,b.imgPreload&&(b.imgPreload.onload=b.imgPreload.onerror=null),a.wrap&&a.wrap.stop(!0,!0).trigger("onReset").remove(),b.coming=null,b.current||
b._afterZoomOut(a))},close:function(a){b.cancel();!1!==b.trigger("beforeClose")&&(b.unbindEvents(),b.isActive&&(!b.isOpen||!0===a?(f(".fancybox-wrap").stop(!0).trigger("onReset").remove(),b._afterZoomOut()):(b.isOpen=b.isOpened=!1,b.isClosing=!0,f(".fancybox-item, .fancybox-nav").remove(),b.wrap.stop(!0,!0).removeClass("fancybox-opened"),b.transitions[b.current.closeMethod]())))},play:function(a){var d=function(){clearTimeout(b.player.timer)},e=function(){d();b.current&&b.player.isActive&&(b.player.timer=
setTimeout(b.next,b.current.playSpeed))},c=function(){d();p.unbind(".player");b.player.isActive=!1;b.trigger("onPlayEnd")};if(!0===a||!b.player.isActive&&!1!==a){if(b.current&&(b.current.loop||b.current.index<b.group.length-1))b.player.isActive=!0,p.bind({"onCancel.player beforeClose.player":c,"onUpdate.player":e,"beforeLoad.player":d}),e(),b.trigger("onPlayStart")}else c()},next:function(a){var d=b.current;d&&(q(a)||(a=d.direction.next),b.jumpto(d.index+1,a,"next"))},prev:function(a){var d=b.current;
d&&(q(a)||(a=d.direction.prev),b.jumpto(d.index-1,a,"prev"))},jumpto:function(a,d,e){var c=b.current;c&&(a=l(a),b.direction=d||c.direction[a>=c.index?"next":"prev"],b.router=e||"jumpto",c.loop&&(0>a&&(a=c.group.length+a%c.group.length),a%=c.group.length),c.group[a]!==v&&(b.cancel(),b._start(a)))},reposition:function(a,d){var e=b.current,c=e?e.wrap:null,k;c&&(k=b._getPosition(d),a&&"scroll"===a.type?(delete k.position,c.stop(!0,!0).animate(k,200)):(c.css(k),e.pos=f.extend({},e.dim,k)))},update:function(a){var d=
a&&a.type,e=!d||"orientationchange"===d;e&&(clearTimeout(B),B=null);b.isOpen&&!B&&(B=setTimeout(function(){var c=b.current;c&&!b.isClosing&&(b.wrap.removeClass("fancybox-tmp"),(e||"load"===d||"resize"===d&&c.autoResize)&&b._setDimension(),"scroll"===d&&c.canShrink||b.reposition(a),b.trigger("onUpdate"),B=null)},e&&!s?0:300))},toggle:function(a){b.isOpen&&(b.current.fitToView="boolean"===f.type(a)?a:!b.current.fitToView,s&&(b.wrap.removeAttr("style").addClass("fancybox-tmp"),b.trigger("onUpdate")),
b.update())},hideLoading:function(){p.unbind(".loading");f("#fancybox-loading").remove()},showLoading:function(){var a,d;b.hideLoading();a=f('<div id="fancybox-loading"><div></div></div>').click(b.cancel).appendTo("body");p.bind("keydown.loading",function(a){if(27===(a.which||a.keyCode))a.preventDefault(),b.cancel()});b.defaults.fixed||(d=b.getViewport(),a.css({position:"absolute",top:0.5*d.h+d.y,left:0.5*d.w+d.x}))},getViewport:function(){var a=b.current&&b.current.locked||!1,d={x:n.scrollLeft(),
y:n.scrollTop()};a?(d.w=a[0].clientWidth,d.h=a[0].clientHeight):(d.w=s&&r.innerWidth?r.innerWidth:n.width(),d.h=s&&r.innerHeight?r.innerHeight:n.height());return d},unbindEvents:function(){b.wrap&&t(b.wrap)&&b.wrap.unbind(".fb");p.unbind(".fb");n.unbind(".fb")},bindEvents:function(){var a=b.current,d;a&&(n.bind("orientationchange.fb"+(s?"":" resize.fb")+(a.autoCenter&&!a.locked?" scroll.fb":""),b.update),(d=a.keys)&&p.bind("keydown.fb",function(e){var c=e.which||e.keyCode,k=e.target||e.srcElement;
if(27===c&&b.coming)return!1;!e.ctrlKey&&(!e.altKey&&!e.shiftKey&&!e.metaKey&&(!k||!k.type&&!f(k).is("[contenteditable]")))&&f.each(d,function(d,k){if(1<a.group.length&&k[c]!==v)return b[d](k[c]),e.preventDefault(),!1;if(-1<f.inArray(c,k))return b[d](),e.preventDefault(),!1})}),f.fn.mousewheel&&a.mouseWheel&&b.wrap.bind("mousewheel.fb",function(d,c,k,g){for(var h=f(d.target||null),j=!1;h.length&&!j&&!h.is(".fancybox-skin")&&!h.is(".fancybox-wrap");)j=h[0]&&!(h[0].style.overflow&&"hidden"===h[0].style.overflow)&&
(h[0].clientWidth&&h[0].scrollWidth>h[0].clientWidth||h[0].clientHeight&&h[0].scrollHeight>h[0].clientHeight),h=f(h).parent();if(0!==c&&!j&&1<b.group.length&&!a.canShrink){if(0<g||0<k)b.prev(0<g?"down":"left");else if(0>g||0>k)b.next(0>g?"up":"right");d.preventDefault()}}))},trigger:function(a,d){var e,c=d||b.coming||b.current;if(c){f.isFunction(c[a])&&(e=c[a].apply(c,Array.prototype.slice.call(arguments,1)));if(!1===e)return!1;c.helpers&&f.each(c.helpers,function(d,e){if(e&&b.helpers[d]&&f.isFunction(b.helpers[d][a]))b.helpers[d][a](f.extend(!0,
{},b.helpers[d].defaults,e),c)});p.trigger(a)}},isImage:function(a){return q(a)&&a.match(/(^data:image\/.*,)|(\.(jp(e|g|eg)|gif|png|bmp|webp|svg)((\?|#).*)?$)/i)},isSWF:function(a){return q(a)&&a.match(/\.(swf)((\?|#).*)?$/i)},_start:function(a){var d={},e,c;a=l(a);e=b.group[a]||null;if(!e)return!1;d=f.extend(!0,{},b.opts,e);e=d.margin;c=d.padding;"number"===f.type(e)&&(d.margin=[e,e,e,e]);"number"===f.type(c)&&(d.padding=[c,c,c,c]);d.modal&&f.extend(!0,d,{closeBtn:!1,closeClick:!1,nextClick:!1,arrows:!1,
mouseWheel:!1,keys:null,helpers:{overlay:{closeClick:!1}}});d.autoSize&&(d.autoWidth=d.autoHeight=!0);"auto"===d.width&&(d.autoWidth=!0);"auto"===d.height&&(d.autoHeight=!0);d.group=b.group;d.index=a;b.coming=d;if(!1===b.trigger("beforeLoad"))b.coming=null;else{c=d.type;e=d.href;if(!c)return b.coming=null,b.current&&b.router&&"jumpto"!==b.router?(b.current.index=a,b[b.router](b.direction)):!1;b.isActive=!0;if("image"===c||"swf"===c)d.autoHeight=d.autoWidth=!1,d.scrolling="visible";"image"===c&&(d.aspectRatio=
!0);"iframe"===c&&s&&(d.scrolling="scroll");d.wrap=f(d.tpl.wrap).addClass("fancybox-"+(s?"mobile":"desktop")+" fancybox-type-"+c+" fancybox-tmp "+d.wrapCSS).appendTo(d.parent||"body");f.extend(d,{skin:f(".fancybox-skin",d.wrap),outer:f(".fancybox-outer",d.wrap),inner:f(".fancybox-inner",d.wrap)});f.each(["Top","Right","Bottom","Left"],function(a,b){d.skin.css("padding"+b,w(d.padding[a]))});b.trigger("onReady");if("inline"===c||"html"===c){if(!d.content||!d.content.length)return b._error("content")}else if(!e)return b._error("href");
"image"===c?b._loadImage():"ajax"===c?b._loadAjax():"iframe"===c?b._loadIframe():b._afterLoad()}},_error:function(a){f.extend(b.coming,{type:"html",autoWidth:!0,autoHeight:!0,minWidth:0,minHeight:0,scrolling:"no",hasError:a,content:b.coming.tpl.error});b._afterLoad()},_loadImage:function(){var a=b.imgPreload=new Image;a.onload=function(){this.onload=this.onerror=null;b.coming.width=this.width/b.opts.pixelRatio;b.coming.height=this.height/b.opts.pixelRatio;b._afterLoad()};a.onerror=function(){this.onload=
this.onerror=null;b._error("image")};a.src=b.coming.href;!0!==a.complete&&b.showLoading()},_loadAjax:function(){var a=b.coming;b.showLoading();b.ajaxLoad=f.ajax(f.extend({},a.ajax,{url:a.href,error:function(a,e){b.coming&&"abort"!==e?b._error("ajax",a):b.hideLoading()},success:function(d,e){"success"===e&&(a.content=d,b._afterLoad())}}))},_loadIframe:function(){var a=b.coming,d=f(a.tpl.iframe.replace(/\{rnd\}/g,(new Date).getTime())).attr("scrolling",s?"auto":a.iframe.scrolling).attr("src",a.href);
f(a.wrap).bind("onReset",function(){try{f(this).find("iframe").hide().attr("src","//about:blank").end().empty()}catch(a){}});a.iframe.preload&&(b.showLoading(),d.one("load",function(){f(this).data("ready",1);s||f(this).bind("load.fb",b.update);f(this).parents(".fancybox-wrap").width("100%").removeClass("fancybox-tmp").show();b._afterLoad()}));a.content=d.appendTo(a.inner);a.iframe.preload||b._afterLoad()},_preloadImages:function(){var a=b.group,d=b.current,e=a.length,c=d.preload?Math.min(d.preload,
e-1):0,f,g;for(g=1;g<=c;g+=1)f=a[(d.index+g)%e],"image"===f.type&&f.href&&((new Image).src=f.href)},_afterLoad:function(){var a=b.coming,d=b.current,e,c,k,g,h;b.hideLoading();if(a&&!1!==b.isActive)if(!1===b.trigger("afterLoad",a,d))a.wrap.stop(!0).trigger("onReset").remove(),b.coming=null;else{d&&(b.trigger("beforeChange",d),d.wrap.stop(!0).removeClass("fancybox-opened").find(".fancybox-item, .fancybox-nav").remove());b.unbindEvents();e=a.content;c=a.type;k=a.scrolling;f.extend(b,{wrap:a.wrap,skin:a.skin,
outer:a.outer,inner:a.inner,current:a,previous:d});g=a.href;switch(c){case "inline":case "ajax":case "html":a.selector?e=f("<div>").html(e).find(a.selector):t(e)&&(e.data("fancybox-placeholder")||e.data("fancybox-placeholder",f('<div class="fancybox-placeholder"></div>').insertAfter(e).hide()),e=e.show().detach(),a.wrap.bind("onReset",function(){f(this).find(e).length&&e.hide().replaceAll(e.data("fancybox-placeholder")).data("fancybox-placeholder",!1)}));break;case "image":e=a.tpl.image.replace("{href}",
g);break;case "swf":e='<object id="fancybox-swf" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="100%" height="100%"><param name="movie" value="'+g+'"></param>',h="",f.each(a.swf,function(a,b){e+='<param name="'+a+'" value="'+b+'"></param>';h+=" "+a+'="'+b+'"'}),e+='<embed src="'+g+'" type="application/x-shockwave-flash" width="100%" height="100%"'+h+"></embed></object>"}(!t(e)||!e.parent().is(a.inner))&&a.inner.append(e);b.trigger("beforeShow");a.inner.css("overflow","yes"===k?"scroll":
"no"===k?"hidden":k);b._setDimension();b.reposition();b.isOpen=!1;b.coming=null;b.bindEvents();if(b.isOpened){if(d.prevMethod)b.transitions[d.prevMethod]()}else f(".fancybox-wrap").not(a.wrap).stop(!0).trigger("onReset").remove();b.transitions[b.isOpened?a.nextMethod:a.openMethod]();b._preloadImages()}},_setDimension:function(){var a=b.getViewport(),d=0,e=!1,c=!1,e=b.wrap,k=b.skin,g=b.inner,h=b.current,c=h.width,j=h.height,m=h.minWidth,u=h.minHeight,n=h.maxWidth,p=h.maxHeight,s=h.scrolling,q=h.scrollOutside?
h.scrollbarWidth:0,x=h.margin,y=l(x[1]+x[3]),r=l(x[0]+x[2]),v,z,t,C,A,F,B,D,H;e.add(k).add(g).width("auto").height("auto").removeClass("fancybox-tmp");x=l(k.outerWidth(!0)-k.width());v=l(k.outerHeight(!0)-k.height());z=y+x;t=r+v;C=E(c)?(a.w-z)*l(c)/100:c;A=E(j)?(a.h-t)*l(j)/100:j;if("iframe"===h.type){if(H=h.content,h.autoHeight&&1===H.data("ready"))try{H[0].contentWindow.document.location&&(g.width(C).height(9999),F=H.contents().find("body"),q&&F.css("overflow-x","hidden"),A=F.outerHeight(!0))}catch(G){}}else if(h.autoWidth||
h.autoHeight)g.addClass("fancybox-tmp"),h.autoWidth||g.width(C),h.autoHeight||g.height(A),h.autoWidth&&(C=g.width()),h.autoHeight&&(A=g.height()),g.removeClass("fancybox-tmp");c=l(C);j=l(A);D=C/A;m=l(E(m)?l(m,"w")-z:m);n=l(E(n)?l(n,"w")-z:n);u=l(E(u)?l(u,"h")-t:u);p=l(E(p)?l(p,"h")-t:p);F=n;B=p;h.fitToView&&(n=Math.min(a.w-z,n),p=Math.min(a.h-t,p));z=a.w-y;r=a.h-r;h.aspectRatio?(c>n&&(c=n,j=l(c/D)),j>p&&(j=p,c=l(j*D)),c<m&&(c=m,j=l(c/D)),j<u&&(j=u,c=l(j*D))):(c=Math.max(m,Math.min(c,n)),h.autoHeight&&
"iframe"!==h.type&&(g.width(c),j=g.height()),j=Math.max(u,Math.min(j,p)));if(h.fitToView)if(g.width(c).height(j),e.width(c+x),a=e.width(),y=e.height(),h.aspectRatio)for(;(a>z||y>r)&&(c>m&&j>u)&&!(19<d++);)j=Math.max(u,Math.min(p,j-10)),c=l(j*D),c<m&&(c=m,j=l(c/D)),c>n&&(c=n,j=l(c/D)),g.width(c).height(j),e.width(c+x),a=e.width(),y=e.height();else c=Math.max(m,Math.min(c,c-(a-z))),j=Math.max(u,Math.min(j,j-(y-r)));q&&("auto"===s&&j<A&&c+x+q<z)&&(c+=q);g.width(c).height(j);e.width(c+x);a=e.width();
y=e.height();e=(a>z||y>r)&&c>m&&j>u;c=h.aspectRatio?c<F&&j<B&&c<C&&j<A:(c<F||j<B)&&(c<C||j<A);f.extend(h,{dim:{width:w(a),height:w(y)},origWidth:C,origHeight:A,canShrink:e,canExpand:c,wPadding:x,hPadding:v,wrapSpace:y-k.outerHeight(!0),skinSpace:k.height()-j});!H&&(h.autoHeight&&j>u&&j<p&&!c)&&g.height("auto")},_getPosition:function(a){var d=b.current,e=b.getViewport(),c=d.margin,f=b.wrap.width()+c[1]+c[3],g=b.wrap.height()+c[0]+c[2],c={position:"absolute",top:c[0],left:c[3]};d.autoCenter&&d.fixed&&
!a&&g<=e.h&&f<=e.w?c.position="fixed":d.locked||(c.top+=e.y,c.left+=e.x);c.top=w(Math.max(c.top,c.top+(e.h-g)*d.topRatio));c.left=w(Math.max(c.left,c.left+(e.w-f)*d.leftRatio));return c},_afterZoomIn:function(){var a=b.current;a&&(b.isOpen=b.isOpened=!0,b.wrap.css("overflow","visible").addClass("fancybox-opened"),b.update(),(a.closeClick||a.nextClick&&1<b.group.length)&&b.inner.css("cursor","pointer").bind("click.fb",function(d){!f(d.target).is("a")&&!f(d.target).parent().is("a")&&(d.preventDefault(),
b[a.closeClick?"close":"next"]())}),a.closeBtn&&f(a.tpl.closeBtn).appendTo(b.skin).bind("click.fb",function(a){a.preventDefault();b.close()}),a.arrows&&1<b.group.length&&((a.loop||0<a.index)&&f(a.tpl.prev).appendTo(b.outer).bind("click.fb",b.prev),(a.loop||a.index<b.group.length-1)&&f(a.tpl.next).appendTo(b.outer).bind("click.fb",b.next)),b.trigger("afterShow"),!a.loop&&a.index===a.group.length-1?b.play(!1):b.opts.autoPlay&&!b.player.isActive&&(b.opts.autoPlay=!1,b.play()))},_afterZoomOut:function(a){a=
a||b.current;f(".fancybox-wrap").trigger("onReset").remove();f.extend(b,{group:{},opts:{},router:!1,current:null,isActive:!1,isOpened:!1,isOpen:!1,isClosing:!1,wrap:null,skin:null,outer:null,inner:null});b.trigger("afterClose",a)}});b.transitions={getOrigPosition:function(){var a=b.current,d=a.element,e=a.orig,c={},f=50,g=50,h=a.hPadding,j=a.wPadding,m=b.getViewport();!e&&(a.isDom&&d.is(":visible"))&&(e=d.find("img:first"),e.length||(e=d));t(e)?(c=e.offset(),e.is("img")&&(f=e.outerWidth(),g=e.outerHeight())):
(c.top=m.y+(m.h-g)*a.topRatio,c.left=m.x+(m.w-f)*a.leftRatio);if("fixed"===b.wrap.css("position")||a.locked)c.top-=m.y,c.left-=m.x;return c={top:w(c.top-h*a.topRatio),left:w(c.left-j*a.leftRatio),width:w(f+j),height:w(g+h)}},step:function(a,d){var e,c,f=d.prop;c=b.current;var g=c.wrapSpace,h=c.skinSpace;if("width"===f||"height"===f)e=d.end===d.start?1:(a-d.start)/(d.end-d.start),b.isClosing&&(e=1-e),c="width"===f?c.wPadding:c.hPadding,c=a-c,b.skin[f](l("width"===f?c:c-g*e)),b.inner[f](l("width"===
f?c:c-g*e-h*e))},zoomIn:function(){var a=b.current,d=a.pos,e=a.openEffect,c="elastic"===e,k=f.extend({opacity:1},d);delete k.position;c?(d=this.getOrigPosition(),a.openOpacity&&(d.opacity=0.1)):"fade"===e&&(d.opacity=0.1);b.wrap.css(d).animate(k,{duration:"none"===e?0:a.openSpeed,easing:a.openEasing,step:c?this.step:null,complete:b._afterZoomIn})},zoomOut:function(){var a=b.current,d=a.closeEffect,e="elastic"===d,c={opacity:0.1};e&&(c=this.getOrigPosition(),a.closeOpacity&&(c.opacity=0.1));b.wrap.animate(c,
{duration:"none"===d?0:a.closeSpeed,easing:a.closeEasing,step:e?this.step:null,complete:b._afterZoomOut})},changeIn:function(){var a=b.current,d=a.nextEffect,e=a.pos,c={opacity:1},f=b.direction,g;e.opacity=0.1;"elastic"===d&&(g="down"===f||"up"===f?"top":"left","down"===f||"right"===f?(e[g]=w(l(e[g])-200),c[g]="+=200px"):(e[g]=w(l(e[g])+200),c[g]="-=200px"));"none"===d?b._afterZoomIn():b.wrap.css(e).animate(c,{duration:a.nextSpeed,easing:a.nextEasing,complete:b._afterZoomIn})},changeOut:function(){var a=
b.previous,d=a.prevEffect,e={opacity:0.1},c=b.direction;"elastic"===d&&(e["down"===c||"up"===c?"top":"left"]=("up"===c||"left"===c?"-":"+")+"=200px");a.wrap.animate(e,{duration:"none"===d?0:a.prevSpeed,easing:a.prevEasing,complete:function(){f(this).trigger("onReset").remove()}})}};b.helpers.overlay={defaults:{closeClick:!0,speedOut:200,showEarly:!0,css:{},locked:!s,fixed:!0},overlay:null,fixed:!1,el:f("html"),create:function(a){a=f.extend({},this.defaults,a);this.overlay&&this.close();this.overlay=
f('<div class="fancybox-overlay"></div>').appendTo(b.coming?b.coming.parent:a.parent);this.fixed=!1;a.fixed&&b.defaults.fixed&&(this.overlay.addClass("fancybox-overlay-fixed"),this.fixed=!0)},open:function(a){var d=this;a=f.extend({},this.defaults,a);this.overlay?this.overlay.unbind(".overlay").width("auto").height("auto"):this.create(a);this.fixed||(n.bind("resize.overlay",f.proxy(this.update,this)),this.update());a.closeClick&&this.overlay.bind("click.overlay",function(a){if(f(a.target).hasClass("fancybox-overlay"))return b.isActive?
b.close():d.close(),!1});this.overlay.css(a.css).show()},close:function(){var a,b;n.unbind("resize.overlay");this.el.hasClass("fancybox-lock")&&(f(".fancybox-margin").removeClass("fancybox-margin"),a=n.scrollTop(),b=n.scrollLeft(),this.el.removeClass("fancybox-lock"),n.scrollTop(a).scrollLeft(b));f(".fancybox-overlay").remove().hide();f.extend(this,{overlay:null,fixed:!1})},update:function(){var a="100%",b;this.overlay.width(a).height("100%");I?(b=Math.max(G.documentElement.offsetWidth,G.body.offsetWidth),
p.width()>b&&(a=p.width())):p.width()>n.width()&&(a=p.width());this.overlay.width(a).height(p.height())},onReady:function(a,b){var e=this.overlay;f(".fancybox-overlay").stop(!0,!0);e||this.create(a);a.locked&&(this.fixed&&b.fixed)&&(e||(this.margin=p.height()>n.height()?f("html").css("margin-right").replace("px",""):!1),b.locked=this.overlay.append(b.wrap),b.fixed=!1);!0===a.showEarly&&this.beforeShow.apply(this,arguments)},beforeShow:function(a,b){var e,c;b.locked&&(!1!==this.margin&&(f("*").filter(function(){return"fixed"===
f(this).css("position")&&!f(this).hasClass("fancybox-overlay")&&!f(this).hasClass("fancybox-wrap")}).addClass("fancybox-margin"),this.el.addClass("fancybox-margin")),e=n.scrollTop(),c=n.scrollLeft(),this.el.addClass("fancybox-lock"),n.scrollTop(e).scrollLeft(c));this.open(a)},onUpdate:function(){this.fixed||this.update()},afterClose:function(a){this.overlay&&!b.coming&&this.overlay.fadeOut(a.speedOut,f.proxy(this.close,this))}};b.helpers.title={defaults:{type:"float",position:"bottom"},beforeShow:function(a){var d=
b.current,e=d.title,c=a.type;f.isFunction(e)&&(e=e.call(d.element,d));if(q(e)&&""!==f.trim(e)){d=f('<div class="fancybox-title fancybox-title-'+c+'-wrap">'+e+"</div>");switch(c){case "inside":c=b.skin;break;case "outside":c=b.wrap;break;case "over":c=b.inner;break;default:c=b.skin,d.appendTo("body"),I&&d.width(d.width()),d.wrapInner('<span class="child"></span>'),b.current.margin[2]+=Math.abs(l(d.css("margin-bottom")))}d["top"===a.position?"prependTo":"appendTo"](c)}}};f.fn.fancybox=function(a){var d,
e=f(this),c=this.selector||"",k=function(g){var h=f(this).blur(),j=d,k,l;!g.ctrlKey&&(!g.altKey&&!g.shiftKey&&!g.metaKey)&&!h.is(".fancybox-wrap")&&(k=a.groupAttr||"data-fancybox-group",l=h.attr(k),l||(k="rel",l=h.get(0)[k]),l&&(""!==l&&"nofollow"!==l)&&(h=c.length?f(c):e,h=h.filter("["+k+'="'+l+'"]'),j=h.index(this)),a.index=j,!1!==b.open(h,a)&&g.preventDefault())};a=a||{};d=a.index||0;!c||!1===a.live?e.unbind("click.fb-start").bind("click.fb-start",k):p.undelegate(c,"click.fb-start").delegate(c+
":not('.fancybox-item, .fancybox-nav')","click.fb-start",k);this.filter("[data-fancybox-start=1]").trigger("click");return this};p.ready(function(){var a,d;f.scrollbarWidth===v&&(f.scrollbarWidth=function(){var a=f('<div style="width:50px;height:50px;overflow:auto"><div/></div>').appendTo("body"),b=a.children(),b=b.innerWidth()-b.height(99).innerWidth();a.remove();return b});if(f.support.fixedPosition===v){a=f.support;d=f('<div style="position:fixed;top:20px;"></div>').appendTo("body");var e=20===
d[0].offsetTop||15===d[0].offsetTop;d.remove();a.fixedPosition=e}f.extend(b.defaults,{scrollbarWidth:f.scrollbarWidth(),fixed:f.support.fixedPosition,parent:f("body")});a=f(r).width();J.addClass("fancybox-lock-test");d=f(r).width();J.removeClass("fancybox-lock-test");f("<style type='text/css'>.fancybox-margin{margin-right:"+(d-a)+"px;}</style>").appendTo("head")})})(window,document,jQuery);;
"use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function") } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor) } } return function (Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor } }(); (function () { var ImagePicker, ImagePickerOption, both_array_are_equal, sanitized_options, indexOf = [].indexOf; jQuery.fn.extend({ imagepicker: function () { var opts = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {}; return this.each(function () { var select; if ((select = jQuery(this)).data("picker") && select.data("picker").destroy(), select.data("picker", new ImagePicker(this, sanitized_options(opts))), null != opts.initialized) return opts.initialized.call(select.data("picker")) }) } }), sanitized_options = function (opts) { var default_options; return default_options = { hide_select: !0, show_label: !1, initialized: void 0, changed: void 0, clicked: void 0, selected: void 0, limit: void 0, limit_reached: void 0, font_awesome: !1 }, jQuery.extend(default_options, opts) }, both_array_are_equal = function (a, b) { var i, j, len, x; if (!a || !b || a.length !== b.length) return !1; for (a = a.slice(0), b = b.slice(0), a.sort(), b.sort(), i = j = 0, len = a.length; j < len; i = ++j)if (x = a[i], b[i] !== x) return !1; return !0 }, ImagePicker = function () { function ImagePicker(select_element) { var opts1 = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {}; _classCallCheck(this, ImagePicker), this.sync_picker_with_select = this.sync_picker_with_select.bind(this), this.opts = opts1, this.select = jQuery(select_element), this.multiple = "multiple" === this.select.attr("multiple"), null != this.select.data("limit") && (this.opts.limit = parseInt(this.select.data("limit"))), this.build_and_append_picker() } return _createClass(ImagePicker, [{ key: "destroy", value: function () { var j, len, ref; for (j = 0, len = (ref = this.picker_options).length; j < len; j++)ref[j].destroy(); return this.picker.remove(), this.select.off("change", this.sync_picker_with_select), this.select.removeData("picker"), this.select.show() } }, { key: "build_and_append_picker", value: function () { return this.opts.hide_select && this.select.hide(), this.select.on("change", this.sync_picker_with_select), null != this.picker && this.picker.remove(), this.create_picker(), this.select.after(this.picker), this.sync_picker_with_select() } }, { key: "sync_picker_with_select", value: function () { var j, len, option, ref, results; for (results = [], j = 0, len = (ref = this.picker_options).length; j < len; j++)(option = ref[j]).is_selected() ? results.push(option.mark_as_selected()) : results.push(option.unmark_as_selected()); return results } }, { key: "create_picker", value: function () { return this.picker = jQuery("<ul class='thumbnails image_picker_selector'></ul>"), this.picker_options = [], this.recursively_parse_option_groups(this.select, this.picker), this.picker } }, { key: "recursively_parse_option_groups", value: function (scoped_dom, target_container) { var container, j, k, len, len1, option, option_group, ref, ref1, results; for (j = 0, len = (ref = scoped_dom.children("optgroup")).length; j < len; j++)option_group = ref[j], option_group = jQuery(option_group), (container = jQuery("<ul></ul>")).append(jQuery("<li class='group_title'>" + option_group.attr("label") + "</li>")), target_container.append(jQuery("<li class='group'>").append(container)), this.recursively_parse_option_groups(option_group, container); for (ref1 = function () { var l, len1, ref1, results1; for (results1 = [], l = 0, len1 = (ref1 = scoped_dom.children("option")).length; l < len1; l++)option = ref1[l], results1.push(new ImagePickerOption(option, this, this.opts)); return results1 }.call(this), results = [], k = 0, len1 = ref1.length; k < len1; k++)option = ref1[k], this.picker_options.push(option), option.has_image() && results.push(target_container.append(option.node)); return results } }, { key: "has_implicit_blanks", value: function () { var option; return function () { var j, len, ref, results; for (results = [], j = 0, len = (ref = this.picker_options).length; j < len; j++)(option = ref[j]).is_blank() && !option.has_image() && results.push(option); return results }.call(this).length > 0 } }, { key: "selected_values", value: function () { return this.multiple ? this.select.val() || [] : [this.select.val()] } }, { key: "toggle", value: function (imagepicker_option, original_event) { var new_values, old_values, selected_value; if (old_values = this.selected_values(), selected_value = imagepicker_option.value().toString(), this.multiple ? indexOf.call(this.selected_values(), selected_value) >= 0 ? ((new_values = this.selected_values()).splice(jQuery.inArray(selected_value, old_values), 1), this.select.val([]), this.select.val(new_values)) : null != this.opts.limit && this.selected_values().length >= this.opts.limit ? null != this.opts.limit_reached && this.opts.limit_reached.call(this.select) : this.select.val(this.selected_values().concat(selected_value)) : this.has_implicit_blanks() && imagepicker_option.is_selected() ? this.select.val("") : this.select.val(selected_value), !both_array_are_equal(old_values, this.selected_values()) && (this.select.change(), null != this.opts.changed)) return this.opts.changed.call(this.select, old_values, this.selected_values(), original_event) } }]), ImagePicker }(), ImagePickerOption = function () { function ImagePickerOption(option_element, picker) { var opts1 = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {}; _classCallCheck(this, ImagePickerOption), this.clicked = this.clicked.bind(this), this.picker = picker, this.opts = opts1, this.option = jQuery(option_element), this.create_node() } return _createClass(ImagePickerOption, [{ key: "destroy", value: function () { return this.node.find(".thumbnail").off("click", this.clicked) } }, { key: "has_image", value: function () { return null != this.option.data("img-src") } }, { key: "is_blank", value: function () { return !(null != this.value() && "" !== this.value()) } }, { key: "is_selected", value: function () { var select_value; return select_value = this.picker.select.val(), this.picker.multiple ? jQuery.inArray(this.value(), select_value) >= 0 : this.value() === select_value } }, { key: "mark_as_selected", value: function () { return this.node.find(".thumbnail").addClass("selected") } }, { key: "unmark_as_selected", value: function () { return this.node.find(".thumbnail").removeClass("selected") } }, { key: "value", value: function () { return this.option.val() } }, { key: "label", value: function () { return this.option.data("img-label") ? this.option.data("img-label") : this.option.text() } }, { key: "clicked", value: function (event) { if (this.picker.toggle(this, event), null != this.opts.clicked && this.opts.clicked.call(this.picker.select, this, event), null != this.opts.selected && this.is_selected()) return this.opts.selected.call(this.picker.select, this, event) } }, { key: "create_node", value: function () { var image, imgAlt, imgClass, thumbnail; return this.node = jQuery("<li/>"), this.option.data("font_awesome") ? (image = jQuery("<i>")).attr("class", "fa-fw " + this.option.data("img-src")) : (image = jQuery("<img class='image_picker_image'/>")).attr("src", this.option.data("img-src")), thumbnail = jQuery("<div class='thumbnail'>"), (imgClass = this.option.data("img-class")) && (this.node.addClass(imgClass), image.addClass(imgClass), thumbnail.addClass(imgClass)), (imgAlt = this.option.data("img-alt")) && image.attr("alt", imgAlt), thumbnail.on("click", this.clicked), thumbnail.append(image), this.opts.show_label && thumbnail.append(jQuery("<p/>").html(this.label())), this.node.append(thumbnail), this.node } }]), ImagePickerOption }() }).call(void 0);;
/*!
 * imagesLoaded PACKAGED v3.0.4
 * https://github.com/desandro/imagesloaded
 * JavaScript is all like "You images are done yet or what?"
 */

(function(){"use strict";function e(){}function t(e,t){for(var n=e.length;n--;)if(e[n].listener===t)return n;return-1}var n=e.prototype;n.getListeners=function(e){var t,n,i=this._getEvents();if("object"==typeof e){t={};for(n in i)i.hasOwnProperty(n)&&e.test(n)&&(t[n]=i[n])}else t=i[e]||(i[e]=[]);return t},n.flattenListeners=function(e){var t,n=[];for(t=0;e.length>t;t+=1)n.push(e[t].listener);return n},n.getListenersAsObject=function(e){var t,n=this.getListeners(e);return n instanceof Array&&(t={},t[e]=n),t||n},n.addListener=function(e,n){var i,r=this.getListenersAsObject(e),o="object"==typeof n;for(i in r)r.hasOwnProperty(i)&&-1===t(r[i],n)&&r[i].push(o?n:{listener:n,once:!1});return this},n.on=n.addListener,n.addOnceListener=function(e,t){return this.addListener(e,{listener:t,once:!0})},n.once=n.addOnceListener,n.defineEvent=function(e){return this.getListeners(e),this},n.defineEvents=function(e){for(var t=0;e.length>t;t+=1)this.defineEvent(e[t]);return this},n.removeListener=function(e,n){var i,r,o=this.getListenersAsObject(e);for(r in o)o.hasOwnProperty(r)&&(i=t(o[r],n),-1!==i&&o[r].splice(i,1));return this},n.off=n.removeListener,n.addListeners=function(e,t){return this.manipulateListeners(!1,e,t)},n.removeListeners=function(e,t){return this.manipulateListeners(!0,e,t)},n.manipulateListeners=function(e,t,n){var i,r,o=e?this.removeListener:this.addListener,s=e?this.removeListeners:this.addListeners;if("object"!=typeof t||t instanceof RegExp)for(i=n.length;i--;)o.call(this,t,n[i]);else for(i in t)t.hasOwnProperty(i)&&(r=t[i])&&("function"==typeof r?o.call(this,i,r):s.call(this,i,r));return this},n.removeEvent=function(e){var t,n=typeof e,i=this._getEvents();if("string"===n)delete i[e];else if("object"===n)for(t in i)i.hasOwnProperty(t)&&e.test(t)&&delete i[t];else delete this._events;return this},n.emitEvent=function(e,t){var n,i,r,o,s=this.getListenersAsObject(e);for(r in s)if(s.hasOwnProperty(r))for(i=s[r].length;i--;)n=s[r][i],o=n.listener.apply(this,t||[]),(o===this._getOnceReturnValue()||n.once===!0)&&this.removeListener(e,s[r][i].listener);return this},n.trigger=n.emitEvent,n.emit=function(e){var t=Array.prototype.slice.call(arguments,1);return this.emitEvent(e,t)},n.setOnceReturnValue=function(e){return this._onceReturnValue=e,this},n._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},n._getEvents=function(){return this._events||(this._events={})},"function"==typeof define&&define.amd?define(function(){return e}):"undefined"!=typeof module&&module.exports?module.exports=e:this.EventEmitter=e}).call(this),function(e){"use strict";var t=document.documentElement,n=function(){};t.addEventListener?n=function(e,t,n){e.addEventListener(t,n,!1)}:t.attachEvent&&(n=function(t,n,i){t[n+i]=i.handleEvent?function(){var t=e.event;t.target=t.target||t.srcElement,i.handleEvent.call(i,t)}:function(){var n=e.event;n.target=n.target||n.srcElement,i.call(t,n)},t.attachEvent("on"+n,t[n+i])});var i=function(){};t.removeEventListener?i=function(e,t,n){e.removeEventListener(t,n,!1)}:t.detachEvent&&(i=function(e,t,n){e.detachEvent("on"+t,e[t+n]);try{delete e[t+n]}catch(i){e[t+n]=void 0}});var r={bind:n,unbind:i};"function"==typeof define&&define.amd?define(r):e.eventie=r}(this),function(e){"use strict";function t(e,t){for(var n in t)e[n]=t[n];return e}function n(e){return"[object Array]"===c.call(e)}function i(e){var t=[];if(n(e))t=e;else if("number"==typeof e.length)for(var i=0,r=e.length;r>i;i++)t.push(e[i]);else t.push(e);return t}function r(e,n){function r(e,n,s){if(!(this instanceof r))return new r(e,n);"string"==typeof e&&(e=document.querySelectorAll(e)),this.elements=i(e),this.options=t({},this.options),"function"==typeof n?s=n:t(this.options,n),s&&this.on("always",s),this.getImages(),o&&(this.jqDeferred=new o.Deferred);var a=this;setTimeout(function(){a.check()})}function c(e){this.img=e}r.prototype=new e,r.prototype.options={},r.prototype.getImages=function(){this.images=[];for(var e=0,t=this.elements.length;t>e;e++){var n=this.elements[e];"IMG"===n.nodeName&&this.addImage(n);for(var i=n.querySelectorAll("img"),r=0,o=i.length;o>r;r++){var s=i[r];this.addImage(s)}}},r.prototype.addImage=function(e){var t=new c(e);this.images.push(t)},r.prototype.check=function(){function e(e,r){return t.options.debug&&a&&s.log("confirm",e,r),t.progress(e),n++,n===i&&t.complete(),!0}var t=this,n=0,i=this.images.length;if(this.hasAnyBroken=!1,!i)return this.complete(),void 0;for(var r=0;i>r;r++){var o=this.images[r];o.on("confirm",e),o.check()}},r.prototype.progress=function(e){this.hasAnyBroken=this.hasAnyBroken||!e.isLoaded;var t=this;setTimeout(function(){t.emit("progress",t,e),t.jqDeferred&&t.jqDeferred.notify(t,e)})},r.prototype.complete=function(){var e=this.hasAnyBroken?"fail":"done";this.isComplete=!0;var t=this;setTimeout(function(){if(t.emit(e,t),t.emit("always",t),t.jqDeferred){var n=t.hasAnyBroken?"reject":"resolve";t.jqDeferred[n](t)}})},o&&(o.fn.imagesLoaded=function(e,t){var n=new r(this,e,t);return n.jqDeferred.promise(o(this))});var f={};return c.prototype=new e,c.prototype.check=function(){var e=f[this.img.src];if(e)return this.useCached(e),void 0;if(f[this.img.src]=this,this.img.complete&&void 0!==this.img.naturalWidth)return this.confirm(0!==this.img.naturalWidth,"naturalWidth"),void 0;var t=this.proxyImage=new Image;n.bind(t,"load",this),n.bind(t,"error",this),t.src=this.img.src},c.prototype.useCached=function(e){if(e.isConfirmed)this.confirm(e.isLoaded,"cached was confirmed");else{var t=this;e.on("confirm",function(e){return t.confirm(e.isLoaded,"cache emitted confirmed"),!0})}},c.prototype.confirm=function(e,t){this.isConfirmed=!0,this.isLoaded=e,this.emit("confirm",this,t)},c.prototype.handleEvent=function(e){var t="on"+e.type;this[t]&&this[t](e)},c.prototype.onload=function(){this.confirm(!0,"onload"),this.unbindProxyEvents()},c.prototype.onerror=function(){this.confirm(!1,"onerror"),this.unbindProxyEvents()},c.prototype.unbindProxyEvents=function(){n.unbind(this.proxyImage,"load",this),n.unbind(this.proxyImage,"error",this)},r}var o=e.jQuery,s=e.console,a=s!==void 0,c=Object.prototype.toString;"function"==typeof define&&define.amd?define(["eventEmitter/EventEmitter","eventie/eventie"],r):e.imagesLoaded=r(e.EventEmitter,e.eventie)}(window);
;
/*! Copyright (c) 2011 Brandon Aaron (http://brandonaaron.net)
 * Licensed under the MIT License (LICENSE.txt).
 *
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 * Thanks to: Seamus Leahy for adding deltaX and deltaY
 *
 * Version: 3.0.6
 * 
 * Requires: 1.2.2+
 */
(function(d){function e(a){var b=a||window.event,c=[].slice.call(arguments,1),f=0,e=0,g=0,a=d.event.fix(b);a.type="mousewheel";b.wheelDelta&&(f=b.wheelDelta/120);b.detail&&(f=-b.detail/3);g=f;b.axis!==void 0&&b.axis===b.HORIZONTAL_AXIS&&(g=0,e=-1*f);b.wheelDeltaY!==void 0&&(g=b.wheelDeltaY/120);b.wheelDeltaX!==void 0&&(e=-1*b.wheelDeltaX/120);c.unshift(a,f,e,g);return(d.event.dispatch||d.event.handle).apply(this,c)}var c=["DOMMouseScroll","mousewheel"];if(d.event.fixHooks)for(var h=c.length;h;)d.event.fixHooks[c[--h]]=
d.event.mouseHooks;d.event.special.mousewheel={setup:function(){if(this.addEventListener)for(var a=c.length;a;)this.addEventListener(c[--a],e,false);else this.onmousewheel=e},teardown:function(){if(this.removeEventListener)for(var a=c.length;a;)this.removeEventListener(c[--a],e,false);else this.onmousewheel=null}};d.fn.extend({mousewheel:function(a){return a?this.bind("mousewheel",a):this.trigger("mousewheel")},unmousewheel:function(a){return this.unbind("mousewheel",a)}})})(jQuery);;
/**
 * Copyright (c) 2007 Ariel Flesler - aflesler ○ gmail • com | https://github.com/flesler
 * Licensed under MIT
 * @author Ariel Flesler
 * @version 2.1.2
 */
; (function (f) { "use strict"; "function" === typeof define && define.amd ? define(["jquery"], f) : "undefined" !== typeof module && module.exports ? module.exports = f(require("jquery")) : f(jQuery) })(function ($) { "use strict"; function n(a) { return !a.nodeName || -1 !== $.inArray(a.nodeName.toLowerCase(), ["iframe", "#document", "html", "body"]) } function h(a) { return $.isFunction(a) || $.isPlainObject(a) ? a : { top: a, left: a } } var p = $.scrollTo = function (a, d, b) { return $(window).scrollTo(a, d, b) }; p.defaults = { axis: "xy", duration: 0, limit: !0 }; $.fn.scrollTo = function (a, d, b) { "object" === typeof d && (b = d, d = 0); "function" === typeof b && (b = { onAfter: b }); "max" === a && (a = 9E9); b = $.extend({}, p.defaults, b); d = d || b.duration; var u = b.queue && 1 < b.axis.length; u && (d /= 2); b.offset = h(b.offset); b.over = h(b.over); return this.each(function () { function k(a) { var k = $.extend({}, b, { queue: !0, duration: d, complete: a && function () { a.call(q, e, b) } }); r.animate(f, k) } if (null !== a) { var l = n(this), q = l ? this.contentWindow || window : this, r = $(q), e = a, f = {}, t; switch (typeof e) { case "number": case "string": if (/^([+-]=?)?\d+(\.\d+)?(px|%)?$/.test(e)) { e = h(e); break } e = l ? $(e) : $(e, q); case "object": if (e.length === 0) return; if (e.is || e.style) t = (e = $(e)).offset() }var v = $.isFunction(b.offset) && b.offset(q, e) || b.offset; $.each(b.axis.split(""), function (a, c) { var d = "x" === c ? "Left" : "Top", m = d.toLowerCase(), g = "scroll" + d, h = r[g](), n = p.max(q, c); t ? (f[g] = t[m] + (l ? 0 : h - r.offset()[m]), b.margin && (f[g] -= parseInt(e.css("margin" + d), 10) || 0, f[g] -= parseInt(e.css("border" + d + "Width"), 10) || 0), f[g] += v[m] || 0, b.over[m] && (f[g] += e["x" === c ? "width" : "height"]() * b.over[m])) : (d = e[m], f[g] = d.slice && "%" === d.slice(-1) ? parseFloat(d) / 100 * n : d); b.limit && /^\d+$/.test(f[g]) && (f[g] = 0 >= f[g] ? 0 : Math.min(f[g], n)); !a && 1 < b.axis.length && (h === f[g] ? f = {} : u && (k(b.onAfterFirst), f = {})) }); k(b.onAfter) } }) }; p.max = function (a, d) { var b = "x" === d ? "Width" : "Height", h = "scroll" + b; if (!n(a)) return a[h] - $(a)[b.toLowerCase()](); var b = "client" + b, k = a.ownerDocument || a.document, l = k.documentElement, k = k.body; return Math.max(l[h], k[h]) - Math.min(l[b], k[b]) }; $.Tween.propHooks.scrollLeft = $.Tween.propHooks.scrollTop = { get: function (a) { return $(a.elem)[a.prop]() }, set: function (a) { var d = this.get(a); if (a.options.interrupt && a._last && a._last !== d) return $(a.elem).stop(); var b = Math.round(a.now); d !== b && ($(a.elem)[a.prop](b), a._last = this.get(a)) } }; return p });;
/**
* jQuery Pub/Sub plugin for Loosely Coupled logic.
*
* Based on Hiroshi Kuwabara's jQuery version of Peter Higgins' port 
* from Dojo to JQuery.
*
* Hiroshi Kuwabara's JQuery version
* https://github.com/kuwabarahiroshi/bloody-jquery-plugins/blob/master/pubsub.js
*
* Peter Higgins' port from Dojo to jQuery
* https://github.com/phiggins42/bloody-jquery-plugins/blob/master/pubsub.js
*
* Perfomance enhanced version based on Lu�s Couto
* https://github.com/phiggins42/bloody-jquery-plugins/blob/55e41df9bf08f42378bb08b93efcb28555b61aeb/pubsub.js
*/
(function ($) {
    "use strict";
    var cache = {},
    /**
    *    Events.publish
    *    e.g.: Events.publish("/Article/added", [article], this);
    *
    *    @class Events
    *    @method publish
    *    @param topic {String}
    *    @param args    {Array}
    *    @param scope {Object} Optional
    */
    publish = function (topic, args, scope) {
        var topics = topic.split('/');
        while (topics[0]) {
            if (cache[topic]) {
                var thisTopic = cache[topic],
                    i = thisTopic.length - 1;

                for (i; i >= 0; i -= 1) {
                    thisTopic[i].apply(scope || this, args || []);
                }
            }
            topics.pop();
            topic = topics.join('/');
        }
    },
    /**
    *    Events.subscribe
    *    e.g.: Events.subscribe("/Article/added", Articles.validate)
    *
    *    @class Events
    *    @method subscribe
    *    @param topic {String}
    *    @param callback {Function}
    *    @return Event handler {Array}
    */
    subscribe = function (topic, callback) {
        if (!cache[topic]) {
            cache[topic] = [];
        }
        cache[topic].push(callback);
        return [topic, callback];
    },
    /**
    *    Events.unsubscribe
    *    e.g.: var handle = Events.subscribe("/Article/added", Articles.validate);
    *        Events.unsubscribe(handle);
    *
    *    @class Events
    *    @method unsubscribe
    *    @param handle {Array}
    *    @param completly {Boolean}
    *    @return {type description }
    */
    unsubscribe = function (handle, completly) {
        var t = handle[0],
            i = cache[t].length - 1;

        if (cache[t]) {
            for (i; i >= 0; i -= 1) {
                if (cache[t][i] === handle[1]) {
                    cache[t].splice(cache[t][i], 1);
                    if (completly) {
                        delete cache[t];
                    }
                }
            }
        }
    };

    $.publish = publish;
    $.subscribe = subscribe;
    $.unsubscribe = unsubscribe;

} (jQuery));;
/**
 * jQuery Unveil
 * A very lightweight jQuery plugin to lazy load images
 * http://luis-almeida.github.com/unveil
 *
 * Licensed under the MIT license.
 * Copyright 2013 Luís Almeida
 * https://github.com/luis-almeida
 */

;(function($) {

  $.fn.unveil = function(threshold, callback) {

    var $w = $(window),
        th = threshold || 0,
        retina = window.devicePixelRatio > 1,
        attrib = retina? "data-src-retina" : "data-src",
        images = this,
        loaded;

    this.one("unveil", function() {
      var source = this.getAttribute(attrib);
      source = source || this.getAttribute("data-src");
      if (source) {
        this.setAttribute("src", source);
        if (typeof callback === "function") callback.call(this);
      }
    });

    function unveil() {
      var inview = images.filter(function() {
        var $e = $(this);
        if ($e.is(":hidden")) return;

        var wt = $w.scrollTop(),
            wb = wt + $w.height(),
            et = $e.offset().top,
            eb = et + $e.height();

        return eb >= wt - th && et <= wb + th;
      });

      loaded = inview.trigger("unveil");
      images = images.not(loaded);
    }

    $w.on("scroll.unveil resize.unveil lookup.unveil", unveil);

    unveil();

    return this;

  };

})(window.jQuery || window.Zepto);
;
!function (e, t) { "object" == typeof exports && "undefined" != typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define(t) : e.moment = t() }(this, function () { "use strict"; var e, i; function c() { return e.apply(null, arguments) } function o(e) { return e instanceof Array || "[object Array]" === Object.prototype.toString.call(e) } function u(e) { return null != e && "[object Object]" === Object.prototype.toString.call(e) } function l(e) { return void 0 === e } function h(e) { return "number" == typeof e || "[object Number]" === Object.prototype.toString.call(e) } function d(e) { return e instanceof Date || "[object Date]" === Object.prototype.toString.call(e) } function f(e, t) { var n, s = []; for (n = 0; n < e.length; ++n)s.push(t(e[n], n)); return s } function m(e, t) { return Object.prototype.hasOwnProperty.call(e, t) } function _(e, t) { for (var n in t) m(t, n) && (e[n] = t[n]); return m(t, "toString") && (e.toString = t.toString), m(t, "valueOf") && (e.valueOf = t.valueOf), e } function y(e, t, n, s) { return Tt(e, t, n, s, !0).utc() } function g(e) { return null == e._pf && (e._pf = { empty: !1, unusedTokens: [], unusedInput: [], overflow: -2, charsLeftOver: 0, nullInput: !1, invalidMonth: null, invalidFormat: !1, userInvalidated: !1, iso: !1, parsedDateParts: [], meridiem: null, rfc2822: !1, weekdayMismatch: !1 }), e._pf } function v(e) { if (null == e._isValid) { var t = g(e), n = i.call(t.parsedDateParts, function (e) { return null != e }), s = !isNaN(e._d.getTime()) && t.overflow < 0 && !t.empty && !t.invalidMonth && !t.invalidWeekday && !t.weekdayMismatch && !t.nullInput && !t.invalidFormat && !t.userInvalidated && (!t.meridiem || t.meridiem && n); if (e._strict && (s = s && 0 === t.charsLeftOver && 0 === t.unusedTokens.length && void 0 === t.bigHour), null != Object.isFrozen && Object.isFrozen(e)) return s; e._isValid = s } return e._isValid } function p(e) { var t = y(NaN); return null != e ? _(g(t), e) : g(t).userInvalidated = !0, t } i = Array.prototype.some ? Array.prototype.some : function (e) { for (var t = Object(this), n = t.length >>> 0, s = 0; s < n; s++)if (s in t && e.call(this, t[s], s, t)) return !0; return !1 }; var r = c.momentProperties = []; function w(e, t) { var n, s, i; if (l(t._isAMomentObject) || (e._isAMomentObject = t._isAMomentObject), l(t._i) || (e._i = t._i), l(t._f) || (e._f = t._f), l(t._l) || (e._l = t._l), l(t._strict) || (e._strict = t._strict), l(t._tzm) || (e._tzm = t._tzm), l(t._isUTC) || (e._isUTC = t._isUTC), l(t._offset) || (e._offset = t._offset), l(t._pf) || (e._pf = g(t)), l(t._locale) || (e._locale = t._locale), 0 < r.length) for (n = 0; n < r.length; n++)l(i = t[s = r[n]]) || (e[s] = i); return e } var t = !1; function M(e) { w(this, e), this._d = new Date(null != e._d ? e._d.getTime() : NaN), this.isValid() || (this._d = new Date(NaN)), !1 === t && (t = !0, c.updateOffset(this), t = !1) } function k(e) { return e instanceof M || null != e && null != e._isAMomentObject } function S(e) { return e < 0 ? Math.ceil(e) || 0 : Math.floor(e) } function D(e) { var t = +e, n = 0; return 0 !== t && isFinite(t) && (n = S(t)), n } function a(e, t, n) { var s, i = Math.min(e.length, t.length), r = Math.abs(e.length - t.length), a = 0; for (s = 0; s < i; s++)(n && e[s] !== t[s] || !n && D(e[s]) !== D(t[s])) && a++; return a + r } function Y(e) { !1 === c.suppressDeprecationWarnings && "undefined" != typeof console && console.warn && console.warn("Deprecation warning: " + e) } function n(i, r) { var a = !0; return _(function () { if (null != c.deprecationHandler && c.deprecationHandler(null, i), a) { for (var e, t = [], n = 0; n < arguments.length; n++) { if (e = "", "object" == typeof arguments[n]) { for (var s in e += "\n[" + n + "] ", arguments[0]) e += s + ": " + arguments[0][s] + ", "; e = e.slice(0, -2) } else e = arguments[n]; t.push(e) } Y(i + "\nArguments: " + Array.prototype.slice.call(t).join("") + "\n" + (new Error).stack), a = !1 } return r.apply(this, arguments) }, r) } var s, O = {}; function T(e, t) { null != c.deprecationHandler && c.deprecationHandler(e, t), O[e] || (Y(t), O[e] = !0) } function b(e) { return e instanceof Function || "[object Function]" === Object.prototype.toString.call(e) } function x(e, t) { var n, s = _({}, e); for (n in t) m(t, n) && (u(e[n]) && u(t[n]) ? (s[n] = {}, _(s[n], e[n]), _(s[n], t[n])) : null != t[n] ? s[n] = t[n] : delete s[n]); for (n in e) m(e, n) && !m(t, n) && u(e[n]) && (s[n] = _({}, s[n])); return s } function P(e) { null != e && this.set(e) } c.suppressDeprecationWarnings = !1, c.deprecationHandler = null, s = Object.keys ? Object.keys : function (e) { var t, n = []; for (t in e) m(e, t) && n.push(t); return n }; var W = {}; function C(e, t) { var n = e.toLowerCase(); W[n] = W[n + "s"] = W[t] = e } function H(e) { return "string" == typeof e ? W[e] || W[e.toLowerCase()] : void 0 } function R(e) { var t, n, s = {}; for (n in e) m(e, n) && (t = H(n)) && (s[t] = e[n]); return s } var U = {}; function F(e, t) { U[e] = t } function L(e, t, n) { var s = "" + Math.abs(e), i = t - s.length; return (0 <= e ? n ? "+" : "" : "-") + Math.pow(10, Math.max(0, i)).toString().substr(1) + s } var N = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|YYYYYY|YYYYY|YYYY|YY|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, G = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, V = {}, E = {}; function I(e, t, n, s) { var i = s; "string" == typeof s && (i = function () { return this[s]() }), e && (E[e] = i), t && (E[t[0]] = function () { return L(i.apply(this, arguments), t[1], t[2]) }), n && (E[n] = function () { return this.localeData().ordinal(i.apply(this, arguments), e) }) } function A(e, t) { return e.isValid() ? (t = j(t, e.localeData()), V[t] = V[t] || function (s) { var e, i, t, r = s.match(N); for (e = 0, i = r.length; e < i; e++)E[r[e]] ? r[e] = E[r[e]] : r[e] = (t = r[e]).match(/\[[\s\S]/) ? t.replace(/^\[|\]$/g, "") : t.replace(/\\/g, ""); return function (e) { var t, n = ""; for (t = 0; t < i; t++)n += b(r[t]) ? r[t].call(e, s) : r[t]; return n } }(t), V[t](e)) : e.localeData().invalidDate() } function j(e, t) { var n = 5; function s(e) { return t.longDateFormat(e) || e } for (G.lastIndex = 0; 0 <= n && G.test(e);)e = e.replace(G, s), G.lastIndex = 0, n -= 1; return e } var Z = /\d/, z = /\d\d/, $ = /\d{3}/, q = /\d{4}/, J = /[+-]?\d{6}/, B = /\d\d?/, Q = /\d\d\d\d?/, X = /\d\d\d\d\d\d?/, K = /\d{1,3}/, ee = /\d{1,4}/, te = /[+-]?\d{1,6}/, ne = /\d+/, se = /[+-]?\d+/, ie = /Z|[+-]\d\d:?\d\d/gi, re = /Z|[+-]\d\d(?::?\d\d)?/gi, ae = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, oe = {}; function ue(e, n, s) { oe[e] = b(n) ? n : function (e, t) { return e && s ? s : n } } function le(e, t) { return m(oe, e) ? oe[e](t._strict, t._locale) : new RegExp(he(e.replace("\\", "").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function (e, t, n, s, i) { return t || n || s || i }))) } function he(e) { return e.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&") } var de = {}; function ce(e, n) { var t, s = n; for ("string" == typeof e && (e = [e]), h(n) && (s = function (e, t) { t[n] = D(e) }), t = 0; t < e.length; t++)de[e[t]] = s } function fe(e, i) { ce(e, function (e, t, n, s) { n._w = n._w || {}, i(e, n._w, n, s) }) } var me = 0, _e = 1, ye = 2, ge = 3, ve = 4, pe = 5, we = 6, Me = 7, ke = 8; function Se(e) { return De(e) ? 366 : 365 } function De(e) { return e % 4 == 0 && e % 100 != 0 || e % 400 == 0 } I("Y", 0, 0, function () { var e = this.year(); return e <= 9999 ? "" + e : "+" + e }), I(0, ["YY", 2], 0, function () { return this.year() % 100 }), I(0, ["YYYY", 4], 0, "year"), I(0, ["YYYYY", 5], 0, "year"), I(0, ["YYYYYY", 6, !0], 0, "year"), C("year", "y"), F("year", 1), ue("Y", se), ue("YY", B, z), ue("YYYY", ee, q), ue("YYYYY", te, J), ue("YYYYYY", te, J), ce(["YYYYY", "YYYYYY"], me), ce("YYYY", function (e, t) { t[me] = 2 === e.length ? c.parseTwoDigitYear(e) : D(e) }), ce("YY", function (e, t) { t[me] = c.parseTwoDigitYear(e) }), ce("Y", function (e, t) { t[me] = parseInt(e, 10) }), c.parseTwoDigitYear = function (e) { return D(e) + (68 < D(e) ? 1900 : 2e3) }; var Ye, Oe = Te("FullYear", !0); function Te(t, n) { return function (e) { return null != e ? (xe(this, t, e), c.updateOffset(this, n), this) : be(this, t) } } function be(e, t) { return e.isValid() ? e._d["get" + (e._isUTC ? "UTC" : "") + t]() : NaN } function xe(e, t, n) { e.isValid() && !isNaN(n) && ("FullYear" === t && De(e.year()) && 1 === e.month() && 29 === e.date() ? e._d["set" + (e._isUTC ? "UTC" : "") + t](n, e.month(), Pe(n, e.month())) : e._d["set" + (e._isUTC ? "UTC" : "") + t](n)) } function Pe(e, t) { if (isNaN(e) || isNaN(t)) return NaN; var n, s = (t % (n = 12) + n) % n; return e += (t - s) / 12, 1 === s ? De(e) ? 29 : 28 : 31 - s % 7 % 2 } Ye = Array.prototype.indexOf ? Array.prototype.indexOf : function (e) { var t; for (t = 0; t < this.length; ++t)if (this[t] === e) return t; return -1 }, I("M", ["MM", 2], "Mo", function () { return this.month() + 1 }), I("MMM", 0, 0, function (e) { return this.localeData().monthsShort(this, e) }), I("MMMM", 0, 0, function (e) { return this.localeData().months(this, e) }), C("month", "M"), F("month", 8), ue("M", B), ue("MM", B, z), ue("MMM", function (e, t) { return t.monthsShortRegex(e) }), ue("MMMM", function (e, t) { return t.monthsRegex(e) }), ce(["M", "MM"], function (e, t) { t[_e] = D(e) - 1 }), ce(["MMM", "MMMM"], function (e, t, n, s) { var i = n._locale.monthsParse(e, s, n._strict); null != i ? t[_e] = i : g(n).invalidMonth = e }); var We = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, Ce = "January_February_March_April_May_June_July_August_September_October_November_December".split("_"); var He = "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"); function Re(e, t) { var n; if (!e.isValid()) return e; if ("string" == typeof t) if (/^\d+$/.test(t)) t = D(t); else if (!h(t = e.localeData().monthsParse(t))) return e; return n = Math.min(e.date(), Pe(e.year(), t)), e._d["set" + (e._isUTC ? "UTC" : "") + "Month"](t, n), e } function Ue(e) { return null != e ? (Re(this, e), c.updateOffset(this, !0), this) : be(this, "Month") } var Fe = ae; var Le = ae; function Ne() { function e(e, t) { return t.length - e.length } var t, n, s = [], i = [], r = []; for (t = 0; t < 12; t++)n = y([2e3, t]), s.push(this.monthsShort(n, "")), i.push(this.months(n, "")), r.push(this.months(n, "")), r.push(this.monthsShort(n, "")); for (s.sort(e), i.sort(e), r.sort(e), t = 0; t < 12; t++)s[t] = he(s[t]), i[t] = he(i[t]); for (t = 0; t < 24; t++)r[t] = he(r[t]); this._monthsRegex = new RegExp("^(" + r.join("|") + ")", "i"), this._monthsShortRegex = this._monthsRegex, this._monthsStrictRegex = new RegExp("^(" + i.join("|") + ")", "i"), this._monthsShortStrictRegex = new RegExp("^(" + s.join("|") + ")", "i") } function Ge(e) { var t; if (e < 100 && 0 <= e) { var n = Array.prototype.slice.call(arguments); n[0] = e + 400, t = new Date(Date.UTC.apply(null, n)), isFinite(t.getUTCFullYear()) && t.setUTCFullYear(e) } else t = new Date(Date.UTC.apply(null, arguments)); return t } function Ve(e, t, n) { var s = 7 + t - n; return -((7 + Ge(e, 0, s).getUTCDay() - t) % 7) + s - 1 } function Ee(e, t, n, s, i) { var r, a, o = 1 + 7 * (t - 1) + (7 + n - s) % 7 + Ve(e, s, i); return a = o <= 0 ? Se(r = e - 1) + o : o > Se(e) ? (r = e + 1, o - Se(e)) : (r = e, o), { year: r, dayOfYear: a } } function Ie(e, t, n) { var s, i, r = Ve(e.year(), t, n), a = Math.floor((e.dayOfYear() - r - 1) / 7) + 1; return a < 1 ? s = a + Ae(i = e.year() - 1, t, n) : a > Ae(e.year(), t, n) ? (s = a - Ae(e.year(), t, n), i = e.year() + 1) : (i = e.year(), s = a), { week: s, year: i } } function Ae(e, t, n) { var s = Ve(e, t, n), i = Ve(e + 1, t, n); return (Se(e) - s + i) / 7 } I("w", ["ww", 2], "wo", "week"), I("W", ["WW", 2], "Wo", "isoWeek"), C("week", "w"), C("isoWeek", "W"), F("week", 5), F("isoWeek", 5), ue("w", B), ue("ww", B, z), ue("W", B), ue("WW", B, z), fe(["w", "ww", "W", "WW"], function (e, t, n, s) { t[s.substr(0, 1)] = D(e) }); function je(e, t) { return e.slice(t, 7).concat(e.slice(0, t)) } I("d", 0, "do", "day"), I("dd", 0, 0, function (e) { return this.localeData().weekdaysMin(this, e) }), I("ddd", 0, 0, function (e) { return this.localeData().weekdaysShort(this, e) }), I("dddd", 0, 0, function (e) { return this.localeData().weekdays(this, e) }), I("e", 0, 0, "weekday"), I("E", 0, 0, "isoWeekday"), C("day", "d"), C("weekday", "e"), C("isoWeekday", "E"), F("day", 11), F("weekday", 11), F("isoWeekday", 11), ue("d", B), ue("e", B), ue("E", B), ue("dd", function (e, t) { return t.weekdaysMinRegex(e) }), ue("ddd", function (e, t) { return t.weekdaysShortRegex(e) }), ue("dddd", function (e, t) { return t.weekdaysRegex(e) }), fe(["dd", "ddd", "dddd"], function (e, t, n, s) { var i = n._locale.weekdaysParse(e, s, n._strict); null != i ? t.d = i : g(n).invalidWeekday = e }), fe(["d", "e", "E"], function (e, t, n, s) { t[s] = D(e) }); var Ze = "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"); var ze = "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"); var $e = "Su_Mo_Tu_We_Th_Fr_Sa".split("_"); var qe = ae; var Je = ae; var Be = ae; function Qe() { function e(e, t) { return t.length - e.length } var t, n, s, i, r, a = [], o = [], u = [], l = []; for (t = 0; t < 7; t++)n = y([2e3, 1]).day(t), s = this.weekdaysMin(n, ""), i = this.weekdaysShort(n, ""), r = this.weekdays(n, ""), a.push(s), o.push(i), u.push(r), l.push(s), l.push(i), l.push(r); for (a.sort(e), o.sort(e), u.sort(e), l.sort(e), t = 0; t < 7; t++)o[t] = he(o[t]), u[t] = he(u[t]), l[t] = he(l[t]); this._weekdaysRegex = new RegExp("^(" + l.join("|") + ")", "i"), this._weekdaysShortRegex = this._weekdaysRegex, this._weekdaysMinRegex = this._weekdaysRegex, this._weekdaysStrictRegex = new RegExp("^(" + u.join("|") + ")", "i"), this._weekdaysShortStrictRegex = new RegExp("^(" + o.join("|") + ")", "i"), this._weekdaysMinStrictRegex = new RegExp("^(" + a.join("|") + ")", "i") } function Xe() { return this.hours() % 12 || 12 } function Ke(e, t) { I(e, 0, 0, function () { return this.localeData().meridiem(this.hours(), this.minutes(), t) }) } function et(e, t) { return t._meridiemParse } I("H", ["HH", 2], 0, "hour"), I("h", ["hh", 2], 0, Xe), I("k", ["kk", 2], 0, function () { return this.hours() || 24 }), I("hmm", 0, 0, function () { return "" + Xe.apply(this) + L(this.minutes(), 2) }), I("hmmss", 0, 0, function () { return "" + Xe.apply(this) + L(this.minutes(), 2) + L(this.seconds(), 2) }), I("Hmm", 0, 0, function () { return "" + this.hours() + L(this.minutes(), 2) }), I("Hmmss", 0, 0, function () { return "" + this.hours() + L(this.minutes(), 2) + L(this.seconds(), 2) }), Ke("a", !0), Ke("A", !1), C("hour", "h"), F("hour", 13), ue("a", et), ue("A", et), ue("H", B), ue("h", B), ue("k", B), ue("HH", B, z), ue("hh", B, z), ue("kk", B, z), ue("hmm", Q), ue("hmmss", X), ue("Hmm", Q), ue("Hmmss", X), ce(["H", "HH"], ge), ce(["k", "kk"], function (e, t, n) { var s = D(e); t[ge] = 24 === s ? 0 : s }), ce(["a", "A"], function (e, t, n) { n._isPm = n._locale.isPM(e), n._meridiem = e }), ce(["h", "hh"], function (e, t, n) { t[ge] = D(e), g(n).bigHour = !0 }), ce("hmm", function (e, t, n) { var s = e.length - 2; t[ge] = D(e.substr(0, s)), t[ve] = D(e.substr(s)), g(n).bigHour = !0 }), ce("hmmss", function (e, t, n) { var s = e.length - 4, i = e.length - 2; t[ge] = D(e.substr(0, s)), t[ve] = D(e.substr(s, 2)), t[pe] = D(e.substr(i)), g(n).bigHour = !0 }), ce("Hmm", function (e, t, n) { var s = e.length - 2; t[ge] = D(e.substr(0, s)), t[ve] = D(e.substr(s)) }), ce("Hmmss", function (e, t, n) { var s = e.length - 4, i = e.length - 2; t[ge] = D(e.substr(0, s)), t[ve] = D(e.substr(s, 2)), t[pe] = D(e.substr(i)) }); var tt, nt = Te("Hours", !0), st = { calendar: { sameDay: "[Today at] LT", nextDay: "[Tomorrow at] LT", nextWeek: "dddd [at] LT", lastDay: "[Yesterday at] LT", lastWeek: "[Last] dddd [at] LT", sameElse: "L" }, longDateFormat: { LTS: "h:mm:ss A", LT: "h:mm A", L: "MM/DD/YYYY", LL: "MMMM D, YYYY", LLL: "MMMM D, YYYY h:mm A", LLLL: "dddd, MMMM D, YYYY h:mm A" }, invalidDate: "Invalid date", ordinal: "%d", dayOfMonthOrdinalParse: /\d{1,2}/, relativeTime: { future: "in %s", past: "%s ago", s: "a few seconds", ss: "%d seconds", m: "a minute", mm: "%d minutes", h: "an hour", hh: "%d hours", d: "a day", dd: "%d days", M: "a month", MM: "%d months", y: "a year", yy: "%d years" }, months: Ce, monthsShort: He, week: { dow: 0, doy: 6 }, weekdays: Ze, weekdaysMin: $e, weekdaysShort: ze, meridiemParse: /[ap]\.?m?\.?/i }, it = {}, rt = {}; function at(e) { return e ? e.toLowerCase().replace("_", "-") : e } function ot(e) { var t = null; if (!it[e] && "undefined" != typeof module && module && module.exports) try { t = tt._abbr, require("./locale/" + e), ut(t) } catch (e) { } return it[e] } function ut(e, t) { var n; return e && ((n = l(t) ? ht(e) : lt(e, t)) ? tt = n : "undefined" != typeof console && console.warn && console.warn("Locale " + e + " not found. Did you forget to load it?")), tt._abbr } function lt(e, t) { if (null === t) return delete it[e], null; var n, s = st; if (t.abbr = e, null != it[e]) T("defineLocaleOverride", "use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."), s = it[e]._config; else if (null != t.parentLocale) if (null != it[t.parentLocale]) s = it[t.parentLocale]._config; else { if (null == (n = ot(t.parentLocale))) return rt[t.parentLocale] || (rt[t.parentLocale] = []), rt[t.parentLocale].push({ name: e, config: t }), null; s = n._config } return it[e] = new P(x(s, t)), rt[e] && rt[e].forEach(function (e) { lt(e.name, e.config) }), ut(e), it[e] } function ht(e) { var t; if (e && e._locale && e._locale._abbr && (e = e._locale._abbr), !e) return tt; if (!o(e)) { if (t = ot(e)) return t; e = [e] } return function (e) { for (var t, n, s, i, r = 0; r < e.length;) { for (t = (i = at(e[r]).split("-")).length, n = (n = at(e[r + 1])) ? n.split("-") : null; 0 < t;) { if (s = ot(i.slice(0, t).join("-"))) return s; if (n && n.length >= t && a(i, n, !0) >= t - 1) break; t-- } r++ } return tt }(e) } function dt(e) { var t, n = e._a; return n && -2 === g(e).overflow && (t = n[_e] < 0 || 11 < n[_e] ? _e : n[ye] < 1 || n[ye] > Pe(n[me], n[_e]) ? ye : n[ge] < 0 || 24 < n[ge] || 24 === n[ge] && (0 !== n[ve] || 0 !== n[pe] || 0 !== n[we]) ? ge : n[ve] < 0 || 59 < n[ve] ? ve : n[pe] < 0 || 59 < n[pe] ? pe : n[we] < 0 || 999 < n[we] ? we : -1, g(e)._overflowDayOfYear && (t < me || ye < t) && (t = ye), g(e)._overflowWeeks && -1 === t && (t = Me), g(e)._overflowWeekday && -1 === t && (t = ke), g(e).overflow = t), e } function ct(e, t, n) { return null != e ? e : null != t ? t : n } function ft(e) { var t, n, s, i, r, a = []; if (!e._d) { var o, u; for (o = e, u = new Date(c.now()), s = o._useUTC ? [u.getUTCFullYear(), u.getUTCMonth(), u.getUTCDate()] : [u.getFullYear(), u.getMonth(), u.getDate()], e._w && null == e._a[ye] && null == e._a[_e] && function (e) { var t, n, s, i, r, a, o, u; if (null != (t = e._w).GG || null != t.W || null != t.E) r = 1, a = 4, n = ct(t.GG, e._a[me], Ie(bt(), 1, 4).year), s = ct(t.W, 1), ((i = ct(t.E, 1)) < 1 || 7 < i) && (u = !0); else { r = e._locale._week.dow, a = e._locale._week.doy; var l = Ie(bt(), r, a); n = ct(t.gg, e._a[me], l.year), s = ct(t.w, l.week), null != t.d ? ((i = t.d) < 0 || 6 < i) && (u = !0) : null != t.e ? (i = t.e + r, (t.e < 0 || 6 < t.e) && (u = !0)) : i = r } s < 1 || s > Ae(n, r, a) ? g(e)._overflowWeeks = !0 : null != u ? g(e)._overflowWeekday = !0 : (o = Ee(n, s, i, r, a), e._a[me] = o.year, e._dayOfYear = o.dayOfYear) }(e), null != e._dayOfYear && (r = ct(e._a[me], s[me]), (e._dayOfYear > Se(r) || 0 === e._dayOfYear) && (g(e)._overflowDayOfYear = !0), n = Ge(r, 0, e._dayOfYear), e._a[_e] = n.getUTCMonth(), e._a[ye] = n.getUTCDate()), t = 0; t < 3 && null == e._a[t]; ++t)e._a[t] = a[t] = s[t]; for (; t < 7; t++)e._a[t] = a[t] = null == e._a[t] ? 2 === t ? 1 : 0 : e._a[t]; 24 === e._a[ge] && 0 === e._a[ve] && 0 === e._a[pe] && 0 === e._a[we] && (e._nextDay = !0, e._a[ge] = 0), e._d = (e._useUTC ? Ge : function (e, t, n, s, i, r, a) { var o; return e < 100 && 0 <= e ? (o = new Date(e + 400, t, n, s, i, r, a), isFinite(o.getFullYear()) && o.setFullYear(e)) : o = new Date(e, t, n, s, i, r, a), o }).apply(null, a), i = e._useUTC ? e._d.getUTCDay() : e._d.getDay(), null != e._tzm && e._d.setUTCMinutes(e._d.getUTCMinutes() - e._tzm), e._nextDay && (e._a[ge] = 24), e._w && void 0 !== e._w.d && e._w.d !== i && (g(e).weekdayMismatch = !0) } } var mt = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, _t = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([\+\-]\d\d(?::?\d\d)?|\s*Z)?)?$/, yt = /Z|[+-]\d\d(?::?\d\d)?/, gt = [["YYYYYY-MM-DD", /[+-]\d{6}-\d\d-\d\d/], ["YYYY-MM-DD", /\d{4}-\d\d-\d\d/], ["GGGG-[W]WW-E", /\d{4}-W\d\d-\d/], ["GGGG-[W]WW", /\d{4}-W\d\d/, !1], ["YYYY-DDD", /\d{4}-\d{3}/], ["YYYY-MM", /\d{4}-\d\d/, !1], ["YYYYYYMMDD", /[+-]\d{10}/], ["YYYYMMDD", /\d{8}/], ["GGGG[W]WWE", /\d{4}W\d{3}/], ["GGGG[W]WW", /\d{4}W\d{2}/, !1], ["YYYYDDD", /\d{7}/]], vt = [["HH:mm:ss.SSSS", /\d\d:\d\d:\d\d\.\d+/], ["HH:mm:ss,SSSS", /\d\d:\d\d:\d\d,\d+/], ["HH:mm:ss", /\d\d:\d\d:\d\d/], ["HH:mm", /\d\d:\d\d/], ["HHmmss.SSSS", /\d\d\d\d\d\d\.\d+/], ["HHmmss,SSSS", /\d\d\d\d\d\d,\d+/], ["HHmmss", /\d\d\d\d\d\d/], ["HHmm", /\d\d\d\d/], ["HH", /\d\d/]], pt = /^\/?Date\((\-?\d+)/i; function wt(e) { var t, n, s, i, r, a, o = e._i, u = mt.exec(o) || _t.exec(o); if (u) { for (g(e).iso = !0, t = 0, n = gt.length; t < n; t++)if (gt[t][1].exec(u[1])) { i = gt[t][0], s = !1 !== gt[t][2]; break } if (null == i) return void (e._isValid = !1); if (u[3]) { for (t = 0, n = vt.length; t < n; t++)if (vt[t][1].exec(u[3])) { r = (u[2] || " ") + vt[t][0]; break } if (null == r) return void (e._isValid = !1) } if (!s && null != r) return void (e._isValid = !1); if (u[4]) { if (!yt.exec(u[4])) return void (e._isValid = !1); a = "Z" } e._f = i + (r || "") + (a || ""), Yt(e) } else e._isValid = !1 } var Mt = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/; function kt(e, t, n, s, i, r) { var a = [function (e) { var t = parseInt(e, 10); { if (t <= 49) return 2e3 + t; if (t <= 999) return 1900 + t } return t }(e), He.indexOf(t), parseInt(n, 10), parseInt(s, 10), parseInt(i, 10)]; return r && a.push(parseInt(r, 10)), a } var St = { UT: 0, GMT: 0, EDT: -240, EST: -300, CDT: -300, CST: -360, MDT: -360, MST: -420, PDT: -420, PST: -480 }; function Dt(e) { var t, n, s, i = Mt.exec(e._i.replace(/\([^)]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").replace(/^\s\s*/, "").replace(/\s\s*$/, "")); if (i) { var r = kt(i[4], i[3], i[2], i[5], i[6], i[7]); if (t = i[1], n = r, s = e, t && ze.indexOf(t) !== new Date(n[0], n[1], n[2]).getDay() && (g(s).weekdayMismatch = !0, !(s._isValid = !1))) return; e._a = r, e._tzm = function (e, t, n) { if (e) return St[e]; if (t) return 0; var s = parseInt(n, 10), i = s % 100; return (s - i) / 100 * 60 + i }(i[8], i[9], i[10]), e._d = Ge.apply(null, e._a), e._d.setUTCMinutes(e._d.getUTCMinutes() - e._tzm), g(e).rfc2822 = !0 } else e._isValid = !1 } function Yt(e) { if (e._f !== c.ISO_8601) if (e._f !== c.RFC_2822) { e._a = [], g(e).empty = !0; var t, n, s, i, r, a, o, u, l = "" + e._i, h = l.length, d = 0; for (s = j(e._f, e._locale).match(N) || [], t = 0; t < s.length; t++)i = s[t], (n = (l.match(le(i, e)) || [])[0]) && (0 < (r = l.substr(0, l.indexOf(n))).length && g(e).unusedInput.push(r), l = l.slice(l.indexOf(n) + n.length), d += n.length), E[i] ? (n ? g(e).empty = !1 : g(e).unusedTokens.push(i), a = i, u = e, null != (o = n) && m(de, a) && de[a](o, u._a, u, a)) : e._strict && !n && g(e).unusedTokens.push(i); g(e).charsLeftOver = h - d, 0 < l.length && g(e).unusedInput.push(l), e._a[ge] <= 12 && !0 === g(e).bigHour && 0 < e._a[ge] && (g(e).bigHour = void 0), g(e).parsedDateParts = e._a.slice(0), g(e).meridiem = e._meridiem, e._a[ge] = function (e, t, n) { var s; if (null == n) return t; return null != e.meridiemHour ? e.meridiemHour(t, n) : (null != e.isPM && ((s = e.isPM(n)) && t < 12 && (t += 12), s || 12 !== t || (t = 0)), t) }(e._locale, e._a[ge], e._meridiem), ft(e), dt(e) } else Dt(e); else wt(e) } function Ot(e) { var t, n, s, i, r = e._i, a = e._f; return e._locale = e._locale || ht(e._l), null === r || void 0 === a && "" === r ? p({ nullInput: !0 }) : ("string" == typeof r && (e._i = r = e._locale.preparse(r)), k(r) ? new M(dt(r)) : (d(r) ? e._d = r : o(a) ? function (e) { var t, n, s, i, r; if (0 === e._f.length) return g(e).invalidFormat = !0, e._d = new Date(NaN); for (i = 0; i < e._f.length; i++)r = 0, t = w({}, e), null != e._useUTC && (t._useUTC = e._useUTC), t._f = e._f[i], Yt(t), v(t) && (r += g(t).charsLeftOver, r += 10 * g(t).unusedTokens.length, g(t).score = r, (null == s || r < s) && (s = r, n = t)); _(e, n || t) }(e) : a ? Yt(e) : l(n = (t = e)._i) ? t._d = new Date(c.now()) : d(n) ? t._d = new Date(n.valueOf()) : "string" == typeof n ? (s = t, null === (i = pt.exec(s._i)) ? (wt(s), !1 === s._isValid && (delete s._isValid, Dt(s), !1 === s._isValid && (delete s._isValid, c.createFromInputFallback(s)))) : s._d = new Date(+i[1])) : o(n) ? (t._a = f(n.slice(0), function (e) { return parseInt(e, 10) }), ft(t)) : u(n) ? function (e) { if (!e._d) { var t = R(e._i); e._a = f([t.year, t.month, t.day || t.date, t.hour, t.minute, t.second, t.millisecond], function (e) { return e && parseInt(e, 10) }), ft(e) } }(t) : h(n) ? t._d = new Date(n) : c.createFromInputFallback(t), v(e) || (e._d = null), e)) } function Tt(e, t, n, s, i) { var r, a = {}; return !0 !== n && !1 !== n || (s = n, n = void 0), (u(e) && function (e) { if (Object.getOwnPropertyNames) return 0 === Object.getOwnPropertyNames(e).length; var t; for (t in e) if (e.hasOwnProperty(t)) return !1; return !0 }(e) || o(e) && 0 === e.length) && (e = void 0), a._isAMomentObject = !0, a._useUTC = a._isUTC = i, a._l = n, a._i = e, a._f = t, a._strict = s, (r = new M(dt(Ot(a))))._nextDay && (r.add(1, "d"), r._nextDay = void 0), r } function bt(e, t, n, s) { return Tt(e, t, n, s, !1) } c.createFromInputFallback = n("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.", function (e) { e._d = new Date(e._i + (e._useUTC ? " UTC" : "")) }), c.ISO_8601 = function () { }, c.RFC_2822 = function () { }; var xt = n("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/", function () { var e = bt.apply(null, arguments); return this.isValid() && e.isValid() ? e < this ? this : e : p() }), Pt = n("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/", function () { var e = bt.apply(null, arguments); return this.isValid() && e.isValid() ? this < e ? this : e : p() }); function Wt(e, t) { var n, s; if (1 === t.length && o(t[0]) && (t = t[0]), !t.length) return bt(); for (n = t[0], s = 1; s < t.length; ++s)t[s].isValid() && !t[s][e](n) || (n = t[s]); return n } var Ct = ["year", "quarter", "month", "week", "day", "hour", "minute", "second", "millisecond"]; function Ht(e) { var t = R(e), n = t.year || 0, s = t.quarter || 0, i = t.month || 0, r = t.week || t.isoWeek || 0, a = t.day || 0, o = t.hour || 0, u = t.minute || 0, l = t.second || 0, h = t.millisecond || 0; this._isValid = function (e) { for (var t in e) if (-1 === Ye.call(Ct, t) || null != e[t] && isNaN(e[t])) return !1; for (var n = !1, s = 0; s < Ct.length; ++s)if (e[Ct[s]]) { if (n) return !1; parseFloat(e[Ct[s]]) !== D(e[Ct[s]]) && (n = !0) } return !0 }(t), this._milliseconds = +h + 1e3 * l + 6e4 * u + 1e3 * o * 60 * 60, this._days = +a + 7 * r, this._months = +i + 3 * s + 12 * n, this._data = {}, this._locale = ht(), this._bubble() } function Rt(e) { return e instanceof Ht } function Ut(e) { return e < 0 ? -1 * Math.round(-1 * e) : Math.round(e) } function Ft(e, n) { I(e, 0, 0, function () { var e = this.utcOffset(), t = "+"; return e < 0 && (e = -e, t = "-"), t + L(~~(e / 60), 2) + n + L(~~e % 60, 2) }) } Ft("Z", ":"), Ft("ZZ", ""), ue("Z", re), ue("ZZ", re), ce(["Z", "ZZ"], function (e, t, n) { n._useUTC = !0, n._tzm = Nt(re, e) }); var Lt = /([\+\-]|\d\d)/gi; function Nt(e, t) { var n = (t || "").match(e); if (null === n) return null; var s = ((n[n.length - 1] || []) + "").match(Lt) || ["-", 0, 0], i = 60 * s[1] + D(s[2]); return 0 === i ? 0 : "+" === s[0] ? i : -i } function Gt(e, t) { var n, s; return t._isUTC ? (n = t.clone(), s = (k(e) || d(e) ? e.valueOf() : bt(e).valueOf()) - n.valueOf(), n._d.setTime(n._d.valueOf() + s), c.updateOffset(n, !1), n) : bt(e).local() } function Vt(e) { return 15 * -Math.round(e._d.getTimezoneOffset() / 15) } function Et() { return !!this.isValid() && (this._isUTC && 0 === this._offset) } c.updateOffset = function () { }; var It = /^(\-|\+)?(?:(\d*)[. ])?(\d+)\:(\d+)(?:\:(\d+)(\.\d*)?)?$/, At = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; function jt(e, t) { var n, s, i, r = e, a = null; return Rt(e) ? r = { ms: e._milliseconds, d: e._days, M: e._months } : h(e) ? (r = {}, t ? r[t] = e : r.milliseconds = e) : (a = It.exec(e)) ? (n = "-" === a[1] ? -1 : 1, r = { y: 0, d: D(a[ye]) * n, h: D(a[ge]) * n, m: D(a[ve]) * n, s: D(a[pe]) * n, ms: D(Ut(1e3 * a[we])) * n }) : (a = At.exec(e)) ? (n = "-" === a[1] ? -1 : 1, r = { y: Zt(a[2], n), M: Zt(a[3], n), w: Zt(a[4], n), d: Zt(a[5], n), h: Zt(a[6], n), m: Zt(a[7], n), s: Zt(a[8], n) }) : null == r ? r = {} : "object" == typeof r && ("from" in r || "to" in r) && (i = function (e, t) { var n; if (!e.isValid() || !t.isValid()) return { milliseconds: 0, months: 0 }; t = Gt(t, e), e.isBefore(t) ? n = zt(e, t) : ((n = zt(t, e)).milliseconds = -n.milliseconds, n.months = -n.months); return n }(bt(r.from), bt(r.to)), (r = {}).ms = i.milliseconds, r.M = i.months), s = new Ht(r), Rt(e) && m(e, "_locale") && (s._locale = e._locale), s } function Zt(e, t) { var n = e && parseFloat(e.replace(",", ".")); return (isNaN(n) ? 0 : n) * t } function zt(e, t) { var n = {}; return n.months = t.month() - e.month() + 12 * (t.year() - e.year()), e.clone().add(n.months, "M").isAfter(t) && --n.months, n.milliseconds = +t - +e.clone().add(n.months, "M"), n } function $t(s, i) { return function (e, t) { var n; return null === t || isNaN(+t) || (T(i, "moment()." + i + "(period, number) is deprecated. Please use moment()." + i + "(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."), n = e, e = t, t = n), qt(this, jt(e = "string" == typeof e ? +e : e, t), s), this } } function qt(e, t, n, s) { var i = t._milliseconds, r = Ut(t._days), a = Ut(t._months); e.isValid() && (s = null == s || s, a && Re(e, be(e, "Month") + a * n), r && xe(e, "Date", be(e, "Date") + r * n), i && e._d.setTime(e._d.valueOf() + i * n), s && c.updateOffset(e, r || a)) } jt.fn = Ht.prototype, jt.invalid = function () { return jt(NaN) }; var Jt = $t(1, "add"), Bt = $t(-1, "subtract"); function Qt(e, t) { var n = 12 * (t.year() - e.year()) + (t.month() - e.month()), s = e.clone().add(n, "months"); return -(n + (t - s < 0 ? (t - s) / (s - e.clone().add(n - 1, "months")) : (t - s) / (e.clone().add(n + 1, "months") - s))) || 0 } function Xt(e) { var t; return void 0 === e ? this._locale._abbr : (null != (t = ht(e)) && (this._locale = t), this) } c.defaultFormat = "YYYY-MM-DDTHH:mm:ssZ", c.defaultFormatUtc = "YYYY-MM-DDTHH:mm:ss[Z]"; var Kt = n("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.", function (e) { return void 0 === e ? this.localeData() : this.locale(e) }); function en() { return this._locale } var tn = 126227808e5; function nn(e, t) { return (e % t + t) % t } function sn(e, t, n) { return e < 100 && 0 <= e ? new Date(e + 400, t, n) - tn : new Date(e, t, n).valueOf() } function rn(e, t, n) { return e < 100 && 0 <= e ? Date.UTC(e + 400, t, n) - tn : Date.UTC(e, t, n) } function an(e, t) { I(0, [e, e.length], 0, t) } function on(e, t, n, s, i) { var r; return null == e ? Ie(this, s, i).year : ((r = Ae(e, s, i)) < t && (t = r), function (e, t, n, s, i) { var r = Ee(e, t, n, s, i), a = Ge(r.year, 0, r.dayOfYear); return this.year(a.getUTCFullYear()), this.month(a.getUTCMonth()), this.date(a.getUTCDate()), this }.call(this, e, t, n, s, i)) } I(0, ["gg", 2], 0, function () { return this.weekYear() % 100 }), I(0, ["GG", 2], 0, function () { return this.isoWeekYear() % 100 }), an("gggg", "weekYear"), an("ggggg", "weekYear"), an("GGGG", "isoWeekYear"), an("GGGGG", "isoWeekYear"), C("weekYear", "gg"), C("isoWeekYear", "GG"), F("weekYear", 1), F("isoWeekYear", 1), ue("G", se), ue("g", se), ue("GG", B, z), ue("gg", B, z), ue("GGGG", ee, q), ue("gggg", ee, q), ue("GGGGG", te, J), ue("ggggg", te, J), fe(["gggg", "ggggg", "GGGG", "GGGGG"], function (e, t, n, s) { t[s.substr(0, 2)] = D(e) }), fe(["gg", "GG"], function (e, t, n, s) { t[s] = c.parseTwoDigitYear(e) }), I("Q", 0, "Qo", "quarter"), C("quarter", "Q"), F("quarter", 7), ue("Q", Z), ce("Q", function (e, t) { t[_e] = 3 * (D(e) - 1) }), I("D", ["DD", 2], "Do", "date"), C("date", "D"), F("date", 9), ue("D", B), ue("DD", B, z), ue("Do", function (e, t) { return e ? t._dayOfMonthOrdinalParse || t._ordinalParse : t._dayOfMonthOrdinalParseLenient }), ce(["D", "DD"], ye), ce("Do", function (e, t) { t[ye] = D(e.match(B)[0]) }); var un = Te("Date", !0); I("DDD", ["DDDD", 3], "DDDo", "dayOfYear"), C("dayOfYear", "DDD"), F("dayOfYear", 4), ue("DDD", K), ue("DDDD", $), ce(["DDD", "DDDD"], function (e, t, n) { n._dayOfYear = D(e) }), I("m", ["mm", 2], 0, "minute"), C("minute", "m"), F("minute", 14), ue("m", B), ue("mm", B, z), ce(["m", "mm"], ve); var ln = Te("Minutes", !1); I("s", ["ss", 2], 0, "second"), C("second", "s"), F("second", 15), ue("s", B), ue("ss", B, z), ce(["s", "ss"], pe); var hn, dn = Te("Seconds", !1); for (I("S", 0, 0, function () { return ~~(this.millisecond() / 100) }), I(0, ["SS", 2], 0, function () { return ~~(this.millisecond() / 10) }), I(0, ["SSS", 3], 0, "millisecond"), I(0, ["SSSS", 4], 0, function () { return 10 * this.millisecond() }), I(0, ["SSSSS", 5], 0, function () { return 100 * this.millisecond() }), I(0, ["SSSSSS", 6], 0, function () { return 1e3 * this.millisecond() }), I(0, ["SSSSSSS", 7], 0, function () { return 1e4 * this.millisecond() }), I(0, ["SSSSSSSS", 8], 0, function () { return 1e5 * this.millisecond() }), I(0, ["SSSSSSSSS", 9], 0, function () { return 1e6 * this.millisecond() }), C("millisecond", "ms"), F("millisecond", 16), ue("S", K, Z), ue("SS", K, z), ue("SSS", K, $), hn = "SSSS"; hn.length <= 9; hn += "S")ue(hn, ne); function cn(e, t) { t[we] = D(1e3 * ("0." + e)) } for (hn = "S"; hn.length <= 9; hn += "S")ce(hn, cn); var fn = Te("Milliseconds", !1); I("z", 0, 0, "zoneAbbr"), I("zz", 0, 0, "zoneName"); var mn = M.prototype; function _n(e) { return e } mn.add = Jt, mn.calendar = function (e, t) { var n = e || bt(), s = Gt(n, this).startOf("day"), i = c.calendarFormat(this, s) || "sameElse", r = t && (b(t[i]) ? t[i].call(this, n) : t[i]); return this.format(r || this.localeData().calendar(i, this, bt(n))) }, mn.clone = function () { return new M(this) }, mn.diff = function (e, t, n) { var s, i, r; if (!this.isValid()) return NaN; if (!(s = Gt(e, this)).isValid()) return NaN; switch (i = 6e4 * (s.utcOffset() - this.utcOffset()), t = H(t)) { case "year": r = Qt(this, s) / 12; break; case "month": r = Qt(this, s); break; case "quarter": r = Qt(this, s) / 3; break; case "second": r = (this - s) / 1e3; break; case "minute": r = (this - s) / 6e4; break; case "hour": r = (this - s) / 36e5; break; case "day": r = (this - s - i) / 864e5; break; case "week": r = (this - s - i) / 6048e5; break; default: r = this - s }return n ? r : S(r) }, mn.endOf = function (e) { var t; if (void 0 === (e = H(e)) || "millisecond" === e || !this.isValid()) return this; var n = this._isUTC ? rn : sn; switch (e) { case "year": t = n(this.year() + 1, 0, 1) - 1; break; case "quarter": t = n(this.year(), this.month() - this.month() % 3 + 3, 1) - 1; break; case "month": t = n(this.year(), this.month() + 1, 1) - 1; break; case "week": t = n(this.year(), this.month(), this.date() - this.weekday() + 7) - 1; break; case "isoWeek": t = n(this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7) - 1; break; case "day": case "date": t = n(this.year(), this.month(), this.date() + 1) - 1; break; case "hour": t = this._d.valueOf(), t += 36e5 - nn(t + (this._isUTC ? 0 : 6e4 * this.utcOffset()), 36e5) - 1; break; case "minute": t = this._d.valueOf(), t += 6e4 - nn(t, 6e4) - 1; break; case "second": t = this._d.valueOf(), t += 1e3 - nn(t, 1e3) - 1; break }return this._d.setTime(t), c.updateOffset(this, !0), this }, mn.format = function (e) { e || (e = this.isUtc() ? c.defaultFormatUtc : c.defaultFormat); var t = A(this, e); return this.localeData().postformat(t) }, mn.from = function (e, t) { return this.isValid() && (k(e) && e.isValid() || bt(e).isValid()) ? jt({ to: this, from: e }).locale(this.locale()).humanize(!t) : this.localeData().invalidDate() }, mn.fromNow = function (e) { return this.from(bt(), e) }, mn.to = function (e, t) { return this.isValid() && (k(e) && e.isValid() || bt(e).isValid()) ? jt({ from: this, to: e }).locale(this.locale()).humanize(!t) : this.localeData().invalidDate() }, mn.toNow = function (e) { return this.to(bt(), e) }, mn.get = function (e) { return b(this[e = H(e)]) ? this[e]() : this }, mn.invalidAt = function () { return g(this).overflow }, mn.isAfter = function (e, t) { var n = k(e) ? e : bt(e); return !(!this.isValid() || !n.isValid()) && ("millisecond" === (t = H(t) || "millisecond") ? this.valueOf() > n.valueOf() : n.valueOf() < this.clone().startOf(t).valueOf()) }, mn.isBefore = function (e, t) { var n = k(e) ? e : bt(e); return !(!this.isValid() || !n.isValid()) && ("millisecond" === (t = H(t) || "millisecond") ? this.valueOf() < n.valueOf() : this.clone().endOf(t).valueOf() < n.valueOf()) }, mn.isBetween = function (e, t, n, s) { var i = k(e) ? e : bt(e), r = k(t) ? t : bt(t); return !!(this.isValid() && i.isValid() && r.isValid()) && ("(" === (s = s || "()")[0] ? this.isAfter(i, n) : !this.isBefore(i, n)) && (")" === s[1] ? this.isBefore(r, n) : !this.isAfter(r, n)) }, mn.isSame = function (e, t) { var n, s = k(e) ? e : bt(e); return !(!this.isValid() || !s.isValid()) && ("millisecond" === (t = H(t) || "millisecond") ? this.valueOf() === s.valueOf() : (n = s.valueOf(), this.clone().startOf(t).valueOf() <= n && n <= this.clone().endOf(t).valueOf())) }, mn.isSameOrAfter = function (e, t) { return this.isSame(e, t) || this.isAfter(e, t) }, mn.isSameOrBefore = function (e, t) { return this.isSame(e, t) || this.isBefore(e, t) }, mn.isValid = function () { return v(this) }, mn.lang = Kt, mn.locale = Xt, mn.localeData = en, mn.max = Pt, mn.min = xt, mn.parsingFlags = function () { return _({}, g(this)) }, mn.set = function (e, t) { if ("object" == typeof e) for (var n = function (e) { var t = []; for (var n in e) t.push({ unit: n, priority: U[n] }); return t.sort(function (e, t) { return e.priority - t.priority }), t }(e = R(e)), s = 0; s < n.length; s++)this[n[s].unit](e[n[s].unit]); else if (b(this[e = H(e)])) return this[e](t); return this }, mn.startOf = function (e) { var t; if (void 0 === (e = H(e)) || "millisecond" === e || !this.isValid()) return this; var n = this._isUTC ? rn : sn; switch (e) { case "year": t = n(this.year(), 0, 1); break; case "quarter": t = n(this.year(), this.month() - this.month() % 3, 1); break; case "month": t = n(this.year(), this.month(), 1); break; case "week": t = n(this.year(), this.month(), this.date() - this.weekday()); break; case "isoWeek": t = n(this.year(), this.month(), this.date() - (this.isoWeekday() - 1)); break; case "day": case "date": t = n(this.year(), this.month(), this.date()); break; case "hour": t = this._d.valueOf(), t -= nn(t + (this._isUTC ? 0 : 6e4 * this.utcOffset()), 36e5); break; case "minute": t = this._d.valueOf(), t -= nn(t, 6e4); break; case "second": t = this._d.valueOf(), t -= nn(t, 1e3); break }return this._d.setTime(t), c.updateOffset(this, !0), this }, mn.subtract = Bt, mn.toArray = function () { var e = this; return [e.year(), e.month(), e.date(), e.hour(), e.minute(), e.second(), e.millisecond()] }, mn.toObject = function () { var e = this; return { years: e.year(), months: e.month(), date: e.date(), hours: e.hours(), minutes: e.minutes(), seconds: e.seconds(), milliseconds: e.milliseconds() } }, mn.toDate = function () { return new Date(this.valueOf()) }, mn.toISOString = function (e) { if (!this.isValid()) return null; var t = !0 !== e, n = t ? this.clone().utc() : this; return n.year() < 0 || 9999 < n.year() ? A(n, t ? "YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYYYY-MM-DD[T]HH:mm:ss.SSSZ") : b(Date.prototype.toISOString) ? t ? this.toDate().toISOString() : new Date(this.valueOf() + 60 * this.utcOffset() * 1e3).toISOString().replace("Z", A(n, "Z")) : A(n, t ? "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYY-MM-DD[T]HH:mm:ss.SSSZ") }, mn.inspect = function () { if (!this.isValid()) return "moment.invalid(/* " + this._i + " */)"; var e = "moment", t = ""; this.isLocal() || (e = 0 === this.utcOffset() ? "moment.utc" : "moment.parseZone", t = "Z"); var n = "[" + e + '("]', s = 0 <= this.year() && this.year() <= 9999 ? "YYYY" : "YYYYYY", i = t + '[")]'; return this.format(n + s + "-MM-DD[T]HH:mm:ss.SSS" + i) }, mn.toJSON = function () { return this.isValid() ? this.toISOString() : null }, mn.toString = function () { return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ") }, mn.unix = function () { return Math.floor(this.valueOf() / 1e3) }, mn.valueOf = function () { return this._d.valueOf() - 6e4 * (this._offset || 0) }, mn.creationData = function () { return { input: this._i, format: this._f, locale: this._locale, isUTC: this._isUTC, strict: this._strict } }, mn.year = Oe, mn.isLeapYear = function () { return De(this.year()) }, mn.weekYear = function (e) { return on.call(this, e, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy) }, mn.isoWeekYear = function (e) { return on.call(this, e, this.isoWeek(), this.isoWeekday(), 1, 4) }, mn.quarter = mn.quarters = function (e) { return null == e ? Math.ceil((this.month() + 1) / 3) : this.month(3 * (e - 1) + this.month() % 3) }, mn.month = Ue, mn.daysInMonth = function () { return Pe(this.year(), this.month()) }, mn.week = mn.weeks = function (e) { var t = this.localeData().week(this); return null == e ? t : this.add(7 * (e - t), "d") }, mn.isoWeek = mn.isoWeeks = function (e) { var t = Ie(this, 1, 4).week; return null == e ? t : this.add(7 * (e - t), "d") }, mn.weeksInYear = function () { var e = this.localeData()._week; return Ae(this.year(), e.dow, e.doy) }, mn.isoWeeksInYear = function () { return Ae(this.year(), 1, 4) }, mn.date = un, mn.day = mn.days = function (e) { if (!this.isValid()) return null != e ? this : NaN; var t, n, s = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); return null != e ? (t = e, n = this.localeData(), e = "string" != typeof t ? t : isNaN(t) ? "number" == typeof (t = n.weekdaysParse(t)) ? t : null : parseInt(t, 10), this.add(e - s, "d")) : s }, mn.weekday = function (e) { if (!this.isValid()) return null != e ? this : NaN; var t = (this.day() + 7 - this.localeData()._week.dow) % 7; return null == e ? t : this.add(e - t, "d") }, mn.isoWeekday = function (e) { if (!this.isValid()) return null != e ? this : NaN; if (null == e) return this.day() || 7; var t, n, s = (t = e, n = this.localeData(), "string" == typeof t ? n.weekdaysParse(t) % 7 || 7 : isNaN(t) ? null : t); return this.day(this.day() % 7 ? s : s - 7) }, mn.dayOfYear = function (e) { var t = Math.round((this.clone().startOf("day") - this.clone().startOf("year")) / 864e5) + 1; return null == e ? t : this.add(e - t, "d") }, mn.hour = mn.hours = nt, mn.minute = mn.minutes = ln, mn.second = mn.seconds = dn, mn.millisecond = mn.milliseconds = fn, mn.utcOffset = function (e, t, n) { var s, i = this._offset || 0; if (!this.isValid()) return null != e ? this : NaN; if (null == e) return this._isUTC ? i : Vt(this); if ("string" == typeof e) { if (null === (e = Nt(re, e))) return this } else Math.abs(e) < 16 && !n && (e *= 60); return !this._isUTC && t && (s = Vt(this)), this._offset = e, this._isUTC = !0, null != s && this.add(s, "m"), i !== e && (!t || this._changeInProgress ? qt(this, jt(e - i, "m"), 1, !1) : this._changeInProgress || (this._changeInProgress = !0, c.updateOffset(this, !0), this._changeInProgress = null)), this }, mn.utc = function (e) { return this.utcOffset(0, e) }, mn.local = function (e) { return this._isUTC && (this.utcOffset(0, e), this._isUTC = !1, e && this.subtract(Vt(this), "m")), this }, mn.parseZone = function () { if (null != this._tzm) this.utcOffset(this._tzm, !1, !0); else if ("string" == typeof this._i) { var e = Nt(ie, this._i); null != e ? this.utcOffset(e) : this.utcOffset(0, !0) } return this }, mn.hasAlignedHourOffset = function (e) { return !!this.isValid() && (e = e ? bt(e).utcOffset() : 0, (this.utcOffset() - e) % 60 == 0) }, mn.isDST = function () { return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset() }, mn.isLocal = function () { return !!this.isValid() && !this._isUTC }, mn.isUtcOffset = function () { return !!this.isValid() && this._isUTC }, mn.isUtc = Et, mn.isUTC = Et, mn.zoneAbbr = function () { return this._isUTC ? "UTC" : "" }, mn.zoneName = function () { return this._isUTC ? "Coordinated Universal Time" : "" }, mn.dates = n("dates accessor is deprecated. Use date instead.", un), mn.months = n("months accessor is deprecated. Use month instead", Ue), mn.years = n("years accessor is deprecated. Use year instead", Oe), mn.zone = n("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/", function (e, t) { return null != e ? ("string" != typeof e && (e = -e), this.utcOffset(e, t), this) : -this.utcOffset() }), mn.isDSTShifted = n("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information", function () { if (!l(this._isDSTShifted)) return this._isDSTShifted; var e = {}; if (w(e, this), (e = Ot(e))._a) { var t = e._isUTC ? y(e._a) : bt(e._a); this._isDSTShifted = this.isValid() && 0 < a(e._a, t.toArray()) } else this._isDSTShifted = !1; return this._isDSTShifted }); var yn = P.prototype; function gn(e, t, n, s) { var i = ht(), r = y().set(s, t); return i[n](r, e) } function vn(e, t, n) { if (h(e) && (t = e, e = void 0), e = e || "", null != t) return gn(e, t, n, "month"); var s, i = []; for (s = 0; s < 12; s++)i[s] = gn(e, s, n, "month"); return i } function pn(e, t, n, s) { t = ("boolean" == typeof e ? h(t) && (n = t, t = void 0) : (t = e, e = !1, h(n = t) && (n = t, t = void 0)), t || ""); var i, r = ht(), a = e ? r._week.dow : 0; if (null != n) return gn(t, (n + a) % 7, s, "day"); var o = []; for (i = 0; i < 7; i++)o[i] = gn(t, (i + a) % 7, s, "day"); return o } yn.calendar = function (e, t, n) { var s = this._calendar[e] || this._calendar.sameElse; return b(s) ? s.call(t, n) : s }, yn.longDateFormat = function (e) { var t = this._longDateFormat[e], n = this._longDateFormat[e.toUpperCase()]; return t || !n ? t : (this._longDateFormat[e] = n.replace(/MMMM|MM|DD|dddd/g, function (e) { return e.slice(1) }), this._longDateFormat[e]) }, yn.invalidDate = function () { return this._invalidDate }, yn.ordinal = function (e) { return this._ordinal.replace("%d", e) }, yn.preparse = _n, yn.postformat = _n, yn.relativeTime = function (e, t, n, s) { var i = this._relativeTime[n]; return b(i) ? i(e, t, n, s) : i.replace(/%d/i, e) }, yn.pastFuture = function (e, t) { var n = this._relativeTime[0 < e ? "future" : "past"]; return b(n) ? n(t) : n.replace(/%s/i, t) }, yn.set = function (e) { var t, n; for (n in e) b(t = e[n]) ? this[n] = t : this["_" + n] = t; this._config = e, this._dayOfMonthOrdinalParseLenient = new RegExp((this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + "|" + /\d{1,2}/.source) }, yn.months = function (e, t) { return e ? o(this._months) ? this._months[e.month()] : this._months[(this._months.isFormat || We).test(t) ? "format" : "standalone"][e.month()] : o(this._months) ? this._months : this._months.standalone }, yn.monthsShort = function (e, t) { return e ? o(this._monthsShort) ? this._monthsShort[e.month()] : this._monthsShort[We.test(t) ? "format" : "standalone"][e.month()] : o(this._monthsShort) ? this._monthsShort : this._monthsShort.standalone }, yn.monthsParse = function (e, t, n) { var s, i, r; if (this._monthsParseExact) return function (e, t, n) { var s, i, r, a = e.toLocaleLowerCase(); if (!this._monthsParse) for (this._monthsParse = [], this._longMonthsParse = [], this._shortMonthsParse = [], s = 0; s < 12; ++s)r = y([2e3, s]), this._shortMonthsParse[s] = this.monthsShort(r, "").toLocaleLowerCase(), this._longMonthsParse[s] = this.months(r, "").toLocaleLowerCase(); return n ? "MMM" === t ? -1 !== (i = Ye.call(this._shortMonthsParse, a)) ? i : null : -1 !== (i = Ye.call(this._longMonthsParse, a)) ? i : null : "MMM" === t ? -1 !== (i = Ye.call(this._shortMonthsParse, a)) ? i : -1 !== (i = Ye.call(this._longMonthsParse, a)) ? i : null : -1 !== (i = Ye.call(this._longMonthsParse, a)) ? i : -1 !== (i = Ye.call(this._shortMonthsParse, a)) ? i : null }.call(this, e, t, n); for (this._monthsParse || (this._monthsParse = [], this._longMonthsParse = [], this._shortMonthsParse = []), s = 0; s < 12; s++) { if (i = y([2e3, s]), n && !this._longMonthsParse[s] && (this._longMonthsParse[s] = new RegExp("^" + this.months(i, "").replace(".", "") + "$", "i"), this._shortMonthsParse[s] = new RegExp("^" + this.monthsShort(i, "").replace(".", "") + "$", "i")), n || this._monthsParse[s] || (r = "^" + this.months(i, "") + "|^" + this.monthsShort(i, ""), this._monthsParse[s] = new RegExp(r.replace(".", ""), "i")), n && "MMMM" === t && this._longMonthsParse[s].test(e)) return s; if (n && "MMM" === t && this._shortMonthsParse[s].test(e)) return s; if (!n && this._monthsParse[s].test(e)) return s } }, yn.monthsRegex = function (e) { return this._monthsParseExact ? (m(this, "_monthsRegex") || Ne.call(this), e ? this._monthsStrictRegex : this._monthsRegex) : (m(this, "_monthsRegex") || (this._monthsRegex = Le), this._monthsStrictRegex && e ? this._monthsStrictRegex : this._monthsRegex) }, yn.monthsShortRegex = function (e) { return this._monthsParseExact ? (m(this, "_monthsRegex") || Ne.call(this), e ? this._monthsShortStrictRegex : this._monthsShortRegex) : (m(this, "_monthsShortRegex") || (this._monthsShortRegex = Fe), this._monthsShortStrictRegex && e ? this._monthsShortStrictRegex : this._monthsShortRegex) }, yn.week = function (e) { return Ie(e, this._week.dow, this._week.doy).week }, yn.firstDayOfYear = function () { return this._week.doy }, yn.firstDayOfWeek = function () { return this._week.dow }, yn.weekdays = function (e, t) { var n = o(this._weekdays) ? this._weekdays : this._weekdays[e && !0 !== e && this._weekdays.isFormat.test(t) ? "format" : "standalone"]; return !0 === e ? je(n, this._week.dow) : e ? n[e.day()] : n }, yn.weekdaysMin = function (e) { return !0 === e ? je(this._weekdaysMin, this._week.dow) : e ? this._weekdaysMin[e.day()] : this._weekdaysMin }, yn.weekdaysShort = function (e) { return !0 === e ? je(this._weekdaysShort, this._week.dow) : e ? this._weekdaysShort[e.day()] : this._weekdaysShort }, yn.weekdaysParse = function (e, t, n) { var s, i, r; if (this._weekdaysParseExact) return function (e, t, n) { var s, i, r, a = e.toLocaleLowerCase(); if (!this._weekdaysParse) for (this._weekdaysParse = [], this._shortWeekdaysParse = [], this._minWeekdaysParse = [], s = 0; s < 7; ++s)r = y([2e3, 1]).day(s), this._minWeekdaysParse[s] = this.weekdaysMin(r, "").toLocaleLowerCase(), this._shortWeekdaysParse[s] = this.weekdaysShort(r, "").toLocaleLowerCase(), this._weekdaysParse[s] = this.weekdays(r, "").toLocaleLowerCase(); return n ? "dddd" === t ? -1 !== (i = Ye.call(this._weekdaysParse, a)) ? i : null : "ddd" === t ? -1 !== (i = Ye.call(this._shortWeekdaysParse, a)) ? i : null : -1 !== (i = Ye.call(this._minWeekdaysParse, a)) ? i : null : "dddd" === t ? -1 !== (i = Ye.call(this._weekdaysParse, a)) ? i : -1 !== (i = Ye.call(this._shortWeekdaysParse, a)) ? i : -1 !== (i = Ye.call(this._minWeekdaysParse, a)) ? i : null : "ddd" === t ? -1 !== (i = Ye.call(this._shortWeekdaysParse, a)) ? i : -1 !== (i = Ye.call(this._weekdaysParse, a)) ? i : -1 !== (i = Ye.call(this._minWeekdaysParse, a)) ? i : null : -1 !== (i = Ye.call(this._minWeekdaysParse, a)) ? i : -1 !== (i = Ye.call(this._weekdaysParse, a)) ? i : -1 !== (i = Ye.call(this._shortWeekdaysParse, a)) ? i : null }.call(this, e, t, n); for (this._weekdaysParse || (this._weekdaysParse = [], this._minWeekdaysParse = [], this._shortWeekdaysParse = [], this._fullWeekdaysParse = []), s = 0; s < 7; s++) { if (i = y([2e3, 1]).day(s), n && !this._fullWeekdaysParse[s] && (this._fullWeekdaysParse[s] = new RegExp("^" + this.weekdays(i, "").replace(".", "\\.?") + "$", "i"), this._shortWeekdaysParse[s] = new RegExp("^" + this.weekdaysShort(i, "").replace(".", "\\.?") + "$", "i"), this._minWeekdaysParse[s] = new RegExp("^" + this.weekdaysMin(i, "").replace(".", "\\.?") + "$", "i")), this._weekdaysParse[s] || (r = "^" + this.weekdays(i, "") + "|^" + this.weekdaysShort(i, "") + "|^" + this.weekdaysMin(i, ""), this._weekdaysParse[s] = new RegExp(r.replace(".", ""), "i")), n && "dddd" === t && this._fullWeekdaysParse[s].test(e)) return s; if (n && "ddd" === t && this._shortWeekdaysParse[s].test(e)) return s; if (n && "dd" === t && this._minWeekdaysParse[s].test(e)) return s; if (!n && this._weekdaysParse[s].test(e)) return s } }, yn.weekdaysRegex = function (e) { return this._weekdaysParseExact ? (m(this, "_weekdaysRegex") || Qe.call(this), e ? this._weekdaysStrictRegex : this._weekdaysRegex) : (m(this, "_weekdaysRegex") || (this._weekdaysRegex = qe), this._weekdaysStrictRegex && e ? this._weekdaysStrictRegex : this._weekdaysRegex) }, yn.weekdaysShortRegex = function (e) { return this._weekdaysParseExact ? (m(this, "_weekdaysRegex") || Qe.call(this), e ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex) : (m(this, "_weekdaysShortRegex") || (this._weekdaysShortRegex = Je), this._weekdaysShortStrictRegex && e ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex) }, yn.weekdaysMinRegex = function (e) { return this._weekdaysParseExact ? (m(this, "_weekdaysRegex") || Qe.call(this), e ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex) : (m(this, "_weekdaysMinRegex") || (this._weekdaysMinRegex = Be), this._weekdaysMinStrictRegex && e ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex) }, yn.isPM = function (e) { return "p" === (e + "").toLowerCase().charAt(0) }, yn.meridiem = function (e, t, n) { return 11 < e ? n ? "pm" : "PM" : n ? "am" : "AM" }, ut("en", { dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: function (e) { var t = e % 10; return e + (1 === D(e % 100 / 10) ? "th" : 1 === t ? "st" : 2 === t ? "nd" : 3 === t ? "rd" : "th") } }), c.lang = n("moment.lang is deprecated. Use moment.locale instead.", ut), c.langData = n("moment.langData is deprecated. Use moment.localeData instead.", ht); var wn = Math.abs; function Mn(e, t, n, s) { var i = jt(t, n); return e._milliseconds += s * i._milliseconds, e._days += s * i._days, e._months += s * i._months, e._bubble() } function kn(e) { return e < 0 ? Math.floor(e) : Math.ceil(e) } function Sn(e) { return 4800 * e / 146097 } function Dn(e) { return 146097 * e / 4800 } function Yn(e) { return function () { return this.as(e) } } var On = Yn("ms"), Tn = Yn("s"), bn = Yn("m"), xn = Yn("h"), Pn = Yn("d"), Wn = Yn("w"), Cn = Yn("M"), Hn = Yn("Q"), Rn = Yn("y"); function Un(e) { return function () { return this.isValid() ? this._data[e] : NaN } } var Fn = Un("milliseconds"), Ln = Un("seconds"), Nn = Un("minutes"), Gn = Un("hours"), Vn = Un("days"), En = Un("months"), In = Un("years"); var An = Math.round, jn = { ss: 44, s: 45, m: 45, h: 22, d: 26, M: 11 }; var Zn = Math.abs; function zn(e) { return (0 < e) - (e < 0) || +e } function $n() { if (!this.isValid()) return this.localeData().invalidDate(); var e, t, n = Zn(this._milliseconds) / 1e3, s = Zn(this._days), i = Zn(this._months); t = S((e = S(n / 60)) / 60), n %= 60, e %= 60; var r = S(i / 12), a = i %= 12, o = s, u = t, l = e, h = n ? n.toFixed(3).replace(/\.?0+$/, "") : "", d = this.asSeconds(); if (!d) return "P0D"; var c = d < 0 ? "-" : "", f = zn(this._months) !== zn(d) ? "-" : "", m = zn(this._days) !== zn(d) ? "-" : "", _ = zn(this._milliseconds) !== zn(d) ? "-" : ""; return c + "P" + (r ? f + r + "Y" : "") + (a ? f + a + "M" : "") + (o ? m + o + "D" : "") + (u || l || h ? "T" : "") + (u ? _ + u + "H" : "") + (l ? _ + l + "M" : "") + (h ? _ + h + "S" : "") } var qn = Ht.prototype; return qn.isValid = function () { return this._isValid }, qn.abs = function () { var e = this._data; return this._milliseconds = wn(this._milliseconds), this._days = wn(this._days), this._months = wn(this._months), e.milliseconds = wn(e.milliseconds), e.seconds = wn(e.seconds), e.minutes = wn(e.minutes), e.hours = wn(e.hours), e.months = wn(e.months), e.years = wn(e.years), this }, qn.add = function (e, t) { return Mn(this, e, t, 1) }, qn.subtract = function (e, t) { return Mn(this, e, t, -1) }, qn.as = function (e) { if (!this.isValid()) return NaN; var t, n, s = this._milliseconds; if ("month" === (e = H(e)) || "quarter" === e || "year" === e) switch (t = this._days + s / 864e5, n = this._months + Sn(t), e) { case "month": return n; case "quarter": return n / 3; case "year": return n / 12 } else switch (t = this._days + Math.round(Dn(this._months)), e) { case "week": return t / 7 + s / 6048e5; case "day": return t + s / 864e5; case "hour": return 24 * t + s / 36e5; case "minute": return 1440 * t + s / 6e4; case "second": return 86400 * t + s / 1e3; case "millisecond": return Math.floor(864e5 * t) + s; default: throw new Error("Unknown unit " + e) } }, qn.asMilliseconds = On, qn.asSeconds = Tn, qn.asMinutes = bn, qn.asHours = xn, qn.asDays = Pn, qn.asWeeks = Wn, qn.asMonths = Cn, qn.asQuarters = Hn, qn.asYears = Rn, qn.valueOf = function () { return this.isValid() ? this._milliseconds + 864e5 * this._days + this._months % 12 * 2592e6 + 31536e6 * D(this._months / 12) : NaN }, qn._bubble = function () { var e, t, n, s, i, r = this._milliseconds, a = this._days, o = this._months, u = this._data; return 0 <= r && 0 <= a && 0 <= o || r <= 0 && a <= 0 && o <= 0 || (r += 864e5 * kn(Dn(o) + a), o = a = 0), u.milliseconds = r % 1e3, e = S(r / 1e3), u.seconds = e % 60, t = S(e / 60), u.minutes = t % 60, n = S(t / 60), u.hours = n % 24, o += i = S(Sn(a += S(n / 24))), a -= kn(Dn(i)), s = S(o / 12), o %= 12, u.days = a, u.months = o, u.years = s, this }, qn.clone = function () { return jt(this) }, qn.get = function (e) { return e = H(e), this.isValid() ? this[e + "s"]() : NaN }, qn.milliseconds = Fn, qn.seconds = Ln, qn.minutes = Nn, qn.hours = Gn, qn.days = Vn, qn.weeks = function () { return S(this.days() / 7) }, qn.months = En, qn.years = In, qn.humanize = function (e) { if (!this.isValid()) return this.localeData().invalidDate(); var t, n, s, i, r, a, o, u, l, h, d, c = this.localeData(), f = (n = !e, s = c, i = jt(t = this).abs(), r = An(i.as("s")), a = An(i.as("m")), o = An(i.as("h")), u = An(i.as("d")), l = An(i.as("M")), h = An(i.as("y")), (d = r <= jn.ss && ["s", r] || r < jn.s && ["ss", r] || a <= 1 && ["m"] || a < jn.m && ["mm", a] || o <= 1 && ["h"] || o < jn.h && ["hh", o] || u <= 1 && ["d"] || u < jn.d && ["dd", u] || l <= 1 && ["M"] || l < jn.M && ["MM", l] || h <= 1 && ["y"] || ["yy", h])[2] = n, d[3] = 0 < +t, d[4] = s, function (e, t, n, s, i) { return i.relativeTime(t || 1, !!n, e, s) }.apply(null, d)); return e && (f = c.pastFuture(+this, f)), c.postformat(f) }, qn.toISOString = $n, qn.toString = $n, qn.toJSON = $n, qn.locale = Xt, qn.localeData = en, qn.toIsoString = n("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)", $n), qn.lang = Kt, I("X", 0, 0, "unix"), I("x", 0, 0, "valueOf"), ue("x", se), ue("X", /[+-]?\d+(\.\d{1,3})?/), ce("X", function (e, t, n) { n._d = new Date(1e3 * parseFloat(e, 10)) }), ce("x", function (e, t, n) { n._d = new Date(D(e)) }), c.version = "2.24.0", e = bt, c.fn = mn, c.min = function () { return Wt("isBefore", [].slice.call(arguments, 0)) }, c.max = function () { return Wt("isAfter", [].slice.call(arguments, 0)) }, c.now = function () { return Date.now ? Date.now() : +new Date }, c.utc = y, c.unix = function (e) { return bt(1e3 * e) }, c.months = function (e, t) { return vn(e, t, "months") }, c.isDate = d, c.locale = ut, c.invalid = p, c.duration = jt, c.isMoment = k, c.weekdays = function (e, t, n) { return pn(e, t, n, "weekdays") }, c.parseZone = function () { return bt.apply(null, arguments).parseZone() }, c.localeData = ht, c.isDuration = Rt, c.monthsShort = function (e, t) { return vn(e, t, "monthsShort") }, c.weekdaysMin = function (e, t, n) { return pn(e, t, n, "weekdaysMin") }, c.defineLocale = lt, c.updateLocale = function (e, t) { if (null != t) { var n, s, i = st; null != (s = ot(e)) && (i = s._config), (n = new P(t = x(i, t))).parentLocale = it[e], it[e] = n, ut(e) } else null != it[e] && (null != it[e].parentLocale ? it[e] = it[e].parentLocale : null != it[e] && delete it[e]); return it[e] }, c.locales = function () { return s(it) }, c.weekdaysShort = function (e, t, n) { return pn(e, t, n, "weekdaysShort") }, c.normalizeUnits = H, c.relativeTimeRounding = function (e) { return void 0 === e ? An : "function" == typeof e && (An = e, !0) }, c.relativeTimeThreshold = function (e, t) { return void 0 !== jn[e] && (void 0 === t ? jn[e] : (jn[e] = t, "s" === e && (jn.ss = t - 1), !0)) }, c.calendarFormat = function (e, t) { var n = e.diff(t, "days", !0); return n < -6 ? "sameElse" : n < -1 ? "lastWeek" : n < 0 ? "lastDay" : n < 1 ? "sameDay" : n < 2 ? "nextDay" : n < 7 ? "nextWeek" : "sameElse" }, c.prototype = mn, c.HTML5_FMT = { DATETIME_LOCAL: "YYYY-MM-DDTHH:mm", DATETIME_LOCAL_SECONDS: "YYYY-MM-DDTHH:mm:ss", DATETIME_LOCAL_MS: "YYYY-MM-DDTHH:mm:ss.SSS", DATE: "YYYY-MM-DD", TIME: "HH:mm", TIME_SECONDS: "HH:mm:ss", TIME_MS: "HH:mm:ss.SSS", WEEK: "GGGG-[W]WW", MONTH: "YYYY-MM" }, c });;
/*! PhotoSwipe Default UI - 4.1.1 - 2015-12-24
* http://photoswipe.com
* Copyright (c) 2015 Dmitry Semenov; */
!function(a,b){"function"==typeof define&&define.amd?define(b):"object"==typeof exports?module.exports=b():a.PhotoSwipeUI_Default=b()}(this,function(){"use strict";var a=function(a,b){var c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v=this,w=!1,x=!0,y=!0,z={barsSize:{top:44,bottom:"auto"},closeElClasses:["item","caption","zoom-wrap","ui","top-bar"],timeToIdle:4e3,timeToIdleOutside:1e3,loadingIndicatorDelay:1e3,addCaptionHTMLFn:function(a,b){return a.title?(b.children[0].innerHTML=a.title,!0):(b.children[0].innerHTML="",!1)},closeEl:!0,captionEl:!0,fullscreenEl:!0,zoomEl:!0,shareEl:!0,counterEl:!0,arrowEl:!0,preloaderEl:!0,tapToClose:!1,tapToToggleControls:!0,clickToCloseNonZoomable:!0,shareButtons:[{id:"facebook",label:"Share on Facebook",url:"https://www.facebook.com/sharer/sharer.php?u={{url}}"},{id:"twitter",label:"Tweet",url:"https://twitter.com/intent/tweet?text={{text}}&url={{url}}"},{id:"pinterest",label:"Pin it",url:"http://www.pinterest.com/pin/create/button/?url={{url}}&media={{image_url}}&description={{text}}"},{id:"download",label:"Download image",url:"{{raw_image_url}}",download:!0}],getImageURLForShare:function(){return a.currItem.src||""},getPageURLForShare:function(){return window.location.href},getTextForShare:function(){return a.currItem.title||""},indexIndicatorSep:" / ",fitControlsWidth:1200},A=function(a){if(r)return!0;a=a||window.event,q.timeToIdle&&q.mouseUsed&&!k&&K();for(var c,d,e=a.target||a.srcElement,f=e.getAttribute("class")||"",g=0;g<S.length;g++)c=S[g],c.onTap&&f.indexOf("pswp__"+c.name)>-1&&(c.onTap(),d=!0);if(d){a.stopPropagation&&a.stopPropagation(),r=!0;var h=b.features.isOldAndroid?600:30;s=setTimeout(function(){r=!1},h)}},B=function(){return!a.likelyTouchDevice||q.mouseUsed||screen.width>q.fitControlsWidth},C=function(a,c,d){b[(d?"add":"remove")+"Class"](a,"pswp__"+c)},D=function(){var a=1===q.getNumItemsFn();a!==p&&(C(d,"ui--one-slide",a),p=a)},E=function(){C(i,"share-modal--hidden",y)},F=function(){return y=!y,y?(b.removeClass(i,"pswp__share-modal--fade-in"),setTimeout(function(){y&&E()},300)):(E(),setTimeout(function(){y||b.addClass(i,"pswp__share-modal--fade-in")},30)),y||H(),!1},G=function(b){b=b||window.event;var c=b.target||b.srcElement;return a.shout("shareLinkClick",b,c),c.href?c.hasAttribute("download")?!0:(window.open(c.href,"pswp_share","scrollbars=yes,resizable=yes,toolbar=no,location=yes,width=550,height=420,top=100,left="+(window.screen?Math.round(screen.width/2-275):100)),y||F(),!1):!1},H=function(){for(var a,b,c,d,e,f="",g=0;g<q.shareButtons.length;g++)a=q.shareButtons[g],c=q.getImageURLForShare(a),d=q.getPageURLForShare(a),e=q.getTextForShare(a),b=a.url.replace("{{url}}",encodeURIComponent(d)).replace("{{image_url}}",encodeURIComponent(c)).replace("{{raw_image_url}}",c).replace("{{text}}",encodeURIComponent(e)),f+='<a href="'+b+'" target="_blank" class="pswp__share--'+a.id+'"'+(a.download?"download":"")+">"+a.label+"</a>",q.parseShareButtonOut&&(f=q.parseShareButtonOut(a,f));i.children[0].innerHTML=f,i.children[0].onclick=G},I=function(a){for(var c=0;c<q.closeElClasses.length;c++)if(b.hasClass(a,"pswp__"+q.closeElClasses[c]))return!0},J=0,K=function(){clearTimeout(u),J=0,k&&v.setIdle(!1)},L=function(a){a=a?a:window.event;var b=a.relatedTarget||a.toElement;b&&"HTML"!==b.nodeName||(clearTimeout(u),u=setTimeout(function(){v.setIdle(!0)},q.timeToIdleOutside))},M=function(){q.fullscreenEl&&!b.features.isOldAndroid&&(c||(c=v.getFullscreenAPI()),c?(b.bind(document,c.eventK,v.updateFullscreen),v.updateFullscreen(),b.addClass(a.template,"pswp--supports-fs")):b.removeClass(a.template,"pswp--supports-fs"))},N=function(){q.preloaderEl&&(O(!0),l("beforeChange",function(){clearTimeout(o),o=setTimeout(function(){a.currItem&&a.currItem.loading?(!a.allowProgressiveImg()||a.currItem.img&&!a.currItem.img.naturalWidth)&&O(!1):O(!0)},q.loadingIndicatorDelay)}),l("imageLoadComplete",function(b,c){a.currItem===c&&O(!0)}))},O=function(a){n!==a&&(C(m,"preloader--active",!a),n=a)},P=function(a){var c=a.vGap;if(B()){var g=q.barsSize;if(q.captionEl&&"auto"===g.bottom)if(f||(f=b.createEl("pswp__caption pswp__caption--fake"),f.appendChild(b.createEl("pswp__caption__center")),d.insertBefore(f,e),b.addClass(d,"pswp__ui--fit")),q.addCaptionHTMLFn(a,f,!0)){var h=f.clientHeight;c.bottom=parseInt(h,10)||44}else c.bottom=g.top;else c.bottom="auto"===g.bottom?0:g.bottom;c.top=g.top}else c.top=c.bottom=0},Q=function(){q.timeToIdle&&l("mouseUsed",function(){b.bind(document,"mousemove",K),b.bind(document,"mouseout",L),t=setInterval(function(){J++,2===J&&v.setIdle(!0)},q.timeToIdle/2)})},R=function(){l("onVerticalDrag",function(a){x&&.95>a?v.hideControls():!x&&a>=.95&&v.showControls()});var a;l("onPinchClose",function(b){x&&.9>b?(v.hideControls(),a=!0):a&&!x&&b>.9&&v.showControls()}),l("zoomGestureEnded",function(){a=!1,a&&!x&&v.showControls()})},S=[{name:"caption",option:"captionEl",onInit:function(a){e=a}},{name:"share-modal",option:"shareEl",onInit:function(a){i=a},onTap:function(){F()}},{name:"button--share",option:"shareEl",onInit:function(a){h=a},onTap:function(){F()}},{name:"button--zoom",option:"zoomEl",onTap:a.toggleDesktopZoom},{name:"counter",option:"counterEl",onInit:function(a){g=a}},{name:"button--close",option:"closeEl",onTap:a.close},{name:"button--arrow--left",option:"arrowEl",onTap:a.prev},{name:"button--arrow--right",option:"arrowEl",onTap:a.next},{name:"button--fs",option:"fullscreenEl",onTap:function(){c.isFullscreen()?c.exit():c.enter()}},{name:"preloader",option:"preloaderEl",onInit:function(a){m=a}}],T=function(){var a,c,e,f=function(d){if(d)for(var f=d.length,g=0;f>g;g++){a=d[g],c=a.className;for(var h=0;h<S.length;h++)e=S[h],c.indexOf("pswp__"+e.name)>-1&&(q[e.option]?(b.removeClass(a,"pswp__element--disabled"),e.onInit&&e.onInit(a)):b.addClass(a,"pswp__element--disabled"))}};f(d.children);var g=b.getChildByClass(d,"pswp__top-bar");g&&f(g.children)};v.init=function(){b.extend(a.options,z,!0),q=a.options,d=b.getChildByClass(a.scrollWrap,"pswp__ui"),l=a.listen,R(),l("beforeChange",v.update),l("doubleTap",function(b){var c=a.currItem.initialZoomLevel;a.getZoomLevel()!==c?a.zoomTo(c,b,333):a.zoomTo(q.getDoubleTapZoom(!1,a.currItem),b,333)}),l("preventDragEvent",function(a,b,c){var d=a.target||a.srcElement;d&&d.getAttribute("class")&&a.type.indexOf("mouse")>-1&&(d.getAttribute("class").indexOf("__caption")>0||/(SMALL|STRONG|EM)/i.test(d.tagName))&&(c.prevent=!1)}),l("bindEvents",function(){b.bind(d,"pswpTap click",A),b.bind(a.scrollWrap,"pswpTap",v.onGlobalTap),a.likelyTouchDevice||b.bind(a.scrollWrap,"mouseover",v.onMouseOver)}),l("unbindEvents",function(){y||F(),t&&clearInterval(t),b.unbind(document,"mouseout",L),b.unbind(document,"mousemove",K),b.unbind(d,"pswpTap click",A),b.unbind(a.scrollWrap,"pswpTap",v.onGlobalTap),b.unbind(a.scrollWrap,"mouseover",v.onMouseOver),c&&(b.unbind(document,c.eventK,v.updateFullscreen),c.isFullscreen()&&(q.hideAnimationDuration=0,c.exit()),c=null)}),l("destroy",function(){q.captionEl&&(f&&d.removeChild(f),b.removeClass(e,"pswp__caption--empty")),i&&(i.children[0].onclick=null),b.removeClass(d,"pswp__ui--over-close"),b.addClass(d,"pswp__ui--hidden"),v.setIdle(!1)}),q.showAnimationDuration||b.removeClass(d,"pswp__ui--hidden"),l("initialZoomIn",function(){q.showAnimationDuration&&b.removeClass(d,"pswp__ui--hidden")}),l("initialZoomOut",function(){b.addClass(d,"pswp__ui--hidden")}),l("parseVerticalMargin",P),T(),q.shareEl&&h&&i&&(y=!0),D(),Q(),M(),N()},v.setIdle=function(a){k=a,C(d,"ui--idle",a)},v.update=function(){x&&a.currItem?(v.updateIndexIndicator(),q.captionEl&&(q.addCaptionHTMLFn(a.currItem,e),C(e,"caption--empty",!a.currItem.title)),w=!0):w=!1,y||F(),D()},v.updateFullscreen=function(d){d&&setTimeout(function(){a.setScrollOffset(0,b.getScrollY())},50),b[(c.isFullscreen()?"add":"remove")+"Class"](a.template,"pswp--fs")},v.updateIndexIndicator=function(){q.counterEl&&(g.innerHTML=a.getCurrentIndex()+1+q.indexIndicatorSep+q.getNumItemsFn())},v.onGlobalTap=function(c){c=c||window.event;var d=c.target||c.srcElement;if(!r)if(c.detail&&"mouse"===c.detail.pointerType){if(I(d))return void a.close();b.hasClass(d,"pswp__img")&&(1===a.getZoomLevel()&&a.getZoomLevel()<=a.currItem.fitRatio?q.clickToCloseNonZoomable&&a.close():a.toggleDesktopZoom(c.detail.releasePoint))}else if(q.tapToToggleControls&&(x?v.hideControls():v.showControls()),q.tapToClose&&(b.hasClass(d,"pswp__img")||I(d)))return void a.close()},v.onMouseOver=function(a){a=a||window.event;var b=a.target||a.srcElement;C(d,"ui--over-close",I(b))},v.hideControls=function(){b.addClass(d,"pswp__ui--hidden"),x=!1},v.showControls=function(){x=!0,w||v.update(),b.removeClass(d,"pswp__ui--hidden")},v.supportsFullscreen=function(){var a=document;return!!(a.exitFullscreen||a.mozCancelFullScreen||a.webkitExitFullscreen||a.msExitFullscreen)},v.getFullscreenAPI=function(){var b,c=document.documentElement,d="fullscreenchange";return c.requestFullscreen?b={enterK:"requestFullscreen",exitK:"exitFullscreen",elementK:"fullscreenElement",eventK:d}:c.mozRequestFullScreen?b={enterK:"mozRequestFullScreen",exitK:"mozCancelFullScreen",elementK:"mozFullScreenElement",eventK:"moz"+d}:c.webkitRequestFullscreen?b={enterK:"webkitRequestFullscreen",exitK:"webkitExitFullscreen",elementK:"webkitFullscreenElement",eventK:"webkit"+d}:c.msRequestFullscreen&&(b={enterK:"msRequestFullscreen",exitK:"msExitFullscreen",elementK:"msFullscreenElement",eventK:"MSFullscreenChange"}),b&&(b.enter=function(){return j=q.closeOnScroll,q.closeOnScroll=!1,"webkitRequestFullscreen"!==this.enterK?a.template[this.enterK]():void a.template[this.enterK](Element.ALLOW_KEYBOARD_INPUT)},b.exit=function(){return q.closeOnScroll=j,document[this.exitK]()},b.isFullscreen=function(){return document[this.elementK]}),b}};return a});;
/*! PhotoSwipe - v4.1.1 - 2015-12-24
* http://photoswipe.com
* Copyright (c) 2015 Dmitry Semenov; */
!function(a,b){"function"==typeof define&&define.amd?define(b):"object"==typeof exports?module.exports=b():a.PhotoSwipe=b()}(this,function(){"use strict";var a=function(a,b,c,d){var e={features:null,bind:function(a,b,c,d){var e=(d?"remove":"add")+"EventListener";b=b.split(" ");for(var f=0;f<b.length;f++)b[f]&&a[e](b[f],c,!1)},isArray:function(a){return a instanceof Array},createEl:function(a,b){var c=document.createElement(b||"div");return a&&(c.className=a),c},getScrollY:function(){var a=window.pageYOffset;return void 0!==a?a:document.documentElement.scrollTop},unbind:function(a,b,c){e.bind(a,b,c,!0)},removeClass:function(a,b){var c=new RegExp("(\\s|^)"+b+"(\\s|$)");a.className=a.className.replace(c," ").replace(/^\s\s*/,"").replace(/\s\s*$/,"")},addClass:function(a,b){e.hasClass(a,b)||(a.className+=(a.className?" ":"")+b)},hasClass:function(a,b){return a.className&&new RegExp("(^|\\s)"+b+"(\\s|$)").test(a.className)},getChildByClass:function(a,b){for(var c=a.firstChild;c;){if(e.hasClass(c,b))return c;c=c.nextSibling}},arraySearch:function(a,b,c){for(var d=a.length;d--;)if(a[d][c]===b)return d;return-1},extend:function(a,b,c){for(var d in b)if(b.hasOwnProperty(d)){if(c&&a.hasOwnProperty(d))continue;a[d]=b[d]}},easing:{sine:{out:function(a){return Math.sin(a*(Math.PI/2))},inOut:function(a){return-(Math.cos(Math.PI*a)-1)/2}},cubic:{out:function(a){return--a*a*a+1}}},detectFeatures:function(){if(e.features)return e.features;var a=e.createEl(),b=a.style,c="",d={};if(d.oldIE=document.all&&!document.addEventListener,d.touch="ontouchstart"in window,window.requestAnimationFrame&&(d.raf=window.requestAnimationFrame,d.caf=window.cancelAnimationFrame),d.pointerEvent=navigator.pointerEnabled||navigator.msPointerEnabled,!d.pointerEvent){var f=navigator.userAgent;if(/iP(hone|od)/.test(navigator.platform)){var g=navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/);g&&g.length>0&&(g=parseInt(g[1],10),g>=1&&8>g&&(d.isOldIOSPhone=!0))}var h=f.match(/Android\s([0-9\.]*)/),i=h?h[1]:0;i=parseFloat(i),i>=1&&(4.4>i&&(d.isOldAndroid=!0),d.androidVersion=i),d.isMobileOpera=/opera mini|opera mobi/i.test(f)}for(var j,k,l=["transform","perspective","animationName"],m=["","webkit","Moz","ms","O"],n=0;4>n;n++){c=m[n];for(var o=0;3>o;o++)j=l[o],k=c+(c?j.charAt(0).toUpperCase()+j.slice(1):j),!d[j]&&k in b&&(d[j]=k);c&&!d.raf&&(c=c.toLowerCase(),d.raf=window[c+"RequestAnimationFrame"],d.raf&&(d.caf=window[c+"CancelAnimationFrame"]||window[c+"CancelRequestAnimationFrame"]))}if(!d.raf){var p=0;d.raf=function(a){var b=(new Date).getTime(),c=Math.max(0,16-(b-p)),d=window.setTimeout(function(){a(b+c)},c);return p=b+c,d},d.caf=function(a){clearTimeout(a)}}return d.svg=!!document.createElementNS&&!!document.createElementNS("http://www.w3.org/2000/svg","svg").createSVGRect,e.features=d,d}};e.detectFeatures(),e.features.oldIE&&(e.bind=function(a,b,c,d){b=b.split(" ");for(var e,f=(d?"detach":"attach")+"Event",g=function(){c.handleEvent.call(c)},h=0;h<b.length;h++)if(e=b[h])if("object"==typeof c&&c.handleEvent){if(d){if(!c["oldIE"+e])return!1}else c["oldIE"+e]=g;a[f]("on"+e,c["oldIE"+e])}else a[f]("on"+e,c)});var f=this,g=25,h=3,i={allowPanToNext:!0,spacing:.12,bgOpacity:1,mouseUsed:!1,loop:!0,pinchToClose:!0,closeOnScroll:!0,closeOnVerticalDrag:!0,verticalDragRange:.75,hideAnimationDuration:333,showAnimationDuration:333,showHideOpacity:!1,focus:!0,escKey:!0,arrowKeys:!0,mainScrollEndFriction:.35,panEndFriction:.35,isClickableElement:function(a){return"A"===a.tagName},getDoubleTapZoom:function(a,b){return a?1:b.initialZoomLevel<.7?1:1.33},maxSpreadZoom:1.33,modal:!0,scaleMode:"fit"};e.extend(i,d);var j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,aa,ba,ca,da,ea,fa,ga,ha,ia,ja,ka,la=function(){return{x:0,y:0}},ma=la(),na=la(),oa=la(),pa={},qa=0,ra={},sa=la(),ta=0,ua=!0,va=[],wa={},xa=!1,ya=function(a,b){e.extend(f,b.publicMethods),va.push(a)},za=function(a){var b=_b();return a>b-1?a-b:0>a?b+a:a},Aa={},Ba=function(a,b){return Aa[a]||(Aa[a]=[]),Aa[a].push(b)},Ca=function(a){var b=Aa[a];if(b){var c=Array.prototype.slice.call(arguments);c.shift();for(var d=0;d<b.length;d++)b[d].apply(f,c)}},Da=function(){return(new Date).getTime()},Ea=function(a){ia=a,f.bg.style.opacity=a*i.bgOpacity},Fa=function(a,b,c,d,e){(!xa||e&&e!==f.currItem)&&(d/=e?e.fitRatio:f.currItem.fitRatio),a[E]=u+b+"px, "+c+"px"+v+" scale("+d+")"},Ga=function(a){da&&(a&&(s>f.currItem.fitRatio?xa||(lc(f.currItem,!1,!0),xa=!0):xa&&(lc(f.currItem),xa=!1)),Fa(da,oa.x,oa.y,s))},Ha=function(a){a.container&&Fa(a.container.style,a.initialPosition.x,a.initialPosition.y,a.initialZoomLevel,a)},Ia=function(a,b){b[E]=u+a+"px, 0px"+v},Ja=function(a,b){if(!i.loop&&b){var c=m+(sa.x*qa-a)/sa.x,d=Math.round(a-sb.x);(0>c&&d>0||c>=_b()-1&&0>d)&&(a=sb.x+d*i.mainScrollEndFriction)}sb.x=a,Ia(a,n)},Ka=function(a,b){var c=tb[a]-ra[a];return na[a]+ma[a]+c-c*(b/t)},La=function(a,b){a.x=b.x,a.y=b.y,b.id&&(a.id=b.id)},Ma=function(a){a.x=Math.round(a.x),a.y=Math.round(a.y)},Na=null,Oa=function(){Na&&(e.unbind(document,"mousemove",Oa),e.addClass(a,"pswp--has_mouse"),i.mouseUsed=!0,Ca("mouseUsed")),Na=setTimeout(function(){Na=null},100)},Pa=function(){e.bind(document,"keydown",f),N.transform&&e.bind(f.scrollWrap,"click",f),i.mouseUsed||e.bind(document,"mousemove",Oa),e.bind(window,"resize scroll",f),Ca("bindEvents")},Qa=function(){e.unbind(window,"resize",f),e.unbind(window,"scroll",r.scroll),e.unbind(document,"keydown",f),e.unbind(document,"mousemove",Oa),N.transform&&e.unbind(f.scrollWrap,"click",f),U&&e.unbind(window,p,f),Ca("unbindEvents")},Ra=function(a,b){var c=hc(f.currItem,pa,a);return b&&(ca=c),c},Sa=function(a){return a||(a=f.currItem),a.initialZoomLevel},Ta=function(a){return a||(a=f.currItem),a.w>0?i.maxSpreadZoom:1},Ua=function(a,b,c,d){return d===f.currItem.initialZoomLevel?(c[a]=f.currItem.initialPosition[a],!0):(c[a]=Ka(a,d),c[a]>b.min[a]?(c[a]=b.min[a],!0):c[a]<b.max[a]?(c[a]=b.max[a],!0):!1)},Va=function(){if(E){var b=N.perspective&&!G;return u="translate"+(b?"3d(":"("),void(v=N.perspective?", 0px)":")")}E="left",e.addClass(a,"pswp--ie"),Ia=function(a,b){b.left=a+"px"},Ha=function(a){var b=a.fitRatio>1?1:a.fitRatio,c=a.container.style,d=b*a.w,e=b*a.h;c.width=d+"px",c.height=e+"px",c.left=a.initialPosition.x+"px",c.top=a.initialPosition.y+"px"},Ga=function(){if(da){var a=da,b=f.currItem,c=b.fitRatio>1?1:b.fitRatio,d=c*b.w,e=c*b.h;a.width=d+"px",a.height=e+"px",a.left=oa.x+"px",a.top=oa.y+"px"}}},Wa=function(a){var b="";i.escKey&&27===a.keyCode?b="close":i.arrowKeys&&(37===a.keyCode?b="prev":39===a.keyCode&&(b="next")),b&&(a.ctrlKey||a.altKey||a.shiftKey||a.metaKey||(a.preventDefault?a.preventDefault():a.returnValue=!1,f[b]()))},Xa=function(a){a&&(X||W||ea||S)&&(a.preventDefault(),a.stopPropagation())},Ya=function(){f.setScrollOffset(0,e.getScrollY())},Za={},$a=0,_a=function(a){Za[a]&&(Za[a].raf&&I(Za[a].raf),$a--,delete Za[a])},ab=function(a){Za[a]&&_a(a),Za[a]||($a++,Za[a]={})},bb=function(){for(var a in Za)Za.hasOwnProperty(a)&&_a(a)},cb=function(a,b,c,d,e,f,g){var h,i=Da();ab(a);var j=function(){if(Za[a]){if(h=Da()-i,h>=d)return _a(a),f(c),void(g&&g());f((c-b)*e(h/d)+b),Za[a].raf=H(j)}};j()},db={shout:Ca,listen:Ba,viewportSize:pa,options:i,isMainScrollAnimating:function(){return ea},getZoomLevel:function(){return s},getCurrentIndex:function(){return m},isDragging:function(){return U},isZooming:function(){return _},setScrollOffset:function(a,b){ra.x=a,M=ra.y=b,Ca("updateScrollOffset",ra)},applyZoomPan:function(a,b,c,d){oa.x=b,oa.y=c,s=a,Ga(d)},init:function(){if(!j&&!k){var c;f.framework=e,f.template=a,f.bg=e.getChildByClass(a,"pswp__bg"),J=a.className,j=!0,N=e.detectFeatures(),H=N.raf,I=N.caf,E=N.transform,L=N.oldIE,f.scrollWrap=e.getChildByClass(a,"pswp__scroll-wrap"),f.container=e.getChildByClass(f.scrollWrap,"pswp__container"),n=f.container.style,f.itemHolders=y=[{el:f.container.children[0],wrap:0,index:-1},{el:f.container.children[1],wrap:0,index:-1},{el:f.container.children[2],wrap:0,index:-1}],y[0].el.style.display=y[2].el.style.display="none",Va(),r={resize:f.updateSize,scroll:Ya,keydown:Wa,click:Xa};var d=N.isOldIOSPhone||N.isOldAndroid||N.isMobileOpera;for(N.animationName&&N.transform&&!d||(i.showAnimationDuration=i.hideAnimationDuration=0),c=0;c<va.length;c++)f["init"+va[c]]();if(b){var g=f.ui=new b(f,e);g.init()}Ca("firstUpdate"),m=m||i.index||0,(isNaN(m)||0>m||m>=_b())&&(m=0),f.currItem=$b(m),(N.isOldIOSPhone||N.isOldAndroid)&&(ua=!1),a.setAttribute("aria-hidden","false"),i.modal&&(ua?a.style.position="fixed":(a.style.position="absolute",a.style.top=e.getScrollY()+"px")),void 0===M&&(Ca("initialLayout"),M=K=e.getScrollY());var l="pswp--open ";for(i.mainClass&&(l+=i.mainClass+" "),i.showHideOpacity&&(l+="pswp--animate_opacity "),l+=G?"pswp--touch":"pswp--notouch",l+=N.animationName?" pswp--css_animation":"",l+=N.svg?" pswp--svg":"",e.addClass(a,l),f.updateSize(),o=-1,ta=null,c=0;h>c;c++)Ia((c+o)*sa.x,y[c].el.style);L||e.bind(f.scrollWrap,q,f),Ba("initialZoomInEnd",function(){f.setContent(y[0],m-1),f.setContent(y[2],m+1),y[0].el.style.display=y[2].el.style.display="block",i.focus&&a.focus(),Pa()}),f.setContent(y[1],m),f.updateCurrItem(),Ca("afterInit"),ua||(w=setInterval(function(){$a||U||_||s!==f.currItem.initialZoomLevel||f.updateSize()},1e3)),e.addClass(a,"pswp--visible")}},close:function(){j&&(j=!1,k=!0,Ca("close"),Qa(),bc(f.currItem,null,!0,f.destroy))},destroy:function(){Ca("destroy"),Wb&&clearTimeout(Wb),a.setAttribute("aria-hidden","true"),a.className=J,w&&clearInterval(w),e.unbind(f.scrollWrap,q,f),e.unbind(window,"scroll",f),yb(),bb(),Aa=null},panTo:function(a,b,c){c||(a>ca.min.x?a=ca.min.x:a<ca.max.x&&(a=ca.max.x),b>ca.min.y?b=ca.min.y:b<ca.max.y&&(b=ca.max.y)),oa.x=a,oa.y=b,Ga()},handleEvent:function(a){a=a||window.event,r[a.type]&&r[a.type](a)},goTo:function(a){a=za(a);var b=a-m;ta=b,m=a,f.currItem=$b(m),qa-=b,Ja(sa.x*qa),bb(),ea=!1,f.updateCurrItem()},next:function(){f.goTo(m+1)},prev:function(){f.goTo(m-1)},updateCurrZoomItem:function(a){if(a&&Ca("beforeChange",0),y[1].el.children.length){var b=y[1].el.children[0];da=e.hasClass(b,"pswp__zoom-wrap")?b.style:null}else da=null;ca=f.currItem.bounds,t=s=f.currItem.initialZoomLevel,oa.x=ca.center.x,oa.y=ca.center.y,a&&Ca("afterChange")},invalidateCurrItems:function(){x=!0;for(var a=0;h>a;a++)y[a].item&&(y[a].item.needsUpdate=!0)},updateCurrItem:function(a){if(0!==ta){var b,c=Math.abs(ta);if(!(a&&2>c)){f.currItem=$b(m),xa=!1,Ca("beforeChange",ta),c>=h&&(o+=ta+(ta>0?-h:h),c=h);for(var d=0;c>d;d++)ta>0?(b=y.shift(),y[h-1]=b,o++,Ia((o+2)*sa.x,b.el.style),f.setContent(b,m-c+d+1+1)):(b=y.pop(),y.unshift(b),o--,Ia(o*sa.x,b.el.style),f.setContent(b,m+c-d-1-1));if(da&&1===Math.abs(ta)){var e=$b(z);e.initialZoomLevel!==s&&(hc(e,pa),lc(e),Ha(e))}ta=0,f.updateCurrZoomItem(),z=m,Ca("afterChange")}}},updateSize:function(b){if(!ua&&i.modal){var c=e.getScrollY();if(M!==c&&(a.style.top=c+"px",M=c),!b&&wa.x===window.innerWidth&&wa.y===window.innerHeight)return;wa.x=window.innerWidth,wa.y=window.innerHeight,a.style.height=wa.y+"px"}if(pa.x=f.scrollWrap.clientWidth,pa.y=f.scrollWrap.clientHeight,Ya(),sa.x=pa.x+Math.round(pa.x*i.spacing),sa.y=pa.y,Ja(sa.x*qa),Ca("beforeResize"),void 0!==o){for(var d,g,j,k=0;h>k;k++)d=y[k],Ia((k+o)*sa.x,d.el.style),j=m+k-1,i.loop&&_b()>2&&(j=za(j)),g=$b(j),g&&(x||g.needsUpdate||!g.bounds)?(f.cleanSlide(g),f.setContent(d,j),1===k&&(f.currItem=g,f.updateCurrZoomItem(!0)),g.needsUpdate=!1):-1===d.index&&j>=0&&f.setContent(d,j),g&&g.container&&(hc(g,pa),lc(g),Ha(g));x=!1}t=s=f.currItem.initialZoomLevel,ca=f.currItem.bounds,ca&&(oa.x=ca.center.x,oa.y=ca.center.y,Ga(!0)),Ca("resize")},zoomTo:function(a,b,c,d,f){b&&(t=s,tb.x=Math.abs(b.x)-oa.x,tb.y=Math.abs(b.y)-oa.y,La(na,oa));var g=Ra(a,!1),h={};Ua("x",g,h,a),Ua("y",g,h,a);var i=s,j={x:oa.x,y:oa.y};Ma(h);var k=function(b){1===b?(s=a,oa.x=h.x,oa.y=h.y):(s=(a-i)*b+i,oa.x=(h.x-j.x)*b+j.x,oa.y=(h.y-j.y)*b+j.y),f&&f(b),Ga(1===b)};c?cb("customZoomTo",0,1,c,d||e.easing.sine.inOut,k):k(1)}},eb=30,fb=10,gb={},hb={},ib={},jb={},kb={},lb=[],mb={},nb=[],ob={},pb=0,qb=la(),rb=0,sb=la(),tb=la(),ub=la(),vb=function(a,b){return a.x===b.x&&a.y===b.y},wb=function(a,b){return Math.abs(a.x-b.x)<g&&Math.abs(a.y-b.y)<g},xb=function(a,b){return ob.x=Math.abs(a.x-b.x),ob.y=Math.abs(a.y-b.y),Math.sqrt(ob.x*ob.x+ob.y*ob.y)},yb=function(){Y&&(I(Y),Y=null)},zb=function(){U&&(Y=H(zb),Pb())},Ab=function(){return!("fit"===i.scaleMode&&s===f.currItem.initialZoomLevel)},Bb=function(a,b){return a&&a!==document?a.getAttribute("class")&&a.getAttribute("class").indexOf("pswp__scroll-wrap")>-1?!1:b(a)?a:Bb(a.parentNode,b):!1},Cb={},Db=function(a,b){return Cb.prevent=!Bb(a.target,i.isClickableElement),Ca("preventDragEvent",a,b,Cb),Cb.prevent},Eb=function(a,b){return b.x=a.pageX,b.y=a.pageY,b.id=a.identifier,b},Fb=function(a,b,c){c.x=.5*(a.x+b.x),c.y=.5*(a.y+b.y)},Gb=function(a,b,c){if(a-P>50){var d=nb.length>2?nb.shift():{};d.x=b,d.y=c,nb.push(d),P=a}},Hb=function(){var a=oa.y-f.currItem.initialPosition.y;return 1-Math.abs(a/(pa.y/2))},Ib={},Jb={},Kb=[],Lb=function(a){for(;Kb.length>0;)Kb.pop();return F?(ka=0,lb.forEach(function(a){0===ka?Kb[0]=a:1===ka&&(Kb[1]=a),ka++})):a.type.indexOf("touch")>-1?a.touches&&a.touches.length>0&&(Kb[0]=Eb(a.touches[0],Ib),a.touches.length>1&&(Kb[1]=Eb(a.touches[1],Jb))):(Ib.x=a.pageX,Ib.y=a.pageY,Ib.id="",Kb[0]=Ib),Kb},Mb=function(a,b){var c,d,e,g,h=0,j=oa[a]+b[a],k=b[a]>0,l=sb.x+b.x,m=sb.x-mb.x;return c=j>ca.min[a]||j<ca.max[a]?i.panEndFriction:1,j=oa[a]+b[a]*c,!i.allowPanToNext&&s!==f.currItem.initialZoomLevel||(da?"h"!==fa||"x"!==a||W||(k?(j>ca.min[a]&&(c=i.panEndFriction,h=ca.min[a]-j,d=ca.min[a]-na[a]),(0>=d||0>m)&&_b()>1?(g=l,0>m&&l>mb.x&&(g=mb.x)):ca.min.x!==ca.max.x&&(e=j)):(j<ca.max[a]&&(c=i.panEndFriction,h=j-ca.max[a],d=na[a]-ca.max[a]),(0>=d||m>0)&&_b()>1?(g=l,m>0&&l<mb.x&&(g=mb.x)):ca.min.x!==ca.max.x&&(e=j))):g=l,"x"!==a)?void(ea||Z||s>f.currItem.fitRatio&&(oa[a]+=b[a]*c)):(void 0!==g&&(Ja(g,!0),Z=g===mb.x?!1:!0),ca.min.x!==ca.max.x&&(void 0!==e?oa.x=e:Z||(oa.x+=b.x*c)),void 0!==g)},Nb=function(a){if(!("mousedown"===a.type&&a.button>0)){if(Zb)return void a.preventDefault();if(!T||"mousedown"!==a.type){if(Db(a,!0)&&a.preventDefault(),Ca("pointerDown"),F){var b=e.arraySearch(lb,a.pointerId,"id");0>b&&(b=lb.length),lb[b]={x:a.pageX,y:a.pageY,id:a.pointerId}}var c=Lb(a),d=c.length;$=null,bb(),U&&1!==d||(U=ga=!0,e.bind(window,p,f),R=ja=ha=S=Z=X=V=W=!1,fa=null,Ca("firstTouchStart",c),La(na,oa),ma.x=ma.y=0,La(jb,c[0]),La(kb,jb),mb.x=sa.x*qa,nb=[{x:jb.x,y:jb.y}],P=O=Da(),Ra(s,!0),yb(),zb()),!_&&d>1&&!ea&&!Z&&(t=s,W=!1,_=V=!0,ma.y=ma.x=0,La(na,oa),La(gb,c[0]),La(hb,c[1]),Fb(gb,hb,ub),tb.x=Math.abs(ub.x)-oa.x,tb.y=Math.abs(ub.y)-oa.y,aa=ba=xb(gb,hb))}}},Ob=function(a){if(a.preventDefault(),F){var b=e.arraySearch(lb,a.pointerId,"id");if(b>-1){var c=lb[b];c.x=a.pageX,c.y=a.pageY}}if(U){var d=Lb(a);if(fa||X||_)$=d;else if(sb.x!==sa.x*qa)fa="h";else{var f=Math.abs(d[0].x-jb.x)-Math.abs(d[0].y-jb.y);Math.abs(f)>=fb&&(fa=f>0?"h":"v",$=d)}}},Pb=function(){if($){var a=$.length;if(0!==a)if(La(gb,$[0]),ib.x=gb.x-jb.x,ib.y=gb.y-jb.y,_&&a>1){if(jb.x=gb.x,jb.y=gb.y,!ib.x&&!ib.y&&vb($[1],hb))return;La(hb,$[1]),W||(W=!0,Ca("zoomGestureStarted"));var b=xb(gb,hb),c=Ub(b);c>f.currItem.initialZoomLevel+f.currItem.initialZoomLevel/15&&(ja=!0);var d=1,e=Sa(),g=Ta();if(e>c)if(i.pinchToClose&&!ja&&t<=f.currItem.initialZoomLevel){var h=e-c,j=1-h/(e/1.2);Ea(j),Ca("onPinchClose",j),ha=!0}else d=(e-c)/e,d>1&&(d=1),c=e-d*(e/3);else c>g&&(d=(c-g)/(6*e),d>1&&(d=1),c=g+d*e);0>d&&(d=0),aa=b,Fb(gb,hb,qb),ma.x+=qb.x-ub.x,ma.y+=qb.y-ub.y,La(ub,qb),oa.x=Ka("x",c),oa.y=Ka("y",c),R=c>s,s=c,Ga()}else{if(!fa)return;if(ga&&(ga=!1,Math.abs(ib.x)>=fb&&(ib.x-=$[0].x-kb.x),Math.abs(ib.y)>=fb&&(ib.y-=$[0].y-kb.y)),jb.x=gb.x,jb.y=gb.y,0===ib.x&&0===ib.y)return;if("v"===fa&&i.closeOnVerticalDrag&&!Ab()){ma.y+=ib.y,oa.y+=ib.y;var k=Hb();return S=!0,Ca("onVerticalDrag",k),Ea(k),void Ga()}Gb(Da(),gb.x,gb.y),X=!0,ca=f.currItem.bounds;var l=Mb("x",ib);l||(Mb("y",ib),Ma(oa),Ga())}}},Qb=function(a){if(N.isOldAndroid){if(T&&"mouseup"===a.type)return;a.type.indexOf("touch")>-1&&(clearTimeout(T),T=setTimeout(function(){T=0},600))}Ca("pointerUp"),Db(a,!1)&&a.preventDefault();var b;if(F){var c=e.arraySearch(lb,a.pointerId,"id");if(c>-1)if(b=lb.splice(c,1)[0],navigator.pointerEnabled)b.type=a.pointerType||"mouse";else{var d={4:"mouse",2:"touch",3:"pen"};b.type=d[a.pointerType],b.type||(b.type=a.pointerType||"mouse")}}var g,h=Lb(a),j=h.length;if("mouseup"===a.type&&(j=0),2===j)return $=null,!0;1===j&&La(kb,h[0]),0!==j||fa||ea||(b||("mouseup"===a.type?b={x:a.pageX,y:a.pageY,type:"mouse"}:a.changedTouches&&a.changedTouches[0]&&(b={x:a.changedTouches[0].pageX,y:a.changedTouches[0].pageY,type:"touch"})),Ca("touchRelease",a,b));var k=-1;if(0===j&&(U=!1,e.unbind(window,p,f),yb(),_?k=0:-1!==rb&&(k=Da()-rb)),rb=1===j?Da():-1,g=-1!==k&&150>k?"zoom":"swipe",_&&2>j&&(_=!1,1===j&&(g="zoomPointerUp"),Ca("zoomGestureEnded")),$=null,X||W||ea||S)if(bb(),Q||(Q=Rb()),Q.calculateSwipeSpeed("x"),S){var l=Hb();if(l<i.verticalDragRange)f.close();else{var m=oa.y,n=ia;cb("verticalDrag",0,1,300,e.easing.cubic.out,function(a){oa.y=(f.currItem.initialPosition.y-m)*a+m,Ea((1-n)*a+n),Ga()}),Ca("onVerticalDrag",1)}}else{if((Z||ea)&&0===j){var o=Tb(g,Q);if(o)return;g="zoomPointerUp"}if(!ea)return"swipe"!==g?void Vb():void(!Z&&s>f.currItem.fitRatio&&Sb(Q))}},Rb=function(){var a,b,c={lastFlickOffset:{},lastFlickDist:{},lastFlickSpeed:{},slowDownRatio:{},slowDownRatioReverse:{},speedDecelerationRatio:{},speedDecelerationRatioAbs:{},distanceOffset:{},backAnimDestination:{},backAnimStarted:{},calculateSwipeSpeed:function(d){nb.length>1?(a=Da()-P+50,b=nb[nb.length-2][d]):(a=Da()-O,b=kb[d]),c.lastFlickOffset[d]=jb[d]-b,c.lastFlickDist[d]=Math.abs(c.lastFlickOffset[d]),c.lastFlickDist[d]>20?c.lastFlickSpeed[d]=c.lastFlickOffset[d]/a:c.lastFlickSpeed[d]=0,Math.abs(c.lastFlickSpeed[d])<.1&&(c.lastFlickSpeed[d]=0),c.slowDownRatio[d]=.95,c.slowDownRatioReverse[d]=1-c.slowDownRatio[d],c.speedDecelerationRatio[d]=1},calculateOverBoundsAnimOffset:function(a,b){c.backAnimStarted[a]||(oa[a]>ca.min[a]?c.backAnimDestination[a]=ca.min[a]:oa[a]<ca.max[a]&&(c.backAnimDestination[a]=ca.max[a]),void 0!==c.backAnimDestination[a]&&(c.slowDownRatio[a]=.7,c.slowDownRatioReverse[a]=1-c.slowDownRatio[a],c.speedDecelerationRatioAbs[a]<.05&&(c.lastFlickSpeed[a]=0,c.backAnimStarted[a]=!0,cb("bounceZoomPan"+a,oa[a],c.backAnimDestination[a],b||300,e.easing.sine.out,function(b){oa[a]=b,Ga()}))))},calculateAnimOffset:function(a){c.backAnimStarted[a]||(c.speedDecelerationRatio[a]=c.speedDecelerationRatio[a]*(c.slowDownRatio[a]+c.slowDownRatioReverse[a]-c.slowDownRatioReverse[a]*c.timeDiff/10),c.speedDecelerationRatioAbs[a]=Math.abs(c.lastFlickSpeed[a]*c.speedDecelerationRatio[a]),c.distanceOffset[a]=c.lastFlickSpeed[a]*c.speedDecelerationRatio[a]*c.timeDiff,oa[a]+=c.distanceOffset[a])},panAnimLoop:function(){return Za.zoomPan&&(Za.zoomPan.raf=H(c.panAnimLoop),c.now=Da(),c.timeDiff=c.now-c.lastNow,c.lastNow=c.now,c.calculateAnimOffset("x"),c.calculateAnimOffset("y"),Ga(),c.calculateOverBoundsAnimOffset("x"),c.calculateOverBoundsAnimOffset("y"),c.speedDecelerationRatioAbs.x<.05&&c.speedDecelerationRatioAbs.y<.05)?(oa.x=Math.round(oa.x),oa.y=Math.round(oa.y),Ga(),void _a("zoomPan")):void 0}};return c},Sb=function(a){return a.calculateSwipeSpeed("y"),ca=f.currItem.bounds,a.backAnimDestination={},a.backAnimStarted={},Math.abs(a.lastFlickSpeed.x)<=.05&&Math.abs(a.lastFlickSpeed.y)<=.05?(a.speedDecelerationRatioAbs.x=a.speedDecelerationRatioAbs.y=0,a.calculateOverBoundsAnimOffset("x"),a.calculateOverBoundsAnimOffset("y"),!0):(ab("zoomPan"),a.lastNow=Da(),void a.panAnimLoop())},Tb=function(a,b){var c;ea||(pb=m);var d;if("swipe"===a){var g=jb.x-kb.x,h=b.lastFlickDist.x<10;g>eb&&(h||b.lastFlickOffset.x>20)?d=-1:-eb>g&&(h||b.lastFlickOffset.x<-20)&&(d=1)}var j;d&&(m+=d,0>m?(m=i.loop?_b()-1:0,j=!0):m>=_b()&&(m=i.loop?0:_b()-1,j=!0),(!j||i.loop)&&(ta+=d,qa-=d,c=!0));var k,l=sa.x*qa,n=Math.abs(l-sb.x);return c||l>sb.x==b.lastFlickSpeed.x>0?(k=Math.abs(b.lastFlickSpeed.x)>0?n/Math.abs(b.lastFlickSpeed.x):333,k=Math.min(k,400),k=Math.max(k,250)):k=333,pb===m&&(c=!1),ea=!0,Ca("mainScrollAnimStart"),cb("mainScroll",sb.x,l,k,e.easing.cubic.out,Ja,function(){bb(),ea=!1,pb=-1,(c||pb!==m)&&f.updateCurrItem(),Ca("mainScrollAnimComplete")}),c&&f.updateCurrItem(!0),c},Ub=function(a){return 1/ba*a*t},Vb=function(){var a=s,b=Sa(),c=Ta();b>s?a=b:s>c&&(a=c);var d,g=1,h=ia;return ha&&!R&&!ja&&b>s?(f.close(),!0):(ha&&(d=function(a){Ea((g-h)*a+h)}),f.zoomTo(a,0,200,e.easing.cubic.out,d),!0)};ya("Gestures",{publicMethods:{initGestures:function(){var a=function(a,b,c,d,e){A=a+b,B=a+c,C=a+d,D=e?a+e:""};F=N.pointerEvent,F&&N.touch&&(N.touch=!1),F?navigator.pointerEnabled?a("pointer","down","move","up","cancel"):a("MSPointer","Down","Move","Up","Cancel"):N.touch?(a("touch","start","move","end","cancel"),G=!0):a("mouse","down","move","up"),p=B+" "+C+" "+D,q=A,F&&!G&&(G=navigator.maxTouchPoints>1||navigator.msMaxTouchPoints>1),f.likelyTouchDevice=G,r[A]=Nb,r[B]=Ob,r[C]=Qb,D&&(r[D]=r[C]),N.touch&&(q+=" mousedown",p+=" mousemove mouseup",r.mousedown=r[A],r.mousemove=r[B],r.mouseup=r[C]),G||(i.allowPanToNext=!1)}}});var Wb,Xb,Yb,Zb,$b,_b,ac,bc=function(b,c,d,g){Wb&&clearTimeout(Wb),Zb=!0,Yb=!0;var h;b.initialLayout?(h=b.initialLayout,b.initialLayout=null):h=i.getThumbBoundsFn&&i.getThumbBoundsFn(m);var j=d?i.hideAnimationDuration:i.showAnimationDuration,k=function(){_a("initialZoom"),d?(f.template.removeAttribute("style"),f.bg.removeAttribute("style")):(Ea(1),c&&(c.style.display="block"),e.addClass(a,"pswp--animated-in"),Ca("initialZoom"+(d?"OutEnd":"InEnd"))),g&&g(),Zb=!1};if(!j||!h||void 0===h.x)return Ca("initialZoom"+(d?"Out":"In")),s=b.initialZoomLevel,La(oa,b.initialPosition),Ga(),a.style.opacity=d?0:1,Ea(1),void(j?setTimeout(function(){k()},j):k());var n=function(){var c=l,g=!f.currItem.src||f.currItem.loadError||i.showHideOpacity;b.miniImg&&(b.miniImg.style.webkitBackfaceVisibility="hidden"),d||(s=h.w/b.w,oa.x=h.x,oa.y=h.y-K,f[g?"template":"bg"].style.opacity=.001,Ga()),ab("initialZoom"),d&&!c&&e.removeClass(a,"pswp--animated-in"),g&&(d?e[(c?"remove":"add")+"Class"](a,"pswp--animate_opacity"):setTimeout(function(){e.addClass(a,"pswp--animate_opacity")},30)),Wb=setTimeout(function(){if(Ca("initialZoom"+(d?"Out":"In")),d){var f=h.w/b.w,i={x:oa.x,y:oa.y},l=s,m=ia,n=function(b){1===b?(s=f,oa.x=h.x,oa.y=h.y-M):(s=(f-l)*b+l,oa.x=(h.x-i.x)*b+i.x,oa.y=(h.y-M-i.y)*b+i.y),Ga(),g?a.style.opacity=1-b:Ea(m-b*m)};c?cb("initialZoom",0,1,j,e.easing.cubic.out,n,k):(n(1),Wb=setTimeout(k,j+20))}else s=b.initialZoomLevel,La(oa,b.initialPosition),Ga(),Ea(1),g?a.style.opacity=1:Ea(1),Wb=setTimeout(k,j+20)},d?25:90)};n()},cc={},dc=[],ec={index:0,errorMsg:'<div class="pswp__error-msg"><a href="%url%" target="_blank">The image</a> could not be loaded.</div>',forceProgressiveLoading:!1,preload:[1,1],getNumItemsFn:function(){return Xb.length}},fc=function(){return{center:{x:0,y:0},max:{x:0,y:0},min:{x:0,y:0}}},gc=function(a,b,c){var d=a.bounds;d.center.x=Math.round((cc.x-b)/2),d.center.y=Math.round((cc.y-c)/2)+a.vGap.top,d.max.x=b>cc.x?Math.round(cc.x-b):d.center.x,d.max.y=c>cc.y?Math.round(cc.y-c)+a.vGap.top:d.center.y,d.min.x=b>cc.x?0:d.center.x,d.min.y=c>cc.y?a.vGap.top:d.center.y},hc=function(a,b,c){if(a.src&&!a.loadError){var d=!c;if(d&&(a.vGap||(a.vGap={top:0,bottom:0}),Ca("parseVerticalMargin",a)),cc.x=b.x,cc.y=b.y-a.vGap.top-a.vGap.bottom,d){var e=cc.x/a.w,f=cc.y/a.h;a.fitRatio=f>e?e:f;var g=i.scaleMode;"orig"===g?c=1:"fit"===g&&(c=a.fitRatio),c>1&&(c=1),a.initialZoomLevel=c,a.bounds||(a.bounds=fc())}if(!c)return;return gc(a,a.w*c,a.h*c),d&&c===a.initialZoomLevel&&(a.initialPosition=a.bounds.center),a.bounds}return a.w=a.h=0,a.initialZoomLevel=a.fitRatio=1,a.bounds=fc(),a.initialPosition=a.bounds.center,a.bounds},ic=function(a,b,c,d,e,g){b.loadError||d&&(b.imageAppended=!0,lc(b,d,b===f.currItem&&xa),c.appendChild(d),g&&setTimeout(function(){b&&b.loaded&&b.placeholder&&(b.placeholder.style.display="none",b.placeholder=null)},500))},jc=function(a){a.loading=!0,a.loaded=!1;var b=a.img=e.createEl("pswp__img","img"),c=function(){a.loading=!1,a.loaded=!0,a.loadComplete?a.loadComplete(a):a.img=null,b.onload=b.onerror=null,b=null};return b.onload=c,b.onerror=function(){a.loadError=!0,c()},b.src=a.src,b},kc=function(a,b){return a.src&&a.loadError&&a.container?(b&&(a.container.innerHTML=""),a.container.innerHTML=i.errorMsg.replace("%url%",a.src),!0):void 0},lc=function(a,b,c){if(a.src){b||(b=a.container.lastChild);var d=c?a.w:Math.round(a.w*a.fitRatio),e=c?a.h:Math.round(a.h*a.fitRatio);a.placeholder&&!a.loaded&&(a.placeholder.style.width=d+"px",a.placeholder.style.height=e+"px"),b.style.width=d+"px",b.style.height=e+"px"}},mc=function(){if(dc.length){for(var a,b=0;b<dc.length;b++)a=dc[b],a.holder.index===a.index&&ic(a.index,a.item,a.baseDiv,a.img,!1,a.clearPlaceholder);dc=[]}};ya("Controller",{publicMethods:{lazyLoadItem:function(a){a=za(a);var b=$b(a);b&&(!b.loaded&&!b.loading||x)&&(Ca("gettingData",a,b),b.src&&jc(b))},initController:function(){e.extend(i,ec,!0),f.items=Xb=c,$b=f.getItemAt,_b=i.getNumItemsFn,ac=i.loop,_b()<3&&(i.loop=!1),Ba("beforeChange",function(a){var b,c=i.preload,d=null===a?!0:a>=0,e=Math.min(c[0],_b()),g=Math.min(c[1],_b());for(b=1;(d?g:e)>=b;b++)f.lazyLoadItem(m+b);for(b=1;(d?e:g)>=b;b++)f.lazyLoadItem(m-b)}),Ba("initialLayout",function(){f.currItem.initialLayout=i.getThumbBoundsFn&&i.getThumbBoundsFn(m)}),Ba("mainScrollAnimComplete",mc),Ba("initialZoomInEnd",mc),Ba("destroy",function(){for(var a,b=0;b<Xb.length;b++)a=Xb[b],a.container&&(a.container=null),a.placeholder&&(a.placeholder=null),a.img&&(a.img=null),a.preloader&&(a.preloader=null),a.loadError&&(a.loaded=a.loadError=!1);dc=null})},getItemAt:function(a){return a>=0&&void 0!==Xb[a]?Xb[a]:!1},allowProgressiveImg:function(){return i.forceProgressiveLoading||!G||i.mouseUsed||screen.width>1200},setContent:function(a,b){i.loop&&(b=za(b));var c=f.getItemAt(a.index);c&&(c.container=null);var d,g=f.getItemAt(b);if(!g)return void(a.el.innerHTML="");Ca("gettingData",b,g),a.index=b,a.item=g;var h=g.container=e.createEl("pswp__zoom-wrap");if(!g.src&&g.html&&(g.html.tagName?h.appendChild(g.html):h.innerHTML=g.html),kc(g),hc(g,pa),!g.src||g.loadError||g.loaded)g.src&&!g.loadError&&(d=e.createEl("pswp__img","img"),d.style.opacity=1,d.src=g.src,lc(g,d),ic(b,g,h,d,!0));else{if(g.loadComplete=function(c){if(j){if(a&&a.index===b){if(kc(c,!0))return c.loadComplete=c.img=null,hc(c,pa),Ha(c),void(a.index===m&&f.updateCurrZoomItem());c.imageAppended?!Zb&&c.placeholder&&(c.placeholder.style.display="none",c.placeholder=null):N.transform&&(ea||Zb)?dc.push({item:c,baseDiv:h,img:c.img,index:b,holder:a,clearPlaceholder:!0}):ic(b,c,h,c.img,ea||Zb,!0)}c.loadComplete=null,c.img=null,Ca("imageLoadComplete",b,c)}},e.features.transform){var k="pswp__img pswp__img--placeholder";k+=g.msrc?"":" pswp__img--placeholder--blank";var l=e.createEl(k,g.msrc?"img":"");g.msrc&&(l.src=g.msrc),lc(g,l),h.appendChild(l),g.placeholder=l}g.loading||jc(g),f.allowProgressiveImg()&&(!Yb&&N.transform?dc.push({item:g,baseDiv:h,img:g.img,index:b,holder:a}):ic(b,g,h,g.img,!0,!0))}Yb||b!==m?Ha(g):(da=h.style,bc(g,d||g.img)),a.el.innerHTML="",a.el.appendChild(h)},cleanSlide:function(a){a.img&&(a.img.onload=a.img.onerror=null),a.loaded=a.loading=a.img=a.imageAppended=!1}}});var nc,oc={},pc=function(a,b,c){var d=document.createEvent("CustomEvent"),e={origEvent:a,target:a.target,releasePoint:b,pointerType:c||"touch"};d.initCustomEvent("pswpTap",!0,!0,e),a.target.dispatchEvent(d)};ya("Tap",{publicMethods:{initTap:function(){Ba("firstTouchStart",f.onTapStart),Ba("touchRelease",f.onTapRelease),Ba("destroy",function(){oc={},nc=null})},onTapStart:function(a){a.length>1&&(clearTimeout(nc),nc=null)},onTapRelease:function(a,b){if(b&&!X&&!V&&!$a){var c=b;if(nc&&(clearTimeout(nc),nc=null,wb(c,oc)))return void Ca("doubleTap",c);if("mouse"===b.type)return void pc(a,b,"mouse");var d=a.target.tagName.toUpperCase();if("BUTTON"===d||e.hasClass(a.target,"pswp__single-tap"))return void pc(a,b);La(oc,c),nc=setTimeout(function(){pc(a,b),nc=null},300)}}}});var qc;ya("DesktopZoom",{publicMethods:{initDesktopZoom:function(){L||(G?Ba("mouseUsed",function(){f.setupDesktopZoom()}):f.setupDesktopZoom(!0))},setupDesktopZoom:function(b){qc={};var c="wheel mousewheel DOMMouseScroll";Ba("bindEvents",function(){e.bind(a,c,f.handleMouseWheel)}),Ba("unbindEvents",function(){qc&&e.unbind(a,c,f.handleMouseWheel)}),f.mouseZoomedIn=!1;var d,g=function(){f.mouseZoomedIn&&(e.removeClass(a,"pswp--zoomed-in"),f.mouseZoomedIn=!1),1>s?e.addClass(a,"pswp--zoom-allowed"):e.removeClass(a,"pswp--zoom-allowed"),h()},h=function(){d&&(e.removeClass(a,"pswp--dragging"),d=!1)};Ba("resize",g),Ba("afterChange",g),Ba("pointerDown",function(){f.mouseZoomedIn&&(d=!0,e.addClass(a,"pswp--dragging"))}),Ba("pointerUp",h),b||g()},handleMouseWheel:function(a){if(s<=f.currItem.fitRatio)return i.modal&&(!i.closeOnScroll||$a||U?a.preventDefault():E&&Math.abs(a.deltaY)>2&&(l=!0,f.close())),!0;if(a.stopPropagation(),qc.x=0,"deltaX"in a)1===a.deltaMode?(qc.x=18*a.deltaX,qc.y=18*a.deltaY):(qc.x=a.deltaX,qc.y=a.deltaY);else if("wheelDelta"in a)a.wheelDeltaX&&(qc.x=-.16*a.wheelDeltaX),a.wheelDeltaY?qc.y=-.16*a.wheelDeltaY:qc.y=-.16*a.wheelDelta;else{if(!("detail"in a))return;qc.y=a.detail}Ra(s,!0);var b=oa.x-qc.x,c=oa.y-qc.y;(i.modal||b<=ca.min.x&&b>=ca.max.x&&c<=ca.min.y&&c>=ca.max.y)&&a.preventDefault(),f.panTo(b,c)},toggleDesktopZoom:function(b){b=b||{x:pa.x/2+ra.x,y:pa.y/2+ra.y};var c=i.getDoubleTapZoom(!0,f.currItem),d=s===c;f.mouseZoomedIn=!d,f.zoomTo(d?f.currItem.initialZoomLevel:c,b,333),e[(d?"remove":"add")+"Class"](a,"pswp--zoomed-in")}}});var rc,sc,tc,uc,vc,wc,xc,yc,zc,Ac,Bc,Cc,Dc={history:!0,galleryUID:1},Ec=function(){return Bc.hash.substring(1)},Fc=function(){rc&&clearTimeout(rc),tc&&clearTimeout(tc)},Gc=function(){var a=Ec(),b={};if(a.length<5)return b;var c,d=a.split("&");for(c=0;c<d.length;c++)if(d[c]){var e=d[c].split("=");e.length<2||(b[e[0]]=e[1])}if(i.galleryPIDs){var f=b.pid;for(b.pid=0,c=0;c<Xb.length;c++)if(Xb[c].pid===f){b.pid=c;break}}else b.pid=parseInt(b.pid,10)-1;return b.pid<0&&(b.pid=0),b},Hc=function(){if(tc&&clearTimeout(tc),$a||U)return void(tc=setTimeout(Hc,500));uc?clearTimeout(sc):uc=!0;var a=m+1,b=$b(m);b.hasOwnProperty("pid")&&(a=b.pid);var c=xc+"&gid="+i.galleryUID+"&pid="+a;yc||-1===Bc.hash.indexOf(c)&&(Ac=!0);var d=Bc.href.split("#")[0]+"#"+c;Cc?"#"+c!==window.location.hash&&history[yc?"replaceState":"pushState"]("",document.title,d):yc?Bc.replace(d):Bc.hash=c,yc=!0,sc=setTimeout(function(){uc=!1},60)};ya("History",{publicMethods:{initHistory:function(){if(e.extend(i,Dc,!0),i.history){Bc=window.location,Ac=!1,zc=!1,yc=!1,xc=Ec(),Cc="pushState"in history,xc.indexOf("gid=")>-1&&(xc=xc.split("&gid=")[0],xc=xc.split("?gid=")[0]),Ba("afterChange",f.updateURL),Ba("unbindEvents",function(){e.unbind(window,"hashchange",f.onHashChange)});var a=function(){wc=!0,zc||(Ac?history.back():xc?Bc.hash=xc:Cc?history.pushState("",document.title,Bc.pathname+Bc.search):Bc.hash=""),Fc()};Ba("unbindEvents",function(){l&&a()}),Ba("destroy",function(){wc||a()}),Ba("firstUpdate",function(){m=Gc().pid});var b=xc.indexOf("pid=");b>-1&&(xc=xc.substring(0,b),"&"===xc.slice(-1)&&(xc=xc.slice(0,-1))),setTimeout(function(){j&&e.bind(window,"hashchange",f.onHashChange)},40)}},onHashChange:function(){return Ec()===xc?(zc=!0,void f.close()):void(uc||(vc=!0,f.goTo(Gc().pid),vc=!1))},updateURL:function(){Fc(),vc||(yc?rc=setTimeout(Hc,800):Hc())}}}),e.extend(f,db)};return a});;
/* Placeholders.js v3.0.2 */
(function(t){"use strict";function e(t,e,r){return t.addEventListener?t.addEventListener(e,r,!1):t.attachEvent?t.attachEvent("on"+e,r):void 0}function r(t,e){var r,n;for(r=0,n=t.length;n>r;r++)if(t[r]===e)return!0;return!1}function n(t,e){var r;t.createTextRange?(r=t.createTextRange(),r.move("character",e),r.select()):t.selectionStart&&(t.focus(),t.setSelectionRange(e,e))}function a(t,e){try{return t.type=e,!0}catch(r){return!1}}t.Placeholders={Utils:{addEventListener:e,inArray:r,moveCaret:n,changeType:a}}})(this),function(t){"use strict";function e(){}function r(){try{return document.activeElement}catch(t){}}function n(t,e){var r,n,a=!!e&&t.value!==e,u=t.value===t.getAttribute(V);return(a||u)&&"true"===t.getAttribute(P)?(t.removeAttribute(P),t.value=t.value.replace(t.getAttribute(V),""),t.className=t.className.replace(R,""),n=t.getAttribute(z),parseInt(n,10)>=0&&(t.setAttribute("maxLength",n),t.removeAttribute(z)),r=t.getAttribute(D),r&&(t.type=r),!0):!1}function a(t){var e,r,n=t.getAttribute(V);return""===t.value&&n?(t.setAttribute(P,"true"),t.value=n,t.className+=" "+I,r=t.getAttribute(z),r||(t.setAttribute(z,t.maxLength),t.removeAttribute("maxLength")),e=t.getAttribute(D),e?t.type="text":"password"===t.type&&K.changeType(t,"text")&&t.setAttribute(D,"password"),!0):!1}function u(t,e){var r,n,a,u,i,l,o;if(t&&t.getAttribute(V))e(t);else for(a=t?t.getElementsByTagName("input"):f,u=t?t.getElementsByTagName("textarea"):h,r=a?a.length:0,n=u?u.length:0,o=0,l=r+n;l>o;o++)i=r>o?a[o]:u[o-r],e(i)}function i(t){u(t,n)}function l(t){u(t,a)}function o(t){return function(){b&&t.value===t.getAttribute(V)&&"true"===t.getAttribute(P)?K.moveCaret(t,0):n(t)}}function c(t){return function(){a(t)}}function s(t){return function(e){return A=t.value,"true"===t.getAttribute(P)&&A===t.getAttribute(V)&&K.inArray(C,e.keyCode)?(e.preventDefault&&e.preventDefault(),!1):void 0}}function d(t){return function(){n(t,A),""===t.value&&(t.blur(),K.moveCaret(t,0))}}function v(t){return function(){t===r()&&t.value===t.getAttribute(V)&&"true"===t.getAttribute(P)&&K.moveCaret(t,0)}}function g(t){return function(){i(t)}}function p(t){t.form&&(T=t.form,"string"==typeof T&&(T=document.getElementById(T)),T.getAttribute(U)||(K.addEventListener(T,"submit",g(T)),T.setAttribute(U,"true"))),K.addEventListener(t,"focus",o(t)),K.addEventListener(t,"blur",c(t)),b&&(K.addEventListener(t,"keydown",s(t)),K.addEventListener(t,"keyup",d(t)),K.addEventListener(t,"click",v(t))),t.setAttribute(j,"true"),t.setAttribute(V,x),(b||t!==r())&&a(t)}var f,h,b,m,A,y,E,x,L,T,S,N,w,B=["text","search","url","tel","email","password","number","textarea"],C=[27,33,34,35,36,37,38,39,40,8,46],k="#ccc",I="placeholdersjs",R=RegExp("(?:^|\\s)"+I+"(?!\\S)"),V="data-placeholder-value",P="data-placeholder-active",D="data-placeholder-type",U="data-placeholder-submit",j="data-placeholder-bound",q="data-placeholder-focus",Q="data-placeholder-live",z="data-placeholder-maxlength",F=document.createElement("input"),G=document.getElementsByTagName("head")[0],H=document.documentElement,J=t.Placeholders,K=J.Utils;if(J.nativeSupport=void 0!==F.placeholder,!J.nativeSupport){for(f=document.getElementsByTagName("input"),h=document.getElementsByTagName("textarea"),b="false"===H.getAttribute(q),m="false"!==H.getAttribute(Q),y=document.createElement("style"),y.type="text/css",E=document.createTextNode("."+I+" { color:"+k+"; }"),y.styleSheet?y.styleSheet.cssText=E.nodeValue:y.appendChild(E),G.insertBefore(y,G.firstChild),w=0,N=f.length+h.length;N>w;w++)S=f.length>w?f[w]:h[w-f.length],x=S.attributes.placeholder,x&&(x=x.nodeValue,x&&K.inArray(B,S.type)&&p(S));L=setInterval(function(){for(w=0,N=f.length+h.length;N>w;w++)S=f.length>w?f[w]:h[w-f.length],x=S.attributes.placeholder,x?(x=x.nodeValue,x&&K.inArray(B,S.type)&&(S.getAttribute(j)||p(S),(x!==S.getAttribute(V)||"password"===S.type&&!S.getAttribute(D))&&("password"===S.type&&!S.getAttribute(D)&&K.changeType(S,"text")&&S.setAttribute(D,"password"),S.value===S.getAttribute(V)&&(S.value=x),S.setAttribute(V,x)))):S.getAttribute(P)&&(n(S),S.removeAttribute(V));m||clearInterval(L)},100)}K.addEventListener(t,"beforeunload",function(){J.disable()}),J.disable=J.nativeSupport?e:i,J.enable=J.nativeSupport?e:l}(this),function(t){"use strict";var e=t.fn.val,r=t.fn.prop;Placeholders.nativeSupport||(t.fn.val=function(t){var r=e.apply(this,arguments),n=this.eq(0).data("placeholder-value");return void 0===t&&this.eq(0).data("placeholder-active")&&r===n?"":r},t.fn.prop=function(t,e){return void 0===e&&this.eq(0).data("placeholder-active")&&"value"===t?"":r.apply(this,arguments)})}(jQuery);;
/**
 * @preserve
 * Project: Bootstrap Hover Dropdown
 * Author: Cameron Spear
 * Version: v2.2.1
 * Contributors: Mattia Larentis
 * Dependencies: Bootstrap's Dropdown plugin, jQuery
 * Description: A simple plugin to enable Bootstrap dropdowns to active on hover and provide a nice user experience.
 * License: MIT
 * Homepage: http://cameronspear.com/blog/bootstrap-dropdown-on-hover-plugin/
 */
;(function ($, window, undefined) {
    // outside the scope of the jQuery plugin to
    // keep track of all dropdowns
    var $allDropdowns = $();

    // if instantlyCloseOthers is true, then it will instantly
    // shut other nav items when a new one is hovered over
    $.fn.dropdownHover = function (options) {
        // don't do anything if touch is supported
        // (plugin causes some issues on mobile)
        if('ontouchstart' in document) return this; // don't want to affect chaining

        // the element we really care about
        // is the dropdown-toggle's parent
        $allDropdowns = $allDropdowns.add(this.parent());

        return this.each(function () {
            var $this = $(this),
                $parent = $this.parent(),
                defaults = {
                    delay: 500,
                    hoverDelay: 0,
                    instantlyCloseOthers: true
                },
                data = {
                    delay: $(this).data('delay'),
                    hoverDelay: $(this).data('hover-delay'),
                    instantlyCloseOthers: $(this).data('close-others')
                },
                showEvent   = 'show.bs.dropdown',
                hideEvent   = 'hide.bs.dropdown',
                // shownEvent  = 'shown.bs.dropdown',
                // hiddenEvent = 'hidden.bs.dropdown',
                settings = $.extend(true, {}, defaults, options, data),
                timeout, timeoutHover;

            $parent.hover(function (event) {
                // so a neighbor can't open the dropdown
                if(!$parent.hasClass('open') && !$this.is(event.target)) {
                    // stop this event, stop executing any code
                    // in this callback but continue to propagate
                    return true;
                }

                openDropdown(event);
            }, function () {
                // clear timer for hover event
                window.clearTimeout(timeoutHover)
                timeout = window.setTimeout(function () {
                    $this.attr('aria-expanded', 'false');
                    $parent.removeClass('open');
                    $this.trigger(hideEvent);
                }, settings.delay);
            });

            // this helps with button groups!
            $this.hover(function (event) {
                // this helps prevent a double event from firing.
                // see https://github.com/CWSpear/bootstrap-hover-dropdown/issues/55
                if($parent.hasClass('open') && !$parent.is(event.target)) {
                    // stop this event, stop executing any code
                    // in this callback but continue to propagate
                    return true;
                }

                openDropdown(event);
            });

            // handle submenus
            $parent.find('.dropdown-submenu').each(function (){
                var $this = $(this);
                var subTimeout;
                $this.hover(function () {
                    window.clearTimeout(subTimeout);
                    $this.children('.dropdown-menu').show();
                    // always close submenu siblings instantly
                    $this.siblings().children('.dropdown-menu').hide();
                }, function () {
                    var $submenu = $this.children('.dropdown-menu');
                    subTimeout = window.setTimeout(function () {
                        $submenu.hide();
                    }, settings.delay);
                });
            });

            function openDropdown(event) {
                if($this.parents(".navbar").find(".navbar-toggle").is(":visible")) {
                    // If we're inside a navbar, don't do anything when the
                    // navbar is collapsed, as it makes the navbar pretty unusable.
                    return;
                }

                // clear dropdown timeout here so it doesnt close before it should
                window.clearTimeout(timeout);
                // restart hover timer
                window.clearTimeout(timeoutHover);
                
                // delay for hover event.  
                timeoutHover = window.setTimeout(function () {
                    $allDropdowns.find(':focus').blur();

                    if(settings.instantlyCloseOthers === true)
                        $allDropdowns.removeClass('open');
                    
                    // clear timer for hover event
                    window.clearTimeout(timeoutHover);
                    $this.attr('aria-expanded', 'true');
                    $parent.addClass('open');
                    $this.trigger(showEvent);
                }, settings.hoverDelay);
            }
        });
    };

    $(document).ready(function () {
        // apply dropdownHover to all elements with the data-hover="dropdown" attribute
        $('[data-hover="dropdown"]').dropdownHover();
    });
})(jQuery, window);;
/*!
 * typeahead.js 0.10.2
 * https://github.com/twitter/typeahead.js
 * Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
 */

!function(a){var b={isMsie:function(){return/(msie|trident)/i.test(navigator.userAgent)?navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2]:!1},isBlankString:function(a){return!a||/^\s*$/.test(a)},escapeRegExChars:function(a){return a.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&")},isString:function(a){return"string"==typeof a},isNumber:function(a){return"number"==typeof a},isArray:a.isArray,isFunction:a.isFunction,isObject:a.isPlainObject,isUndefined:function(a){return"undefined"==typeof a},bind:a.proxy,each:function(b,c){function d(a,b){return c(b,a)}a.each(b,d)},map:a.map,filter:a.grep,every:function(b,c){var d=!0;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?void 0:!1}),!!d):d},some:function(b,c){var d=!1;return b?(a.each(b,function(a,e){return(d=c.call(null,e,a,b))?!1:void 0}),!!d):d},mixin:a.extend,getUniqueId:function(){var a=0;return function(){return a++}}(),templatify:function(b){function c(){return String(b)}return a.isFunction(b)?b:c},defer:function(a){setTimeout(a,0)},debounce:function(a,b,c){var d,e;return function(){var f,g,h=this,i=arguments;return f=function(){d=null,c||(e=a.apply(h,i))},g=c&&!d,clearTimeout(d),d=setTimeout(f,b),g&&(e=a.apply(h,i)),e}},throttle:function(a,b){var c,d,e,f,g,h;return g=0,h=function(){g=new Date,e=null,f=a.apply(c,d)},function(){var i=new Date,j=b-(i-g);return c=this,d=arguments,0>=j?(clearTimeout(e),e=null,g=i,f=a.apply(c,d)):e||(e=setTimeout(h,j)),f}},noop:function(){}},c="0.10.2",d=function(){function a(a){return a.split(/\s+/)}function b(a){return a.split(/\W+/)}function c(a){return function(b){return function(c){return a(c[b])}}}return{nonword:b,whitespace:a,obj:{nonword:c(b),whitespace:c(a)}}}(),e=function(){function a(a){this.maxSize=a||100,this.size=0,this.hash={},this.list=new c}function c(){this.head=this.tail=null}function d(a,b){this.key=a,this.val=b,this.prev=this.next=null}return b.mixin(a.prototype,{set:function(a,b){var c,e=this.list.tail;this.size>=this.maxSize&&(this.list.remove(e),delete this.hash[e.key]),(c=this.hash[a])?(c.val=b,this.list.moveToFront(c)):(c=new d(a,b),this.list.add(c),this.hash[a]=c,this.size++)},get:function(a){var b=this.hash[a];return b?(this.list.moveToFront(b),b.val):void 0}}),b.mixin(c.prototype,{add:function(a){this.head&&(a.next=this.head,this.head.prev=a),this.head=a,this.tail=this.tail||a},remove:function(a){a.prev?a.prev.next=a.next:this.head=a.next,a.next?a.next.prev=a.prev:this.tail=a.prev},moveToFront:function(a){this.remove(a),this.add(a)}}),a}(),f=function(){function a(a){this.prefix=["__",a,"__"].join(""),this.ttlKey="__ttl__",this.keyMatcher=new RegExp("^"+this.prefix)}function c(){return(new Date).getTime()}function d(a){return JSON.stringify(b.isUndefined(a)?null:a)}function e(a){return JSON.parse(a)}var f,g;try{f=window.localStorage,f.setItem("~~~","!"),f.removeItem("~~~")}catch(h){f=null}return g=f&&window.JSON?{_prefix:function(a){return this.prefix+a},_ttlKey:function(a){return this._prefix(a)+this.ttlKey},get:function(a){return this.isExpired(a)&&this.remove(a),e(f.getItem(this._prefix(a)))},set:function(a,e,g){return b.isNumber(g)?f.setItem(this._ttlKey(a),d(c()+g)):f.removeItem(this._ttlKey(a)),f.setItem(this._prefix(a),d(e))},remove:function(a){return f.removeItem(this._ttlKey(a)),f.removeItem(this._prefix(a)),this},clear:function(){var a,b,c=[],d=f.length;for(a=0;d>a;a++)(b=f.key(a)).match(this.keyMatcher)&&c.push(b.replace(this.keyMatcher,""));for(a=c.length;a--;)this.remove(c[a]);return this},isExpired:function(a){var d=e(f.getItem(this._ttlKey(a)));return b.isNumber(d)&&c()>d?!0:!1}}:{get:b.noop,set:b.noop,remove:b.noop,clear:b.noop,isExpired:b.noop},b.mixin(a.prototype,g),a}(),g=function(){function c(b){b=b||{},this._send=b.transport?d(b.transport):a.ajax,this._get=b.rateLimiter?b.rateLimiter(this._get):this._get}function d(c){return function(d,e){function f(a){b.defer(function(){h.resolve(a)})}function g(a){b.defer(function(){h.reject(a)})}var h=a.Deferred();return c(d,e,f,g),h}}var f=0,g={},h=6,i=new e(10);return c.setMaxPendingRequests=function(a){h=a},c.resetCache=function(){i=new e(10)},b.mixin(c.prototype,{_get:function(a,b,c){function d(b){c&&c(null,b),i.set(a,b)}function e(){c&&c(!0)}function j(){f--,delete g[a],l.onDeckRequestArgs&&(l._get.apply(l,l.onDeckRequestArgs),l.onDeckRequestArgs=null)}var k,l=this;(k=g[a])?k.done(d).fail(e):h>f?(f++,g[a]=this._send(a,b).done(d).fail(e).always(j)):this.onDeckRequestArgs=[].slice.call(arguments,0)},get:function(a,c,d){var e;return b.isFunction(c)&&(d=c,c={}),(e=i.get(a))?b.defer(function(){d&&d(null,e)}):this._get(a,c,d),!!e}}),c}(),h=function(){function c(b){b=b||{},b.datumTokenizer&&b.queryTokenizer||a.error("datumTokenizer and queryTokenizer are both required"),this.datumTokenizer=b.datumTokenizer,this.queryTokenizer=b.queryTokenizer,this.reset()}function d(a){return a=b.filter(a,function(a){return!!a}),a=b.map(a,function(a){return a.toLowerCase()})}function e(){return{ids:[],children:{}}}function f(a){for(var b={},c=[],d=0;d<a.length;d++)b[a[d]]||(b[a[d]]=!0,c.push(a[d]));return c}function g(a,b){function c(a,b){return a-b}var d=0,e=0,f=[];for(a=a.sort(c),b=b.sort(c);d<a.length&&e<b.length;)a[d]<b[e]?d++:a[d]>b[e]?e++:(f.push(a[d]),d++,e++);return f}return b.mixin(c.prototype,{bootstrap:function(a){this.datums=a.datums,this.trie=a.trie},add:function(a){var c=this;a=b.isArray(a)?a:[a],b.each(a,function(a){var f,g;f=c.datums.push(a)-1,g=d(c.datumTokenizer(a)),b.each(g,function(a){var b,d,g;for(b=c.trie,d=a.split("");g=d.shift();)b=b.children[g]||(b.children[g]=e()),b.ids.push(f)})})},get:function(a){var c,e,h=this;return c=d(this.queryTokenizer(a)),b.each(c,function(a){var b,c,d,f;if(e&&0===e.length)return!1;for(b=h.trie,c=a.split("");b&&(d=c.shift());)b=b.children[d];return b&&0===c.length?(f=b.ids.slice(0),void(e=e?g(e,f):f)):(e=[],!1)}),e?b.map(f(e),function(a){return h.datums[a]}):[]},reset:function(){this.datums=[],this.trie=e()},serialize:function(){return{datums:this.datums,trie:this.trie}}}),c}(),i=function(){function d(a){return a.local||null}function e(d){var e,f;return f={url:null,thumbprint:"",ttl:864e5,filter:null,ajax:{}},(e=d.prefetch||null)&&(e=b.isString(e)?{url:e}:e,e=b.mixin(f,e),e.thumbprint=c+e.thumbprint,e.ajax.type=e.ajax.type||"GET",e.ajax.dataType=e.ajax.dataType||"json",!e.url&&a.error("prefetch requires url to be set")),e}function f(c){function d(a){return function(c){return b.debounce(c,a)}}function e(a){return function(c){return b.throttle(c,a)}}var f,g;return g={url:null,wildcard:"%QUERY",replace:null,rateLimitBy:"debounce",rateLimitWait:300,send:null,filter:null,ajax:{}},(f=c.remote||null)&&(f=b.isString(f)?{url:f}:f,f=b.mixin(g,f),f.rateLimiter=/^throttle$/i.test(f.rateLimitBy)?e(f.rateLimitWait):d(f.rateLimitWait),f.ajax.type=f.ajax.type||"GET",f.ajax.dataType=f.ajax.dataType||"json",delete f.rateLimitBy,delete f.rateLimitWait,!f.url&&a.error("remote requires url to be set")),f}return{local:d,prefetch:e,remote:f}}();!function(c){function e(b){b&&(b.local||b.prefetch||b.remote)||a.error("one of local, prefetch, or remote is required"),this.limit=b.limit||5,this.sorter=j(b.sorter),this.dupDetector=b.dupDetector||k,this.local=i.local(b),this.prefetch=i.prefetch(b),this.remote=i.remote(b),this.cacheKey=this.prefetch?this.prefetch.cacheKey||this.prefetch.url:null,this.index=new h({datumTokenizer:b.datumTokenizer,queryTokenizer:b.queryTokenizer}),this.storage=this.cacheKey?new f(this.cacheKey):null}function j(a){function c(b){return b.sort(a)}function d(a){return a}return b.isFunction(a)?c:d}function k(){return!1}var l,m;return l=c.Bloodhound,m={data:"data",protocol:"protocol",thumbprint:"thumbprint"},c.Bloodhound=e,e.noConflict=function(){return c.Bloodhound=l,e},e.tokenizers=d,b.mixin(e.prototype,{_loadPrefetch:function(b){function c(a){f.clear(),f.add(b.filter?b.filter(a):a),f._saveToStorage(f.index.serialize(),b.thumbprint,b.ttl)}var d,e,f=this;return(d=this._readFromStorage(b.thumbprint))?(this.index.bootstrap(d),e=a.Deferred().resolve()):e=a.ajax(b.url,b.ajax).done(c),e},_getFromRemote:function(a,b){function c(a,c){b(a?[]:f.remote.filter?f.remote.filter(c):c)}var d,e,f=this;return a=a||"",e=encodeURIComponent(a),d=this.remote.replace?this.remote.replace(this.remote.url,a):this.remote.url.replace(this.remote.wildcard,e),this.transport.get(d,this.remote.ajax,c)},_saveToStorage:function(a,b,c){this.storage&&(this.storage.set(m.data,a,c),this.storage.set(m.protocol,location.protocol,c),this.storage.set(m.thumbprint,b,c))},_readFromStorage:function(a){var b,c={};return this.storage&&(c.data=this.storage.get(m.data),c.protocol=this.storage.get(m.protocol),c.thumbprint=this.storage.get(m.thumbprint)),b=c.thumbprint!==a||c.protocol!==location.protocol,c.data&&!b?c.data:null},_initialize:function(){function c(){e.add(b.isFunction(f)?f():f)}var d,e=this,f=this.local;return d=this.prefetch?this._loadPrefetch(this.prefetch):a.Deferred().resolve(),f&&d.done(c),this.transport=this.remote?new g(this.remote):null,this.initPromise=d.promise()},initialize:function(a){return!this.initPromise||a?this._initialize():this.initPromise},add:function(a){this.index.add(a)},get:function(a,c){function d(a){var d=f.slice(0);b.each(a,function(a){var c;return c=b.some(d,function(b){return e.dupDetector(a,b)}),!c&&d.push(a),d.length<e.limit}),c&&c(e.sorter(d))}var e=this,f=[],g=!1;f=this.index.get(a),f=this.sorter(f).slice(0,this.limit),f.length<this.limit&&this.transport&&(g=this._getFromRemote(a,d)),g||(f.length>0||!this.transport)&&c&&c(f)},clear:function(){this.index.reset()},clearPrefetchCache:function(){this.storage&&this.storage.clear()},clearRemoteCache:function(){this.transport&&g.resetCache()},ttAdapter:function(){return b.bind(this.get,this)}}),e}(this);var j={wrapper:'<span class="twitter-typeahead"></span>',dropdown:'<span class="tt-dropdown-menu"></span>',dataset:'<div class="tt-dataset-%CLASS%"></div>',suggestions:'<span class="tt-suggestions"></span>',suggestion:'<div class="tt-suggestion"></div>'},k={wrapper:{position:"relative",display:"inline-block"},hint:{position:"absolute",top:"0",left:"0",borderColor:"transparent",boxShadow:"none"},input:{position:"relative",verticalAlign:"top",backgroundColor:"transparent"},inputWithNoHint:{position:"relative",verticalAlign:"top"},dropdown:{position:"absolute",top:"100%",left:"0",zIndex:"100",display:"none"},suggestions:{display:"block"},suggestion:{whiteSpace:"nowrap",cursor:"pointer"},suggestionChild:{whiteSpace:"normal"},ltr:{left:"0",right:"auto"},rtl:{left:"auto",right:" 0"}};b.isMsie()&&b.mixin(k.input,{backgroundImage:"url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"}),b.isMsie()&&b.isMsie()<=7&&b.mixin(k.input,{marginTop:"-1px"});var l=function(){function c(b){b&&b.el||a.error("EventBus initialized without el"),this.$el=a(b.el)}var d="typeahead:";return b.mixin(c.prototype,{trigger:function(a){var b=[].slice.call(arguments,1);this.$el.trigger(d+a,b)}}),c}(),m=function(){function a(a,b,c,d){var e;if(!c)return this;for(b=b.split(i),c=d?h(c,d):c,this._callbacks=this._callbacks||{};e=b.shift();)this._callbacks[e]=this._callbacks[e]||{sync:[],async:[]},this._callbacks[e][a].push(c);return this}function b(b,c,d){return a.call(this,"async",b,c,d)}function c(b,c,d){return a.call(this,"sync",b,c,d)}function d(a){var b;if(!this._callbacks)return this;for(a=a.split(i);b=a.shift();)delete this._callbacks[b];return this}function e(a){var b,c,d,e,g;if(!this._callbacks)return this;for(a=a.split(i),d=[].slice.call(arguments,1);(b=a.shift())&&(c=this._callbacks[b]);)e=f(c.sync,this,[b].concat(d)),g=f(c.async,this,[b].concat(d)),e()&&j(g);return this}function f(a,b,c){function d(){for(var d,e=0;!d&&e<a.length;e+=1)d=a[e].apply(b,c)===!1;return!d}return d}function g(){var a;return a=window.setImmediate?function(a){setImmediate(function(){a()})}:function(a){setTimeout(function(){a()},0)}}function h(a,b){return a.bind?a.bind(b):function(){a.apply(b,[].slice.call(arguments,0))}}var i=/\s+/,j=g();return{onSync:c,onAsync:b,off:d,trigger:e}}(),n=function(a){function c(a,c,d){for(var e,f=[],g=0;g<a.length;g++)f.push(b.escapeRegExChars(a[g]));return e=d?"\\b("+f.join("|")+")\\b":"("+f.join("|")+")",c?new RegExp(e):new RegExp(e,"i")}var d={node:null,pattern:null,tagName:"strong",className:null,wordsOnly:!1,caseSensitive:!1};return function(e){function f(b){var c,d;return(c=h.exec(b.data))&&(wrapperNode=a.createElement(e.tagName),e.className&&(wrapperNode.className=e.className),d=b.splitText(c.index),d.splitText(c[0].length),wrapperNode.appendChild(d.cloneNode(!0)),b.parentNode.replaceChild(wrapperNode,d)),!!c}function g(a,b){for(var c,d=3,e=0;e<a.childNodes.length;e++)c=a.childNodes[e],c.nodeType===d?e+=b(c)?1:0:g(c,b)}var h;e=b.mixin({},d,e),e.node&&e.pattern&&(e.pattern=b.isArray(e.pattern)?e.pattern:[e.pattern],h=c(e.pattern,e.caseSensitive,e.wordsOnly),g(e.node,f))}}(window.document),o=function(){function c(c){var e,f,h,i,j=this;c=c||{},c.input||a.error("input is missing"),e=b.bind(this._onBlur,this),f=b.bind(this._onFocus,this),h=b.bind(this._onKeydown,this),i=b.bind(this._onInput,this),this.$hint=a(c.hint),this.$input=a(c.input).on("blur.tt",e).on("focus.tt",f).on("keydown.tt",h),0===this.$hint.length&&(this.setHint=this.getHint=this.clearHint=this.clearHintIfInvalid=b.noop),b.isMsie()?this.$input.on("keydown.tt keypress.tt cut.tt paste.tt",function(a){g[a.which||a.keyCode]||b.defer(b.bind(j._onInput,j,a))}):this.$input.on("input.tt",i),this.query=this.$input.val(),this.$overflowHelper=d(this.$input)}function d(b){return a('<pre aria-hidden="true"></pre>').css({position:"absolute",visibility:"hidden",whiteSpace:"pre",fontFamily:b.css("font-family"),fontSize:b.css("font-size"),fontStyle:b.css("font-style"),fontVariant:b.css("font-variant"),fontWeight:b.css("font-weight"),wordSpacing:b.css("word-spacing"),letterSpacing:b.css("letter-spacing"),textIndent:b.css("text-indent"),textRendering:b.css("text-rendering"),textTransform:b.css("text-transform")}).insertAfter(b)}function e(a,b){return c.normalizeQuery(a)===c.normalizeQuery(b)}function f(a){return a.altKey||a.ctrlKey||a.metaKey||a.shiftKey}var g;return g={9:"tab",27:"esc",37:"left",39:"right",13:"enter",38:"up",40:"down"},c.normalizeQuery=function(a){return(a||"").replace(/^\s*/g,"").replace(/\s{2,}/g," ")},b.mixin(c.prototype,m,{_onBlur:function(){this.resetInputValue(),this.trigger("blurred")},_onFocus:function(){this.trigger("focused")},_onKeydown:function(a){var b=g[a.which||a.keyCode];this._managePreventDefault(b,a),b&&this._shouldTrigger(b,a)&&this.trigger(b+"Keyed",a)},_onInput:function(){this._checkInputValue()},_managePreventDefault:function(a,b){var c,d,e;switch(a){case"tab":d=this.getHint(),e=this.getInputValue(),c=d&&d!==e&&!f(b);break;case"up":case"down":c=!f(b);break;default:c=!1}c&&b.preventDefault()},_shouldTrigger:function(a,b){var c;switch(a){case"tab":c=!f(b);break;default:c=!0}return c},_checkInputValue:function(){var a,b,c;a=this.getInputValue(),b=e(a,this.query),c=b?this.query.length!==a.length:!1,b?c&&this.trigger("whitespaceChanged",this.query):this.trigger("queryChanged",this.query=a)},focus:function(){this.$input.focus()},blur:function(){this.$input.blur()},getQuery:function(){return this.query},setQuery:function(a){this.query=a},getInputValue:function(){return this.$input.val()},setInputValue:function(a,b){this.$input.val(a),b?this.clearHint():this._checkInputValue()},resetInputValue:function(){this.setInputValue(this.query,!0)},getHint:function(){return this.$hint.val()},setHint:function(a){this.$hint.val(a)},clearHint:function(){this.setHint("")},clearHintIfInvalid:function(){var a,b,c,d;a=this.getInputValue(),b=this.getHint(),c=a!==b&&0===b.indexOf(a),d=""!==a&&c&&!this.hasOverflow(),!d&&this.clearHint()},getLanguageDirection:function(){return(this.$input.css("direction")||"ltr").toLowerCase()},hasOverflow:function(){var a=this.$input.width()-2;return this.$overflowHelper.text(this.getInputValue()),this.$overflowHelper.width()>=a},isCursorAtEnd:function(){var a,c,d;return a=this.$input.val().length,c=this.$input[0].selectionStart,b.isNumber(c)?c===a:document.selection?(d=document.selection.createRange(),d.moveStart("character",-a),a===d.text.length):!0},destroy:function(){this.$hint.off(".tt"),this.$input.off(".tt"),this.$hint=this.$input=this.$overflowHelper=null}}),c}(),p=function(){function c(c){c=c||{},c.templates=c.templates||{},c.source||a.error("missing source"),c.name&&!f(c.name)&&a.error("invalid dataset name: "+c.name),this.query=null,this.highlight=!!c.highlight,this.name=c.name||b.getUniqueId(),this.source=c.source,this.displayFn=d(c.display||c.displayKey),this.templates=e(c.templates,this.displayFn),this.$el=a(j.dataset.replace("%CLASS%",this.name))}function d(a){function c(b){return b[a]}return a=a||"value",b.isFunction(a)?a:c}function e(a,c){function d(a){return"<p>"+c(a)+"</p>"}return{empty:a.empty&&b.templatify(a.empty),header:a.header&&b.templatify(a.header),footer:a.footer&&b.templatify(a.footer),suggestion:a.suggestion||d}}function f(a){return/^[_a-zA-Z0-9-]+$/.test(a)}var g="ttDataset",h="ttValue",i="ttDatum";return c.extractDatasetName=function(b){return a(b).data(g)},c.extractValue=function(b){return a(b).data(h)},c.extractDatum=function(b){return a(b).data(i)},b.mixin(c.prototype,m,{_render:function(c,d){function e(){return p.templates.empty({query:c,isEmpty:!0})}function f(){function e(b){var c;return c=a(j.suggestion).append(p.templates.suggestion(b)).data(g,p.name).data(h,p.displayFn(b)).data(i,b),c.children().each(function(){a(this).css(k.suggestionChild)}),c}var f,l;return f=a(j.suggestions).css(k.suggestions),l=b.map(d,e),f.append.apply(f,l),p.highlight&&n({node:f[0],pattern:c}),f}function l(){return p.templates.header({query:c,isEmpty:!o})}function m(){return p.templates.footer({query:c,isEmpty:!o})}if(this.$el){var o,p=this;this.$el.empty(),o=d&&d.length,!o&&this.templates.empty?this.$el.html(e()).prepend(p.templates.header?l():null).append(p.templates.footer?m():null):o&&this.$el.html(f()).prepend(p.templates.header?l():null).append(p.templates.footer?m():null),this.trigger("rendered")}},getRoot:function(){return this.$el},update:function(a){function b(b){c.canceled||a!==c.query||c._render(a,b)}var c=this;this.query=a,this.canceled=!1,this.source(a,b)},cancel:function(){this.canceled=!0},clear:function(){this.cancel(),this.$el.empty(),this.trigger("rendered")},isEmpty:function(){return this.$el.is(":empty")},destroy:function(){this.$el=null}}),c}(),q=function(){function c(c){var e,f,g,h=this;c=c||{},c.menu||a.error("menu is required"),this.isOpen=!1,this.isEmpty=!0,this.datasets=b.map(c.datasets,d),e=b.bind(this._onSuggestionClick,this),f=b.bind(this._onSuggestionMouseEnter,this),g=b.bind(this._onSuggestionMouseLeave,this),this.$menu=a(c.menu).on("click.tt",".tt-suggestion",e).on("mouseenter.tt",".tt-suggestion",f).on("mouseleave.tt",".tt-suggestion",g),b.each(this.datasets,function(a){h.$menu.append(a.getRoot()),a.onSync("rendered",h._onRendered,h)})}function d(a){return new p(a)}return b.mixin(c.prototype,m,{_onSuggestionClick:function(b){this.trigger("suggestionClicked",a(b.currentTarget))},_onSuggestionMouseEnter:function(b){this._removeCursor(),this._setCursor(a(b.currentTarget),!0)},_onSuggestionMouseLeave:function(){this._removeCursor()},_onRendered:function(){function a(a){return a.isEmpty()}this.isEmpty=b.every(this.datasets,a),this.isEmpty?this._hide():this.isOpen&&this._show(),this.trigger("datasetRendered")},_hide:function(){this.$menu.hide()},_show:function(){this.$menu.css("display","block")},_getSuggestions:function(){return this.$menu.find(".tt-suggestion")},_getCursor:function(){return this.$menu.find(".tt-cursor").first()},_setCursor:function(a,b){a.first().addClass("tt-cursor"),!b&&this.trigger("cursorMoved")},_removeCursor:function(){this._getCursor().removeClass("tt-cursor")},_moveCursor:function(a){var b,c,d,e;if(this.isOpen){if(c=this._getCursor(),b=this._getSuggestions(),this._removeCursor(),d=b.index(c)+a,d=(d+1)%(b.length+1)-1,-1===d)return void this.trigger("cursorRemoved");-1>d&&(d=b.length-1),this._setCursor(e=b.eq(d)),this._ensureVisible(e)}},_ensureVisible:function(a){var b,c,d,e;b=a.position().top,c=b+a.outerHeight(!0),d=this.$menu.scrollTop(),e=this.$menu.height()+parseInt(this.$menu.css("paddingTop"),10)+parseInt(this.$menu.css("paddingBottom"),10),0>b?this.$menu.scrollTop(d+b):c>e&&this.$menu.scrollTop(d+(c-e))},close:function(){this.isOpen&&(this.isOpen=!1,this._removeCursor(),this._hide(),this.trigger("closed"))},open:function(){this.isOpen||(this.isOpen=!0,!this.isEmpty&&this._show(),this.trigger("opened"))},setLanguageDirection:function(a){this.$menu.css("ltr"===a?k.ltr:k.rtl)},moveCursorUp:function(){this._moveCursor(-1)},moveCursorDown:function(){this._moveCursor(1)},getDatumForSuggestion:function(a){var b=null;return a.length&&(b={raw:p.extractDatum(a),value:p.extractValue(a),datasetName:p.extractDatasetName(a)}),b},getDatumForCursor:function(){return this.getDatumForSuggestion(this._getCursor().first())},getDatumForTopSuggestion:function(){return this.getDatumForSuggestion(this._getSuggestions().first())},update:function(a){function c(b){b.update(a)}b.each(this.datasets,c)},empty:function(){function a(a){a.clear()}b.each(this.datasets,a),this.isEmpty=!0},isVisible:function(){return this.isOpen&&!this.isEmpty},destroy:function(){function a(a){a.destroy()}this.$menu.off(".tt"),this.$menu=null,b.each(this.datasets,a)}}),c}(),r=function(){function c(c){var e,f,g;c=c||{},c.input||a.error("missing input"),this.isActivated=!1,this.autoselect=!!c.autoselect,this.minLength=b.isNumber(c.minLength)?c.minLength:1,this.$node=d(c.input,c.withHint),e=this.$node.find(".tt-dropdown-menu"),f=this.$node.find(".tt-input"),g=this.$node.find(".tt-hint"),f.on("blur.tt",function(a){var c,d,g;c=document.activeElement,d=e.is(c),g=e.has(c).length>0,b.isMsie()&&(d||g)&&(a.preventDefault(),a.stopImmediatePropagation(),b.defer(function(){f.focus()}))}),e.on("mousedown.tt",function(a){a.preventDefault()}),this.eventBus=c.eventBus||new l({el:f}),this.dropdown=new q({menu:e,datasets:c.datasets}).onSync("suggestionClicked",this._onSuggestionClicked,this).onSync("cursorMoved",this._onCursorMoved,this).onSync("cursorRemoved",this._onCursorRemoved,this).onSync("opened",this._onOpened,this).onSync("closed",this._onClosed,this).onAsync("datasetRendered",this._onDatasetRendered,this),this.input=new o({input:f,hint:g}).onSync("focused",this._onFocused,this).onSync("blurred",this._onBlurred,this).onSync("enterKeyed",this._onEnterKeyed,this).onSync("tabKeyed",this._onTabKeyed,this).onSync("escKeyed",this._onEscKeyed,this).onSync("upKeyed",this._onUpKeyed,this).onSync("downKeyed",this._onDownKeyed,this).onSync("leftKeyed",this._onLeftKeyed,this).onSync("rightKeyed",this._onRightKeyed,this).onSync("queryChanged",this._onQueryChanged,this).onSync("whitespaceChanged",this._onWhitespaceChanged,this),this._setLanguageDirection()}function d(b,c){var d,f,h,i;d=a(b),f=a(j.wrapper).css(k.wrapper),h=a(j.dropdown).css(k.dropdown),i=d.clone().css(k.hint).css(e(d)),i.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder").prop("disabled",!0).attr({autocomplete:"off",spellcheck:"false"}),d.data(g,{dir:d.attr("dir"),autocomplete:d.attr("autocomplete"),spellcheck:d.attr("spellcheck"),style:d.attr("style")}),d.addClass("tt-input").attr({autocomplete:"off",spellcheck:!1}).css(c?k.input:k.inputWithNoHint);try{!d.attr("dir")&&d.attr("dir","auto")}catch(l){}return d.wrap(f).parent().prepend(c?i:null).append(h)}function e(a){return{backgroundAttachment:a.css("background-attachment"),backgroundClip:a.css("background-clip"),backgroundColor:a.css("background-color"),backgroundImage:a.css("background-image"),backgroundOrigin:a.css("background-origin"),backgroundPosition:a.css("background-position"),backgroundRepeat:a.css("background-repeat"),backgroundSize:a.css("background-size")}}function f(a){var c=a.find(".tt-input");b.each(c.data(g),function(a,d){b.isUndefined(a)?c.removeAttr(d):c.attr(d,a)}),c.detach().removeData(g).removeClass("tt-input").insertAfter(a),a.remove()}var g="ttAttrs";return b.mixin(c.prototype,{_onSuggestionClicked:function(a,b){var c;(c=this.dropdown.getDatumForSuggestion(b))&&this._select(c)},_onCursorMoved:function(){var a=this.dropdown.getDatumForCursor();this.input.setInputValue(a.value,!0),this.eventBus.trigger("cursorchanged",a.raw,a.datasetName)},_onCursorRemoved:function(){this.input.resetInputValue(),this._updateHint()},_onDatasetRendered:function(){this._updateHint()},_onOpened:function(){this._updateHint(),this.eventBus.trigger("opened")},_onClosed:function(){this.input.clearHint(),this.eventBus.trigger("closed")},_onFocused:function(){this.isActivated=!0,this.dropdown.open()},_onBlurred:function(){this.isActivated=!1,this.dropdown.empty(),this.dropdown.close()},_onEnterKeyed:function(a,b){var c,d;c=this.dropdown.getDatumForCursor(),d=this.dropdown.getDatumForTopSuggestion(),c?(this._select(c),b.preventDefault()):this.autoselect&&d&&(this._select(d),b.preventDefault())},_onTabKeyed:function(a,b){var c;(c=this.dropdown.getDatumForCursor())?(this._select(c),b.preventDefault()):this._autocomplete(!0)},_onEscKeyed:function(){this.dropdown.close(),this.input.resetInputValue()},_onUpKeyed:function(){var a=this.input.getQuery();this.dropdown.isEmpty&&a.length>=this.minLength?this.dropdown.update(a):this.dropdown.moveCursorUp(),this.dropdown.open()},_onDownKeyed:function(){var a=this.input.getQuery();this.dropdown.isEmpty&&a.length>=this.minLength?this.dropdown.update(a):this.dropdown.moveCursorDown(),this.dropdown.open()},_onLeftKeyed:function(){"rtl"===this.dir&&this._autocomplete()},_onRightKeyed:function(){"ltr"===this.dir&&this._autocomplete()},_onQueryChanged:function(a,b){this.input.clearHintIfInvalid(),b.length>=this.minLength?this.dropdown.update(b):this.dropdown.empty(),this.dropdown.open(),this._setLanguageDirection()},_onWhitespaceChanged:function(){this._updateHint(),this.dropdown.open()},_setLanguageDirection:function(){var a;this.dir!==(a=this.input.getLanguageDirection())&&(this.dir=a,this.$node.css("direction",a),this.dropdown.setLanguageDirection(a))},_updateHint:function(){var a,c,d,e,f,g;a=this.dropdown.getDatumForTopSuggestion(),a&&this.dropdown.isVisible()&&!this.input.hasOverflow()?(c=this.input.getInputValue(),d=o.normalizeQuery(c),e=b.escapeRegExChars(d),f=new RegExp("^(?:"+e+")(.+$)","i"),g=f.exec(a.value),g?this.input.setHint(c+g[1]):this.input.clearHint()):this.input.clearHint()},_autocomplete:function(a){var b,c,d,e;b=this.input.getHint(),c=this.input.getQuery(),d=a||this.input.isCursorAtEnd(),b&&c!==b&&d&&(e=this.dropdown.getDatumForTopSuggestion(),e&&this.input.setInputValue(e.value),this.eventBus.trigger("autocompleted",e.raw,e.datasetName))},_select:function(a){this.input.setQuery(a.value),this.input.setInputValue(a.value,!0),this._setLanguageDirection(),this.eventBus.trigger("selected",a.raw,a.datasetName),this.dropdown.close(),b.defer(b.bind(this.dropdown.empty,this.dropdown))},open:function(){this.dropdown.open()},close:function(){this.dropdown.close()},setVal:function(a){this.isActivated?this.input.setInputValue(a):(this.input.setQuery(a),this.input.setInputValue(a,!0)),this._setLanguageDirection()},getVal:function(){return this.input.getQuery()},destroy:function(){this.input.destroy(),this.dropdown.destroy(),f(this.$node),this.$node=null}}),c}();!function(){var c,d,e;c=a.fn.typeahead,d="ttTypeahead",e={initialize:function(c,e){function f(){var f,g,h=a(this);b.each(e,function(a){a.highlight=!!c.highlight}),g=new r({input:h,eventBus:f=new l({el:h}),withHint:b.isUndefined(c.hint)?!0:!!c.hint,minLength:c.minLength,autoselect:c.autoselect,datasets:e}),h.data(d,g)}return e=b.isArray(e)?e:[].slice.call(arguments,1),c=c||{},this.each(f)},open:function(){function b(){var b,c=a(this);(b=c.data(d))&&b.open()}return this.each(b)},close:function(){function b(){var b,c=a(this);(b=c.data(d))&&b.close()}return this.each(b)},val:function(b){function c(){var c,e=a(this);(c=e.data(d))&&c.setVal(b)}function e(a){var b,c;return(b=a.data(d))&&(c=b.getVal()),c}return arguments.length?this.each(c):e(this.first())},destroy:function(){function b(){var b,c=a(this);(b=c.data(d))&&(b.destroy(),c.removeData(d))}return this.each(b)}},a.fn.typeahead=function(a){return e[a]?e[a].apply(this,[].slice.call(arguments,1)):e.initialize.apply(this,arguments)},a.fn.typeahead.noConflict=function(){return a.fn.typeahead=c,this}}()}(window.jQuery);;
var app = angular.module("netsigns", []);

function setupController(elementName) {
    app.directive(elementName, function () {
        return {
            controller: elementName + 'Controller',
            controllerAs: '$ctrl',
            scope: true
        };
    });
}

setupController('cartItem');
setupController('priceList');
setupController('priceListChoices');
setupController('singlePriceChoices');
setupController('orderTotals');


/*** Directives ***/


app.directive('onimageload', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind('load', function () {
                scope.$apply(attrs.onimageload);
            });
        }
    };
});

app.directive('ngPressEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                if (attrs.ngPressEnter) {
                    scope.$apply(function () {
                        scope.$eval(attrs.ngPressEnter);
                    });

                    event.preventDefault();
                }
            }
        });
    };
});

app.directive('requiredSafe', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, elm, attr, ctrl) {
            if (!ctrl) return;

            ctrl.$validators.requiredSafe = function (modelValue, viewValue) {
                return !ctrl.$isEmpty(viewValue);
            };

            attr.$observe('requiredSafe', function () {
                ctrl.$validate();
            });

        }
    };
});

app.directive('decimalPlaces', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            ngModel.$formatters.push(function (value) {
                var multiplier = Math.pow(10, attrs.decimalPlaces);
                var precise = parseFloat((value * multiplier).toFixed(11));
                return Math.round(precise) / multiplier;
            });

        }
    }
});

app.directive('numericOnly', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModel) {
            ngModel.$parsers.push(function (viewValue) {
                if (!viewValue || viewValue.toString().match(/^[0-9.]*$/)) {
                    return viewValue;
                }
                var transformedValue = ngModel.$modelValue;
                ngModel.$setViewValue(transformedValue);
                ngModel.$render();
                return transformedValue;
            });
        }
    }
});

app.directive('preventEnterSubmit', function () {
    return function (scope, el, attrs) {
        el.bind('keydown keypress', function (event) {
            if (13 == event.which) {
                event.preventDefault();
            }
        });
    };
});

/*** Filters ***/


app.filter('productFilter', function () {
    return function (products, selectedOption) {

        if (!products) return;

        var productsToShow = [];
        for (var i = 0; i < products.length; i++) {
            if (products[i].Options.length > 0) productsToShow.push(products[i]);
        }
        return productsToShow;
    };
});

app.filter('between', function () {
    return function (values, property, min, max) {

        if (!values) return;

        var valuesToShow = [];
        for (var i = 0; i < values.length; i++) {
            if (!values[i][property] || values[i][property] >= min && values[i][property] <= max) valuesToShow.push(values[i]);
        }
        return valuesToShow;
    };
});



/*** Cart Item ***/



app.controller('cartItemController', ['$http', '$attrs', '$filter', '$rootScope', '$timeout', function ($http, $attrs, $filter, $rootScope, $timeout) {

    var $ctrl = this;

    // Private vars

    var orderNumber = $attrs.orderNumber;
    var sessionId = $attrs.orderSessionId;
    var productGroupId = $attrs.productGroupId;
    var productId = $attrs.productId;
    var designShape = $attrs.designShape;
    var orderItemId = $attrs.orderItemId;
    var designSessionId = $attrs.designSessionId;
    var tryLoadPreview = $attrs.clientLoadsPreview == "True";
    var requireDesign = $attrs.requireDesign == "True";
    var selectedProductProductOptionId = $attrs.selectedProductProductOptionId.replace(/-/g, '');
    var selectedProductOptionAddonChoices = $attrs.selectedProductOptionAddonChoices ? $attrs.selectedProductOptionAddonChoices.split(',') : null;
    var selectedWidth = $attrs.selectedWidth;
    var selectedHeight = $attrs.selectedHeight;
    var selectedQuantity = $attrs.selectedQuantity;
    var selectedSpecialInstructions = $attrs.selectedSpecialInstructions;
    var calcPriceOnLoad = $attrs.calcPriceOnLoad == "True";
    var validateOnCheckout = $attrs.validateOnCheckout == "True";
    var duplicateDesignOnAdd = $attrs.duplicateDesign == "True";
    var commitChanges = $attrs.commitChanges == "True";
    //var singleSizeWidth = $attrs.singleSizeWidth;
    //var singleSizeHeight = $attrs.singleSizeHeight;

    var getPreviewRetryCounter = 0;

    var previouslyChosenWidth;
    var previouslyChosenHeight;

    var designInformation = {};

    // Public vars

    $ctrl.designNumber = $attrs.designNumber;
    $ctrl.designAspectRatio = $attrs.designAspectRatio;
    $ctrl.imageUrl = $attrs.imageUrl;
    if ($attrs.price) {
        $ctrl.price = $attrs.price;
    }
    if ($attrs.unitPrice) {
        $ctrl.unitPrice = $attrs.unitPrice;
    }
    if ($attrs.priceUndiscounted) {
        $ctrl.priceUndiscounted = $attrs.priceUndiscounted;
    }
    $ctrl.showWarning = false;
    $ctrl.productData = [];
    $ctrl.quantity;
    $ctrl.minWidth = 0;
    $ctrl.minHeight = 0;
    $ctrl.maxWidth = null;
    $ctrl.maxHeight = null;
    $ctrl.minDimension = 0;
    $ctrl.maxDimension = null;
    $ctrl.discountDescription = $attrs.discountDescription;
    $ctrl.isLoadingPrice = false;
    $ctrl.isLoadingProducts = false;

    $ctrl.isSavingDesign = false;
    $ctrl.isAddingToCart = false;

    $ctrl.sizeTypes = {
        none: 'None',
        fixed: 'Fixed',
        custom: 'Custom',
        generated: 'Generated',
        customAndGenerated: 'CustomAndGenerated',
        single: 'Single'
    };

    $ctrl.quantityTypes = {
        fixed: 'Fixed',
        custom: 'Custom',
        packs: 'Packs'
    };

    $ctrl.quantityPacks = [
        { quantity: 1, label: "1" },
        { quantity: 2, label: "2" },
        { quantity: 5, label: "5" },
        { quantity: 10, label: "10" },
        { quantity: 25, label: "25" },
        { quantity: 50, label: "50" },
        { quantity: 100, label: "100" },
        { quantity: 250, label: "250" },
        { quantity: 500, label: "500" },
        { quantity: 1000, label: "1,000" },
        { quantity: 2500, label: "2,500" },
        { quantity: 5000, label: "5,000" },
        { quantity: 10000, label: "10,000" },
        { quantity: 20000, label: "20,000" },
        { quantity: 50000, label: "50,000" },
        { quantity: 100000, label: "100,000" }
    ];

    // Inter-Controller Communication

    $rootScope.$on('designCreated', function (e, data) {

        var loadProducts = false;

        $ctrl.showWarning = false;
        $ctrl.designNumber = data.DesignNumber;
        designSessionId = data.SessionId;
        //designShape = data.DesignShape;
        $ctrl.specialInstructions = data.SpecialInstructions;

        if (data.DesignAspectRatio && data.DesignAspectRatio > 0 && $ctrl.designAspectRatio != data.DesignAspectRatio) {
            $ctrl.designAspectRatio = data.DesignAspectRatio;
            loadProducts = true;
        }

        if (data.ProductId) {
            productGroupId = "";
            productId = data.ProductId;
        }

        if (data.SVG) {
            designInformation = data;
        }

        //if (data.SingleSize) {
        //    singleSizeWidth = data.SingleSize.Width;
        //    singleSizeHeight = data.SingleSize.Height;
        //} else {
        //    $ctrl.setPreviousSize();
        //}

        if (loadProducts) {
            $ctrl.loadProducts();
        }

    });

    // Private Functions

    function loadSelections() {

        if (selectedProductProductOptionId) {
            for (var i = 0; i < $ctrl.productData.length; i++) {
                for (var j = 0; j < $ctrl.productData[i].Options.length; j++) {
                    if ($ctrl.productData[i].Options[j].Id == selectedProductProductOptionId) {
                        $ctrl.product = $ctrl.productData[i];
                        $ctrl.productOption = $ctrl.productData[i].Options[j];
                    }
                }
            }
        }

        if (selectedProductOptionAddonChoices) {
            for (var i = 0; i < $ctrl.productOption.Addons.length; i++) {
                for (var j = 0; j < $ctrl.productOption.Addons[i].Options.length; j++) {
                    if (selectedProductOptionAddonChoices.indexOf($ctrl.productOption.Addons[i].Options[j].Id) > -1) {
                        $ctrl.productOption.Addons[i].selected = $ctrl.productOption.Addons[i].Options[j].Id;
                        if ($ctrl.productOption.Addons[i].SelectType == 'LabelOrientation' && $ctrl.productOption.Addons[i].selected != $ctrl.getAddonIdFromChoiceValue($ctrl.productOption.Addons[i], "Any")) {
                            $ctrl.productOption.Addons[i].showDesignOrientation = 'true';
                        }
                    }
                }
            }
        }

        var selectedWidthFloat = parseFloat(selectedWidth);
        var selectedHeightFloat = parseFloat(selectedHeight);
        if (!isNaN(selectedWidthFloat) && !isNaN(selectedHeightFloat) && selectedWidthFloat > 0 && selectedHeightFloat > 0) {
            $ctrl.selectSize(selectedWidthFloat, selectedHeightFloat);
            $ctrl.setPreviousSize();
        }

        $ctrl.setDimensionBounds();

        var selectedQuantityInt = parseInt(selectedQuantity, 10);
        if (selectedQuantity && !isNaN(selectedQuantityInt) && selectedQuantity > 0) {
            $ctrl.quantity = selectedQuantityInt;
            var foundQuantity = false;
            for (var i = 0; i < $ctrl.quantityPacks.length; i++) {
                if ($ctrl.quantityPacks[i].quantity == selectedQuantityInt) {
                    $ctrl.quantitySelect = $ctrl.quantityPacks[i];
                    foundQuantity = true;
                }
            }
            if (!foundQuantity) {
                $ctrl.quantitySelect = $ctrl.quantityPacks[$ctrl.quantityPacks.length - 1];
            }
        } else if ($ctrl.productOption && $ctrl.productOption.CustomerMinQuantity) {
            $ctrl.quantity = $ctrl.productOption.CustomerMinQuantity;
        } else {
            $ctrl.quantity = 1;
        }

        if (selectedSpecialInstructions) {
            $ctrl.specialInstructions = selectedSpecialInstructions;
        }

    }

    // Public Functions

    $ctrl.checkoutValidate = function () {
        if (validateOnCheckout) {
            console.log($ctrl.form.$valid);
            return $ctrl.form.$valid;
        }
        return true;
    };

    $ctrl.isAboutSame = function (num1, num2, percentDifferenceAllowed) {
        if (!percentDifferenceAllowed) percentDifferenceAllowed = 0.01;
        return Math.abs(num1 - num2) < num1 * percentDifferenceAllowed;
    };

    $ctrl.getOptionDropdownLabel = function (optionLabel) {
        if (!optionLabel) return;
        if ((/^[aeiou]$/i).test(optionLabel[0])) {
            return "an " + optionLabel;
        }
        return "a " + optionLabel;
    };

    $ctrl.loadProducts = function () {

        $ctrl.isLoadingProducts = true;

        $http.get('/ssapi/productOptions/find', {
            params: {
                ProductGroupId: productGroupId,
                ProductId: productId,
                DesignAspectRatio: $ctrl.designAspectRatio,
                //DesignShape: designShape, //this is not part of the service right now
                //SingleSizeWidth: singleSizeWidth,
                //SingleSizeHeight: singleSizeHeight
            }
        }).then(function success(response) {

            $ctrl.productData = response.data.Products;

            //transform sizes for UI purposes
            for (var i = 0; i < $ctrl.productData.length; i++) {

                //use reverse while loop so we can splice out items without ruining index
                var j = $ctrl.productData[i].Options.length;
                while (j--) {

                    var po = $ctrl.productData[i].Options[j];

                    //remove if it's not valid to order online and it's not the order item being loaded
                    if (!po.IsOrderableOnline && po.Id != selectedProductProductOptionId) {
                        $ctrl.productData[i].Options.splice(j, 1);
                    }

                    if (po.SingleSizeWidth && po.SingleSizeHeight) {

                        po.SizeType = $ctrl.sizeTypes.single;
                        po.SingleSize = {
                            width: po.SingleSizeWidth,
                            height: po.SingleSizeHeight
                        };

                    } else {

                        switch (po.SizeType) {
                            case $ctrl.sizeTypes.none:
                                break;
                            case $ctrl.sizeTypes.fixed:
                                for (var k = 0; k < po.FixedSizes.length; k++) {
                                    po.FixedSizes[k].label = po.FixedSizes[k].Width.toFixed(2) + '" x ' + po.FixedSizes[k].Height.toFixed(2) + '"';
                                }
                                $ctrl.productData[i].hide = true;
                                break;
                            case $ctrl.sizeTypes.custom:
                                break;
                            case $ctrl.sizeTypes.generated:
                                for (var k = 0; k < po.GeneratedSizes.length; k++) {
                                    if (po.DesignShape == "Oval" && po.GeneratedSizes[k].Width == po.GeneratedSizes[k].Height) {
                                        po.GeneratedSizes[k].label = po.GeneratedSizes[k].Width.toFixed(0) + '" Circle';
                                    } else {
                                        var width = Math.round(po.GeneratedSizes[k].Width * 100) / 100;
                                        var height = Math.round(po.GeneratedSizes[k].Height * 100) / 100;
                                        po.GeneratedSizes[k].label = width + '" x ' + height + '"';
                                    }
                                }
                                break;
                            case $ctrl.sizeTypes.customAndGenerated:
                                for (var k = 0; k < po.GeneratedSizes.length; k++) {
                                    if (po.DesignShape == "Oval" && po.GeneratedSizes[k].Width == po.GeneratedSizes[k].Height) {
                                        po.GeneratedSizes[k].label = po.GeneratedSizes[k].Width.toFixed(0) + '" Circle';
                                    } else {
                                        var width = Math.round(po.GeneratedSizes[k].Width * 100) / 100;
                                        var height = Math.round(po.GeneratedSizes[k].Height * 100) / 100;
                                        po.GeneratedSizes[k].label = width + '" x ' + height + '"';
                                    }
                                }
                                po.GeneratedSizes.push({
                                    label: "Other",
                                    width: "",
                                    height: "",
                                    showCustom: true
                                });
                                break;
                        }

                    }



                }
            }

            if ($ctrl.productData.length == 1) {
                $ctrl.product = $ctrl.productData[0];
                $ctrl.autoSelectProductOption();
            }

            loadSelections();
            $ctrl.reselectSize(!$ctrl.singleSize);

            if (calcPriceOnLoad) {
                $ctrl.calcPrice();
            } else {
                $ctrl.calcPackPrices();
            }

            $ctrl.isLoadingProducts = false;

            setTimeout(function () {
                $.publish("app/elements/stickysidebar");
            }, 100);

        }, function error(response) {

            $ctrl.isLoadingProducts = false;

        });
    };

    $ctrl.handleProductChoice = function () {
        $ctrl.autoSelectProductOption();
        $ctrl.setDimensionBounds();
        $ctrl.calcPrice();
    }

    $ctrl.handleProductOptionChoice = function () {
        $ctrl.reselectSize();
        $ctrl.autoSelectProductOptionFixedSize();
        $ctrl.setDimensionBounds();

        if ($ctrl.productOption) {
            if ($ctrl.quantity < $ctrl.productOption.CustomerMinQuantity) {
                $ctrl.quantity = $ctrl.productOption.CustomerMinQuantity;
            }
            if ($ctrl.quantity > $ctrl.productOption.CustomerMaxQuantity) {
                $ctrl.quantity = $ctrl.productOption.CustomerMaxQuantity;
            }
        }

        $ctrl.calcPrice()
    }

    $ctrl.autoSelectProductOption = function () {
        if ($ctrl.product && $ctrl.product.Options.length == 1) {
            $ctrl.productOption = $ctrl.product.Options[0];
            $ctrl.autoSelectProductOptionFixedSize();
        }
    };

    $ctrl.autoSelectProductOptionFixedSize = function () {
        if ($ctrl.productOption && $ctrl.productOption.FixedSizes && $ctrl.productOption.FixedSizes.length == 1) {
            $ctrl.sizeFixed = $ctrl.productOption.FixedSizes[0];
        }
    };

    $ctrl.setPreviousSize = function () {

        var size = $ctrl.getSize();

        if (size && size.width) {
            previouslyChosenWidth = size.width;
        }
        if (size && size.height) {
            previouslyChosenHeight = size.height;
        }

    };

    $ctrl.reselectSize = function (generatedOnly) {
        $ctrl.selectSize(previouslyChosenWidth, previouslyChosenHeight, generatedOnly);
    };

    $ctrl.selectSize = function (width, height, generatedOnly) {

        if (width && height) {

            if ($ctrl.productOption && $ctrl.productOption.SizeType) {

                if ($ctrl.productOption.SizeType == $ctrl.sizeTypes.fixed) {

                    for (var i = 0; i < $ctrl.productOption.FixedSizes.length; i++) {
                        if ($ctrl.isAboutSame($ctrl.productOption.FixedSizes[i].Width, width) && $ctrl.isAboutSame($ctrl.productOption.FixedSizes[i].Height, height)) {
                            $ctrl.sizeFixed = $ctrl.productOption.FixedSizes[i];
                        }
                    }

                }

                var matchesGeneratedSize = false;
                if ($ctrl.productOption.GeneratedSizes) {

                    for (var i = 0; i < $ctrl.productOption.GeneratedSizes.length; i++) {
                        if ($ctrl.isAboutSame($ctrl.productOption.GeneratedSizes[i].Width, width) && $ctrl.isAboutSame($ctrl.productOption.GeneratedSizes[i].Height, height)) {
                            $ctrl.sizeGenerated = $ctrl.productOption.GeneratedSizes[i];
                            matchesGeneratedSize = true;
                        }
                    }

                    if (!matchesGeneratedSize && $ctrl.productOption.SizeType == $ctrl.sizeTypes.customAndGenerated && !generatedOnly) {
                        //last item is "other"
                        $ctrl.sizeGenerated = $ctrl.productOption.GeneratedSizes[$ctrl.productOption.GeneratedSizes.length - 1];
                        $ctrl.sizeCustom = {
                            width: width,
                            height: height
                        };
                    }

                }

                if ($ctrl.productOption.SizeType == $ctrl.sizeTypes.custom) {
                    $ctrl.sizeCustom = {
                        width: width,
                        height: height
                    };
                }
            }

            $ctrl.setPreviousSize();

        }
    };

    $ctrl.openPackSelection = function () {
        $ctrl.packSelectionVisible = true;
        $timeout(function () {
            var ps = jQuery(".js-packselection:visible .quantity-dropdown").first();
            if (ps.length > 0) {
                var sel = ps.find(".quantity-option.active");
                ps[0].scrollTop = sel[0].offsetTop;
            }
        }, 1);

    }

    $ctrl.closePackSelection = function () {
        $ctrl.packSelectionVisible = false;
    }

    $ctrl.setQuantityFromSelect = function () {
        if ($ctrl.quantitySelect != "other") $ctrl.quantity = $ctrl.quantitySelect;
    };

    $ctrl.getAddonIdFromChoiceValue = function (addon, choiceValue) {
        for (var i = 0; i < addon.Options.length; i++) {
            if (addon.Options[i].ChoiceValue == choiceValue) return addon.Options[i].Id;
        }
    }

    $ctrl.clearPrice = function (alsoClearQuantityDropdownPrices) {
        $ctrl.price = null;
        $ctrl.unitPrice = null;
        $ctrl.priceUndiscounted = null;
        $ctrl.discountDescription = null;
        if (alsoClearQuantityDropdownPrices) {
            for (var i = 0; i < $ctrl.quantityPacks.length; i++) {
                $ctrl.quantityPacks[i].price = null;
            }
        }
    };

    var calcPricePromise;
    $ctrl.calcPrice = function () {

        $timeout.cancel(calcPricePromise);
        calcPricePromise = $timeout(function () {

            $.publish("app/elements/stickysidebar");

            if (!$ctrl.product || !$ctrl.productOption) {
                $ctrl.clearPrice(true);
                return;
            }

            var size = $ctrl.getSize();
            if ($ctrl.productOption.SizeType != $ctrl.sizeTypes.none) {
                if (!size || !size.width || !size.height) {
                    $ctrl.clearPrice(true);
                    return;
                }
                if ($ctrl.productOption.MustMatchDesignAspectRatio && $ctrl.designAspectRatio && size.width && size.height && !$ctrl.isAboutSame($ctrl.designAspectRatio, size.width / size.height)) {
                    $ctrl.clearPrice(true);
                    return;
                }
            }

            // Calc packs prices
            $ctrl.calcPackPrices();

            // Gather AddOnChoices
            var addonChoices = getAddonChoices();

            // Determine quantity
            var quantity = $ctrl.quantity;
            if (!quantity) {
                $ctrl.clearPrice(false);
                $ctrl.isLoadingPrice = false;
                return;
            }

            if (!$ctrl.form.$valid) {
                $ctrl.clearPrice(true);
                $ctrl.isLoadingPrice = false;
                return;
            }

            var longLoadTimePromise;
            longLoadTimePromise = $timeout(function () {
                $ctrl.isLoadingPrice = true;
            }, 200);

            // Update order item if it exists, otherwise just calc
            if (commitChanges && orderItemId && orderItemId > 0) {

                $http.put('/ssapi/orderitem/' + orderItemId + '/updateprice', {
                    OrderSessionId: sessionId,
                    ProductProductOptionId: $ctrl.productOption.Id,
                    Width: size ? size.width : null,
                    Height: size ? size.height : null,
                    ProductOptionAddonChoiceIds: addonChoices,
                    Quantity: quantity,
                    CustomerPrintingInstructions: $ctrl.specialInstruction
                }).then(function success(response) {

                    $ctrl.price = response.data.PriceTotal;
                    $ctrl.unitPrice = Math.ceil(100 * response.data.PriceTotal / response.data.Quantity) / 100;
                    $ctrl.priceUndiscounted = response.data.ListPrice;
                    $ctrl.discountDescription = response.data.DiscountDescription;

                    $rootScope.$broadcast('updateOrderTotals', {
                        subtotal: response.data.OrderPrice.Subtotal,
                        discountName: response.data.OrderPrice.PromoCodeId,
                        discountAmount: response.data.OrderPrice.PromoCodeDiscountAmount,
                        discountResult: response.data.OrderPrice.PromoCodeResult,
                        discountResultMessage: response.data.OrderPrice.PromoCodeResultMessage,
                        shipping: response.data.OrderPrice.ShippingPrice,
                        tax: response.data.OrderPrice.TaxPrice,
                        rushFee: response.data.OrderPrice.RushServicePrice,
                        total: response.data.OrderPrice.PriceTotal
                    });

                    setTimeout(function () {
                        $.publish("app/elements/stickysidebar");
                    }, 100);

                    $.publish('app/order/updateEstimatedShipping');

                    $timeout.cancel(longLoadTimePromise);
                    $ctrl.isLoadingPrice = false;

                }, function error(response) {

                    $timeout.cancel(longLoadTimePromise);
                    $ctrl.isLoadingPrice = false;

                });

            } else {
                $http.get('/ssapi/prices/calcPrice', {
                    params: {
                        ProductProductOptionId: $ctrl.productOption.Id,
                        Width: size ? size.width : "",
                        Height: size ? size.height : "",
                        ProductOptionAddonOptionIds: addonChoices,
                        Quantity: quantity
                    }
                }).then(function success(response) {

                    $ctrl.price = response.data.PriceTotal;
                    $ctrl.unitPrice = Math.ceil(100 * response.data.PriceTotal / response.data.Quantity) / 100;
                    $ctrl.priceUndiscounted = response.data.ListPrice;
                    $ctrl.discountDescription = response.data.DiscountDescription;

                    setTimeout(function () {
                        $.publish("app/elements/stickysidebar");
                    }, 100);

                    $timeout.cancel(longLoadTimePromise);
                    $ctrl.isLoadingPrice = false;

                }, function error(response) {

                    $timeout.cancel(longLoadTimePromise);
                    $ctrl.isLoadingPrice = false;

                });
            }

        }, 150);

    };

    $ctrl.calcPackPrices = function () {

        if ($ctrl.form.$invalid) {
            for (var i = 0; i < $ctrl.quantityPacks.length; i++) {
                $ctrl.quantityPacks[i].unitPrice = null;
            }
            return;
        }

        if ($ctrl.productOption && $ctrl.productOption.QuantityType == $ctrl.quantityTypes.packs) {

            var size = $ctrl.getSize();

            if (!size && $ctrl.productOption.SizeType != $ctrl.sizeTypes.none) {
                return
            }

            var addonChoices = getAddonChoices();

            var pricesToCalc = [];
            for (var i = 0; i < $ctrl.quantityPacks.length; i++) {
                if ($ctrl.quantityPacks[i].quantity && $ctrl.quantityPacks[i].quantity >= $ctrl.productOption.MinQuantity && $ctrl.quantityPacks[i].quantity <= $ctrl.productOption.MaxQuantity) {
                    pricesToCalc.push({
                        ProductProductOptionId: $ctrl.productOption.Id,
                        Width: size ? size.width : "",
                        Height: size ? size.height : "",
                        Quantity: $ctrl.quantityPacks[i].quantity,
                        ProductOptionAddonOptionIds: addonChoices
                    });
                }
            }

            $http({
                method: 'POST',
                url: '/ssapi/prices/calcPrices',
                data: {
                    PricesToCalc: pricesToCalc
                }
            }).then(function success(response) {

                for (var i = 0; i < response.data.Prices.length; i++) {
                    for (var j = 0; j < $ctrl.quantityPacks.length; j++) {
                        if (response.data.Prices[i].Quantity == $ctrl.quantityPacks[j].quantity) {
                            $ctrl.quantityPacks[j].price = $filter('currency')(response.data.Prices[i].PriceTotal, "$", 2);
                            if (response.data.Prices[i].Quantity > 1) {
                                $ctrl.quantityPacks[j].unitPrice = $filter('currency')(Math.ceil(response.data.Prices[i].PriceTotal / response.data.Prices[i].Quantity * 100) / 100, "$", 2) + ' each';
                            }

                        }
                    }
                }

            }, function error(response) {

            });
        }

    }

    $ctrl.addToCart = function () {

        // Prevent doubleclick
        if ($ctrl.isAddingToCart || $ctrl.isSavingDesign) {
            return;
        }

        // Handle invalid form
        if ($ctrl.form.$invalid) {

            angular.forEach($ctrl.form.$error, function (field) {
                angular.forEach(field, function (errorField) {
                    errorField.$setTouched();
                });
            });

            return;
        }

        // Upload SVG
        if (designInformation && designInformation.SVG && !$ctrl.designNumber && !$ctrl.isSavingDesign) {

            $ctrl.isSavingDesign = true;

            $http({
                method: 'POST',
                url: '/ssapi/engine/save-design',
                data: {
                    SVG: designInformation.SVG,
                    PreviewDataUri: designInformation.PreviewDataUri,
                    TemplateId: designInformation.TemplateId,
                    Width: designInformation.Width,
                    Height: designInformation.Height
                }
            }).then(function success(response) {

                $ctrl.designNumber = response.data.DesignNumber;
                designSessionId = response.data.DesignSessionId;
                $ctrl.isSavingDesign = false;

                if (orderItemId && orderItemId > 0) {
                    saveOrderItem();
                } else {
                    addToOrder();
                }


            }, function error(response) {

                $ctrl.isSavingDesign = false;

                var message = "Could not save design. ";
                if (response.data && response.data.ExceptionMessage) {
                    message += response.data.ExceptionMessage;
                }
                window.graphicsland.showError(message);

            });

            return;
        }

        if (orderItemId && orderItemId > 0) {
            saveOrderItem();
        } else {
            addToOrder();
        }

    };

    function addToOrder() {

        $ctrl.isAddingToCart = true;

        if ($ctrl.product && $ctrl.productOption) {
            if (typeof gtag == "function") {
                gtag('event', 'add_to_cart', {
                    'items': [
                        {
                            'id': $ctrl.product.Id,
                            'name': $ctrl.product.Name,
                            'variant': $ctrl.productOption.Name
                        }
                    ]
                });
            }
        }

        var size = $ctrl.getSize();

        $http({
            method: 'POST',
            url: '/api/order/PostAddOrderItemToOrder',
            data: {
                ProductProductOptionId: $ctrl.productOption.Id,
                DesignNumber: $ctrl.designNumber,
                DesignSessionId: designSessionId,
                Width: size ? size.width : null,
                Height: size ? size.height : null,
                ProductOptionAddonChoiceIds: getAddonChoices() || [],
                Quantity: $ctrl.quantity,
                CustomerPrintingInstructions: $ctrl.specialInstructions,
                DuplicateDesign: duplicateDesignOnAdd
            }
        }).then(function success(response) {

            window.location.href = "/cart.aspx";

        }, function error(response) {

            $ctrl.isAddingToCart = false;

            var message = "Could not add item to order. ";
            if (response.data && response.data.ExceptionMessage) {
                message += response.data.ExceptionMessage;
            }
            window.graphicsland.showError(message);

        });

    }

    function saveOrderItem() {

        $ctrl.isAddingToCart = true;

        var size = $ctrl.getSize();

        $http.put('/ssapi/orderitem/' + orderItemId + '/updateprice', {
            OrderSessionId: sessionId,
            ProductProductOptionId: $ctrl.productOption.Id,
            Width: size ? size.width : null,
            Height: size ? size.height : null,
            ProductOptionAddonChoiceIds: getAddonChoices() || [],
            Quantity: $ctrl.quantity,
            CustomerPrintingInstructions: $ctrl.specialInstructions,
            DesignNumber: $ctrl.designNumber,
            DesignSessionId: designSessionId
        }).then(function success(response) {

            window.location.href = "/cart.aspx"

        }, function error(response) {

            $ctrl.isAddingToCart = false;

            var message = "Could not save edits. ";
            if (response.data && response.data.ExceptionMessage) {
                message += response.data.ExceptionMessage;
            }
            window.graphicsland.showError(message);

        });

    }

    $ctrl.getSize = function () {

        if ($ctrl.productOption && $ctrl.productOption.SizeType) {
            if ($ctrl.productOption.SizeType == $ctrl.sizeTypes.fixed && $ctrl.sizeFixed) {
                return {
                    width: $ctrl.sizeFixed.Width,
                    height: $ctrl.sizeFixed.Height
                };
            } else if ($ctrl.sizeGenerated && !$ctrl.sizeGenerated.showCustom) {
                $ctrl.form.$setValidity('sizeMin', true);
                $ctrl.form.$setValidity('sizeMax', true);
                return {
                    width: $ctrl.sizeGenerated.Width,
                    height: $ctrl.sizeGenerated.Height
                };
            } else if ($ctrl.sizeCustom) {
                return {
                    width: $ctrl.sizeCustom.width,
                    height: $ctrl.sizeCustom.height
                };
            } else if ($ctrl.productOption.SizeType == $ctrl.sizeTypes.single) {
                return $ctrl.productOption.SingleSize;

            }
        }
        return;

    };

    $ctrl.isSizeAboveMin = function () {
        var size = $ctrl.getSize();
        if (!size || !size.width || !size.height) return true;

        if (fitsIn($ctrl.minWidth, $ctrl.minHeight, size.width, size.height)) {
            $ctrl.form.$setValidity('sizeMin', true)
            return true;
        } else {
            $ctrl.form.$setValidity('sizeMin', false)
            return false;
        }
    }

    $ctrl.isSizeBelowMax = function () {
        var size = $ctrl.getSize();
        if (!size || !size.width || !size.height) return true;

        if (fitsIn(size.width, size.height, $ctrl.maxWidth, $ctrl.maxHeight)) {
            $ctrl.form.$setValidity('sizeMax', true)
            return true;
        } else {
            $ctrl.form.$setValidity('sizeMax', false)
            return false;
        }
    }

    $ctrl.setDimensionBounds = function () {

        if ($ctrl.productOption) {

            $ctrl.minDimension = Math.min($ctrl.productOption.MinWidth, $ctrl.productOption.MinHeight);
            $ctrl.maxDimension = Math.max($ctrl.productOption.MaxWidth, $ctrl.productOption.MaxHeight);

            if (!$ctrl.designAspectRatio || $ctrl.designAspectRatio >= 1) {
                $ctrl.minWidth = $ctrl.productOption.MinHeight;
                $ctrl.minHeight = $ctrl.productOption.MinWidth;
                $ctrl.maxWidth = $ctrl.productOption.MaxHeight;
                $ctrl.maxHeight = $ctrl.productOption.MaxWidth;
            } else {
                $ctrl.minWidth = $ctrl.productOption.MinWidth;
                $ctrl.minHeight = $ctrl.productOption.MinHeight;
                $ctrl.maxWidth = $ctrl.productOption.MaxWidth;
                $ctrl.maxHeight = $ctrl.productOption.MaxHeight;
            }

        }

    };

    $ctrl.sizeAspectRatioMismatch = function (formWidth, formHeight) {
        if ($ctrl.productOption && $ctrl.designAspectRatio && $ctrl.productOption.MustMatchDesignAspectRatio && $ctrl.sizeCustom && $ctrl.sizeCustom.width && $ctrl.sizeCustom.height) {
            if (!$ctrl.isAboutSame($ctrl.designAspectRatio, $ctrl.sizeCustom.width / $ctrl.sizeCustom.height)) {
                formWidth.$setValidity("aspectRatioMismatch", false);
                formHeight.$setValidity("aspectRatioMismatch", false);
                return true;
            }
        }

        formWidth.$setValidity("aspectRatioMismatch", true);
        formHeight.$setValidity("aspectRatioMismatch", true);
        return false;
    };

    $ctrl.changeSpecialInstructions = function () {
        $ctrl.specialInstructions = $ctrl.specialInstructions.replace("<", "").replace(">", "");
    }

    $ctrl.addSpecialInstruction = function (instruction, event) {
        if ($ctrl.specialInstructions) {
            $ctrl.specialInstructions += "\r\n";
        } else {
            $ctrl.specialInstructions = "";
        }

        $ctrl.specialInstructions += instruction;
        $ctrl.calcPrice();
        $ctrl.changeSpecialInstructions();

        if (event) event.preventDefault();

    }

    $ctrl.round = function (number, digitsAfterDecimal) {
        //http://stackoverflow.com/questions/11832914/round-to-at-most-2-decimal-places
        return +(Math.round(number + "e+" + digitsAfterDecimal) + "e-" + digitsAfterDecimal);
    };

    $ctrl.tryLoadPreviewImage = function () {
        getPreviewRetryCounter += 1;
        $ctrl.imageUrl = "/image/shared/generating-preview.jpg";
        $http.get('/api/cart/getPreviewThumbnail',
            {
                params: {
                    DesignNumber: $ctrl.designNumber
                }
            }).then(function success(response) {
                if (response.data.PreviewStatus == "disabled") {
                    $ctrl.imageUrl = "/image/shared/no-preview.jpg";
                    getPreviewRetryCounter = 0;
                } else if (response.data.PreviewStatus == "created") {
                    $ctrl.imageUrl = response.data.PreviewUri;
                    getPreviewRetryCounter = 0;
                } else if (response.data.PreviewStatus == "processing") {
                    if (getPreviewRetryCounter <= 5) {
                        //increase the timeout by 1 second, every iteration
                        setTimeout(function () { $ctrl.tryLoadPreviewImage(); }, getPreviewRetryCounter * 1000);
                    } else {
                        getPreviewRetryCounter = 0;
                    }
                }
            }, function error(response) {
                $ctrl.imageUrl = "/image/shared/no-preview.jpg";
            });
    };

    $ctrl.showMaterialOptions = function () {

        if (typeof Handlebars != "undefined") {

            var materialOptions = jQuery("<div class='modal' />");

            Handlebars.fillElementWithTemplate(materialOptions, "material_options", {}, function () {
                materialOptions.modal();
            });
        }

    }

    function fitsIn(sizeOne, sizeTwo, containerOne, containerTwo) {
        return (sizeOne <= containerOne && sizeTwo <= containerTwo) || (sizeOne <= containerTwo && sizeTwo <= containerOne);
    }

    function getAddonChoices() {
        var addonChoices;
        if ($ctrl.productOption.Addons) {
            addonChoices = [];
            for (var i = 0; i < $ctrl.productOption.Addons.length; i++) {
                if ($ctrl.productOption.Addons[i].selected) addonChoices.push($ctrl.productOption.Addons[i].selected);
            }
        }
        return addonChoices;
    }

    // Init

    if (requireDesign && !$ctrl.designNumber) {

        $ctrl.showWarning = true;

    } else {

        $ctrl.loadProducts();
        if (tryLoadPreview) {
            $ctrl.tryLoadPreviewImage();
        }
    }

}]);



/*** Price List ***/



app.controller('priceListController', ['$http', '$attrs', '$rootScope', '$timeout', function ($http, $attrs, $rootScope, $timeout) {

    var $ctrl = this;

    $ctrl.ProductProductOptionId = $attrs.productProductOptionId;
    $ctrl.width = $attrs.sizeWidth;
    $ctrl.height = $attrs.sizeHeight;
    $ctrl.minQuantity = 1;
    $ctrl.maxQuantity = 1;
    $ctrl.listWidth = $ctrl.width;
    $ctrl.listHeight = $ctrl.height;
    $ctrl.quantities = $attrs.quantities.split(',').map(function (x) { return parseInt(x, 10); });
    $ctrl.prices = [];

    $ctrl.updatePrices = function () {

        if (!$ctrl.width || !$ctrl.height) {
            $ctrl.prices = [];
            return;
        }

        $ctrl.isUpdatingPrices = true;

        var pricesToCalc = [];

        var quantitiesToCalculate = angular.copy($ctrl.quantities);

        if ($ctrl.customQuantity && parseInt($ctrl.customQuantity)) {
            quantitiesToCalculate.push(parseInt($ctrl.customQuantity, 10));
            quantitiesToCalculate.sort(function (a, b) { return a - b });
        }

        for (var i = 0; i < quantitiesToCalculate.length; i++) {
            if (quantitiesToCalculate[i] && (!$ctrl.minQuantity || quantitiesToCalculate[i] >= $ctrl.minQuantity) && (!$ctrl.maxQuantity || quantitiesToCalculate[i] <= $ctrl.maxQuantity)) {
                pricesToCalc.push({
                    ProductProductOptionId: $ctrl.ProductProductOptionId,
                    Height: $ctrl.height,
                    Width: $ctrl.width,
                    Quantity: quantitiesToCalculate[i],
                    ProductOptionAddonOptionIds: $ctrl.addOns
                });
            }
        }

        var loadStarted = new Date();

        $http({
            method: 'POST',
            url: '/ssapi/prices/calcPrices',
            data: {
                PricesToCalc: pricesToCalc
            }
        }).then(function success(response) {

            $ctrl.isError = false;

            var loadFinished = new Date();
            var msElapsed = loadFinished - loadStarted;

            if (msElapsed < 300) {
                $timeout(function () {
                    $ctrl.isUpdatingPrices = false;
                    $ctrl.listWidth = $ctrl.width;
                    $ctrl.listHeight = $ctrl.height;
                    $ctrl.prices = response.data.Prices;
                }, 300 - msElapsed);
            } else {
                $ctrl.isUpdatingPrices = false;
                $ctrl.listWidth = $ctrl.width;
                $ctrl.listHeight = $ctrl.height;
                $ctrl.prices = response.data.Prices;
            }


        }, function error(response) {

            $ctrl.isError = true;
            $ctrl.isUpdatingPrices = false;
            $ctrl.prices = [];

        });
    };

    $ctrl.getUnitPrice = function (price, quantity) {
        return Math.ceil(100 * price / quantity) / 100;
    };

    $rootScope.$on('updatePriceList', function (e, data) {
        $ctrl.ProductProductOptionId = data.productProductOptionId;
        $ctrl.width = data.width;
        $ctrl.height = data.height;
        $ctrl.minQuantity = data.minQuantity;
        $ctrl.maxQuantity = data.maxQuantity;
        $ctrl.addOns = data.addOns;
        $ctrl.updatePrices();
    });

    $rootScope.$on('clearPriceList', function (e, data) {
        $ctrl.prices = [];
    });

}]);



/***Product Price Choice***/



app.controller('priceListChoicesController', ['$http', '$attrs', '$rootScope', '$timeout', function ($http, $attrs, $rootScope, $timeout) {

    var $ctrl = this;

    $ctrl.productOptions = [];
    $ctrl.selectedSKU = $attrs.initialSku;
    $ctrl.productGroup = 'custom-stickers';
    $ctrl.width = $attrs.sizeWidth;
    $ctrl.height = $attrs.sizeHeight;

    $ctrl.minWidth;
    $ctrl.maxWidth;
    $ctrl.minHeight;
    $ctrl.maxHeight;

    var productId = $attrs.productId;
    var addOtherToSizeList = $attrs.addOtherToSizeList;

    $ctrl.handleChangeSKU = function () {

        $ctrl.sizes = $ctrl.skus[$ctrl.selectedSKU].sizes;

        var reselectedSize = false;
        var otherSelected = false;

        if ($ctrl.sizeSelectedDropdown) {

            for (var i = 0; i < $ctrl.skus[$ctrl.selectedSKU].sizes.length; i++) {
                if ($ctrl.skus[$ctrl.selectedSKU].sizes[i].width == $ctrl.sizeSelectedDropdown.width && $ctrl.skus[$ctrl.selectedSKU].sizes[i].height == $ctrl.sizeSelectedDropdown.height) {
                    $ctrl.sizeSelected = $ctrl.skus[$ctrl.selectedSKU].sizes[i];
                    $ctrl.sizeSelectedDropdown = $ctrl.skus[$ctrl.selectedSKU].sizes[i];
                    reselectedSize = true;

                    if ($ctrl.sizeSelectedDropdown.isOther) {
                        otherSelected = true;
                    }

                }
            }
        }

        if (!reselectedSize) {
            $ctrl.sizeSelected = $ctrl.skus[$ctrl.selectedSKU].sizes[0];
            $ctrl.sizeSelectedDropdown = $ctrl.skus[$ctrl.selectedSKU].sizes[0];
        }

        $ctrl.minWidth = $ctrl.skus[$ctrl.selectedSKU].minWidth;
        $ctrl.maxWidth = $ctrl.skus[$ctrl.selectedSKU].maxWidth;
        $ctrl.minHeight = $ctrl.skus[$ctrl.selectedSKU].minHeight;
        $ctrl.maxHeight = $ctrl.skus[$ctrl.selectedSKU].maxHeight;
        $ctrl.hasOneSizeOther = $ctrl.skus[$ctrl.selectedSKU].hasOneSizeOther

        if (otherSelected) {
            $ctrl.loadPrices($ctrl.otherWidth, $ctrl.otherHeight);
        } else {
            $ctrl.loadPrices($ctrl.sizeSelected.width, $ctrl.sizeSelected.height);
        }

    };

    $ctrl.loadPrices = function (width, height) {

        $ctrl.width = width;

        if ($ctrl.skus[$ctrl.selectedSKU].hasOneSizeOther) {
            $ctrl.height = width;
        } else {
            $ctrl.height = height;
        }

        if (
            !$ctrl.width ||
            !$ctrl.height ||
            $ctrl.minWidth && $ctrl.width < $ctrl.minWidth ||
            $ctrl.minHeight && $ctrl.height < $ctrl.minHeight ||
            $ctrl.maxWidth && $ctrl.width > $ctrl.maxWidth ||
            $ctrl.maxHeight && $ctrl.height > $ctrl.maxHeight
        ) {
            $rootScope.$broadcast('clearPriceList');
        } else {
            $rootScope.$broadcast('updatePriceList', {
                productProductOptionId: $ctrl.skus[$ctrl.selectedSKU].productProductOptionId,
                addOns: $ctrl.skus[$ctrl.selectedSKU].addOns,
                width: $ctrl.width,
                height: $ctrl.height,
                minQuantity: $ctrl.skus[$ctrl.selectedSKU].minQuantity,
                maxQuantity: $ctrl.skus[$ctrl.selectedSKU].maxQuantity
            });
        }

    };

    $ctrl.logSizeChanged = function () {
        if (typeof ga_track_event == 'function') {
            ga_track_event('Product Detail Actions', 'Changed Size', $ctrl.sizeSelectedDropdown.width + 'x' + $ctrl.sizeSelectedDropdown.height);
        }
    };

    $http.get('/api/Products/GetProductSizeChoices').then(function success(response) {

        $ctrl.skus = [];

        for (var i = 0; i < response.data.length; i++) {

            if (productId && productId == response.data[i].ProductId.replace(/-/g, '')) {
                $ctrl.productOptions.push({
                    sku: response.data[i].Sku,
                    name: response.data[i].Name
                })
            }

            var sizes = [];

            for (var j = 0; j < response.data[i].SizeList.length; j++) {
                sizes.push({
                    width: response.data[i].SizeList[j].Width,
                    height: response.data[i].SizeList[j].Height,
                    text: response.data[i].SizeList[j].Text
                });
            }

            if (addOtherToSizeList) {
                sizes.push({ text: 'Other', isOther: true });
            }

            $ctrl.skus[response.data[i].Sku] = {
                productProductOptionId: response.data[i].ProductProductOptionId,
                minWidth: response.data[i].MinWidth,
                maxWidth: response.data[i].MaxWidth,
                minHeight: response.data[i].MinHeight,
                maxHeight: response.data[i].MaxHeight,
                minQuantity: response.data[i].MinQuantity,
                maxQuantity: response.data[i].MaxQuantity,
                addOns: response.data[i].AddonsChoices,
                sizes: sizes,
                hasOneSizeOther: response.data[i].IsOneToOneAspectRatio
            };
        }

        if ($ctrl.selectedSKU) {
            $ctrl.handleChangeSKU();
        }

    }, function error(response) {

    });

}]);

app.controller('singlePriceChoicesController', ['$http', '$attrs', '$rootScope', '$timeout', function ($http, $attrs, $rootScope, $timeout) {

    var $ctrl = this;

    $ctrl.productId = $attrs.productId;
    $ctrl.initialSKU = $attrs.initialSku;

    $ctrl.width = $attrs.sizeWidth;
    $ctrl.height = $attrs.sizeHeight;

    $ctrl.productOptions = [];
    $ctrl.sizeOptions = {
        'Sign-PaperLightweightMatte': {
            sizes: [
                { width: 36, height: 24, text: '36" x 24"' },
                { width: 48, height: 36, text: '48" x 36"' },
                { isOther: true, text: 'Other' }
            ]
        },
        'Sign-PaperHeavyweightMatte': {
            sizes: [
                { width: 36, height: 24, text: '36" x 24"' },
                { width: 48, height: 36, text: '48" x 36"' },
                { isOther: true, text: 'Other' }
            ]
        },
        'Sign-PaperHeavyweightGlossy': {
            sizes: [
                { width: 36, height: 24, text: '36" x 24"' },
                { width: 48, height: 36, text: '48" x 36"' },
                { isOther: true, text: 'Other' }
            ]
        },
        'Sign-SelfAdhesivePoster': {
            sizes: [
                { width: 16, height: 24, text: '16" x 24"' },
                { width: 24, height: 16, text: '24" x 16"' },
                { width: 24, height: 36, text: '24" x 36"' },
                { width: 36, height: 24, text: '36" x 24"' },
                { width: 48, height: 36, text: '36" x 48"' },
                { width: 48, height: 36, text: '48" x 36"' },
                { isOther: true, text: 'Other' }
            ]
        },
        'Poster-GlossyPaper': {
            sizes: [
                { width: 42, height: 36, text: '42" x 36"' },
                { width: 48, height: 36, text: '48" x 36"' },
                { width: 54, height: 36, text: '54" x 36"' },
                { width: 56, height: 36, text: '56" x 36"' },
                { width: 72, height: 36, text: '72" x 36"' },
                { isOther: true, text: 'Other' }
            ]
        },
        'Poster-MattePaper': {
            sizes: [
                { width: 42, height: 36, text: '42" x 36"' },
                { width: 48, height: 36, text: '48" x 36"' },
                { width: 54, height: 36, text: '54" x 36"' },
                { width: 56, height: 36, text: '56" x 36"' },
                { width: 72, height: 36, text: '72" x 36"' },
                { isOther: true, text: 'Other' }
            ]
        },
        'Poster-Fabric': {
            sizes: [
                { width: 42, height: 36, text: '42" x 36"' },
                { width: 48, height: 36, text: '48" x 36"' },
                { width: 54, height: 36, text: '54" x 36"' },
                { width: 56, height: 36, text: '56" x 36"' },
                { width: 72, height: 36, text: '72" x 36"' },
                { isOther: true, text: 'Other' }
            ]
        },
        'Poster-Trifold': {
            sizes: [
                { width: 48, height: 36, text: '48" x 36"' }
            ]
        }
    };

    $ctrl.loadSKU = function (sku) {

        $ctrl.selectedSKU = sku;
        $ctrl.ProductProductOptionId = $ctrl.sizeOptions[sku].productProductOptionId;

        $ctrl.sizeList = $ctrl.sizeOptions[sku].sizes;

        if ($ctrl.sizeList.length == 1) {
            $ctrl.sizeSelectedDropdown = $ctrl.sizeList[0];
            $ctrl.width = $ctrl.sizeList[0].width;
            $ctrl.height = $ctrl.sizeList[0].height;
        } else {
            for (var i = 0; i < $ctrl.sizeList.length; i++) {
                if (!$ctrl.sizeList[i].isOther && $ctrl.sizeList[i].width == $ctrl.width && $ctrl.sizeList[i].height == $ctrl.height) {
                    $ctrl.sizeSelectedDropdown = $ctrl.sizeList[i];
                }
            }
        }

        $ctrl.minWidth = $ctrl.sizeOptions[sku].minWidth;
        $ctrl.maxWidth = $ctrl.sizeOptions[sku].maxWidth;
        $ctrl.minHeight = $ctrl.sizeOptions[sku].minHeight;
        $ctrl.maxHeight = $ctrl.sizeOptions[sku].maxHeight;

        $ctrl.loadPrice();

    };

    $ctrl.loadPrice = function () {

        $ctrl.sizeError = false;

        $timeout(function () {

            if (!$ctrl.width || !$ctrl.height) {

                $ctrl.price = 0;

            } else if (
                $ctrl.minWidth && Math.min($ctrl.width, $ctrl.height) < $ctrl.minWidth ||
                $ctrl.minHeight && Math.max($ctrl.width, $ctrl.height) < $ctrl.minHeight ||
                $ctrl.maxWidth && Math.min($ctrl.width, $ctrl.height) > $ctrl.maxWidth ||
                $ctrl.maxHeight && Math.max($ctrl.width, $ctrl.height) > $ctrl.maxHeight
            ) {

                $ctrl.sizeError = true;
                $ctrl.price = 0;

            } else {

                $ctrl.isUpdatingPrice = true;

                var pricesToCalc = [];

                var loadStarted = new Date();

                $http({
                    method: 'GET',
                    url: '/ssapi/prices/calcPrice',
                    params: {
                        ProductProductOptionId: $ctrl.ProductProductOptionId,
                        Height: $ctrl.height,
                        Width: $ctrl.width,
                        Quantity: 1
                    }
                }).then(function success(response) {

                    $ctrl.isError = false;

                    var loadFinished = new Date();
                    var msElapsed = loadFinished - loadStarted;

                    if (msElapsed < 300) {
                        $timeout(function () {
                            $ctrl.isUpdatingPrice = false;
                            $ctrl.price = response.data.ListPrice;
                        }, 300 - msElapsed);
                    } else {
                        $ctrl.isUpdatingPrice = false;
                        $ctrl.price = response.data.ListPrice;
                    }


                }, function error(response) {

                    $ctrl.isError = true;
                    $ctrl.isUpdatingPrice = false;
                    $ctrl.price = 0;

                });

            }


        }, 1);
    };

    $ctrl.logOptionChanged = function () {
        if (typeof ga_track_event == 'function') {
            ga_track_event('Product Detail Actions', 'Changed Option', $ctrl.selectedSKU);
        }
    };

    $ctrl.logSizeChanged = function () {
        if (typeof ga_track_event == 'function') {
            if ($ctrl.sizeSelectedDropdown.isOther) {
                ga_track_event('Product Detail Actions', 'Changed Size', 'Other');
            } else {
                ga_track_event('Product Detail Actions', 'Changed Size', $ctrl.sizeSelectedDropdown.width + 'x' + $ctrl.sizeSelectedDropdown.height);
            }
        }
    };

    $http.get('/ssapi/productOptions/find').then(function success(response) {

        for (var i = 0; i < response.data.Products.length; i++) {
            for (var j = 0; j < response.data.Products[i].Options.length; j++) {
                var option = response.data.Products[i].Options[j];

                if ($ctrl.sizeOptions[option.SKU]) {

                    if ($ctrl.productId == option.ProductId) {
                        $ctrl.productOptions.push({
                            name: option.Name,
                            sku: option.SKU
                        });
                    }

                    $ctrl.sizeOptions[option.SKU].minWidth = option.MinWidth;
                    $ctrl.sizeOptions[option.SKU].maxWidth = option.MaxWidth;
                    $ctrl.sizeOptions[option.SKU].minHeight = option.MinHeight;
                    $ctrl.sizeOptions[option.SKU].maxHeight = option.MaxHeight;
                    $ctrl.sizeOptions[option.SKU].productProductOptionId = option.Id;

                }

            }
        }

        $ctrl.loadSKU($ctrl.productOptions[0].sku);

    }, function error(response) {

        window.graphicsland.showError("Could not load products");

    });

}]);

app.controller('orderTotalsController', ['$http', '$attrs', '$rootScope', function ($http, $attrs, $rootScope) {

    var $ctrl = this;

    $ctrl.subtotal = $attrs.subtotal;
    $ctrl.rushFee = $attrs.rushFee;
    $ctrl.discountName = $attrs.discountName;
    $ctrl.discountAmount = $attrs.discountAmount;
    $ctrl.discountResult = $attrs.discountResult;
    $ctrl.discountResultMessage = $attrs.discountResultMessage;
    $ctrl.shipping = $attrs.shipping;
    $ctrl.tax = $attrs.tax;
    $ctrl.total = $attrs.total;

    $rootScope.$on('updateOrderTotals', function (e, data) {

        $ctrl.subtotal = data.subtotal;
        $ctrl.rushFee = data.rushFee;
        $ctrl.discountName = data.discountName;
        $ctrl.discountAmount = data.discountAmount;
        $ctrl.discountResult = data.discountResult;
        $ctrl.discountResultMessage = data.discountResultMessage;
        $ctrl.shipping = data.shipping;
        $ctrl.tax = data.tax;
        $ctrl.total = data.total;

    });

}]);;
// @reference app.helpers.js

/***
*    ███████╗██╗     ███████╗███╗   ███╗███████╗███╗   ██╗████████╗███████╗
*    ██╔════╝██║     ██╔════╝████╗ ████║██╔════╝████╗  ██║╚══██╔══╝██╔════╝
*    █████╗  ██║     █████╗  ██╔████╔██║█████╗  ██╔██╗ ██║   ██║   ███████╗
*    ██╔══╝  ██║     ██╔══╝  ██║╚██╔╝██║██╔══╝  ██║╚██╗██║   ██║   ╚════██║
*    ███████╗███████╗███████╗██║ ╚═╝ ██║███████╗██║ ╚████║   ██║   ███████║
*    ╚══════╝╚══════╝╚══════╝╚═╝     ╚═╝╚══════╝╚═╝  ╚═══╝   ╚═╝   ╚══════╝
*                                                                          
*/

function initElement_templatecarousel($caller) {
    
    var left = $('<span class="left carousel-control"><span class="glyphicon glyphicon-chevron-left"></span></span>');
    var right = $('<span class="right carousel-control"><span class="glyphicon glyphicon-chevron-right"></span></span>');

    left.click(function () {
        $(this).closest(".carousel").carousel("prev");
        return false;
    });

    right.click(function () {
        $(this).closest(".carousel").carousel("next");
        return false;
    });

    $caller.append(left, right);

    var options = {
        pause: true,
        interval: false
    };

    if ($caller.data("carousel-options-pause")) options.pause = $caller.data("carousel-options-pause");
    if ($caller.data("carousel-options-interval")) options.pause = $caller.data("carousel-options-interval");

    $caller.carousel(options);
}

function initElement_orderhistory($caller) {
    
    $caller.find(".js-order-items-show").click(function () {
        $(this).closest(".js-order").toggleClass("collapsed");
        return false;
    });

    $caller.find(".js-order-items-show-all input").click(function () {
        if ($(this).is(":checked")) {
            $caller.find(".js-order").removeClass("collapsed");
        } else {
            $caller.find(".js-order").addClass("collapsed");
        }
    });
    $caller.find(".js-order-items-show-all input").click().click(); //click twice to get back to original state.
}

function initElement_topmessagebar($caller) {
    $caller.find(".js-close").click(function () {
        $.cookie($caller.data("cookie"), $caller.data("sessionid"), {expires: 30});
        $caller.hide();
    });
}

function initElement_statechooser($caller) {

    $caller.attr("autocomplete", "off");
    $caller.attr("autocorrect", "off");
    $caller.attr("autocapitalize", "off");
    $caller.attr("spellcheck", "off");

    $caller.typeahead({
        hint: true,
        highlight: true,
        minLength: 0
    }, {
        name: 'states',
        displayKey: 'code',
        source: autoCompleteStates.ttAdapter(),
        templates: {
            suggestion: Handlebars.compile("<p>{{code}} ({{name}})</p>")
        }
    });

    $caller.on("typeahead:selected", function (a) {
        var validators = $caller.data("associated_validators");
        for (var i = 0; i < validators.length; i++) {
            var $validator = $("#" + validators[i]);
            ValidatorValidate($validator[0]);
        }
    });
}

function initElement_checkoutsidebar($caller) {
    $caller.find(".js-order-item-thumb").css("display", "none").removeClass("hidden");
    $caller.find(".js-show-thumb, .js-order-item-thumb").click(function () {
        $(this).closest("li").find(".js-order-item-thumb").slideToggle(function () {
            $.publish("app/elements/stickysidebar");
        });
        return false;
    });
}

function initElement_stickysidebar($caller) {

    $caller.addClass("sticky-sidebar");

    function updateStickySidebar() {
        var $parent = $caller.closest(".row");
        var top = $(window).scrollTop() + $("#main-header").height() - $parent.offset().top + 15; //15px top padding
        var maxtop = $parent.height() - $caller.height();

        if (maxtop <= 0) {
            $parent.css("min-height", $caller.height() + "px");
            maxtop = 0;
        }

        if ($caller.height() > $(window).height()) top = 0;

        if ($(window).width() > 991) {
            $caller.parent().css("padding-top", $caller.height() + "px");
        } else {
            $caller.parent().css("padding-top", "0");
        }

        $caller.css("top", Math.max(Math.min(top, maxtop), 0));
    }

    $(window).scroll(function () {
        updateStickySidebar();
    });
    $.subscribe("app/elements/stickysidebar", updateStickySidebar);

    $(function () {
        updateStickySidebar();
    });
    
}

function initElement_deliverycalculator($caller) {

    var timeleft = moment.duration($caller.data("timeRemaining"));
    var $timeleft_el = $caller.find(".time");

    function updateOrderCountdown() {
        timeleft.subtract(1, 'seconds');

        var output = "";
        output += addOutput(timeleft.days(), "day");
        output += addOutput(timeleft.hours(), "hour");
        output += addOutput(timeleft.minutes(), "minute");

        if (timeleft.days() === 0 && timeleft.hours() === 0 && timeleft.minutes() <= 10) {
            output += addOutput(timeleft.seconds(), "second");
        }

        if (output === "") { //ran out of time, let's get a new time
            var reload_link = $('<a href="#">click to reload calculator</a>');
            reload_link.click(function () {
                window.location = window.location.href;
            });
            $caller.empty().append(reload_link);
            clearInterval(calculator_timer);
        }

        $timeleft_el.text(output.substring(0, output.length - 2)); //substring takes off last ", "
    }

    function addOutput(time, timeunit) {
        if (time > 1) return time + " " + timeunit + "s, ";
        else if (time == 1) return time + " " + timeunit + ", ";
        else return "";
    }

    var calculator_timer = setInterval(function () {
        updateOrderCountdown();
    }, 1000);

    updateOrderCountdown();
}

function initElement_deliverydatecalc($caller) {

    var productProductOptionId = $caller.data("productProductOptionId");

    function calculateDeliveryDate() {

        var ordertime = moment($caller.find(".js-deliverycalc-date").val(), "MM/DD/YYYY");
        if ($caller.find(".js-deliverycalc-time").val() == "PM") {
            ordertime.hour(13);
        }

        $caller.find(".js-deliverycalc-result").html('<img src="https://glimages.s3.amazonaws.com/image/shared/bounce-loading.gif" />');

        $.ajax({
            type: "GET",
            url: "/ssapi/production/calcProductionTime",
            data: {
                ProductProductOptionId: productProductOptionId,
                ProductionStartDate: ordertime.toISOString(),
                ShippingMethodId: $caller.find(".js-deliverycalc-shippingservice").val()
            },
            success: function (data) {
                if (data) {
                    $caller.find(".js-deliverycalc .alert").remove();
                    $caller.find(".js-deliverycalc-result").text(moment(data.DeliveryDate).format('dddd, MMMM D'));
                } else {
                    $caller.find(".js-deliverycalc").append('<div class="alert alert-danger">Delivery date could not be calculated. Please contact supprt.</div>');
                    $caller.find(".js-deliverycalc-result").empty();
                }
            },
            dataType: 'json'
        });
    }

    $caller.find(".js-deliverycalc-date").datepicker({
        startDate: "+0d",
        endDate: "+3m",
        autoclose: true
    }).on("changeDate", function () {
        calculateDeliveryDate();
    });

    $caller.find(".js-deliverycalc-time, .js-deliverycalc-shippingservice").change(function () {
        calculateDeliveryDate();
    });

    calculateDeliveryDate();

}

function initElement_contactform($caller) {

    var status_div = $('<div class="text-center" />');
    $caller.after(status_div);

    $caller.find(".js-contact-submit-button").click(function (e) {
        
        var button = $(this);

        if (Page_ClientValidate($caller.data("validationGroup"))) {

            status_div.empty().append($('<img src="https://glimages.s3.amazonaws.com/image/shared/loading.gif" />'));

            var defaults = JSON.parse($caller.find(".js-contactus-sessionvars input").val());

            var user_inputs = {
                'Name': $caller.find(".js-contactus-name").val(),
                'Email': $caller.find(".js-contactus-email").val(),
                'Phone': $caller.find(".js-contactus-phone").val(),
                'OrderNumber': $caller.find(".js-contactus-ordernumber").val(),
                'Subject': $caller.find(".js-contactus-subject").val(),
                'Comments': $caller.find(".js-contactus-comments").val(),
                'Title': $caller.find(".js-contactus-title").val(),
                'Industry': $caller.find(".js-contactus-industry").val(),
                'Company': $caller.find(".js-contactus-company").val(),
                'NumberOfStores': $caller.find(".js-contactus-numberofstores").val(),
                'Website': $caller.find(".js-contactus-website").val(),
                'Timestamp': $caller.find(".js-contactus-timeticks input").val(),
                'FeedbackRating': $caller.find(".js-contactus-feedback input:checked").val()
            };

            button.prop("disabled", true);

            var api_call_in_progress = true;

            $.post('/api/misc/PostSendContactMessage', $.extend(defaults, user_inputs), function (data) {

                button.prop("disabled", false);
                api_call_in_progress = false;

                if (data.Success) {
                    status_div.empty().attr("class", "bump-top alert alert-success").text(data.Message);
                    $caller.find(".js-contactus-comments").val("");
                    $caller.hide();
                    $("#js-main-contactus-modal").on("hidden.bs.modal", function () {
                        status_div.empty().attr("class", "");
                        $caller.show();
                    });
                } else {
                    status_div.empty().attr("class", "bump-top alert alert-danger").text(data.Message);
                }
            }, 'json');

            setTimeout(function () {
                if (api_call_in_progress) {
                    button.prop("disabled", false);
                    status_div.empty().attr("class", "bump-top alert alert-success").text("Thank you for your message");
                    $caller.find(".js-contactus-comments").val("");
                    $caller.hide();
                    $("#js-main-contactus-modal").on("hidden.bs.modal", function () {
                        status_div.empty().attr("class", "");
                        $caller.show();
                    });
                }
            }, 5000);

        }

        return false;
    });

}


function initElement_instagramfeed($caller) {

    $caller.hover(function () {
        $(this).addClass("hovered");
    }, function () {
        $(this).removeClass("hovered");
    });

    var offset = 187;
    if ($caller.data("tilewidth")) {
        offset = $caller.data("tilewidth");
    }

    $.ajax({
        type: "GET",
        url: "/ssapi/get-instagram-token",
        success: function (data) {
            createFeed(data.Token);
        },
        dataType: "json"
    });

    function createFeed(token) {

        var feed = new Instafeed({
            'accessToken': token,
            'limit': 10,
            'after': function () {
                var left = 0;
                $caller.find("a").each(function () {
                    $(this).attr("target", "_blank").css("left", left).data("left", left); //we use data so we can do maths
                    left += offset;
                });
                left -= offset;

                //we do't run on the first iteration so the element doesn't weirdly disappear
                var first = true;

                setInterval(function () {
                    if (!$caller.hasClass("hovered")) {

                        if (!first) $caller.append($caller.find("a:first").data("left", left)); //take first element and append to the end
                        $caller.find("a").each(function () { //shift everything over one slot
                            var newleft = $(this).data("left") - offset;
                            $(this).css("left", newleft).data("left", newleft);

                        });
                        first = false;

                    }

                }, 2000);
            }
        });

        feed.run();

    }
    
}

function initElement_mailchimpsignup($caller) {

    $caller.find(".js-mailchimp-form").after('<div class="response js-mailchimp-response" />');

    $caller.find("#mc-embedded-subscribe").click(function () {

        $.ajax({
            'type': 'POST',
            'url': $caller.data("target"),
            'data': $caller.find("input").serialize(),
            'dataType': 'json',
            'success': function (data) {
                if (data.result == "success") {
                    $caller.find(".js-mailchimp-response").removeClass("error").addClass("success").html(data.msg);
                } else {
                    $caller.find(".js-mailchimp-response").removeClass("success").addClass("error").html(data.msg.replace("0 - ", ""));
                }
            }
        });

        return false;

    });

}

function initElement_socialsharing($caller) {

    $caller.updateSharingLink = function ($caller) {
        $caller.sharer({
            title: $caller.data("title"),
            url: $caller.find(".js-share-link").val(),
            description: $caller.data("description"),
            track_label: $caller.data("page")
        });
    };

    $caller.removeClass("hidden");
    $caller.updateSharingLink($caller);

    //store a reference to self so function can be called elsewhere
    $caller.data("self", $caller);

}


function initElement_faqcollapse($caller) {

    $caller.find("h2 a").click(function () {
        $(this).find(".glyphicon").toggleClass("rotate-90");
    });

    $caller.find(".questions li p, .questions li .answer").addClass("soft-hidden");
    $caller.find(".questions li h4").click(function () {
        var target = $(this).closest("li").find("p, .answer");

        if (target.hasClass("active")) {
            target.slideUp().removeClass("active");
        } else {
            $caller.find(".questions li p.active, .questions li .answer.active").slideUp().removeClass("active");
            target.slideDown().addClass("active");
        }

        if (typeof ga_track_event == 'function') {
            ga_track_event("Actions", "Clicked FAQ", $(this).text());
        }

    });

}

function initElement_faqsearch($caller) {

    var noresults = $(".js-faq-search-noresults");

    $.expr[":"].contains_nc = $.expr.createPseudo(function (arg) {
        return function (elem) {
            return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
        };
    });

    $caller.find(".js-faq-search-text").on("keydown keypress keyup", function (e) {
        if (e.keyCode == 13) {
            e.preventDefault();
        }
    });

    $caller.find(".js-faq-search-text").keyup(function () {
        var str = $(this).val();

        if (str.length > 2) {

            $("#faq-sections h2").addClass("hidden");
            $("ul.questions").addClass("search-results").removeAttr("style");
            $("ul.questions > li").addClass("hidden");
            $("ul.questions > li p").addClass("soft-hidden");

            var results = $("ul.questions > li:contains_nc(" + str + "):not(.js-hide-from-search)");
            results.removeClass("hidden");
            results.find("p").removeClass("soft-hidden");

            if (results.length === 0) {
                noresults.removeClass("hidden");
            } else {
                noresults.addClass("hidden");
            }

        } else {

            $("#faq-sections h2").removeClass("hidden");
            $(".questions").removeClass("search-results");
            $("ul.questions > li").removeClass("hidden");
            $("ul.questions > li p").addClass("soft-hidden");

            noresults.addClass("hidden");

        }

        return false;
    });

}

function initElement_productreview($caller) {

    var rating = $caller.data("rating");

    function setStars(setRating, setClass) {

        $caller.find(".js-star").addClass("glyphicon-star-empty").removeClass("glyphicon-star");

        var stars = $caller.find(".js-star").slice(0, setRating);

        stars.addClass(setClass + " " + "glyphicon-star").removeClass("glyphicon-star-empty");

    }

    function clearMessage() {

        $caller.find(".js-review-message").text("").removeClass("alert-info alert-success alert-warning alert-danger").addClass("hidden");

    }

    function showMessage(text, alertClass) {
        clearMessage();

        $caller.find(".js-review-message").text(text).removeClass("hidden").addClass(alertClass);
    }

    $caller.find(".js-star").hover(function () {

        setStars($(this).data("rating"), "star-hover");

    }, function () {

        $caller.find(".js-star").removeClass("star-hover");
        setStars(rating);

    });

    $caller.find(".js-star").click(function () {

        rating = $(this).data("rating");

        setStars(rating);

    });

    $caller.find(".js-review-save").click(function () {

        var button = $(this);

        var review = {
            FeedbackId: $caller.data("feedbackid"),
            ProductProductOptionId: $caller.data("productProductOptionId"),
            Rating: rating,
            Name: $caller.find(".js-review-name").val(),
            Title: $caller.find(".js-review-title").val(),
            Comments: $caller.find(".js-review-comments").val(),
            OrderNumber: $caller.data("ordernumber"),
            CartId: $caller.data("cartid")
        };

        //validate

        if (review.Rating == 0) {
            showMessage("Choose a star rating", "alert-danger");
            return false;
        }

        if (!review.Name) {
            showMessage("Enter your name", "alert-danger");
            return false;
        }

        clearMessage();

        button.prop("disabled", true);

        $.ajax({
            type: "POST",
            url: "/api/Products/PostProductReview",
            data: review,
            success: function (data) {

                button.prop("disabled", false);

                if (data.Success == "false") showMessage(data.Message, "alert-danger");
                else {

                    if (data.WasNegative) {
                        $caller.find(".js-review-success-negative").removeClass("hidden");
                    } else {
                        $caller.find(".js-review-success").removeClass("hidden");
                    }

                    $caller.find(".js-review-form, .js-review-save").addClass("hidden");
                    $caller.data("feedbackid", data.FeedbackId);
                }

            },
            error: function () {

                button.prop("disabled", false);

                showMessage("We had a problem saving your review. Please contact customer support.", "alert-danger");

            }
        });


    });

    setStars(rating);

}

function initElement_pickupnameedit($caller) {

    function clearMessage() {

        $caller.find(".js-pickupname-message").text("").removeClass("alert-info alert-success alert-warning alert-danger").addClass("hidden");

    }

    function showMessage(text, alertClass) {
        clearMessage();

        $caller.find(".js-pickupname-message").text(text).removeClass("hidden").addClass(alertClass);
    }


    $caller.find(".js-pickupname-save").click(function () {

        var button = $(this);

        var request = {
            OrderItemId: $caller.data("orderItemId"),
            CartId: $caller.data("cartId"),
            FirstName: $caller.find(".js-pickupname-first").val(),
            LastName: $caller.find(".js-pickupname-last").val()
        };

        //validate

        if (!request.FirstName || !request.LastName) {
            showMessage("Please enter a first and last name", "alert-danger");
            return false;
        }

        clearMessage();

        button.prop("disabled", true);

        $.ajax({
            type: "POST",
            url: "/api/Order/PostUpdatePickupName",
            data: request,
            success: function (data) {

                button.prop("disabled", false);

                if (data.IsSuccess == "false") {

                    showMessage(data.Message, "alert-danger");

                } else {

                    showMessage("Your name has been updated!", "alert-success");

                }

            },
            error: function () {

                button.prop("disabled", false);

                showMessage("We had a problem saving your pickup name. Please contact customer support.", "alert-danger");

            }
        });

    });

};
function ga_track_event(category, action, label, value, noninteraction) {
    if (!noninteraction) noninteraction = false;
    if (category && action) {
        gtag('event', action, {
            'event_category': category,
            'event_label': label,
            'event_value': value,
            'non_interaction': noninteraction
        });
    }
}

function is_touch_device() {
    return 'ontouchstart' in window // works on most browsers 
      || 'onmsgesturechange' in window; // works on ie10
}

function getCanadianProvinces() {
    return [
        { name: "Alberta", code: "AB" },
        { name: "British Columbia", code: "BC" },
        { name: "Manitoba", code: "MB" },
        { name: "New Brunswick", code: "NB" },
        { name: "Newfoundland and Labrador", code: "NL" },
        { name: "Northwest Territories", code: "NT" },
        { name: "Nova Scotia", code: "NS" },
        { name: "Nunavut", code: "NU" },
        { name: "Ontario", code: "ON" },
        { name: "Prince Edward Island", code: "PE" },
        { name: "Quebec", code: "QC" },
        { name: "Saskatchewan", code: "SK" },
        { name: "Yukon", code: "YT" }
    ];
}

function getStatesWithPostalCode() {
    return [
        { name: "Alabama", code: "AL" }, { name: "Alaska", code: "AK" }, { name: "American Samoa", code: "AS" }, { name: "Arizona", code: "AZ" },
        { name: "Arkansas", code: "AR" }, { name: "Armed Forces Europe", code: "AE" }, { name: "Armed Forces Pacific", code: "AP" },
        { name: "Armed Forces the Americas", code: "AA" }, { name: "California", code: "CA" }, { name: "Colorado", code: "CO" },
        { name: "Connecticut", code: "CT" }, { name: "Delaware", code: "DE" }, { name: "District of Columbia", code: "DC" },
        { name: "Federated States of Micronesia", code: "FM" }, { name: "Florida", code: "FL" }, { name: "Georgia", code: "GA" },
        { name: "Guam", code: "GU" }, { name: "Hawaii", code: "HI" }, { name: "Idaho", code: "ID" }, { name: "Illinois", code: "IL" },
        { name: "Indiana", code: "IN" }, { name: "Iowa", code: "IA" }, { name: "Kansas", code: "KS" }, { name: "Kentucky", code: "KY" },
        { name: "Louisiana", code: "LA" }, { name: "Maine", code: "ME" }, { name: "Marshall Islands", code: "MH" }, { name: "Maryland", code: "MD" },
        { name: "Massachusetts", code: "MA" }, { name: "Michigan", code: "MI" }, { name: "Minnesota", code: "MN" }, { name: "Mississippi", code: "MS" },
        { name: "Missouri", code: "MO" }, { name: "Montana", code: "MT" }, { name: "Nebraska", code: "NE" }, { name: "Nevada", code: "NV" },
        { name: "New Hampshire", code: "NH" }, { name: "New Jersey", code: "NJ" }, { name: "New Mexico", code: "NM" }, { name: "New York", code: "NY" },
        { name: "North Carolina", code: "NC" }, { name: "North Dakota", code: "ND" }, { name: "Northern Mariana Islands", code: "MP" },
        { name: "Ohio", code: "OH" }, { name: "Oklahoma", code: "OK" }, { name: "Oregon", code: "OR" }, { name: "Palau", code: "PW" }, { name: "Pennsylvania", code: "PA" },
        { name: "Puerto Rico", code: "PR" }, { name: "Rhode Island", code: "RI" }, { name: "South Carolina", code: "SC" },
        { name: "South Dakota", code: "SD" }, { name: "Tennessee", code: "TN" }, { name: "Texas", code: "TX" }, { name: "Utah", code: "UT" },
        { name: "Vermont", code: "VT" }, { name: "Virgin Islands, U.S.", code: "VI" }, { name: "Virginia", code: "VA" }, { name: "Washington", code: "WA" },
        { name: "West Virginia", code: "WV" }, { name: "Wisconsin", code: "WI" }, { name: "Wyoming", code: "WY" }
    ];
}

var autoCompleteStates = new Bloodhound({
    datumTokenizer: function (data) {
        var nameTokens = Bloodhound.tokenizers.whitespace(data.name);
        var codeTokens = Bloodhound.tokenizers.whitespace(data.code);
        return nameTokens.concat(codeTokens);
    },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: getStatesWithPostalCode()
});

function check_levenshtein(s1, s2) {
    var matrix = [], row = [], cols = s2.length + 1, rows = s1.length + 1, i, j;
    while (cols--) row.push(0);
    while (rows--) matrix.push(row.slice());

    for (i = 1; i <= s1.length; i++) {
        matrix[i][0] = i;
    }

    for (i = 1; i <= s2.length; i++) {
        matrix[0][i] = i;
    }

    for (j = 1; j <= s2.length; j++) {
        for (i = 1; i <= s1.length; i++) {
            if (s1[i - 1] == s2[j - 1]) {
                matrix[i][j] = matrix[i - 1][j - 1];
            } else {
                matrix[i][j] = Math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + 1);
            }
        }
    }

    var longer = Math.max(s1.length, s2.length);

    return 100 - (100 * (matrix[i - 1][j - 1]) / longer);

}

function copyToClipboard(elem) {

    //adapted from: http://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery

    //make sure element exists and is something that text can be copied from
    if (!(elem.tagName === "INPUT" || elem.tagName === "TEXTAREA")) return;

    // select the content
    var currentFocus = document.activeElement;
    var origSelectionStart = elem.selectionStart;
    var origSelectionEnd = elem.selectionEnd;
    elem.focus();
    elem.setSelectionRange(0, elem.value.length);

    // copy the selection
    var succeed;
    try {
        succeed = document.execCommand("copy");
    } catch (e) {
        succeed = false;
    }

    //restore
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }
    elem.setSelectionRange(origSelectionStart, origSelectionEnd);

    return succeed;
};
// @reference app.elements.js
// @reference app.helpers.js

/***
 *     ██████╗ ██╗      ██████╗ ██████╗  █████╗ ██╗         ███████╗ ██████╗██████╗ ██╗██████╗ ████████╗███████╗
 *    ██╔════╝ ██║     ██╔═══██╗██╔══██╗██╔══██╗██║         ██╔════╝██╔════╝██╔══██╗██║██╔══██╗╚══██╔══╝██╔════╝
 *    ██║  ███╗██║     ██║   ██║██████╔╝███████║██║         ███████╗██║     ██████╔╝██║██████╔╝   ██║   ███████╗
 *    ██║   ██║██║     ██║   ██║██╔══██╗██╔══██║██║         ╚════██║██║     ██╔══██╗██║██╔═══╝    ██║   ╚════██║
 *    ╚██████╔╝███████╗╚██████╔╝██████╔╝██║  ██║███████╗    ███████║╚██████╗██║  ██║██║██║        ██║   ███████║
 *     ╚═════╝ ╚══════╝ ╚═════╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝    ╚══════╝ ╚═════╝╚═╝  ╚═╝╚═╝╚═╝        ╚═╝   ╚══════╝
 *
 */

"use strict";

window.graphicsland = window.graphicsland || {};

window.graphicsland.init = function () {

    function execute(level, functionName, caller) {
        var fn = window['init' + level + '_' + functionName.toLowerCase()];
        if (typeof fn === 'function') {
            fn($(caller));
        }
    }

    // Load Common Functions
    initPage_All();

    // Load Page Functions
    execute("Page", $("body").data("pageId"));

    // Load Element Functions
    $("[data-control-name]").each(function () {
        execute("Element", $(this).data("control-name"), this);
    });

}

window.graphicsland.showError = function (additionalMessage) {
    var message = '<h4>Something went wrong :(</h3><p>Please try again, or <a href="/contact">contact our support team</a> if you continue to have issues.</p>';
    if (additionalMessage) {
        message += '<h5>Error Details</h5><p>' + additionalMessage + '</p>'
    }
    if (bootbox) {
        bootbox.alert(message);
    }
}


/* End Execute Page Functionality */


/***
*     ██████╗ ██████╗ ███╗   ███╗███╗   ███╗ ██████╗ ███╗   ██╗    ██████╗  █████╗  ██████╗ ███████╗    ███████╗ ██████╗██████╗ ██╗██████╗ ████████╗███████╗
*    ██╔════╝██╔═══██╗████╗ ████║████╗ ████║██╔═══██╗████╗  ██║    ██╔══██╗██╔══██╗██╔════╝ ██╔════╝    ██╔════╝██╔════╝██╔══██╗██║██╔══██╗╚══██╔══╝██╔════╝
*    ██║     ██║   ██║██╔████╔██║██╔████╔██║██║   ██║██╔██╗ ██║    ██████╔╝███████║██║  ███╗█████╗      ███████╗██║     ██████╔╝██║██████╔╝   ██║   ███████╗
*    ██║     ██║   ██║██║╚██╔╝██║██║╚██╔╝██║██║   ██║██║╚██╗██║    ██╔═══╝ ██╔══██║██║   ██║██╔══╝      ╚════██║██║     ██╔══██╗██║██╔═══╝    ██║   ╚════██║
*    ╚██████╗╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║╚██████╔╝██║ ╚████║    ██║     ██║  ██║╚██████╔╝███████╗    ███████║╚██████╗██║  ██║██║██║        ██║   ███████║
*     ╚═════╝ ╚═════╝ ╚═╝     ╚═╝╚═╝     ╚═╝ ╚═════╝ ╚═╝  ╚═══╝    ╚═╝     ╚═╝  ╚═╝ ╚═════╝ ╚══════╝    ╚══════╝ ╚═════╝╚═╝  ╚═╝╚═╝╚═╝        ╚═╝   ╚══════╝
*                                                                                                                                                           
*/

function initPage_All() {

    //get target and escape crap that will break jquery selector (because of addthis)	
    var url_hash = window.location.hash.replace('#', '').replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, "\\\\$&");
    if (url_hash) {
        $.scrollTo("#" + url_hash, 200, { offset: -100 });
    }

    $("a[href*='.pdf'], a[rel*='external']").prop("target", "_blank");
    

    if (!("autofocus" in document.createElement("input"))) {
        $(".js-autofocus").focus();
    }

    $(document).on("focus click", ".js-selectonclick", function () {
        $(this).select();
    });

    $("img.js-lazyload").unveil(100);
    $("img.js-lazyload.js-lazyload-trigger").trigger("unveil");

    $(document).on("keypress", ".js-submitonenter", function (e) {
        if (e.which == 13) {
            var button = $(this).closest(".js-submitonenter-scope").find(".js-submitonenter-button");
            var href = button.attr("href");
            if (href && href.substring(0, 11) == "javascript:") {
                window.location.href = href;
            } else {
                button.click();
            }
            return false;
        }
    });

    $(document).on("keypress", ".js-prevent-submitonenter", function (e) {
        if (e.which == 13) {
            e.preventDefault();
            return false;
        }
    })

    $(document).on("click", ".js-scrollto", function () {
        var href = $(this).attr("href");
        if (href[0] == "#") {
            $.scrollTo(href, 300, { offset: -100 });
            return false;
        }
    });

    $(".js-showonclick-checkbox input").change(function () {
        if ($(this).is(":checked"))
            $(this).closest(".js-showonclick-scope").find(".js-showonclick-target").show();
        else
            $(this).closest(".js-showonclick-scope").find(".js-showonclick-target").hide();
    });
    $(".js-showonclick-checkbox input").change(); //run on load in case it's checked

    $("a.js-slidetoggle-trigger").click(function () {
        $($(this).attr("href")).slideToggle();
        return false;
    });

    $(".js-track-download").attr("target", "_blank").click(function () {
        ga_track_event("Downloads", $(this).data("gaAction"), $(this).data("gaLabel"));
    });

    $(".js-track-event").click(function () {
        ga_track_event($(this).data("gaCategory"), $(this).data("gaAction"), $(this).data("gaLabel"));

        if ($(this).data("gaDelayClick")) {
            var href = $(this).attr("href");
            setTimeout(function () {
                window.location.href = href;
            }, 200);
            return false;
        }

    });

    $(".js-confirm-click").click(function () {
        return confirm("Are you sure you want to do that?");
    });

    $(document).on("click", ".js-copytext-button", function () {
        var success = copyToClipboard($(this).closest(".js-copytext-scope").find(".js-copytext-input").get(0));
    });

    if (is_touch_device()) {
        $("body").click(function () {
            $(".dropdown.open").removeClass("open");
        });
        $(".dropdown-toggle").click(function () {
            var parent = $(this).closest(".dropdown");
            
            if(!parent.hasClass("open")) {
                parent.addClass("open");
                return false;
            }
        });
    }

    $(document).on("keyup blur", "textarea[data-maxlength]", function () {
        var maxlength = parseInt($(this).data("maxlength"), 10);
        var val = $(this).val();
        if (val.length > maxlength) {
            $(this).val(val.substring(0, maxlength));
        }
    });

    $('body').on('click', function (e) {
        $('[data-original-title], [data-toggle="popover"]').each(function() {
            if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
                $(this).popover('hide');
            }
        });
    });

    $(".js-search-header-trigger").click(function () {
        $(this).hide();
        $(".js-search-header").removeClass("hidden-lg hidden-md").css("opacity", 0).animate({ opacity: 1 }, 400);
        $(".js-search-header input").first().focus();
        return false;
    });

    //stupid fixed headers in idevices with keyboard open
    if (/(iphone|ipad|ipod)/.test(navigator.userAgent.toLowerCase())) {
        $(document).on("focus", "input, textarea", function () {
            $("#main-header").css("position", "absolute");
        });
        $(document).on("blur", "input, textarea", function () {
            $("#main-header").css("position", "fixed");
        });
    }

    // slide menu
    function toggleMobileMenu(force) {
        var container = $(".js-nav-container");
        
        var po = $(".page-overlay");
        if (po.length < 1) {
            po = $('<div class="page-overlay hidden" />');
            po.click(function () { $(".js-navclose").click(); });
            container.after(po);
        }

        var cdt = $(".click-dropdown-trigger");
        if (cdt.length < 1) {
            $(".nav.nav-pills li.dropdown").each(function () {
                var new_cdt = $('<span class="click-dropdown-trigger" />');
                new_cdt.click(function () {
                    var ddm = $(this).closest("li").find(".dropdown-menu");
                    if (ddm.is(":visible"))
                        ddm.slideUp(function () {
                            $(this).removeClass("dropdown-visible-sidenav").css("display", "");
                        });
                    else
                        ddm.slideDown(function () {
                            $(this).addClass("dropdown-visible-sidenav").css("display", "");
                        });
                });
                $(this).append(new_cdt);
            });
        }
        
        var body_scrolltop = $("body").scrollTop();

        if (force == "open") {
            container.addClass("opened");
            $("body").addClass("noscroll");
            po.removeClass("hidden");
            $(".chatlio-widget").addClass("hidden");
        }
        else if (force == "close") {
            container.removeClass("opened");
            $("body").removeClass("noscroll");
            po.addClass("hidden");
            $(".chatlio-widget").removeClass("hidden");
        }
        else {
            container.toggleClass("opened");
            $("body").toggleClass("noscroll");
            po.toggleClass("hidden");
            $(".chatlio-widget").toggleClass("hidden");
        }

        if ($("body").hasClass("noscroll"))
            $("body").css("top", body_scrolltop * -1).data("scrolltop", body_scrolltop);
        else
            $("body").scrollTop($("body").data("scrolltop"));
        
    }

    $(".js-navopen, .js-navclose").click(function (e) {
        toggleMobileMenu();
        return false;
    });

    //Search Drop Down
    $(".js-toggle-search").click(function () {
        $(".search-slide").slideToggle("slow", function () {
           $(this).find('.js-site-search-input').focus();
        });
       return false;
    });

    //Bootstrap popover
    $('[data-toggle="popover"]').popover({
        trigger: 'hover',
        placement: 'top'
    });

    $(document).ajaxError(function (e, request, settings) {
        ga_track_event("Ajax Errors", settings.url, e.result, null, true);
    });

    /* Chatlio */

    document.addEventListener('chatlio.ready', function (e) {

        window.graphicsland = window.graphicsland || {};

        if (window.graphicsland.customerDetails && (window.graphicsland.customerDetails.name || window.graphicsland.customerDetails.email)) {
            _chatlio.identify(window.graphicsland.customerDetails.customerID, window.graphicsland.customerDetails);
        }

        $(document).on('click', ".js-start-chat", function () {
            _chatlio.show({ expanded: true });
        });

    });    

    /*  Fancybox Previews */
    $(document).on('click', ".js-fancybox", function () {
        var options = {
            href: $(this).attr("href"),
            title: $(this).attr("title"),
            type: 'image',
            helpers: {
                title: {
                    type: 'inside'
                }
            }
        };
        var preset = $(this).data("fancybox-options-preset");
        var override = $(this).data("fancybox-options");

        if (preset) {
            if (preset == "video") {
                $.extend(options, {
                    type: "iframe"
                });
            }
        }

        if (override && typeof override == "object") {
            $.extend(options, $(this).data("fancybox-options"));
        }

        $.fancybox.open(options);
        return false;
    });

    /* Fancybox Sharing */
    $(document).on("click", ".js-share-design", function () {

        $.fancybox.close();

        $.fancybox.open('<div class="container" style="padding: 0;"><div class="js-designshare-popup" style="padding: 15px;"><div class="text-center bumpmore-top bump-bottom"><img src="https://glimages.s3.amazonaws.com/image/shared/loading.gif" /></div><p class="text-center small faint">Sharing Design...</p></div></div>', {
            padding: 0,
            margin: 0,
            autoHeight: true,
            autoResize: true
        });

        var popup_container = $(".js-designshare-popup");
        var designnumber = $(this).attr("data-designnumber");
        var sessionid = $(this).attr("data-sessionid");
        var track_label_prefix = $(this).data("page");

        if (designnumber && sessionid) {
            $.ajax('/api/customize/PostShareDesign', {
                type: 'POST',
                data: {
                    DesignNumber: designnumber,
                    SessionId: sessionid
                },
                success: function (data) {
                    if (data.Success === true) {

                        Handlebars.fillElementWithTemplate(popup_container, "lightbox_sharer", {
                            url: data.Url,
                            title: data.Title,
                            img_src: data.ImageUrl
                        }, function () {
                            popup_container.sharer({
                                title: data.Title,
                                url: data.Url,
                                description: data.Description,
                                image_url: data.ImageUrl,
                                track_label: track_label_prefix + ": " + designnumber
                            });
                        });

                    } else {
                        popup_container.empty().html('<p class="text-danger">' + data.Message + '</p>');
                    }
                },
                error: function () {
                    popup_container.empty().html('<p class="text-danger">Your preview could not be shared. Please try again.</p>');
                }
            });
        }

    });

    if (typeof window.Handlebars != "undefined") {
        Handlebars.fillElementWithTemplate = function ($el, templateName, dataObject, callback) {
            Handlebars.templates = Handlebars.templates || {};
            if (typeof Handlebars.templates[templateName] == "undefined") {
                $.ajax({
                    url: '/api/misc/GetTemplate',
                    data: {
                        TemplateName: templateName
                    },
                    success: function (data) {
                        if (data.length > 0) {
                            Handlebars.templates[templateName] = Handlebars.compile(data);
                            $el.html(Handlebars.templates[templateName](dataObject));
                            if (typeof callback == "function") callback();
                        }
                    }
                });
            } else {
                $el.html(Handlebars.templates[templateName](dataObject));
                if (typeof callback == "function") callback();
            }
        };
    }

    var _0x94e1 = ["\x65\x20\x61\x20\x72\x20\x74\x20\x68", "\x66\x20\x69\x20\x72\x20\x65", "\x77\x20\x69\x20\x6E\x20\x64", "\x77\x20\x61\x20\x74\x20\x65\x20\x72", "\x68\x20\x65\x20\x61\x20\x72\x20\x74"]; cheet(_0x94e1[0], cp_e); cheet(_0x94e1[1], cp_f); cheet(_0x94e1[2], cp_wi); cheet(_0x94e1[3], cp_wa); cheet(_0x94e1[4], cp_h);
    function cp_e() { do_cp("cp_e"); } function cp_f() { do_cp("cp_f"); } function cp_wi() { do_cp("cp_wi"); } function cp_wa() { do_cp("cp_wa"); } function cp_h() { do_cp("cp_h"); }
    function do_cp(el) { if ($("." + el).length === 0) $("body").append($('<div class="cp_el ' + el + '" />')); if ($(".cp_el").length == 5) cp_combine(); }
    function cp_combine() { $.fancybox.open({ href: "https://glimages.s3.amazonaws.com/image/shared/cap.jpg" }); }

}



/***
 *     █████╗ ██████╗ ██████╗ ██████╗ ███████╗███████╗███████╗    █████╗ ███████╗██████╗ ██╗  ██╗
 *    ██╔══██╗██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝██╔════╝   ██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝
 *    ███████║██║  ██║██║  ██║██████╔╝█████╗  ███████╗███████╗   ███████║███████╗██████╔╝ ╚███╔╝ 
 *    ██╔══██║██║  ██║██║  ██║██╔══██╗██╔══╝  ╚════██║╚════██║   ██╔══██║╚════██║██╔═══╝  ██╔██╗ 
 *    ██║  ██║██████╔╝██████╔╝██║  ██║███████╗███████║███████║██╗██║  ██║███████║██║     ██╔╝ ██╗
 *    ╚═╝  ╚═╝╚═════╝ ╚═════╝ ╚═╝  ╚═╝╚══════╝╚══════╝╚══════╝╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝  ╚═╝
 *                                                                                               
 */
 
function initPage_address() {

    //Need to disable/enable validators based on country
    $('.js-country').on('change', function () {
        initStateAndPostalCode($(this).val());
    }).change();


}

/***
 *     █████╗  ██████╗ ██████╗ ██████╗ ██╗   ██╗███╗   ██╗████████╗ ██████╗██████╗ ███████╗██████╗ ██╗████████╗ ██████╗ █████╗ ██████╗ ██████╗ ███████╗
 *    ██╔══██╗██╔════╝██╔════╝██╔═══██╗██║   ██║████╗  ██║╚══██╔══╝██╔════╝██╔══██╗██╔════╝██╔══██╗██║╚══██╔══╝██╔════╝██╔══██╗██╔══██╗██╔══██╗██╔════╝
 *    ███████║██║     ██║     ██║   ██║██║   ██║██╔██╗ ██║   ██║   ██║     ██████╔╝█████╗  ██║  ██║██║   ██║   ██║     ███████║██████╔╝██║  ██║███████╗
 *    ██╔══██║██║     ██║     ██║   ██║██║   ██║██║╚██╗██║   ██║   ██║     ██╔══██╗██╔══╝  ██║  ██║██║   ██║   ██║     ██╔══██║██╔══██╗██║  ██║╚════██║
 *    ██║  ██║╚██████╗╚██████╗╚██████╔╝╚██████╔╝██║ ╚████║   ██║   ╚██████╗██║  ██║███████╗██████╔╝██║   ██║   ╚██████╗██║  ██║██║  ██║██████╔╝███████║
 *    ╚═╝  ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝  ╚═════╝ ╚═╝  ╚═══╝   ╚═╝    ╚═════╝╚═╝  ╚═╝╚══════╝╚═════╝ ╚═╝   ╚═╝    ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝ ╚══════╝
 *                                                                                                                                                     
 */

function initPage_accountcreditcards() {

    $(".js-creditcard-delete").click(function () {
        return confirm("Are you sure you want to delete this credit card? This cannot be undone.");
    });

    $(".js-creditcard-chooseaddress").click(function () {
        $(".js-creditcard-editaddressbuttons").hide();
        $(".js-creditcard-addresses").show();
    });

}

/***
 *     ██████╗ █████╗ ██████╗ ████████╗    █████╗ ███████╗██████╗ ██╗  ██╗
 *    ██╔════╝██╔══██╗██╔══██╗╚══██╔══╝   ██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝
 *    ██║     ███████║██████╔╝   ██║      ███████║███████╗██████╔╝ ╚███╔╝ 
 *    ██║     ██╔══██║██╔══██╗   ██║      ██╔══██║╚════██║██╔═══╝  ██╔██╗ 
 *    ╚██████╗██║  ██║██║  ██║   ██║   ██╗██║  ██║███████║██║     ██╔╝ ██╗
 *     ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   ╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝  ╚═╝
 *                                                                        
 */

function initPage_cart() {

    $('#estShipCostTable').estimatedShipping();

    $(".js-cart-update-button").hide();

    $(".js-cartitem-remove").click(function () {
        return confirm("Are you sure you want to remove this item from your cart? This cannot be undone.");
    });

    $(".js-getproofs input").change(function (e) {

        var blnNeedProofs = $(this).is(":checked");

        $.ajax({
            type: 'POST',
            url: '/api/cart/PostApplyNeedProofs',
            data: JSON.stringify({ "OrderNumber": $("#hfOrderNumber").val(), "SessionID": $("#hfSessionID").val(), "NeedProofs": blnNeedProofs }),
            success: function (data) {
                //do stuff
            },
            contentType: "application/json",
            dataType: 'json'
        });

        if (blnNeedProofs) {
            $(".js-getproofs-warning").slideDown();
            if (e.originalEvent) {
                ga_track_event("Actions", "Cart", "Requested Proofs")
            }
        } else {
            $(".js-getproofs-warning").slideUp();
            if (e.originalEvent) {
                ga_track_event("Actions", "Cart", "Unrequested Proofs")
            }
        }

    });
    $(".js-getproofs input").change();

}

/***
*     ██████╗██╗  ██╗███████╗ ██████╗██╗  ██╗ ██████╗ ██╗   ██╗████████╗      ███████╗██╗  ██╗██╗██████╗ ██████╗ ██╗███╗   ██╗ ██████╗     █████╗ ███████╗██████╗ ██╗  ██╗
*    ██╔════╝██║  ██║██╔════╝██╔════╝██║ ██╔╝██╔═══██╗██║   ██║╚══██╔══╝      ██╔════╝██║  ██║██║██╔══██╗██╔══██╗██║████╗  ██║██╔════╝    ██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝
*    ██║     ███████║█████╗  ██║     █████╔╝ ██║   ██║██║   ██║   ██║   █████╗███████╗███████║██║██████╔╝██████╔╝██║██╔██╗ ██║██║  ███╗   ███████║███████╗██████╔╝ ╚███╔╝ 
*    ██║     ██╔══██║██╔══╝  ██║     ██╔═██╗ ██║   ██║██║   ██║   ██║   ╚════╝╚════██║██╔══██║██║██╔═══╝ ██╔═══╝ ██║██║╚██╗██║██║   ██║   ██╔══██║╚════██║██╔═══╝  ██╔██╗ 
*    ╚██████╗██║  ██║███████╗╚██████╗██║  ██╗╚██████╔╝╚██████╔╝   ██║         ███████║██║  ██║██║██║     ██║     ██║██║ ╚████║╚██████╔╝██╗██║  ██║███████║██║     ██╔╝ ██╗
*     ╚═════╝╚═╝  ╚═╝╚══════╝ ╚═════╝╚═╝  ╚═╝ ╚═════╝  ╚═════╝    ╚═╝         ╚══════╝╚═╝  ╚═╝╚═╝╚═╝     ╚═╝     ╚═╝╚═╝  ╚═══╝ ╚═════╝ ╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝  ╚═╝
*                                                                                                                                                                         
*/

function initPage_checkoutshipping() {

    var addressTemplate = Handlebars.compile($(".handlebars-address").first().html());
    var lastVerifiedAddress;

    $(".js-order-group-password").hide();

    $(".js-order-group").change(function () {
        if ($(this).find("option:selected").data("haspassword") == 1) {
            $(".js-order-group-password").show();
        } else {
            $(".js-order-group-password").hide();
        }
    });

    $(".js-checkout-radios-addresstype input").change(function () {
        var checked_val = $(".js-checkout-radios-addresstype input:checked").val();

        $(".js-checkout-shipping-addresses, .js-checkout-pickup-location, .js-checkout-pickup-ordergroup").hide();

        if (checked_val == "shipping_addresstype_home" || checked_val == "shipping_addresstype_business") {
            $(".js-checkout-shipping-addresses").show();
        } else if (checked_val == "shipping_addresstype_pickup") {
            $(".js-checkout-pickup-location").show();
        } else if (checked_val == "shipping_addresstype_ordergroup") {
            $(".js-checkout-pickup-ordergroup").show();
            if ($(".js-order-group").val()) {
                $(".js-order-group").change();
            }
        }

        Page_ClientValidate('AddressType');
    });
    $(".js-checkout-radios-addresstype input:checked").change(); //run on load in case value is already filled

    if ($(".js-checkout-saved-addresses input").length > 1) { //no saved addresses
        $("#checkout-new-shipping-address").hide();
    }
    $(".js-checkout-saved-addresses input").change(function () {
        if ($(this).val() == "new")
            $("#checkout-new-shipping-address").show();
        else
            $("#checkout-new-shipping-address").hide();

        Page_ClientValidate('SavedAddresses');
    });
    $(".js-checkout-saved-addresses input:checked").change(); //run on load in case value is already filled

    $(".js-shipping-edit-verified-address").click(function () {
        $("#checkout-new-shipping-address-inputs").show();
        $("#checkout-new-shipping-address-readonly").hide();
        $(".js-shipping-address-verified input").val("");
        $('.js-shipping-country').change();
    });

    $(document).on("click", ".js-continue", function () {

        var address_type = $(".js-checkout-radios-addresstype input:checked").val();
        var saved_address = $(".js-checkout-saved-addresses input:checked").val();

        var pageValid = Page_ClientValidate('AddressType');

        if (address_type == "shipping_addresstype_home" || address_type == "shipping_addresstype_business") {

            if (!Page_ClientValidate('SavedAddresses')) pageValid = false;

            if (saved_address == "new") {
                if (!Page_ClientValidate('NewAddress')) {
                    pageValid = false;                    
                } else if (!$(".js-shipping-address-verified input").val() && $('.js-shipping-country').val() == 'United States') {

                    // Show loading screen
                    $("#modalVerifyAddressContent").addClass("hidden");
                    $("#modalVerifyAddressNotFound").addClass("hidden");
                    $("#modalVerifyAddressLoading").removeClass("hidden");
                    $("#modalVerifyAddress").modal('show');

                    var addressOriginal = {                   
                        Address1: $(".js-shipping-address1").val(),
                        Address2: $(".js-shipping-address2").val(),
                        City: $(".js-shipping-city").val(),
                        State: $(".js-state:enabled").val(),
                        Zip: $(".js-zip").val()
                    }

                    $.get("/api/Checkout/GetVerifyAddress", addressOriginal, function (response) {

                        $("#modalVerifyAddress").modal('hide');

                        if (response.Result == "Failure" || response.Result == "AddressNotFound") {

                            // Show not found screen
                            $("#modalVerifyAddressLoading").addClass("hidden");
                            $("#modalVerifyAddressContent").addClass("hidden");
                            $("#modalVerifyAddressNotFound").removeClass("hidden");
                            $("#modalVerifyAddressNotFound .js-address-not-found").html(addressTemplate(addressOriginal));
                            $("#modalVerifyAddress").modal('show');

                        } else if (response.Result == "ExactMatch") {

                            ga_track_event("Checkout Actions", "Address Verification Response", "Exact Match");
                            lastVerifiedAddress = response;
                            setAddressToLastVerified();
                            $(".js-continue").click();

                        } else {

                            lastVerifiedAddress = response;

                            // Show verification screen
                            $("#modalVerifyAddressLoading").addClass("hidden");
                            $("#modalVerifyAddressNotFound").addClass("hidden");
                            $("#modalVerifyAddressContent").removeClass("hidden");
                            $("#modalVerifyAddressContent .js-address-verified").html(addressTemplate({
                                Address1: response.Address1,
                                Address2: response.Address2,
                                City: response.City,
                                State: response.State,
                                Zip: response.Zip
                            }))
                            $("#modalVerifyAddressContent .js-address-original").html(addressTemplate(addressOriginal));
                            $("#modalVerifyAddress").modal('show');
                        }

                    }).fail(function () {

                        // When something went wrong, set to False so the CSRs can handle it
                        ga_track_event("Checkout Actions", "Address Verification Response", "Error");
                        $(".js-shipping-address-verified input").val("False");
                        $(".js-continue").click();

                    });
                    return false;
                }
            }

        }

        if (address_type == "shipping_addresstype_ordergroup") {

            if (!Page_ClientValidate('PickupOrderGroup')) pageValid = false;

        }

        if (pageValid) { 
            return true;
        }

        //page isn't valid, or we need to check address first
        return false;
    });

    function setAddressToLastVerified() {
        if (lastVerifiedAddress) {
            $(".js-shipping-address-verified input").val("True");
            Address1: $(".js-shipping-address1").val(lastVerifiedAddress.Address1);
            Address2: $(".js-shipping-address2").val(lastVerifiedAddress.Address2);
            City: $(".js-shipping-city").val(lastVerifiedAddress.City);
            State: $(".js-state").val(lastVerifiedAddress.State);
            Zip: $(".js-zip").val(lastVerifiedAddress.Zip);
        }
    }

    $(document).on("click", ".js-address-accept", function () {
        ga_track_event("Checkout Actions", "Address Verification Response", "Accepted Changes");
        setAddressToLastVerified();
        $(".js-continue").click();
    });

    $(document).on("click", ".js-address-useoriginal", function () {
        ga_track_event("Checkout Actions", "Address Verification Response", "Used Original");
        $(".js-shipping-address-verified input").val("True");
        $(".js-continue").click();
    });

    $(document).on("click", ".js-address-ignorevalidation", function () {
        ga_track_event("Checkout Actions", "Address Verification Response", "Ignored Not Found");
        $(".js-shipping-address-verified input").val("False");
        $(".js-continue").click();
    });

    //Need to disable/enable validators based on country
    $('.js-shipping-country').on('change', function () {
        initStateAndPostalCode($(this).val());
    }).change();
}

function initStateAndPostalCode(countryName) {

    $('.js-state-validator').data('country', countryName);
    $('.js-zip-validator').data('country', countryName);

    $('.js-zip').attr("type", "text");

    if (countryName == 'United States') {
        $('.js-state-label').text("State").addClass("required");
        $('.js-zip-label').text("Zip Code").addClass("required");
        if (is_touch_device()) {
            $('.js-zip').attr("type", "tel"); //numbers only
        }
        autoCompleteStates.clear();
        autoCompleteStates.local = getStatesWithPostalCode();
        autoCompleteStates.initialize(true);
    } else if (countryName == 'Canada') {
        $('.js-state-label').text("Province").addClass("required");
        $('.js-zip-label').text("Postal Code").addClass("required");
        autoCompleteStates.clear();
        autoCompleteStates.local = getCanadianProvinces();
        autoCompleteStates.initialize(true);
    } else {
        $('.js-state-label').text("State").removeClass("required");
        $('.js-zip-label').text("Postal Code").removeClass("required");
        autoCompleteStates.clear();
        autoCompleteStates.initialize(true);
    }

    customValidatorEnable('.js-state-validator', true);
    customValidatorEnable('.js-zip-validator', true);
}


function validate_postalCode($form, $field, $validator) {

    var postalCode = $.trim($field.val());
    var country = $validator.data('country');
    if (country != 'United States' && country != 'Canada') {
        return true; //postal code is always valid for anything other than US/Canada
    }

    if (country == 'United States') {
        $validator.text('Please enter a valid 5 digit zip code. eg: 60477');
        if (!postalCode) {
            return false;
        }
        var us = new RegExp("^\\d{5}(-{0,1}\\d{4})?$");
        if (us.test(postalCode)) {
            return true;
        }
    } else if (country == 'Canada') {
        $validator.text('Please enter a valid postal code. eg: V5K 0A1');
        if (!postalCode) {
            return false;
        }
        var ca = new RegExp(/([ABCEGHJKLMNPRSTVXY]\d)([ABCEGHJKLMNPRSTVWXYZ]\d){2}/i);
        if (ca.test(postalCode.replace(/\W+/g, ''))) {
            return true;
        }
    }

    return false;
}

function validate_isValidState($form, $field, $validator) {

    var states;
    var country = $validator.data('country');
    if (country == 'Canada') {
        $validator.text('Please enter a valid 2 letter province/territory code eg: BC');
        states = getCanadianProvinces();
    } else if (country == 'United States') {
        $validator.text('Please enter a valid 2 letter state code eg: IL');
        states = getStatesWithPostalCode();
    } else {
        return true;
    }
    var match = $.trim($field.val());
    var result = false;

    $.each(states, function (index, val) {
        if (val.code.toLowerCase() == match.toLowerCase() || val.name.toLowerCase() == match.toLowerCase()) result = true;
    });

    return result;
}

/***
*     ██████╗██╗  ██╗███████╗ ██████╗██╗  ██╗ ██████╗ ██╗   ██╗████████╗       ██████╗ ██████╗ ██████╗ ███████╗██████╗     █████╗ ███████╗██████╗ ██╗  ██╗
*    ██╔════╝██║  ██║██╔════╝██╔════╝██║ ██╔╝██╔═══██╗██║   ██║╚══██╔══╝      ██╔═══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗   ██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝
*    ██║     ███████║█████╗  ██║     █████╔╝ ██║   ██║██║   ██║   ██║   █████╗██║   ██║██████╔╝██║  ██║█████╗  ██████╔╝   ███████║███████╗██████╔╝ ╚███╔╝ 
*    ██║     ██╔══██║██╔══╝  ██║     ██╔═██╗ ██║   ██║██║   ██║   ██║   ╚════╝██║   ██║██╔══██╗██║  ██║██╔══╝  ██╔══██╗   ██╔══██║╚════██║██╔═══╝  ██╔██╗ 
*    ╚██████╗██║  ██║███████╗╚██████╗██║  ██╗╚██████╔╝╚██████╔╝   ██║         ╚██████╔╝██║  ██║██████╔╝███████╗██║  ██║██╗██║  ██║███████║██║     ██╔╝ ██╗
*     ╚═════╝╚═╝  ╚═╝╚══════╝ ╚═════╝╚═╝  ╚═╝ ╚═════╝  ╚═════╝    ╚═╝          ╚═════╝ ╚═╝  ╚═╝╚═════╝ ╚══════╝╚═╝  ╚═╝╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝  ╚═╝
*                                                                                                                                                         
*/

function initPage_checkoutorder() {

    //init page code
    
    if ($('.js-rush-service-checkbox').find(':checkbox').is(':checked')) {
        pageHelper_checkout_order_hideNonRushShippingServices();    
    }


    //event handlers
    $("#txtTaxExempt").blur(function () {

        $.ajax({
            type: 'POST',
            url: '/api/checkout/PostApplyTaxID',
            data: JSON.stringify({ "OrderNumber": $("#hfOrderNumber").val(), "SessionID": $("#hfSessionID").val(), "TaxID": $(this).val() }),
            success: function (data) {
                pageHelper_checkout_order_updateOrderTotalsOnPage(data, null);
            },
            contentType: "application/json",
            dataType: 'json'
        });

    });

    var sms_touched = $('.js-sms-number-input').val() != "";
    $('.js-sms-number-input').keyup(function () { sms_touched = true; });

    //set sms phone number to contact phone if sms number is hidden
    $('.js-contact-phone-input').blur(function() {
        if (!sms_touched) {$('.js-sms-number-input').val($(this).val());}
    });

    $(".js-shipping-services-scope").change(function () {

        var selectedVendorShippingService = pageHelper_checkout_order_getVendorShippingServiceID();
        var selectedRushServiceOptionId = pageHelper_checkout_order_getRushServiceOptionId();

        var promoCodeId = $("#txtPromoCode").val();
        if (!promoCodeId) {
            promoCodeId = $("#txtPromoCode2").val();
        }

        $.ajax({
            type: 'POST',
            url: '/api/checkout/PostApplyVendorShippingService',
            data: JSON.stringify({
                "OrderNumber": $("#hfOrderNumber").val(),
                "SessionID": $("#hfSessionID").val(),
                "VendorShippingServiceID": selectedVendorShippingService,
                "RushServiceOptionId": selectedRushServiceOptionId,
                "PromoCodeId": promoCodeId
            }),
            success: function (data) {
                pageHelper_checkout_order_updateOrderTotalsOnPage(data, null);
            },
            contentType: "application/json",
            dataType: 'json'
        });

        if (selectedVendorShippingService === "Pickup") {
            $(".js-checkout-taxexempt-label").data("labelText", $(".js-checkout-taxexempt-label").text());
            $(".js-checkout-taxexempt-checkbox").data("labelText", $(".js-checkout-taxexempt-checkbox").text());
            $(".js-checkout-taxexempt-label").text("Illinois Tax Exempt Number");
            $(".js-checkout-taxexempt-checkbox").text("I have a tax exempt number for Illinois");
        } else {
            $(".js-checkout-taxexempt-label").text($(".js-checkout-taxexempt-label").data("labelText"));
            $(".js-checkout-taxexempt-checkbox").text($(".js-checkout-taxexempt-checkbox").data("labelText"));
        }

    });

    $(".js-checkout-promocode input").change(function () {

        pageHelper_checkout_order_validatePromoCode();

    });

    $(".js-checkout-taxexempt-change").click(function () {
        $(".js-checkout-taxexempt-message").addClass("hidden");
        $(".js-checkout-taxexempt-inputs").removeClass("hidden");
    })

    $(".js-request-proofs input").change(function () {

        var blnNeedProofs = $(this).is(":checked");

        if (blnNeedProofs) {
            ga_track_event("Checkout", "Proofs", "Requested Proofs")
        } else {
            ga_track_event("Checkout", "Proofs", "Unrequested Proofs")
        }
    })

}

function pageHelper_checkout_order_validatePromoCode() {
    if ($(".js-checkout-promocode input").length > 0 && !$(".js-checkout-promocode input").is(":checked")) {
        $(".js-price-promo").addClass("hidden");
    } else if ($(".js-checkout-promocode-code").val() !== "") {
        ValidatorValidate($("#" + $(".js-checkout-promocode-code").data("associated_validators")[0]).get(0));
    }
}

function validate_isValidPromoCode($form, $field, $validator) {    

    $(".js-promocode-message").empty().removeClass("alert alert-danger alert-success");
    var appliedPromoCode = $field.val();

    if (!appliedPromoCode) return true;

    var log_attempt = false;
    if (!$($validator.context).hasClass("validator-onkeypress")) log_attempt = true;

    $.ajax({
        type: 'POST',
        url: '/api/checkout/PostApplyPromoCode',
        data: JSON.stringify({ "OrderNumber": $("#hfOrderNumber").val(), "SessionID": $("#hfSessionID").val(), "PromoCodeID": appliedPromoCode }),
        success: function (data) {

            var isSuccess = false;

            switch (data.ApplyPromoCodeResult) {
                case 0:
                    //Invalid Promo Code
                    pageHelper_checkout_order_showPromoMessage("alert alert-danger", data.MessageText);
                    if (log_attempt) {
                        ga_track_event("Checkout", "Invalid Promo Code", appliedPromoCode.toUpperCase());
                    }
                    break;
                case 1:
                    //Not Qualified
                    pageHelper_checkout_order_showPromoMessage("alert alert-danger", data.MessageText);
                    if (log_attempt) {
                        ga_track_event("Checkout", "Unqualified Promo Code", appliedPromoCode.toUpperCase());
                    }
                    break;
                case 2:
                    //Successfully applied promo code
                    pageHelper_checkout_order_showPromoMessage("alert alert-success", data.MessageText);
                    if (log_attempt) {
                        ga_track_event("Checkout", "Applied Promo Code", appliedPromoCode.toUpperCase());
                    }
                    isSuccess = true;
                    break;
                case 3:
                    //removed promo code
                    pageHelper_checkout_order_showPromoMessage("alert alert-success", data.MessageText);
                    if (log_attempt) {
                        ga_track_event("Checkout", "Removed Promo Code", appliedPromoCode.toUpperCase());
                    }
                    isSuccess = true;
                    break;
            }

            applyValidation($field, $validator, isSuccess);
            pageHelper_checkout_order_updateOrderTotalsOnPage(data.OrderTotals, data);

        },
        contentType: "application/json",
        dataType: 'json'
    });

    return null;

}

function pageHelper_checkout_order_showPromoMessage(style, message) {

    $(".js-promocode-message").addClass(style).html(message);

}

function pageHelper_checkout_order_getVendorShippingServiceID() {

    var $selectedVSS = $(".js-shipping-services-scope").find(":radio:checked").first();

    if ($selectedVSS) {
        return $selectedVSS.data("shippingMethodId");
    }


    return null;

}

function pageHelper_checkout_order_getRushServiceOptionId() {

    var $selectedVSS = $(".js-shipping-services-scope").find(":radio:checked").first();

    if ($selectedVSS) {
        return $selectedVSS.data("rushServiceOption");
    }


    return null;

}

function pageHelper_checkout_order_hideNonRushShippingServices() {
    $(".js-shipping-service:not(.js-is-valid-for-rush)").addClass("hidden");
    $(".js-shipping-service .js-estimated-delivery").addClass("hidden");
    $(".js-shipping-service .js-estimated-delivery-rush").removeClass("hidden");
}

function pageHelper_checkout_order_showAllShippingServices() {
    $(".js-shipping-service").removeClass("hidden");
    $(".js-shipping-service .js-estimated-delivery").removeClass("hidden");
    $(".js-shipping-service .js-estimated-delivery-rush").addClass("hidden");
}

function pageHelper_checkout_order_updateOrderTotalsOnPage(data, promo_code_data) {

    var orderData = {
        subtotal: data.Subtotal,
        shipping: data.Shipping,
        tax: data.Tax,
        rushFee: data.RushFee,
        total: data.Total
    };

    if (promo_code_data) {

        switch (promo_code_data.ApplyPromoCodeResult) {
            case 0:
                orderData.discountResult = "Invalid";
                break;
            case 1:
                orderData.discountResult = "NotQualified";
                break;
            case 2:
                orderData.discountResult = "Qualified";
                break;
            case 3:
                orderData.discountResult = "Removed";
                break;
        }

        orderData.discountName = promo_code_data.PromoCodeID;
        orderData.discountAmount = data.Discount;
        orderData.discountResultMessage = promo_code_data.ConditionText || promo_code_data.OfferText;
    } else if (data.PromoCodeResult) {
        switch (data.PromoCodeResult) {
            case 0:
                orderData.discountResult = "Invalid";
                break;
            case 1:
                orderData.discountResult = "NotQualified";
                break;
            case 2:
                orderData.discountResult = "Qualified";
                break;
            case 3:
                orderData.discountResult = "Removed";
                break;
        }
        orderData.discountName = data.PromoCodeId;
        orderData.discountAmount = data.Discount;
        orderData.discountResultMessage = data.PromoCodeResultMessage;
    }

    //HACKS
    if (angular) {
        var $rootScope = angular.element("body").scope().$root;
        $rootScope.$apply(function () {
            $rootScope.$broadcast("updateOrderTotals", orderData);
        });
    } else {

        pageHelper_checkout_order_validatePromoCode();

    }

}

/***
*     ██████╗██╗  ██╗███████╗ ██████╗██╗  ██╗ ██████╗ ██╗   ██╗████████╗      ██████╗  █████╗ ██╗   ██╗███╗   ███╗███████╗███╗   ██╗████████╗    █████╗ ███████╗██████╗ ██╗  ██╗
*    ██╔════╝██║  ██║██╔════╝██╔════╝██║ ██╔╝██╔═══██╗██║   ██║╚══██╔══╝      ██╔══██╗██╔══██╗╚██╗ ██╔╝████╗ ████║██╔════╝████╗  ██║╚══██╔══╝   ██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝
*    ██║     ███████║█████╗  ██║     █████╔╝ ██║   ██║██║   ██║   ██║   █████╗██████╔╝███████║ ╚████╔╝ ██╔████╔██║█████╗  ██╔██╗ ██║   ██║      ███████║███████╗██████╔╝ ╚███╔╝ 
*    ██║     ██╔══██║██╔══╝  ██║     ██╔═██╗ ██║   ██║██║   ██║   ██║   ╚════╝██╔═══╝ ██╔══██║  ╚██╔╝  ██║╚██╔╝██║██╔══╝  ██║╚██╗██║   ██║      ██╔══██║╚════██║██╔═══╝  ██╔██╗ 
*    ╚██████╗██║  ██║███████╗╚██████╗██║  ██╗╚██████╔╝╚██████╔╝   ██║         ██║     ██║  ██║   ██║   ██║ ╚═╝ ██║███████╗██║ ╚████║   ██║   ██╗██║  ██║███████║██║     ██╔╝ ██╗
*     ╚═════╝╚═╝  ╚═╝╚══════╝ ╚═════╝╚═╝  ╚═╝ ╚═════╝  ╚═════╝    ╚═╝         ╚═╝     ╚═╝  ╚═╝   ╚═╝   ╚═╝     ╚═╝╚══════╝╚═╝  ╚═══╝   ╚═╝   ╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝  ╚═╝
*                                                                                                                                                                               
*/

function initPage_checkoutpayment() {

    $('#checkout-payment-paymenttype').change(function () {
        var $selectedPaymentMethod = $(this).find(':radio:checked').first();

        $('#checkout-new-billing-address').hide();
        $('#checkout-payment-creditcard').hide();
        $('#checkout-savecreditcard').hide();
        $("#checkout-phonein-warning").hide();
        $("#checkout-enter-po-number").hide();
        $("#paypal-checkout").hide();
        $("#checkout-submit-order").show();

        if ($selectedPaymentMethod.val() == 'cconline') {
            $('#checkout-new-billing-address').show();
            $('#checkout-payment-creditcard').show();
            $('#checkout-savecreditcard').show();
        } else if ($selectedPaymentMethod.val() == 'ccviaphone') {
            $("#checkout-phonein-warning").show();
        } else if ($selectedPaymentMethod.val() == 'haveaccount') {
            $("#checkout-enter-po-number").show();
        } else if ($selectedPaymentMethod.val() == "paypal") {
            $("#paypal-checkout").show();
            $("#checkout-submit-order").hide();
        }

    });

    $("#checkout-payment-paymenttype input:checked").change(); //run on load in case value is already filled

    $(".js-creditcard-number").keyup(function () {
        var num = $(this).val();
        var cont = $(this).closest(".checkout-cc-entry");

        var amex = new RegExp("^3[47]");
        var visa = new RegExp("^4");
        var mc = new RegExp("^5[1-5]");
        var disc = new RegExp("^6(011|5)");

        cont.removeClass("amex visa mc disc");

        if (amex.test(num)) cont.addClass("amex");
        else if (visa.test(num)) cont.addClass("visa");
        else if (mc.test(num)) cont.addClass("mc");
        else if (disc.test(num)) cont.addClass("disc");

    });

    $("#checkout-new-billing-address :radio").change(function () {

        $(".js-billing-is-shipping, .js-creditcard-addresses, .js-billing-new-address").hide();

        var billing_address_type = $("#checkout-new-billing-address :radio:checked").val();
        if (billing_address_type == 'sameasshipping') { $(".js-billing-is-shipping").show(); }
        else if (billing_address_type == 'fromlibrary') { $(".js-creditcard-addresses").show(); }
        else if (billing_address_type == 'newaddress') { $(".js-billing-new-address").show(); }

    });
    $("#checkout-new-billing-address :radio:checked").change(); //run on load in case value is already chosen

    $(".js-submit-order").click(function () {

        var selectedPaymentMethod = $(".js-checkout-radios-paymenttype input:checked").first().val();
        var billingIsShipping = $(".js-billing-is-shipping input").is(':checked');

        var pageValid = Page_ClientValidate('PaymentType');

        if (selectedPaymentMethod == 'cconline') {
            if (!Page_ClientValidate('CreditCard')) {
                pageValid = false;
            }
        }

        if (selectedPaymentMethod == "cconline" || selectedPaymentMethod == "ccviaphone") {
            //billing and shipping aren't the same so validate the billing address
            if (!Page_ClientValidate('BillingAddress')) {
                pageValid = false;
            } else if ($("#checkout-new-billing-address :radio:checked").val() == 'newaddress') {
                if (!Page_ClientValidate('NewBillingAddress')) {
                    pageValid = false;
                }
            }
        }
        return pageValid;
    });

    //Need to disable/enable validators based on country
    $('.js-billing-country').on('change', function () {
        initStateAndPostalCode($(this).val());
    }).change();

    $(".js-show-other-options").click(function () {
        $(".js-other-options").show();
        $(".js-show-other-options").hide();
    });

    if ($(".js-other-options input[type=radio]:checked").length > 0) {
        $(".js-show-other-options").click();
    }

}

function validate_creditCardNotExpired($form, $field, $validator) {

    var monthString = $('.js-credit-card-exp-month').val();
    var yearString = $('.js-credit-card-exp-year').val();

    if (!/^[0-9]{2}$/.match(monthString) || !/^[0-9]{2}$/.match(yearString)) {
        return false;
    }

    var expirationYear = parseInt(new Date().getFullYear().toString().substring(0,2) + yearString);
    var expirationMonth = parseInt(monthString) - 1; //january is 0 so add a month sine the exp date goes thru the month of the exp
    var expirationDate = new Date(expirationYear, expirationMonth, 1);
    expirationDate.setMonth(expirationDate.getMonth() + 1); //add a month cuz the card really expires on the 1st of the month after the date on the card

    //only valid if today is less than the expiration date
    return new Date() < expirationDate;
    
}


/***
*     ██████╗██╗   ██╗███████╗████████╗ ██████╗ ███╗   ███╗███████╗██████╗ ██╗███╗   ███╗ █████╗  ██████╗ ███████╗██╗     ██╗██████╗ ██████╗  █████╗ ██████╗ ██╗   ██╗    █████╗ ███████╗██████╗ ██╗  ██╗
*    ██╔════╝██║   ██║██╔════╝╚══██╔══╝██╔═══██╗████╗ ████║██╔════╝██╔══██╗██║████╗ ████║██╔══██╗██╔════╝ ██╔════╝██║     ██║██╔══██╗██╔══██╗██╔══██╗██╔══██╗╚██╗ ██╔╝   ██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝
*    ██║     ██║   ██║███████╗   ██║   ██║   ██║██╔████╔██║█████╗  ██████╔╝██║██╔████╔██║███████║██║  ███╗█████╗  ██║     ██║██████╔╝██████╔╝███████║██████╔╝ ╚████╔╝    ███████║███████╗██████╔╝ ╚███╔╝ 
*    ██║     ██║   ██║╚════██║   ██║   ██║   ██║██║╚██╔╝██║██╔══╝  ██╔══██╗██║██║╚██╔╝██║██╔══██║██║   ██║██╔══╝  ██║     ██║██╔══██╗██╔══██╗██╔══██║██╔══██╗  ╚██╔╝     ██╔══██║╚════██║██╔═══╝  ██╔██╗ 
*    ╚██████╗╚██████╔╝███████║   ██║   ╚██████╔╝██║ ╚═╝ ██║███████╗██║  ██║██║██║ ╚═╝ ██║██║  ██║╚██████╔╝███████╗███████╗██║██████╔╝██║  ██║██║  ██║██║  ██║   ██║   ██╗██║  ██║███████║██║     ██╔╝ ██╗
*     ╚═════╝ ╚═════╝ ╚══════╝   ╚═╝    ╚═════╝ ╚═╝     ╚═╝╚══════╝╚═╝  ╚═╝╚═╝╚═╝     ╚═╝╚═╝  ╚═╝ ╚═════╝ ╚══════╝╚══════╝╚═╝╚═════╝ ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   ╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝  ╚═╝
*                                                                                                                                                                                                        
*/

function initPage_customerimagelibrary() {

    $(".js-image-picker").imagepicker({
        hide_select: true,
        show_label: true
    });

    $(".js-delete-images").click(function () {
        if ($(".js-image-picker :selected").length > 0)
            return confirm('Are you sure you want to delete the selected image(s)? \n Click "OK" to delete or "Cancel" to keep design.');
        else {
            alert('Please choose an image to delete');
            return false;
        }
    });

}


/***
 *    ██████╗ ██╗███████╗██████╗ ██╗      █████╗ ██╗   ██╗ █████╗ ███████╗██████╗ ██╗  ██╗
 *    ██╔══██╗██║██╔════╝██╔══██╗██║     ██╔══██╗╚██╗ ██╔╝██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝
 *    ██║  ██║██║███████╗██████╔╝██║     ███████║ ╚████╔╝ ███████║███████╗██████╔╝ ╚███╔╝ 
 *    ██║  ██║██║╚════██║██╔═══╝ ██║     ██╔══██║  ╚██╔╝  ██╔══██║╚════██║██╔═══╝  ██╔██╗ 
 *    ██████╔╝██║███████║██║     ███████╗██║  ██║   ██║██╗██║  ██║███████║██║     ██╔╝ ██╗
 *    ╚═════╝ ╚═╝╚══════╝╚═╝     ╚══════╝╚═╝  ╚═╝   ╚═╝╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝  ╚═╝
 *                                                                                        
 */


function initPage_display() {

    var featureTemplateClasses = "col-md-4 col-xs-6 featured";
    var nonFeatureTemplateClasses = "col-lg-2 col-md-3 col-sm-4 col-xs-6";
    var templateContainer = $(".js-templates-container");
    var templateTemplate = Handlebars.compile($(".handlebars-display-output").first().html());

    $(".js-categorypicker").on("change", function () {

        var subCatIds = $(this).val();

        if (!subCatIds) {
            var subCatArr = [];
            $(this).find("option[value!='']").map(function () { subCatArr.push($(this).attr("value")); });
            subCatIds = subCatArr.join(",");
        }

        $.get('/ssapi/templates/find', {
            CategoryIds: subCatIds
        }, function (data) {

            templateContainer.empty();

            $(".js-template-count").text(data.TemplateCount);

            for (var i = 0; i < data.Templates.length; i++) {
                if (i < 6) data.Templates[i].class = featureTemplateClasses;
                else data.Templates[i].class = nonFeatureTemplateClasses;

                templateContainer.append(templateTemplate(data.Templates[i]));
            }

            $("img.js-lazyload").unveil(100);

            $(".js-narrowbypicker").change();

        }, 'json');

    });

    $(".js-narrowbypicker").on("change", function () {

        $(".js-template").addClass("hidden").removeClass(featureTemplateClasses).addClass(nonFeatureTemplateClasses);

        var productId = $(this).val().replace(/-/g, '');

        if (productId) {
            $(".js-template").each(function () {
                if ($(this).data("productids").replace(/-/g, '').indexOf(productId) >= 0) {
                    $(this).removeClass("hidden");
                }
            });
        } else {
            $(".js-template").removeClass("hidden");
        }

        var templates = $(".js-template").not(".hidden");
        $(".js-template-count").text(templates.length);
        templates.slice(0, 6).removeClass(nonFeatureTemplateClasses).addClass(featureTemplateClasses);

        //trigger unveil
        $(window).scroll();

    });

}

/***
 *    ██╗      ██████╗  ██████╗ ██╗███╗   ██╗    █████╗ ███████╗██████╗ ██╗  ██╗
 *    ██║     ██╔═══██╗██╔════╝ ██║████╗  ██║   ██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝
 *    ██║     ██║   ██║██║  ███╗██║██╔██╗ ██║   ███████║███████╗██████╔╝ ╚███╔╝ 
 *    ██║     ██║   ██║██║   ██║██║██║╚██╗██║   ██╔══██║╚════██║██╔═══╝  ██╔██╗ 
 *    ███████╗╚██████╔╝╚██████╔╝██║██║ ╚████║██╗██║  ██║███████║██║     ██╔╝ ██╗
 *    ╚══════╝ ╚═════╝  ╚═════╝ ╚═╝╚═╝  ╚═══╝╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝  ╚═╝
 *                                                                              
 */
function initPage_login() {

    $('.js-tooltip').tooltip({placement: 'bottom'});
    $('.tab-pane.active').find('.js-focus').first().focus();

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        $('.tab-pane.active').find('.js-focus').first().focus();
    });

    $(".js-register-button").removeClass("btn-danger").addClass("btn-info");
    $(".js-register-button").one("click", function () {
        $(".js-register-controls").slideDown();
        $(this).removeClass("btn-info").addClass("btn-danger");
        return false;
    });
    
}

/***
 *     ██████╗ ██████╗ ██████╗ ███████╗██████╗ ███████╗██╗   ██╗███╗   ███╗███╗   ███╗ █████╗ ██████╗ ██╗   ██╗
 *    ██╔═══██╗██╔══██╗██╔══██╗██╔════╝██╔══██╗██╔════╝██║   ██║████╗ ████║████╗ ████║██╔══██╗██╔══██╗╚██╗ ██╔╝
 *    ██║   ██║██████╔╝██║  ██║█████╗  ██████╔╝███████╗██║   ██║██╔████╔██║██╔████╔██║███████║██████╔╝ ╚████╔╝ 
 *    ██║   ██║██╔══██╗██║  ██║██╔══╝  ██╔══██╗╚════██║██║   ██║██║╚██╔╝██║██║╚██╔╝██║██╔══██║██╔══██╗  ╚██╔╝  
 *    ╚██████╔╝██║  ██║██████╔╝███████╗██║  ██║███████║╚██████╔╝██║ ╚═╝ ██║██║ ╚═╝ ██║██║  ██║██║  ██║   ██║   
 *     ╚═════╝ ╚═╝  ╚═╝╚═════╝ ╚══════╝╚═╝  ╚═╝╚══════╝ ╚═════╝ ╚═╝     ╚═╝╚═╝     ╚═╝╚═╝  ╚═╝╚═╝  ╚═╝   ╚═╝   
 *                                                                                                             
 */

function initPage_ordersummary() {

    function shareDesign(row, clicked) {
        clicked.hide();
        var designnumber = clicked.data("designnumber");
        var sessionid = clicked.data("sessionid");
        var track_label_prefix = clicked.data("page");

        if (designnumber && sessionid) {
            $.ajax('/api/customize/PostShareDesign', {
                type: 'POST',
                data: {
                    DesignNumber: designnumber,
                    SessionId: sessionid
                },
                success: function (data) {
                    if (data.Success === true) {

                        row.find(".js-ordersummary-share-link").prop("disabled", false).val(data.Url);
                        row.find(".js-copytext-button").removeClass("hidden");

                        row.sharer({
                            title: data.Title,
                            url: data.Url,
                            description: data.Description,
                            image_url: data.ImageUrl,
                            track_label: track_label_prefix + ": " + designnumber
                        });

                    } else {
                        //popup_container.empty().html('<p class="text-danger">' + data.Message + '</p>');
                    }
                },
                error: function () {
                    //popup_container.empty().html('<p class="text-danger">Your preview could not be shared. Please try again.</p>');
                }
            });
        }
    }

    $(".js-ordersummaryshare-row").each(function () {

        var row = $(this);

        if (row.data("isshared") == "True") {
            shareDesign(row, row.find(".js-ordersummary-share-design"));
        }

        row.find(".js-ordersummary-share-design").click(function () {
            shareDesign(row, $(this));
        });
    });

}

/***
*    ██████╗ ██████╗  ██████╗  ██████╗ ███████╗██╗████████╗███████╗███╗   ███╗    █████╗ ███████╗██████╗ ██╗  ██╗
*    ██╔══██╗██╔══██╗██╔═══██╗██╔═══██╗██╔════╝██║╚══██╔══╝██╔════╝████╗ ████║   ██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝
*    ██████╔╝██████╔╝██║   ██║██║   ██║█████╗  ██║   ██║   █████╗  ██╔████╔██║   ███████║███████╗██████╔╝ ╚███╔╝ 
*    ██╔═══╝ ██╔══██╗██║   ██║██║   ██║██╔══╝  ██║   ██║   ██╔══╝  ██║╚██╔╝██║   ██╔══██║╚════██║██╔═══╝  ██╔██╗ 
*    ██║     ██║  ██║╚██████╔╝╚██████╔╝██║     ██║   ██║   ███████╗██║ ╚═╝ ██║██╗██║  ██║███████║██║     ██╔╝ ██╗
*    ╚═╝     ╚═╝  ╚═╝ ╚═════╝  ╚═════╝ ╚═╝     ╚═╝   ╚═╝   ╚══════╝╚═╝     ╚═╝╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝  ╚═╝
*                                                                                                                
*/

function initPage_proofitem() {

    var order_item_id = $(".js-order-item-id input").val();

    $(".js-proofapproval-fauxradio-approve").click(function () {

        $(".js-proofapproval-fauxradio-decline").removeClass("selected");
        $(this).addClass("selected");

        $(".js-proofapproval-radio-decline input").prop("checked", false);
        $(".js-proofapproval-radio-approve input").prop("checked", true);

        $(".js-proofapproval-comment").hide();
        
    });

    $(".js-proofapproval-fauxradio-decline").click(function () {

        $(".js-proofapproval-fauxradio-approve").removeClass("selected");
        $(this).addClass("selected");

        $(".js-proofapproval-radio-approve input").prop("checked", false);
        $(".js-proofapproval-radio-decline input").prop("checked", true);

        $(".js-proofapproval-comment").show();

    });

    if ($(".js-proofapproval-radio-approve input").is(":checked")) {
        $(".js-proofapproval-fauxradio-approve").click();
    }

    if ($(".js-proofapproval-radio-decline input").is(":checked")) {
        $(".js-proofapproval-fauxradio-decline").click();
    }

    if (order_item_id && typeof window.sessionStorage != undefined && $(".js-proofitem-comments").val() === "") {
        var comments = window.sessionStorage.getItem("proofItemComments" + order_item_id);
        if (comments) $(".js-proofitem-comments").val(comments);
    }

    $(".js-proofitem-comments").change(function () {
        if (order_item_id && typeof window.sessionStorage != undefined) {
            window.sessionStorage.setItem("proofItemComments" + order_item_id, $(this).val());
        }
    });

    var initPhotoSwipeFromDOM = function (gallerySelector) {

        var parseThumbnailElements = function (el) {
            var thumbElements = el.childNodes,
                numNodes = thumbElements.length,
                items = [],
                el,
                childElements,
                thumbnailEl,
                size,
                item;

            for (var i = 0; i < numNodes; i++) {
                el = thumbElements[i];

                // include only element nodes 
                if (el.nodeType !== 1) {
                    continue;
                }

                childElements = el.children;

                size = el.getAttribute('data-size').split('x');

                // create slide object
                item = {
                    src: el.getAttribute('href'),
                    w: parseInt(size[0], 10),
                    h: parseInt(size[1], 10),
                    el: el
                };

                if (childElements.length > 0) {
                    item.msrc = childElements[0].getAttribute('src'); // thumbnail url
                    if (childElements.length > 1) {
                        item.title = childElements[1].innerHTML; // caption (contents of figure)
                    }
                }

                // original image
                item.o = {
                    src: item.src,
                    w: item.w,
                    h: item.h
                };

                items.push(item);
            }

            return items;
        };

        // find nearest parent element
        var closest = function closest(el, fn) {
            return el && (fn(el) ? el : closest(el.parentNode, fn));
        };

        var onThumbnailsClick = function (e) {
            e = e || window.event;
            e.preventDefault ? e.preventDefault() : e.returnValue = false;

            var eTarget = e.target || e.srcElement;

            var clickedListItem = closest(eTarget, function (el) {
                return el.tagName === 'A';
            });

            if (!clickedListItem) {
                return;
            }

            var clickedGallery = clickedListItem.parentNode;

            var childNodes = clickedListItem.parentNode.childNodes,
                numChildNodes = childNodes.length,
                nodeIndex = 0,
                index;

            for (var i = 0; i < numChildNodes; i++) {
                if (childNodes[i].nodeType !== 1) {
                    continue;
                }

                if (childNodes[i] === clickedListItem) {
                    index = nodeIndex;
                    break;
                }
                nodeIndex++;
            }

            if (index >= 0) {
                openPhotoSwipe(index, clickedGallery);
            }
            return false;
        };

        var openPhotoSwipe = function (index, galleryElement, disableAnimation, fromURL) {
            var pswpElement = document.querySelectorAll('.pswp')[0],
                gallery,
                options,
                items;

            items = parseThumbnailElements(galleryElement);

            // define options (if needed)
            options = {

                galleryUID: galleryElement.getAttribute('data-pswp-uid'),

                getThumbBoundsFn: function (index) {
                    // See Options->getThumbBoundsFn section of docs for more info
                    var thumbnail = items[index].el.children[0],
                        pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                        rect = thumbnail.getBoundingClientRect();

                    return { x: rect.left, y: rect.top + pageYScroll, w: rect.width };
                },

                mainClass: 'pswp--minimal--dark',
                barsSize: { top: 0, bottom: 0 },
                captionEl: false,
                fullscreenEl: false,
                shareEl: false,
                bgOpacity: 0.85,
                tapToClose: true,
                tapToToggleControls: false

            };

            if (fromURL) {
                options.index = parseInt(index, 10) - 1;
            } else {
                options.index = parseInt(index, 10);
            }

            // exit if index not found
            if (isNaN(options.index)) {
                return;
            }

            if (disableAnimation) {
                options.showAnimationDuration = 0;
            }

            // Pass data to PhotoSwipe and initialize it
            gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);

            gallery.init();
        };

        // select all gallery elements
        var galleryElements = document.querySelectorAll(gallerySelector);
        for (var i = 0, l = galleryElements.length; i < l; i++) {
            galleryElements[i].setAttribute('data-pswp-uid', i + 1);
            galleryElements[i].onclick = onThumbnailsClick;
        }

    };

    var photoswipe_images = {
        loaded: 0,
        total: $(".js-photoswipe img").length
    };

    function handleLoadedImage(img) {
        photoswipe_images.loaded++;
        img.closest("a").attr("data-size", img[0].naturalWidth + "x" + img[0].naturalHeight);
        if (photoswipe_images.loaded == photoswipe_images.total) {
            initPhotoSwipeFromDOM('.js-photoswipe');
        }
    }

    $(".js-photoswipe img").each(function () {
        var img = $(this);
        if (img[0].complete) {
            handleLoadedImage(img);
        } else {
            img.on('load', function () {
                handleLoadedImage(img);
            });
        }
    });

}

/***
*    ███████╗███████╗ █████╗ ██████╗  ██████╗██╗  ██╗    █████╗ ███████╗██████╗ ██╗  ██╗
*    ██╔════╝██╔════╝██╔══██╗██╔══██╗██╔════╝██║  ██║   ██╔══██╗██╔════╝██╔══██╗╚██╗██╔╝
*    ███████╗█████╗  ███████║██████╔╝██║     ███████║   ███████║███████╗██████╔╝ ╚███╔╝ 
*    ╚════██║██╔══╝  ██╔══██║██╔══██╗██║     ██╔══██║   ██╔══██║╚════██║██╔═══╝  ██╔██╗ 
*    ███████║███████╗██║  ██║██║  ██║╚██████╗██║  ██║██╗██║  ██║███████║██║     ██╔╝ ██╗
*    ╚══════╝╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚═╝╚═╝  ╚═╝╚══════╝╚═╝     ╚═╝  ╚═╝
*                                                                                       
*/
function initPage_searchresults() {
    ga_track_event("Actions", "search", $(".js-searchpage-query").val());
};
/***
 *    ██╗   ██╗ █████╗ ██╗     ██╗██████╗  █████╗ ████████╗██╗ ██████╗ ███╗   ██╗
 *    ██║   ██║██╔══██╗██║     ██║██╔══██╗██╔══██╗╚══██╔══╝██║██╔═══██╗████╗  ██║
 *    ██║   ██║███████║██║     ██║██║  ██║███████║   ██║   ██║██║   ██║██╔██╗ ██║
 *    ╚██╗ ██╔╝██╔══██║██║     ██║██║  ██║██╔══██║   ██║   ██║██║   ██║██║╚██╗██║
 *     ╚████╔╝ ██║  ██║███████╗██║██████╔╝██║  ██║   ██║   ██║╚██████╔╝██║ ╚████║
 *      ╚═══╝  ╚═╝  ╚═╝╚══════╝╚═╝╚═════╝ ╚═╝  ╚═╝   ╚═╝   ╚═╝ ╚═════╝ ╚═╝  ╚═══╝
 *                                                                               
 */

$(function () {

    var Page_Validators = window.Page_Validators || [];

    //add associated validators so we can run on keyup
    for (var i = 0; i < Page_Validators.length; i++) {
        var ctl = Page_Validators[i].controltovalidate;
        if (typeof ctl != "undefined") {
            var $ctl = $("#" + ctl);
            var validators = $ctl.data("associated_validators");
            if (typeof validators == "undefined" || validators === null) {
                validators = [];
            }

            validators.push($(Page_Validators[i]).attr("id"));
            $ctl.data("associated_validators", validators);

            $("#" + ctl).keyup(function (e) {
                if (e.keyCode != 13) {
                    var validators = $(this).data("associated_validators");
                    for (var i = 0; i < validators.length; i++) {
                        var $validator = $("#" + validators[i]);
                        if (!$validator[0].isvalid || $validator.hasClass("validator-onkeypress")) {
                            $validator.addClass("validator-onkeypress");
                            ValidatorValidate($validator[0]);
                        }
                    }
                }
            });
        }
    }

    //make setFocusOnError work better than native
    if (typeof ValidatorSetFocus != "undefined") {
        var ValidatorSetFocus_Native = ValidatorSetFocus;
        /*jshint -W020 */
        ValidatorSetFocus = function (val, event) {

            //event will be null on form submit
            if (event !== null) {
                return;
            }

            ValidatorSetFocus_Native(val, event);

            $(window).scrollTop($(val).offset().top - 200); //make sure the bad element is in view

            var $fg = $(val).closest(".form-group");
            $fg.removeClass("animated shake");
            $fg[0].offsetWidth = $fg[0].offsetWidth; //trigger reflow to restart animation
            $fg.addClass("animated shake");

        };
    }

});

function customValidatorEnable(validatorSelector, enabled) {
    var $validator = $(validatorSelector);
    resetValidation($validator);
    //need to use $validator[0] because the ValidatorEnable function 
    //is an ASP.NET function and accepts a DOM object not jQuery object
    ValidatorEnable($validator[0], enabled);
}

//this function gets called by ASP.net client validator scripts for customvalidator controls
function customClientValidationFunction(sender, args) {

    var Page_Validators = Page_Validators || [];
    var isValid,
        $field = $('#' + sender.controltovalidate),
        $validator = $(sender),
        $form = $($validator.data('validationForm')),
        validatorFn = window["validate_" + $validator.data('validationType')];

    if (typeof sender.controltovalidate == "undefined") {
        //probably a radio list or something else that can't be a validated control in asp.net

        var $fieldGroup = $form.find("[name$='" + $validator.data('inputGroupName') + "']");
        $field = $fieldGroup.first();

        //we need to manually set the control to validate
        for (var i = 0; i < Page_Validators.length; i++) {
            if (Page_Validators[i] == sender) {
                Page_Validators[i].controltovalidate = $field.attr("id");
            }
        }

        $fieldGroup.change(function () {
            var $validator = $(this).parents(".form-group").find(".help-block");
            resetValidation($validator);
            $validator.hide();
        });

        if ($field.length === 0) {
            //invalid if we still can't find the field
            args.IsValid = false;
            return;
        }
    }

    if ($field.is(':hidden')) {
        //if the field isn't even visible to the user then don't validate
        args.IsValid = true;
        return;
    }

    //if enabled on checkbox and checkbox is not checked, mark as valid and return
    if (typeof $validator.data('validationEnabledOnCheckbox') != "undefined") {
        if (!$($validator.data('validationEnabledOnCheckbox')).is(":checked")) {
            args.IsValid = true;
            return;
        }
    }

    //execute validator function if it exists, otherwise it's automatically invalid
    if (typeof validatorFn === 'function') {
        isValid = validatorFn($form, $field, $validator);
        if (isValid !== null) {
            applyValidation($field, $validator, isValid);
        } else {
            //if validation returned null, don't prevent it from submitting page and just clear styles
            isValid = true;
            resetValidation($validator);
        }
    } else {
        //Invalid validator type so return invalid
        isValid = false;
    }

    args.IsValid = isValid;

    return;
}

function validateHelper_luhn(value) {
    var length = value.length,
        mul = 0,
        prodArr = [[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]],
        sum = 0;

    while (length--) {
        sum += prodArr[mul][parseInt(value.charAt(length), 10)];
        mul ^= 1;
    }

    return sum % 10 === 0 && sum > 0;
}

//field is required
function validate_notEmpty($form, $field, $validator) {
    var type = $field.attr('type');
    if ('radio' == type || 'checkbox' == type) {
        return $form.find("[name='" + $field.attr('name') + "']")
            .filter(':checked')
            .length > 0;
    }

    return $.trim($field.val()) !== '';
}

//field must have an email address format
function validate_emailAddress($form, $field, $validator) {
    var value = $field.val();
    if (value === '') {
        return true;
    }

    // Email address regular expression
    // http://stackoverflow.com/questions/46155/validate-email-address-in-javascript
    var emailRegExp = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    if (emailRegExp.test(value)) {

        //ignore fuzzy matching for now
        return true;

        //valid email address, let's check for typos
        //var name = value.split("@")[0];
        //var domain = value.split("@")[1];
        //var suggested_domains = ["gmail.com", "hotmail.com", "hotmail.co.uk", "yahoo.com", "aol.com", "msn.com", "sbcglobal.net", "verizon.net", "cox.net", "bellsouth.net", "att.net", "comcast.net", "uic.edu", "earthlink.net", "live.com", "charter.net", "mac.com", "optonline.net", "juno.com", "ymail.com", "jhmi.edu", "aim.com", "me.com", "rocketmail.com", "mail.com", "duke.edu", "q.com", "bachor.com", "email.com"];
        //var suggested_domain;
        //var best_guess = 0;
        //var stop_guessing = false;

        //for (var i = 0; i < suggested_domains.length; i++) {
        //    if (!stop_guessing) {
        //        var match_percent = check_levenshtein(domain, suggested_domains[i]);
        //        if (match_percent == 100) {
        //            best_guess = 100;
        //            stop_guessing = true;
        //        }
        //        if (match_percent > best_guess) {
        //            suggested_domain = suggested_domains[i];
        //            best_guess = match_percent;
        //        }
        //    }
        //}

        //var suggestion = name + "@" + suggested_domain;

        //if (best_guess >= 80 && best_guess < 100) {
        //    var $content = $('<p class="text-center kill-bottom">Did you mean ' + name + '@<strong>' + suggested_domain + '</em>?<br /></p>');
        //    var $fill_button = $('<button type="button" class="btn btn-link">Yes</button>').click(function () {
        //        $field.val(suggestion);
        //        $field.popover('destroy');
        //    });
        //    var $no_button = $('<button type="button" class="btn btn-sm btn-link">No</button>').click(function () {
        //        ga_track_event('Actions', 'Domain OK', domain, null, true);
        //        $field.popover('destroy');
        //    });
        //    $content.append($fill_button);
        //    $content.append($no_button);

        //    $field.popover({
        //        content: $content,
        //        html: true,
        //        placement: "top"
        //    }).popover('show');

        //} else {
        //    $field.popover('destroy');
        //}

        //return true;
    } else {
        return false;
    }

}

function validate_stringLength($form, $field, $validator) {
    var value = $field.val();
    if (value === '') {
        return true;
    }

    var minLength = $validator.data('validationStringlengthMin');
    var maxLength = $validator.data('validationStringlengthMax');
    var length = $.trim(value).length;
    if ((minLength && length < minLength) || (maxLength && length > maxLength)) {
        return false;
    }

    return true;
}

function validate_greaterThan($form, $field, $validator) {
    var value = $field.val();
    if (value === '') {
        return true;
    }

    var minValue = parseFloat($validator.data('validationValueMin'));
    var value_float = Math.floor(parseFloat(value));

    if (isFinite(value_float) && minValue < value_float) {
        $field.val(value_float);
        return true;
    }

    return false;
}

function validate_greaterThanAllowDecimal($form, $field, $validator) {
    var value = $field.val();
    if (value === '') {
        return true;
    }

    var minValue = parseFloat($validator.data('validationValueMin'));
    var value_float = parseFloat(value);

    if (isFinite(value_float) && minValue < value_float) {
        $field.val(value_float);
        return true;
    }

    return false;
}

function validate_isSame($form, $field, $validator) {

    var thisValue = $field.val();

    if (thisValue === '') {
        return true;
    }

    var thatValue = $form.find("[id$=" + $validator.data("validationIsSame") + "]").first();
    //need to use this style of selector because asp.net client id is generated and we need to use the regular ID for the server side

    if (thatValue === null) {
        return true;
    }

    return thisValue == thatValue.val();

}

function validate_regexMatch($form, $field, $validator) {
    var matches = $.trim($field.val()).match($validator.data("validationRegex"));
    return matches !== null && matches.length > 0;
}

function validate_hasFile($form, $field, $validator) {
    return $.trim($field.val()) !== '';
}

function validate_customFunction($form, $field, $validator) {
    var isValid = false;
    var customValidatorFn = window[$validator.data('validationFunction')];
    if (typeof customValidatorFn === 'function') {
        isValid = customValidatorFn($form, $field, $validator);
    }
    return isValid;
}

function resetValidation($validator) {
    var $parent = $validator.closest('.form-group'),
        $feedback = $parent.find('.form-control-feedback').first();

    $parent.removeClass('has-error has-success');
    $feedback.addClass('hidden');
}

function validate_isValidCreditCard($form, $field, $validator) {

    var value = $field.val();

    //must not be empty
    if (value === '') {
        return false;
    }

    //must contain only digits, dashes, or spaces
    if (/[^0-9-\s]+/.test(value)) {
        return false;
    }

    //strip everything but digits then perform luhn checksum algorithm
    value = value.replace(/\D/g, '');
    if (!validateHelper_luhn(value)) {
        return false;
    }

    // Validate the card number based on prefix (IIN ranges) and length
    var cards = {
        AMERICAN_EXPRESS: {
            length: [15],
            prefix: ['34', '37']
        },
        DINERS_CLUB: {
            length: [14],
            prefix: ['300', '301', '302', '303', '304', '305', '36']
        },
        DINERS_CLUB_US: {
            length: [16],
            prefix: ['54', '55']
        },
        DISCOVER: {
            length: [16],
            prefix: ['6011', '622126', '622127', '622128', '622129', '62213',
                '62214', '62215', '62216', '62217', '62218', '62219',
                '6222', '6223', '6224', '6225', '6226', '6227', '6228',
                '62290', '62291', '622920', '622921', '622922', '622923',
                '622924', '622925', '644', '645', '646', '647', '648',
                '649', '65']
        },
        JCB: {
            length: [16],
            prefix: ['3528', '3529', '353', '354', '355', '356', '357', '358']
        },
        LASER: {
            length: [16, 17, 18, 19],
            prefix: ['6304', '6706', '6771', '6709']
        },
        MAESTRO: {
            length: [12, 13, 14, 15, 16, 17, 18, 19],
            prefix: ['5018', '5020', '5038', '6304', '6759', '6761', '6762', '6763', '6764', '6765', '6766']
        },
        MASTERCARD: {
            length: [16],
            prefix: ['51', '52', '53', '54', '55']
        },
        SOLO: {
            length: [16, 18, 19],
            prefix: ['6334', '6767']
        },
        UNIONPAY: {
            length: [16, 17, 18, 19],
            prefix: ['622126', '622127', '622128', '622129', '62213', '62214',
                '62215', '62216', '62217', '62218', '62219', '6222', '6223',
                '6224', '6225', '6226', '6227', '6228', '62290', '62291',
                '622920', '622921', '622922', '622923', '622924', '622925']
        },
        VISA: {
            length: [16],
            prefix: ['4']
        }
    };

    var type, i;
    for (type in cards) {
        if (cards.hasOwnProperty(type)) {
            for (i in cards[type].prefix) {
                if (value.substr(0, cards[type].prefix[i].length) == cards[type].prefix[i] // Check the prefix
                    && cards[type].length.indexOf(value.length) != -1) // and length
                {
                    return true;
                }
            }
        }
    }

    return false;


}

function validate_creditCardExpiration($form, $field, $validator) {

    var month = parseInt($(".js-credit-card-exp-month").val(), 10);
    var year = parseInt($(".js-credit-card-exp-year").val(), 10);

    if (!isNaN(month) && !isNaN(year)) {

        var now = new Date();
        var expires = new Date(year, month);

        $validator.addClass("validator-isvalidating");

        if ($validator.hasClass("js-validator-cc-month") && !$(".js-validator-cc-year").hasClass("validator-isvalidating")) {
            customValidatorEnable(".js-validator-cc-year");
        }
        if ($validator.hasClass("js-validator-cc-year") && !$(".js-validator-cc-month").hasClass("validator-isvalidating")) {
            customValidatorEnable(".js-validator-cc-month");
        }

        if (now < expires) return true;

    } else {

        return null;

    }

    return false;

}

function validate_orderGroupNeedsPassword($form, $field, $validator) {
    if ($form.find(".js-order-group option:selected").data("haspassword") == 1) {
        return $.trim($field.val()) !== '';
    }
}

function validate_isValidNeedByDate($form, $field, $validator) {
    if ($.trim($field.val())) {
        var needByDate = moment($field.val(), "MM/DD/YYYY");
        return needByDate.isSameOrAfter(moment(), 'day');
    }
}

function applyValidation($field, $validator, validatorIsValid) {

    var allValidators = $field.data('validators'),
        $parent = $field.closest('.form-group'),
        $feedback = $parent.find('.form-control-feedback').first(),
        validationType = $validator.data('validationType'),
        fieldIsValid;

    //init allvalidators object if the element doesn't have it in data already
    if (!allValidators) {
        allValidators = {};
    }

    //save whether the validator is true or false on the object using it's validationtype as the key
    allValidators[validationType] = validatorIsValid;

    //save all of the validator data to the field's data object
    $field.data('validators', allValidators);

    //loop through all of the validators on the object to see if any of them are invalid
    fieldIsValid = validatorIsValid;
    for (var key in allValidators) {
        if (allValidators.hasOwnProperty(key)) {
            if (!allValidators[key]) {
                //we found an invalid entry so the whole field is invalid
                fieldIsValid = false;
                break;
            }
        }
    }

    //add the feedback icon to the input box if it doesn't exist
    if (!$feedback.length) {
        $feedback = $('<span class="form-control-feedback glyphicon hidden" />');
        var $inputGroup = $field.closest(".input-group");
        if ($inputGroup.length > 0)
            $feedback.insertAfter($inputGroup);
        else
            $feedback.insertAfter($field);
    }

    //apply valid styles only if everything is valid on that field
    if (fieldIsValid) {
        $feedback.removeClass('glyphicon-remove hidden').addClass('glyphicon-ok');
        $parent.removeClass('has-error').addClass('has-success has-feedback');
        $validator.hide();
    } else {
        $feedback.removeClass('glyphicon-ok hidden').addClass('glyphicon-remove');
        $parent.removeClass('has-success').addClass('has-error has-feedback');
        $validator.show();
    }

    $(".validator-isvalidating").removeClass("validator-isvalidating");
};
// @reference ../vendor/bootstrap.min.js

(function ($, window, document, undefined) {

    // Create the defaults once
    var pluginName = 'contactUs',
        defaults = {
            name: null,
            title: null,
            industry: null,
            company: null,
            numberOfStores: null,
            email: null,
            subject: null,
            orderNumber: null,
            phoneNumber: null,
            comments: null,
            introText: null,
            showOrderNumberField: true,
            modalSelector: '#js-main-contactus-modal',
            modalTitleSelector: ".js-contactus-modaltitle",
            nameSelector: '.js-contactus-name',
            titleSelector: '.js-contactus-title',
            industrySelector: '.js-contactus-industry',
            companySelector: '.js-contactus-company',
            numberOfStoresSelector: '.js-contacus-numberofstores',
            emailSelector: '.js-contactus-email',
            subjectSelector: '.js-contactus-subject',
            orderNumberSelector: '.js-contactus-ordernumber',
            phoneNumberSelector: '.js-contactus-phone',
            commentsSelector: '.js-contactus-comments',
            introTextSelector: '.js-contactus-introtext',
            submitButtonSelector: '.js-contact-submit-button',
            validationGroup : "ContactUsForm"
        };

    var publicMethods = {
        toggle: function() {
            this.toggle();
        }
    };

    // The actual plugin constructor skeleton, do the rest of the methods with prototypes
    function ContactUs(element, options) {
        this.element = element;
        this.$el = $(element);

        // merge options with defaults (html5 data attributes were merged before this plugin)
        this.options = $.extend({}, defaults, options);

        this.$modal = $(this.options.modalSelector);

        this._defaults = defaults;
        this._name = pluginName;
        
        //init plugin on element
        this.init();

    }

    ContactUs.prototype = {
        init: function () {

            var _self = this;


            //init textbox values with defaults if provided
            if (this.options.modalTitle) {
                _self.setModalTitle(this.options.modalTitle);
            }

            if (this.options.name) {
                _self.setName(this.options.name);
            }

            if (this.options.title) {
                _self.setTitle(this.options.title);
            }

            if (this.options.industry) {
                _self.setIndustry(this.options.industry);
            }

            if (this.options.company) {
                _self.setCompany(this.options.company);
            }

            if (this.options.numberOfStores) {
                _self.setNumberOfStores(this.options.numberOfStores);
            }

            if (this.options.email) {
                _self.setEmail(this.options.email);
            }

            if (this.options.subject) {
                _self.setSubject(this.options.subject);
            }

            if (this.options.orderNumber) {
                _self.setOrderNumber(this.options.orderNumber);
            }

            if (this.options.phoneNumber) {
                _self.setPhoneNumber(this.options.phoneNumber);
            }

            if (this.options.comments) {
                _self.setComments(this.options.comments);
            }

            if (this.options.introText) {
                _self.setIntroText(this.options.introText);
            } else {
                _self.$modal.find(_self.options.introTextSelector).hide();
            }

            if (!this.options.showOrderNumberField) {
                _self.$modal.find(".js-contactus-ordernumberfield").hide();
            }

        },

        log: function (text) {
            //init console for older browsers
            if (!window.console) { window.console = { log: function () { } }; }
            console.log(this._name + ": " + text);
        },

        show: function () {
            this.$modal.modal('show');
        },

        hide: function () {
            this.$modal.modal('hide');
        },

        toggle: function () {
            this.$modal.modal('toggle');
        },

        setModalTitle: function (modalTitle) {
            var _self = this;
            _self.$modal.find(_self.options.modalTitleSelector).text(modalTitle);
        },

        setName: function (name) {
            var _self = this;
            _self.$modal.find(_self.options.nameSelector).val(name);
        },

        setTitle: function (title) {
            var _self = this;
            _self.$modal.find(_self.options.titleSelector).val(title);
        },

        setIndustry: function (industry) {
            var _self = this;
            _self.$modal.find(_self.options.industrySelector).val(industry);
        },

        setCompany: function (company) {
            var _self = this;
            _self.$modal.find(_self.options.companySelector).val(company);
        },

        setNumberOfStores: function (numberOfStores) {
            var _self = this;
            _self.$modal.find(_self.options.numberOfStoresSelector).val(numberOfStores);
        },

        setEmail: function (email) {
            var _self = this;
            _self.$modal.find(_self.options.emailSelector).val(email);
        },

        setSubject: function (subject) {
            var _self = this;
            _self.$modal.find(_self.options.subjectSelector).val(subject);
        },

        setOrderNumber: function (orderNumber) {
            var _self = this;
            _self.$modal.find(_self.options.orderNumberSelector).val(orderNumber);
        },

        setPhoneNumber: function (phoneNumber) {
            var _self = this;
            _self.$modal.find(_self.options.phoneNumberSelector).val(phoneNumber);
        },

        setComments: function (comments) {
            var _self = this;
            _self.$modal.find(_self.options.commentsSelector).val(comments);
        },

        setIntroText: function(introtext) {
            var _self = this;
            _self.$modal.find(_self.options.introTextSelector).text(introtext);
        }
    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (methodOrOptions) {

        if (publicMethods[methodOrOptions]) {
            //method called
            return publicMethods[methodOrOptions].apply($.data(this, 'plugin_' + pluginName), Array.prototype.slice.call(arguments, 1));
        } else if (typeof methodOrOptions == "object" || !methodOrOptions) {
            //init
            if (!$.data(this, 'plugin_' + pluginName)) {

                //merge the data options with the options, taking preference to the options if they exist
                //in order to do camel case, data-camel-case in html is == camelCase
                methodOrOptions = $.extend($(this).data(), methodOrOptions);

                $.data(this, 'plugin_' + pluginName, new ContactUs(this, methodOrOptions));
            }
        }

        return this;
    };

})(jQuery, window, document);

//auto init plugin
$(function () {
    $(document).on('click', '.js-contactus-click', function () {
        $(this).contactUs().contactUs('toggle');

        return false;
    });
});;
(function ($, window, document, undefined) {

    // Create the defaults once
    var pluginName = 'estimatedShipping',
            defaults = {
                orderNumber: null,
                getShippingServicesEndpoint: "/api/products/GetShippingServices",
                shippingServiceRowSelector: ".js-shipping-service-row",
                newShippingServiceRowClass: "estShipCostRow js-shipping-service-row",
                shippingZipInputSelector: ".js-cart-shipping-zip-input",
                shippingZipButtonSelector: ".js-cart-shipping-zip-button",
                shippingZipErrorSelector: ".js-cart-shipping-ziperror"
            };

    // The actual plugin constructor
    function EstimatedShipping(element, options) {
        this.element = element;
        this.$el = $(element);

        this.options = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    EstimatedShipping.prototype = {

        log: function (text) {
            var _self = this;
            //init console for older browsers
            if (!window.console) { window.console = { log: function () { } }; }
            console.log(_self._name + ": " + text);
        },

        init: function () {
            this.validate();
            this.bindEvents();
        },

        validate: function () {
            var _self = this;
            if (!_self.options.orderNumber) {
                _self.log("Error: orderNumber not provided");
            }
        },

        bindEvents: function () {
            var self = this;
            $.subscribe('app/order/updateEstimatedShipping', function () {
                var shippingZip = self.$el.find(self.options.shippingZipInputSelector).val();
                self.refreshShippingEstimates(shippingZip);
            });
            self.$el.find(self.options.shippingZipButtonSelector).click(function () {
                self.updateEstimatedShipping();
            });
            self.$el.find(self.options.shippingZipInputSelector).on('keypress', function (e) {
                if (e.which === 13) {
                    self.updateEstimatedShipping();
                    e.preventDefault();
                }
            });
        },

        refreshShippingEstimates: function (shippingZip) {
            var self = this;
            var shippingZipError = self.$el.find(self.options.shippingZipErrorSelector);
            $.getJSON(self.options.getShippingServicesEndpoint, { "OrderNumber": self.options.orderNumber, "ShippingZip": shippingZip }, function (data) {
                self.$el.find(self.options.shippingServiceRowSelector).remove();

                //show error message if we don't get any shipping services back for this zip code
                if (!data || data.length == 0) {
                    shippingZipError.removeClass("hidden");
                }

                $.each(data, function (index, item) {

                    var rushElement = "";
                    if (item.IsRush) {
                        rushElement = ' <span class="text-blue text-uppercase small"> <br /><span class="glyphicon glyphicon-flash"></span>Rush Service</span>';
                    }

                    var itemNoteElement = "";
                    if (item.Note) {
                        itemNoteElement = '<br><small class="text-muted">' + item.Note + '</small>';
                    }

                    self.$el.append('<tr class="' + self.options.newShippingServiceRowClass + '"><td><span class="nowrap">' + item.NameOrDeliveryDate + '</span>' + rushElement + itemNoteElement + '</td><td class="price">' + item.Cost + "</td></tr>");
                });
            });
        },

        updateEstimatedShipping: function () {
            var self = this;
            var shippingZip = self.$el.find(self.options.shippingZipInputSelector).val();
            var shippingZipError = self.$el.find(self.options.shippingZipErrorSelector);

            if (shippingZip && shippingZip.length >= 5) {
                shippingZipError.addClass("hidden");

                self.refreshShippingEstimates(shippingZip);

                if (typeof ga_track_event == 'function') {
                    ga_track_event("Cart Actions", "Zip Code Delivery Estimate", shippingZip);
                }
            } else {
                shippingZipError.removeClass("hidden");
            }

        }


    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                //merge the data options with the options, taking preference to the options if they exist
                //in order to do camel case, data-camel-case in html is == camelCase
                options = $.extend($(this).data(), options);
                $.data(this, 'plugin_' + pluginName,
                    new EstimatedShipping(this, options));
            }
        });
    };

})(jQuery, window, document);;
(function ($, window, document, undefined) {

    // Create the defaults once
    var pluginName = 'sharer',
            defaults = {
                title: null,
                description: null,
                url: null,
                image_url: null,
                popup: true,
                track_label: "",
                button_class: "btn btn-block"
            };

    // The actual plugin constructor
    function Sharer(element, options) {
        this.element = element;
        this.$el = $(element);

        this.options = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        this.init();
    }

    Sharer.prototype = {

        log: function (text) {
            var _self = this;
            //init console for older browsers
            if (!window.console) { window.console = { log: function () { } }; }
            console.log(_self._name + ": " + text);
        },

        init: function () {

            var _self = this;

            // url and title required
            if (!_self.options.url || !_self.options.title) return;

            _self.$el.find(".js-sharer").each(function () {
                _self.addButton($(this));
            });

        },

        addButton: function ($container) {

            var _self = this;
            var $link = $('<a class="' + _self.options.button_class + '" />');

            var encoded_url = encodeURIComponent(_self.options.url);
            var encoded_description = encodeURIComponent(_self.options.description);
            var encoded_imageurl = encodeURIComponent(_self.options.image_url);
            var should_track = (typeof ga_track_event == "function");

            switch ($container.data("network")) {
                case "facebook" :
                    $link.addClass("btn-facebook");
                    $link.attr("href", "http://www.facebook.com/sharer/sharer.php?u=" + encoded_url);
                    $link.html('<span class="glyphicon custom-icon icon-facebook" /> Share on Facebook');
                    $link.click(function () {
                        if (should_track) {
                            ga_track_event("Social Clicks", "facebook", _self.options.track_label);
                        }
                    });
                    break;
                case "twitter":
                    $link.addClass("btn-twitter");
                    $link.attr("href", "https://twitter.com/intent/tweet?text=" + encoded_description + "%20" + encoded_url);
                    $link.html('<span class="glyphicon custom-icon icon-twitter" /> Tweet on Twitter');
                    $link.click(function () {
                        if (should_track) {
                            ga_track_event("Social Clicks", "twitter", _self.options.track_label);
                        }
                    });
                    break;
                case "pinterest":
                    $link.addClass("btn-pinterest");
                    $link.attr("href", "http://pinterest.com/pin/create/button/?url=" + encoded_url + "&amp;media=" + encoded_imageurl + "&amp;description=" + encoded_description);
                    $link.html('<span class="glyphicon custom-icon icon-pinterest" /> Pin on Pinterest');
                    $link.click(function () {
                        if (should_track) {
                            ga_track_event("Social Clicks", "pinterest", _self.options.track_label);
                        }
                    });
                    break;
            }

            if (_self.options.popup) {
                $link.click(function (e) {
                    _self.popupCenter($(this).attr("href"), _self.options.title, 580, 470);
                    e.preventDefault();
                    return false;
                });
            }

            $container.empty().append($link);

        },

        popupCenter: function(url, title, w, h) {

            var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left;
            var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top;
            var width = window.innerWidth ? window.innerWidth : document.documentElement.clientWidth ? document.documentElement.clientWidth : screen.width;
            var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
            var left = ((width / 2) - (w / 2)) + dualScreenLeft;
            var top = ((height / 3) - (h / 3)) + dualScreenTop;

            var newWindow = window.open(url, title, 'scrollbars=yes, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);

            // Puts focus on the newWindow
            if (newWindow && newWindow.focus) {
                newWindow.focus();
            }
        }

    };

    // A really lightweight plugin wrapper around the constructor,
    // preventing against multiple instantiations
    $.fn[pluginName] = function (options) {
        return this.each(function () {
            if (!$.data(this, 'plugin_' + pluginName)) {
                //merge the data options with the options, taking preference to the options if they exist
                //in order to do camel case, data-camel-case in html is == camelCase
                options = $.extend($(this).data(), options);
                $.data(this, 'plugin_' + pluginName,
                    new Sharer(this, options));
            }
        });
    };

})(jQuery, window, document);;
