/* Minification failed. Returning unminified contents.
(11,7563-7570): run-time error JS1300: Strict-mode does not allow assignment to undefined variables: Promise
 */
/*!
 * https://github.com/paulmillr/es6-shim
 * @license es6-shim Copyright 2013-2016 by Paul Miller (http://paulmillr.com)
 *   and contributors,  MIT License
 * es6-shim: v0.35.4
 * see https://github.com/paulmillr/es6-shim/blob/0.35.3/LICENSE
 * Details and documentation:
 * https://github.com/paulmillr/es6-shim/
 */
(function(e,t){if(typeof define==="function"&&define.amd){define(t)}else if(typeof exports==="object"){module.exports=t()}else{e.returnExports=t()}})(this,function(){"use strict";var e=Function.call.bind(Function.apply);var t=Function.call.bind(Function.call);var r=Array.isArray;var n=Object.keys;var o=function notThunker(t){return function notThunk(){return!e(t,this,arguments)}};var i=function(e){try{e();return false}catch(t){return true}};var a=function valueOrFalseIfThrows(e){try{return e()}catch(t){return false}};var u=o(i);var f=function(){return!i(function(){return Object.defineProperty({},"x",{get:function(){}})})};var s=!!Object.defineProperty&&f();var c=function foo(){}.name==="foo";var l=Function.call.bind(Array.prototype.forEach);var p=Function.call.bind(Array.prototype.reduce);var v=Function.call.bind(Array.prototype.filter);var y=Function.call.bind(Array.prototype.some);var h=function(e,t,r,n){if(!n&&t in e){return}if(s){Object.defineProperty(e,t,{configurable:true,enumerable:false,writable:true,value:r})}else{e[t]=r}};var b=function(e,t,r){l(n(t),function(n){var o=t[n];h(e,n,o,!!r)})};var g=Function.call.bind(Object.prototype.toString);var d=typeof/abc/==="function"?function IsCallableSlow(e){return typeof e==="function"&&g(e)==="[object Function]"}:function IsCallableFast(e){return typeof e==="function"};var m={getter:function(e,t,r){if(!s){throw new TypeError("getters require true ES5 support")}Object.defineProperty(e,t,{configurable:true,enumerable:false,get:r})},proxy:function(e,t,r){if(!s){throw new TypeError("getters require true ES5 support")}var n=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(r,t,{configurable:n.configurable,enumerable:n.enumerable,get:function getKey(){return e[t]},set:function setKey(r){e[t]=r}})},redefine:function(e,t,r){if(s){var n=Object.getOwnPropertyDescriptor(e,t);n.value=r;Object.defineProperty(e,t,n)}else{e[t]=r}},defineByDescriptor:function(e,t,r){if(s){Object.defineProperty(e,t,r)}else if("value"in r){e[t]=r.value}},preserveToString:function(e,t){if(t&&d(t.toString)){h(e,"toString",t.toString.bind(t),true)}}};var O=Object.create||function(e,t){var r=function Prototype(){};r.prototype=e;var o=new r;if(typeof t!=="undefined"){n(t).forEach(function(e){m.defineByDescriptor(o,e,t[e])})}return o};var w=function(e,t){if(!Object.setPrototypeOf){return false}return a(function(){var r=function Subclass(t){var r=new e(t);Object.setPrototypeOf(r,Subclass.prototype);return r};Object.setPrototypeOf(r,e);r.prototype=O(e.prototype,{constructor:{value:r}});return t(r)})};var j=function(){if(typeof self!=="undefined"){return self}if(typeof window!=="undefined"){return window}if(typeof global!=="undefined"){return global}throw new Error("unable to locate global object")};var S=j();var T=S.isFinite;var I=Function.call.bind(String.prototype.indexOf);var E=Function.apply.bind(Array.prototype.indexOf);var P=Function.call.bind(Array.prototype.concat);var C=Function.call.bind(String.prototype.slice);var M=Function.call.bind(Array.prototype.push);var x=Function.apply.bind(Array.prototype.push);var N=Function.call.bind(Array.prototype.join);var A=Function.call.bind(Array.prototype.shift);var R=Math.max;var _=Math.min;var k=Math.floor;var L=Math.abs;var F=Math.exp;var D=Math.log;var z=Math.sqrt;var q=Function.call.bind(Object.prototype.hasOwnProperty);var W;var G=function(){};var H=S.Map;var V=H&&H.prototype["delete"];var B=H&&H.prototype.get;var U=H&&H.prototype.has;var $=H&&H.prototype.set;var J=S.Symbol||{};var X=J.species||"@@species";var K=Number.isNaN||function isNaN(e){return e!==e};var Z=Number.isFinite||function isFinite(e){return typeof e==="number"&&T(e)};var Y=d(Math.sign)?Math.sign:function sign(e){var t=Number(e);if(t===0){return t}if(K(t)){return t}return t<0?-1:1};var Q=function log1p(e){var t=Number(e);if(t<-1||K(t)){return NaN}if(t===0||t===Infinity){return t}if(t===-1){return-Infinity}return 1+t-1===0?t:t*(D(1+t)/(1+t-1))};var ee=function isArguments(e){return g(e)==="[object Arguments]"};var te=function isArguments(e){return e!==null&&typeof e==="object"&&typeof e.length==="number"&&e.length>=0&&g(e)!=="[object Array]"&&g(e.callee)==="[object Function]"};var re=ee(arguments)?ee:te;var ne={primitive:function(e){return e===null||typeof e!=="function"&&typeof e!=="object"},string:function(e){return g(e)==="[object String]"},regex:function(e){return g(e)==="[object RegExp]"},symbol:function(e){return typeof S.Symbol==="function"&&typeof e==="symbol"}};var oe=function overrideNative(e,t,r){var n=e[t];h(e,t,r,true);m.preserveToString(e[t],n)};var ie=typeof J==="function"&&typeof J["for"]==="function"&&ne.symbol(J());var ae=ne.symbol(J.iterator)?J.iterator:"_es6-shim iterator_";if(S.Set&&typeof(new S.Set)["@@iterator"]==="function"){ae="@@iterator"}if(!S.Reflect){h(S,"Reflect",{},true)}var ue=S.Reflect;var fe=String;var se=typeof document==="undefined"||!document?null:document.all;var ce=se==null?function isNullOrUndefined(e){return e==null}:function isNullOrUndefinedAndNotDocumentAll(e){return e==null&&e!==se};var le={Call:function Call(t,r){var n=arguments.length>2?arguments[2]:[];if(!le.IsCallable(t)){throw new TypeError(t+" is not a function")}return e(t,r,n)},RequireObjectCoercible:function(e,t){if(ce(e)){throw new TypeError(t||"Cannot call method on "+e)}return e},TypeIsObject:function(e){if(e===void 0||e===null||e===true||e===false){return false}return typeof e==="function"||typeof e==="object"||e===se},ToObject:function(e,t){return Object(le.RequireObjectCoercible(e,t))},IsCallable:d,IsConstructor:function(e){return le.IsCallable(e)},ToInt32:function(e){return le.ToNumber(e)>>0},ToUint32:function(e){return le.ToNumber(e)>>>0},ToNumber:function(e){if(ie&&g(e)==="[object Symbol]"){throw new TypeError("Cannot convert a Symbol value to a number")}return+e},ToInteger:function(e){var t=le.ToNumber(e);if(K(t)){return 0}if(t===0||!Z(t)){return t}return(t>0?1:-1)*k(L(t))},ToLength:function(e){var t=le.ToInteger(e);if(t<=0){return 0}if(t>Number.MAX_SAFE_INTEGER){return Number.MAX_SAFE_INTEGER}return t},SameValue:function(e,t){if(e===t){if(e===0){return 1/e===1/t}return true}return K(e)&&K(t)},SameValueZero:function(e,t){return e===t||K(e)&&K(t)},IsIterable:function(e){return le.TypeIsObject(e)&&(typeof e[ae]!=="undefined"||re(e))},GetIterator:function(e){if(re(e)){return new W(e,"value")}var t=le.GetMethod(e,ae);if(!le.IsCallable(t)){throw new TypeError("value is not an iterable")}var r=le.Call(t,e);if(!le.TypeIsObject(r)){throw new TypeError("bad iterator")}return r},GetMethod:function(e,t){var r=le.ToObject(e)[t];if(ce(r)){return void 0}if(!le.IsCallable(r)){throw new TypeError("Method not callable: "+t)}return r},IteratorComplete:function(e){return!!e.done},IteratorClose:function(e,t){var r=le.GetMethod(e,"return");if(r===void 0){return}var n,o;try{n=le.Call(r,e)}catch(i){o=i}if(t){return}if(o){throw o}if(!le.TypeIsObject(n)){throw new TypeError("Iterator's return method returned a non-object.")}},IteratorNext:function(e){var t=arguments.length>1?e.next(arguments[1]):e.next();if(!le.TypeIsObject(t)){throw new TypeError("bad iterator")}return t},IteratorStep:function(e){var t=le.IteratorNext(e);var r=le.IteratorComplete(t);return r?false:t},Construct:function(e,t,r,n){var o=typeof r==="undefined"?e:r;if(!n&&ue.construct){return ue.construct(e,t,o)}var i=o.prototype;if(!le.TypeIsObject(i)){i=Object.prototype}var a=O(i);var u=le.Call(e,a,t);return le.TypeIsObject(u)?u:a},SpeciesConstructor:function(e,t){var r=e.constructor;if(r===void 0){return t}if(!le.TypeIsObject(r)){throw new TypeError("Bad constructor")}var n=r[X];if(ce(n)){return t}if(!le.IsConstructor(n)){throw new TypeError("Bad @@species")}return n},CreateHTML:function(e,t,r,n){var o=le.ToString(e);var i="<"+t;if(r!==""){var a=le.ToString(n);var u=a.replace(/"/g,"&quot;");i+=" "+r+'="'+u+'"'}var f=i+">";var s=f+o;return s+"</"+t+">"},IsRegExp:function IsRegExp(e){if(!le.TypeIsObject(e)){return false}var t=e[J.match];if(typeof t!=="undefined"){return!!t}return ne.regex(e)},ToString:function ToString(e){if(ie&&g(e)==="[object Symbol]"){throw new TypeError("Cannot convert a Symbol value to a number")}return fe(e)}};if(s&&ie){var pe=function defineWellKnownSymbol(e){if(ne.symbol(J[e])){return J[e]}var t=J["for"]("Symbol."+e);Object.defineProperty(J,e,{configurable:false,enumerable:false,writable:false,value:t});return t};if(!ne.symbol(J.search)){var ve=pe("search");var ye=String.prototype.search;h(RegExp.prototype,ve,function search(e){return le.Call(ye,e,[this])});var he=function search(e){var t=le.RequireObjectCoercible(this);if(!ce(e)){var r=le.GetMethod(e,ve);if(typeof r!=="undefined"){return le.Call(r,e,[t])}}return le.Call(ye,t,[le.ToString(e)])};oe(String.prototype,"search",he)}if(!ne.symbol(J.replace)){var be=pe("replace");var ge=String.prototype.replace;h(RegExp.prototype,be,function replace(e,t){return le.Call(ge,e,[this,t])});var de=function replace(e,t){var r=le.RequireObjectCoercible(this);if(!ce(e)){var n=le.GetMethod(e,be);if(typeof n!=="undefined"){return le.Call(n,e,[r,t])}}return le.Call(ge,r,[le.ToString(e),t])};oe(String.prototype,"replace",de)}if(!ne.symbol(J.split)){var me=pe("split");var Oe=String.prototype.split;h(RegExp.prototype,me,function split(e,t){return le.Call(Oe,e,[this,t])});var we=function split(e,t){var r=le.RequireObjectCoercible(this);if(!ce(e)){var n=le.GetMethod(e,me);if(typeof n!=="undefined"){return le.Call(n,e,[r,t])}}return le.Call(Oe,r,[le.ToString(e),t])};oe(String.prototype,"split",we)}var je=ne.symbol(J.match);var Se=je&&function(){var e={};e[J.match]=function(){return 42};return"a".match(e)!==42}();if(!je||Se){var Te=pe("match");var Ie=String.prototype.match;h(RegExp.prototype,Te,function match(e){return le.Call(Ie,e,[this])});var Ee=function match(e){var t=le.RequireObjectCoercible(this);if(!ce(e)){var r=le.GetMethod(e,Te);if(typeof r!=="undefined"){return le.Call(r,e,[t])}}return le.Call(Ie,t,[le.ToString(e)])};oe(String.prototype,"match",Ee)}}var Pe=function wrapConstructor(e,t,r){m.preserveToString(t,e);if(Object.setPrototypeOf){Object.setPrototypeOf(e,t)}if(s){l(Object.getOwnPropertyNames(e),function(n){if(n in G||r[n]){return}m.proxy(e,n,t)})}else{l(Object.keys(e),function(n){if(n in G||r[n]){return}t[n]=e[n]})}t.prototype=e.prototype;m.redefine(e.prototype,"constructor",t)};var Ce=function(){return this};var Me=function(e){if(s&&!q(e,X)){m.getter(e,X,Ce)}};var xe=function(e,t){var r=t||function iterator(){return this};h(e,ae,r);if(!e[ae]&&ne.symbol(ae)){e[ae]=r}};var Ne=function createDataProperty(e,t,r){if(s){Object.defineProperty(e,t,{configurable:true,enumerable:true,writable:true,value:r})}else{e[t]=r}};var Ae=function createDataPropertyOrThrow(e,t,r){Ne(e,t,r);if(!le.SameValue(e[t],r)){throw new TypeError("property is nonconfigurable")}};var Re=function(e,t,r,n){if(!le.TypeIsObject(e)){throw new TypeError("Constructor requires `new`: "+t.name)}var o=t.prototype;if(!le.TypeIsObject(o)){o=r}var i=O(o);for(var a in n){if(q(n,a)){var u=n[a];h(i,a,u,true)}}return i};if(String.fromCodePoint&&String.fromCodePoint.length!==1){var _e=String.fromCodePoint;oe(String,"fromCodePoint",function fromCodePoint(e){return le.Call(_e,this,arguments)})}var ke={fromCodePoint:function fromCodePoint(e){var t=[];var r;for(var n=0,o=arguments.length;n<o;n++){r=Number(arguments[n]);if(!le.SameValue(r,le.ToInteger(r))||r<0||r>1114111){throw new RangeError("Invalid code point "+r)}if(r<65536){M(t,String.fromCharCode(r))}else{r-=65536;M(t,String.fromCharCode((r>>10)+55296));M(t,String.fromCharCode(r%1024+56320))}}return N(t,"")},raw:function raw(e){var t=arguments.length-1;var r=le.ToObject(e,"bad template");var raw=le.ToObject(r.raw,"bad raw value");var n=raw.length;var o=le.ToLength(n);if(o<=0){return""}var i=[];var a=0;var u,f,s,c;while(a<o){u=le.ToString(a);s=le.ToString(raw[u]);M(i,s);if(a+1>=o){break}f=a+1<arguments.length?arguments[a+1]:"";c=le.ToString(f);M(i,c);a+=1}return N(i,"")}};if(String.raw&&String.raw({raw:{0:"x",1:"y",length:2}})!=="xy"){oe(String,"raw",ke.raw)}b(String,ke);var Le=function repeat(e,t){if(t<1){return""}if(t%2){return repeat(e,t-1)+e}var r=repeat(e,t/2);return r+r};var Fe=Infinity;var De={repeat:function repeat(e){var t=le.ToString(le.RequireObjectCoercible(this));var r=le.ToInteger(e);if(r<0||r>=Fe){throw new RangeError("repeat count must be less than infinity and not overflow maximum string size")}return Le(t,r)},startsWith:function startsWith(e){var t=le.ToString(le.RequireObjectCoercible(this));if(le.IsRegExp(e)){throw new TypeError('Cannot call method "startsWith" with a regex')}var r=le.ToString(e);var n;if(arguments.length>1){n=arguments[1]}var o=R(le.ToInteger(n),0);return C(t,o,o+r.length)===r},endsWith:function endsWith(e){var t=le.ToString(le.RequireObjectCoercible(this));if(le.IsRegExp(e)){throw new TypeError('Cannot call method "endsWith" with a regex')}var r=le.ToString(e);var n=t.length;var o;if(arguments.length>1){o=arguments[1]}var i=typeof o==="undefined"?n:le.ToInteger(o);var a=_(R(i,0),n);return C(t,a-r.length,a)===r},includes:function includes(e){if(le.IsRegExp(e)){throw new TypeError('"includes" does not accept a RegExp')}var t=le.ToString(e);var r;if(arguments.length>1){r=arguments[1]}return I(this,t,r)!==-1},codePointAt:function codePointAt(e){var t=le.ToString(le.RequireObjectCoercible(this));var r=le.ToInteger(e);var n=t.length;if(r>=0&&r<n){var o=t.charCodeAt(r);var i=r+1===n;if(o<55296||o>56319||i){return o}var a=t.charCodeAt(r+1);if(a<56320||a>57343){return o}return(o-55296)*1024+(a-56320)+65536}}};if(String.prototype.includes&&"a".includes("a",Infinity)!==false){oe(String.prototype,"includes",De.includes)}if(String.prototype.startsWith&&String.prototype.endsWith){var ze=i(function(){return"/a/".startsWith(/a/)});var qe=a(function(){return"abc".startsWith("a",Infinity)===false});if(!ze||!qe){oe(String.prototype,"startsWith",De.startsWith);oe(String.prototype,"endsWith",De.endsWith)}}if(ie){var We=a(function(){var e=/a/;e[J.match]=false;return"/a/".startsWith(e)});if(!We){oe(String.prototype,"startsWith",De.startsWith)}var Ge=a(function(){var e=/a/;e[J.match]=false;return"/a/".endsWith(e)});if(!Ge){oe(String.prototype,"endsWith",De.endsWith)}var He=a(function(){var e=/a/;e[J.match]=false;return"/a/".includes(e)});if(!He){oe(String.prototype,"includes",De.includes)}}b(String.prototype,De);var Ve=["\t\n\x0B\f\r \xa0\u1680\u180e\u2000\u2001\u2002\u2003","\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028","\u2029\ufeff"].join("");var Be=new RegExp("(^["+Ve+"]+)|(["+Ve+"]+$)","g");var Ue=function trim(){return le.ToString(le.RequireObjectCoercible(this)).replace(Be,"")};var $e=["\x85","\u200b","\ufffe"].join("");var Je=new RegExp("["+$e+"]","g");var Xe=/^[-+]0x[0-9a-f]+$/i;var Ke=$e.trim().length!==$e.length;h(String.prototype,"trim",Ue,Ke);var Ze=function(e){return{value:e,done:arguments.length===0}};var Ye=function(e){le.RequireObjectCoercible(e);this._s=le.ToString(e);this._i=0};Ye.prototype.next=function(){var e=this._s;var t=this._i;if(typeof e==="undefined"||t>=e.length){this._s=void 0;return Ze()}var r=e.charCodeAt(t);var n,o;if(r<55296||r>56319||t+1===e.length){o=1}else{n=e.charCodeAt(t+1);o=n<56320||n>57343?1:2}this._i=t+o;return Ze(e.substr(t,o))};xe(Ye.prototype);xe(String.prototype,function(){return new Ye(this)});var Qe={from:function from(e){var r=this;var n;if(arguments.length>1){n=arguments[1]}var o,i;if(typeof n==="undefined"){o=false}else{if(!le.IsCallable(n)){throw new TypeError("Array.from: when provided, the second argument must be a function")}if(arguments.length>2){i=arguments[2]}o=true}var a=typeof(re(e)||le.GetMethod(e,ae))!=="undefined";var u,f,s;if(a){f=le.IsConstructor(r)?Object(new r):[];var c=le.GetIterator(e);var l,p;s=0;while(true){l=le.IteratorStep(c);if(l===false){break}p=l.value;try{if(o){p=typeof i==="undefined"?n(p,s):t(n,i,p,s)}f[s]=p}catch(v){le.IteratorClose(c,true);throw v}s+=1}u=s}else{var y=le.ToObject(e);u=le.ToLength(y.length);f=le.IsConstructor(r)?Object(new r(u)):new Array(u);var h;for(s=0;s<u;++s){h=y[s];if(o){h=typeof i==="undefined"?n(h,s):t(n,i,h,s)}Ae(f,s,h)}}f.length=u;return f},of:function of(){var e=arguments.length;var t=this;var n=r(t)||!le.IsCallable(t)?new Array(e):le.Construct(t,[e]);for(var o=0;o<e;++o){Ae(n,o,arguments[o])}n.length=e;return n}};b(Array,Qe);Me(Array);W=function(e,t){this.i=0;this.array=e;this.kind=t};b(W.prototype,{next:function(){var e=this.i;var t=this.array;if(!(this instanceof W)){throw new TypeError("Not an ArrayIterator")}if(typeof t!=="undefined"){var r=le.ToLength(t.length);if(e<r){var n=this.kind;var o;if(n==="key"){o=e}else if(n==="value"){o=t[e]}else if(n==="entry"){o=[e,t[e]]}this.i=e+1;return Ze(o)}}this.array=void 0;return Ze()}});xe(W.prototype);var et=Array.of===Qe.of||function(){var e=function Foo(e){this.length=e};e.prototype=[];var t=Array.of.apply(e,[1,2]);return t instanceof e&&t.length===2}();if(!et){oe(Array,"of",Qe.of)}var tt={copyWithin:function copyWithin(e,t){var r=le.ToObject(this);var n=le.ToLength(r.length);var o=le.ToInteger(e);var i=le.ToInteger(t);var a=o<0?R(n+o,0):_(o,n);var u=i<0?R(n+i,0):_(i,n);var f;if(arguments.length>2){f=arguments[2]}var s=typeof f==="undefined"?n:le.ToInteger(f);var c=s<0?R(n+s,0):_(s,n);var l=_(c-u,n-a);var p=1;if(u<a&&a<u+l){p=-1;u+=l-1;a+=l-1}while(l>0){if(u in r){r[a]=r[u]}else{delete r[a]}u+=p;a+=p;l-=1}return r},fill:function fill(e){var t;if(arguments.length>1){t=arguments[1]}var r;if(arguments.length>2){r=arguments[2]}var n=le.ToObject(this);var o=le.ToLength(n.length);t=le.ToInteger(typeof t==="undefined"?0:t);r=le.ToInteger(typeof r==="undefined"?o:r);var i=t<0?R(o+t,0):_(t,o);var a=r<0?o+r:r;for(var u=i;u<o&&u<a;++u){n[u]=e}return n},find:function find(e){var r=le.ToObject(this);var n=le.ToLength(r.length);if(!le.IsCallable(e)){throw new TypeError("Array#find: predicate must be a function")}var o=arguments.length>1?arguments[1]:null;for(var i=0,a;i<n;i++){a=r[i];if(o){if(t(e,o,a,i,r)){return a}}else if(e(a,i,r)){return a}}},findIndex:function findIndex(e){var r=le.ToObject(this);var n=le.ToLength(r.length);if(!le.IsCallable(e)){throw new TypeError("Array#findIndex: predicate must be a function")}var o=arguments.length>1?arguments[1]:null;for(var i=0;i<n;i++){if(o){if(t(e,o,r[i],i,r)){return i}}else if(e(r[i],i,r)){return i}}return-1},keys:function keys(){return new W(this,"key")},values:function values(){return new W(this,"value")},entries:function entries(){return new W(this,"entry")}};if(Array.prototype.keys&&!le.IsCallable([1].keys().next)){delete Array.prototype.keys}if(Array.prototype.entries&&!le.IsCallable([1].entries().next)){delete Array.prototype.entries}if(Array.prototype.keys&&Array.prototype.entries&&!Array.prototype.values&&Array.prototype[ae]){b(Array.prototype,{values:Array.prototype[ae]});if(ne.symbol(J.unscopables)){Array.prototype[J.unscopables].values=true}}if(c&&Array.prototype.values&&Array.prototype.values.name!=="values"){var rt=Array.prototype.values;oe(Array.prototype,"values",function values(){return le.Call(rt,this,arguments)});h(Array.prototype,ae,Array.prototype.values,true)}b(Array.prototype,tt);if(1/[true].indexOf(true,-0)<0){h(Array.prototype,"indexOf",function indexOf(e){var t=E(this,arguments);if(t===0&&1/t<0){return 0}return t},true)}xe(Array.prototype,function(){return this.values()});if(Object.getPrototypeOf){xe(Object.getPrototypeOf([].values()))}var nt=function(){return a(function(){return Array.from({length:-1}).length===0})}();var ot=function(){var e=Array.from([0].entries());return e.length===1&&r(e[0])&&e[0][0]===0&&e[0][1]===0}();if(!nt||!ot){oe(Array,"from",Qe.from)}var it=function(){return a(function(){return Array.from([0],void 0)})}();if(!it){var at=Array.from;oe(Array,"from",function from(e){if(arguments.length>1&&typeof arguments[1]!=="undefined"){return le.Call(at,this,arguments)}else{return t(at,this,e)}})}var ut=-(Math.pow(2,32)-1);var ft=function(e,r){var n={length:ut};n[r?(n.length>>>0)-1:0]=true;return a(function(){t(e,n,function(){throw new RangeError("should not reach here")},[]);return true})};if(!ft(Array.prototype.forEach)){var st=Array.prototype.forEach;oe(Array.prototype,"forEach",function forEach(e){return le.Call(st,this.length>=0?this:[],arguments)})}if(!ft(Array.prototype.map)){var ct=Array.prototype.map;oe(Array.prototype,"map",function map(e){return le.Call(ct,this.length>=0?this:[],arguments)})}if(!ft(Array.prototype.filter)){var lt=Array.prototype.filter;oe(Array.prototype,"filter",function filter(e){return le.Call(lt,this.length>=0?this:[],arguments)})}if(!ft(Array.prototype.some)){var pt=Array.prototype.some;oe(Array.prototype,"some",function some(e){return le.Call(pt,this.length>=0?this:[],arguments)})}if(!ft(Array.prototype.every)){var vt=Array.prototype.every;oe(Array.prototype,"every",function every(e){return le.Call(vt,this.length>=0?this:[],arguments)})}if(!ft(Array.prototype.reduce)){var yt=Array.prototype.reduce;oe(Array.prototype,"reduce",function reduce(e){return le.Call(yt,this.length>=0?this:[],arguments)})}if(!ft(Array.prototype.reduceRight,true)){var ht=Array.prototype.reduceRight;oe(Array.prototype,"reduceRight",function reduceRight(e){return le.Call(ht,this.length>=0?this:[],arguments)})}var bt=Number("0o10")!==8;var gt=Number("0b10")!==2;var dt=y($e,function(e){return Number(e+0+e)===0});if(bt||gt||dt){var mt=Number;var Ot=/^0b[01]+$/i;var wt=/^0o[0-7]+$/i;var jt=Ot.test.bind(Ot);var St=wt.test.bind(wt);var Tt=function(e,t){var r;if(typeof e.valueOf==="function"){r=e.valueOf();if(ne.primitive(r)){return r}}if(typeof e.toString==="function"){r=e.toString();if(ne.primitive(r)){return r}}throw new TypeError("No default value")};var It=Je.test.bind(Je);var Et=Xe.test.bind(Xe);var Pt=function(){var e=function Number(t){var r;if(arguments.length>0){r=ne.primitive(t)?t:Tt(t,"number")}else{r=0}if(typeof r==="string"){r=le.Call(Ue,r);if(jt(r)){r=parseInt(C(r,2),2)}else if(St(r)){r=parseInt(C(r,2),8)}else if(It(r)||Et(r)){r=NaN}}var n=this;var o=a(function(){mt.prototype.valueOf.call(n);return true});if(n instanceof e&&!o){return new mt(r)}return mt(r)};return e}();Pe(mt,Pt,{});b(Pt,{NaN:mt.NaN,MAX_VALUE:mt.MAX_VALUE,MIN_VALUE:mt.MIN_VALUE,NEGATIVE_INFINITY:mt.NEGATIVE_INFINITY,POSITIVE_INFINITY:mt.POSITIVE_INFINITY});Number=Pt;m.redefine(S,"Number",Pt)}var Ct=Math.pow(2,53)-1;b(Number,{MAX_SAFE_INTEGER:Ct,MIN_SAFE_INTEGER:-Ct,EPSILON:2.220446049250313e-16,parseInt:S.parseInt,parseFloat:S.parseFloat,isFinite:Z,isInteger:function isInteger(e){return Z(e)&&le.ToInteger(e)===e},isSafeInteger:function isSafeInteger(e){return Number.isInteger(e)&&L(e)<=Number.MAX_SAFE_INTEGER},isNaN:K});h(Number,"parseInt",S.parseInt,Number.parseInt!==S.parseInt);if([,1].find(function(){return true})===1){oe(Array.prototype,"find",tt.find)}if([,1].findIndex(function(){return true})!==0){oe(Array.prototype,"findIndex",tt.findIndex)}var Mt=Function.bind.call(Function.bind,Object.prototype.propertyIsEnumerable);var xt=function ensureEnumerable(e,t){if(s&&Mt(e,t)){Object.defineProperty(e,t,{enumerable:false})}};var Nt=function sliceArgs(){var e=Number(this);var t=arguments.length;var r=t-e;var n=new Array(r<0?0:r);for(var o=e;o<t;++o){n[o-e]=arguments[o]}return n};var At=function assignTo(e){return function assignToSource(t,r){t[r]=e[r];return t}};var Rt=function(e,t){var r=n(Object(t));var o;if(le.IsCallable(Object.getOwnPropertySymbols)){o=v(Object.getOwnPropertySymbols(Object(t)),Mt(t))}return p(P(r,o||[]),At(t),e)};var _t={assign:function(e,t){var r=le.ToObject(e,"Cannot convert undefined or null to object");return p(le.Call(Nt,1,arguments),Rt,r)},is:function is(e,t){return le.SameValue(e,t)}};var kt=Object.assign&&Object.preventExtensions&&function(){var e=Object.preventExtensions({1:2});try{Object.assign(e,"xy")}catch(t){return e[1]==="y"}}();if(kt){oe(Object,"assign",_t.assign)}b(Object,_t);if(s){var Lt={setPrototypeOf:function(e,r){var n;var o=function(e,t){if(!le.TypeIsObject(e)){throw new TypeError("cannot set prototype on a non-object")}if(!(t===null||le.TypeIsObject(t))){throw new TypeError("can only set prototype to an object or null"+t)}};var i=function(e,r){o(e,r);t(n,e,r);return e};try{n=e.getOwnPropertyDescriptor(e.prototype,r).set;t(n,{},null)}catch(a){if(e.prototype!=={}[r]){return}n=function(e){this[r]=e};i.polyfill=i(i({},null),e.prototype)instanceof e}return i}(Object,"__proto__")};b(Object,Lt)}if(Object.setPrototypeOf&&Object.getPrototypeOf&&Object.getPrototypeOf(Object.setPrototypeOf({},null))!==null&&Object.getPrototypeOf(Object.create(null))===null){(function(){var e=Object.create(null);var t=Object.getPrototypeOf;var r=Object.setPrototypeOf;Object.getPrototypeOf=function(r){var n=t(r);return n===e?null:n};Object.setPrototypeOf=function(t,n){var o=n===null?e:n;return r(t,o)};Object.setPrototypeOf.polyfill=false})()}var Ft=!i(function(){return Object.keys("foo")});if(!Ft){var Dt=Object.keys;oe(Object,"keys",function keys(e){return Dt(le.ToObject(e))});n=Object.keys}var zt=i(function(){return Object.keys(/a/g)});if(zt){var qt=Object.keys;oe(Object,"keys",function keys(e){if(ne.regex(e)){var t=[];for(var r in e){if(q(e,r)){M(t,r)}}return t}return qt(e)});n=Object.keys}if(Object.getOwnPropertyNames){var Wt=!i(function(){return Object.getOwnPropertyNames("foo")});if(!Wt){var Gt=typeof window==="object"?Object.getOwnPropertyNames(window):[];var Ht=Object.getOwnPropertyNames;oe(Object,"getOwnPropertyNames",function getOwnPropertyNames(e){var t=le.ToObject(e);if(g(t)==="[object Window]"){try{return Ht(t)}catch(r){return P([],Gt)}}return Ht(t)})}}if(Object.getOwnPropertyDescriptor){var Vt=!i(function(){return Object.getOwnPropertyDescriptor("foo","bar")});if(!Vt){var Bt=Object.getOwnPropertyDescriptor;oe(Object,"getOwnPropertyDescriptor",function getOwnPropertyDescriptor(e,t){return Bt(le.ToObject(e),t)})}}if(Object.seal){var Ut=!i(function(){return Object.seal("foo")});if(!Ut){var $t=Object.seal;oe(Object,"seal",function seal(e){if(!le.TypeIsObject(e)){return e}return $t(e)})}}if(Object.isSealed){var Jt=!i(function(){return Object.isSealed("foo")});if(!Jt){var Xt=Object.isSealed;oe(Object,"isSealed",function isSealed(e){if(!le.TypeIsObject(e)){return true}return Xt(e)})}}if(Object.freeze){var Kt=!i(function(){return Object.freeze("foo")});if(!Kt){var Zt=Object.freeze;oe(Object,"freeze",function freeze(e){if(!le.TypeIsObject(e)){return e}return Zt(e)})}}if(Object.isFrozen){var Yt=!i(function(){return Object.isFrozen("foo")});if(!Yt){var Qt=Object.isFrozen;oe(Object,"isFrozen",function isFrozen(e){if(!le.TypeIsObject(e)){return true}return Qt(e)})}}if(Object.preventExtensions){var er=!i(function(){return Object.preventExtensions("foo")});if(!er){var tr=Object.preventExtensions;oe(Object,"preventExtensions",function preventExtensions(e){if(!le.TypeIsObject(e)){return e}return tr(e)})}}if(Object.isExtensible){var rr=!i(function(){return Object.isExtensible("foo")});if(!rr){var nr=Object.isExtensible;oe(Object,"isExtensible",function isExtensible(e){if(!le.TypeIsObject(e)){return false}return nr(e)})}}if(Object.getPrototypeOf){var or=!i(function(){return Object.getPrototypeOf("foo")});if(!or){var ir=Object.getPrototypeOf;oe(Object,"getPrototypeOf",function getPrototypeOf(e){return ir(le.ToObject(e))})}}var ar=s&&function(){var e=Object.getOwnPropertyDescriptor(RegExp.prototype,"flags");return e&&le.IsCallable(e.get)}();if(s&&!ar){var ur=function flags(){if(!le.TypeIsObject(this)){throw new TypeError("Method called on incompatible type: must be an object.")}var e="";if(this.global){e+="g"}if(this.ignoreCase){e+="i"}if(this.multiline){e+="m"}if(this.unicode){e+="u"}if(this.sticky){e+="y"}return e};m.getter(RegExp.prototype,"flags",ur)}var fr=s&&a(function(){return String(new RegExp(/a/g,"i"))==="/a/i"});var sr=ie&&s&&function(){var e=/./;e[J.match]=false;return RegExp(e)===e}();var cr=a(function(){return RegExp.prototype.toString.call({source:"abc"})==="/abc/"});var lr=cr&&a(function(){return RegExp.prototype.toString.call({source:"a",flags:"b"})==="/a/b"});if(!cr||!lr){var pr=RegExp.prototype.toString;h(RegExp.prototype,"toString",function toString(){var e=le.RequireObjectCoercible(this);if(ne.regex(e)){return t(pr,e)}var r=fe(e.source);var n=fe(e.flags);return"/"+r+"/"+n},true);m.preserveToString(RegExp.prototype.toString,pr)}if(s&&(!fr||sr)){var vr=Object.getOwnPropertyDescriptor(RegExp.prototype,"flags").get;var yr=Object.getOwnPropertyDescriptor(RegExp.prototype,"source")||{};var hr=function(){return this.source};var br=le.IsCallable(yr.get)?yr.get:hr;var gr=RegExp;var dr=function(){return function RegExp(e,t){var r=le.IsRegExp(e);var n=this instanceof RegExp;if(!n&&r&&typeof t==="undefined"&&e.constructor===RegExp){return e}var o=e;var i=t;if(ne.regex(e)){o=le.Call(br,e);i=typeof t==="undefined"?le.Call(vr,e):t;return new RegExp(o,i)}else if(r){o=e.source;i=typeof t==="undefined"?e.flags:t}return new gr(e,t)}}();Pe(gr,dr,{$input:true});RegExp=dr;m.redefine(S,"RegExp",dr)}if(s){var mr={input:"$_",lastMatch:"$&",lastParen:"$+",leftContext:"$`",rightContext:"$'"};l(n(mr),function(e){if(e in RegExp&&!(mr[e]in RegExp)){m.getter(RegExp,mr[e],function get(){return RegExp[e]})}})}Me(RegExp);var Or=1/Number.EPSILON;var wr=function roundTiesToEven(e){return e+Or-Or};var jr=Math.pow(2,-23);var Sr=Math.pow(2,127)*(2-jr);var Tr=Math.pow(2,-126);var Ir=Math.E;var Er=Math.LOG2E;var Pr=Math.LOG10E;var Cr=Number.prototype.clz;delete Number.prototype.clz;var Mr={acosh:function acosh(e){var t=Number(e);if(K(t)||e<1){return NaN}if(t===1){return 0}if(t===Infinity){return t}var r=1/(t*t);if(t<2){return Q(t-1+z(1-r)*t)}var n=t/2;return Q(n+z(1-r)*n-1)+1/Er},asinh:function asinh(e){var t=Number(e);if(t===0||!T(t)){return t}var r=L(t);var n=r*r;var o=Y(t);if(r<1){return o*Q(r+n/(z(n+1)+1))}return o*(Q(r/2+z(1+1/n)*r/2-1)+1/Er)},atanh:function atanh(e){var t=Number(e);if(t===0){return t}if(t===-1){return-Infinity}if(t===1){return Infinity}if(K(t)||t<-1||t>1){return NaN}var r=L(t);return Y(t)*Q(2*r/(1-r))/2},cbrt:function cbrt(e){var t=Number(e);if(t===0){return t}var r=t<0;var n;if(r){t=-t}if(t===Infinity){n=Infinity}else{n=F(D(t)/3);n=(t/(n*n)+2*n)/3}return r?-n:n},clz32:function clz32(e){var t=Number(e);var r=le.ToUint32(t);if(r===0){return 32}return Cr?le.Call(Cr,r):31-k(D(r+.5)*Er)},cosh:function cosh(e){var t=Number(e);if(t===0){return 1}if(K(t)){return NaN}if(!T(t)){return Infinity}var r=F(L(t)-1);return(r+1/(r*Ir*Ir))*(Ir/2)},expm1:function expm1(e){var t=Number(e);if(t===-Infinity){return-1}if(!T(t)||t===0){return t}if(L(t)>.5){return F(t)-1}var r=t;var n=0;var o=1;while(n+r!==n){n+=r;o+=1;r*=t/o}return n},hypot:function hypot(e,t){var r=0;var n=0;for(var o=0;o<arguments.length;++o){var i=L(Number(arguments[o]));if(n<i){r*=n/i*(n/i);r+=1;n=i}else{r+=i>0?i/n*(i/n):i}}return n===Infinity?Infinity:n*z(r)},log2:function log2(e){return D(e)*Er},log10:function log10(e){return D(e)*Pr},log1p:Q,sign:Y,sinh:function sinh(e){var t=Number(e);if(!T(t)||t===0){return t}var r=L(t);if(r<1){var n=Math.expm1(r);return Y(t)*n*(1+1/(n+1))/2}var o=F(r-1);return Y(t)*(o-1/(o*Ir*Ir))*(Ir/2)},tanh:function tanh(e){var t=Number(e);if(K(t)||t===0){return t}if(t>=20){return 1}if(t<=-20){return-1}return(Math.expm1(t)-Math.expm1(-t))/(F(t)+F(-t))},trunc:function trunc(e){var t=Number(e);return t<0?-k(-t):k(t)},imul:function imul(e,t){var r=le.ToUint32(e);var n=le.ToUint32(t);var o=r>>>16&65535;var i=r&65535;var a=n>>>16&65535;var u=n&65535;return i*u+(o*u+i*a<<16>>>0)|0},fround:function fround(e){var t=Number(e);if(t===0||t===Infinity||t===-Infinity||K(t)){return t}var r=Y(t);var n=L(t);if(n<Tr){return r*wr(n/Tr/jr)*Tr*jr}var o=(1+jr/Number.EPSILON)*n;var i=o-(o-n);if(i>Sr||K(i)){return r*Infinity}return r*i}};var xr=function withinULPDistance(e,t,r){return L(1-e/t)/Number.EPSILON<(r||8)};b(Math,Mr);h(Math,"sinh",Mr.sinh,Math.sinh(710)===Infinity);h(Math,"cosh",Mr.cosh,Math.cosh(710)===Infinity);h(Math,"log1p",Mr.log1p,Math.log1p(-1e-17)!==-1e-17);h(Math,"asinh",Mr.asinh,Math.asinh(-1e7)!==-Math.asinh(1e7));
h(Math,"asinh",Mr.asinh,Math.asinh(1e300)===Infinity);h(Math,"atanh",Mr.atanh,Math.atanh(1e-300)===0);h(Math,"tanh",Mr.tanh,Math.tanh(-2e-17)!==-2e-17);h(Math,"acosh",Mr.acosh,Math.acosh(Number.MAX_VALUE)===Infinity);h(Math,"acosh",Mr.acosh,!xr(Math.acosh(1+Number.EPSILON),Math.sqrt(2*Number.EPSILON)));h(Math,"cbrt",Mr.cbrt,!xr(Math.cbrt(1e-300),1e-100));h(Math,"sinh",Mr.sinh,Math.sinh(-2e-17)!==-2e-17);var Nr=Math.expm1(10);h(Math,"expm1",Mr.expm1,Nr>22025.465794806718||Nr<22025.465794806718);h(Math,"hypot",Mr.hypot,Math.hypot(Infinity,NaN)!==Infinity);var Ar=Math.round;var Rr=Math.round(.5-Number.EPSILON/4)===0&&Math.round(-.5+Number.EPSILON/3.99)===1;var _r=Or+1;var kr=2*Or-1;var Lr=[_r,kr].every(function(e){return Math.round(e)===e});h(Math,"round",function round(e){var t=k(e);var r=t===-1?-0:t+1;return e-t<.5?t:r},!Rr||!Lr);m.preserveToString(Math.round,Ar);var Fr=Math.imul;if(Math.imul(4294967295,5)!==-5){Math.imul=Mr.imul;m.preserveToString(Math.imul,Fr)}if(Math.imul.length!==2){oe(Math,"imul",function imul(e,t){return le.Call(Fr,Math,arguments)})}var Dr=function(){var e=S.setTimeout;if(typeof e!=="function"&&typeof e!=="object"){return}le.IsPromise=function(e){if(!le.TypeIsObject(e)){return false}if(typeof e._promise==="undefined"){return false}return true};var r=function(e){if(!le.IsConstructor(e)){throw new TypeError("Bad promise constructor")}var t=this;var r=function(e,r){if(t.resolve!==void 0||t.reject!==void 0){throw new TypeError("Bad Promise implementation!")}t.resolve=e;t.reject=r};t.resolve=void 0;t.reject=void 0;t.promise=new e(r);if(!(le.IsCallable(t.resolve)&&le.IsCallable(t.reject))){throw new TypeError("Bad promise constructor")}};var n;if(typeof window!=="undefined"&&le.IsCallable(window.postMessage)){n=function(){var e=[];var t="zero-timeout-message";var r=function(r){M(e,r);window.postMessage(t,"*")};var n=function(r){if(r.source===window&&r.data===t){r.stopPropagation();if(e.length===0){return}var n=A(e);n()}};window.addEventListener("message",n,true);return r}}var o=function(){var e=S.Promise;var t=e&&e.resolve&&e.resolve();return t&&function(e){return t.then(e)}};var i=le.IsCallable(S.setImmediate)?S.setImmediate:typeof process==="object"&&process.nextTick?process.nextTick:o()||(le.IsCallable(n)?n():function(t){e(t,0)});var a=function(e){return e};var u=function(e){throw e};var f=0;var s=1;var c=2;var l=0;var p=1;var v=2;var y={};var h=function(e,t,r){i(function(){g(e,t,r)})};var g=function(e,t,r){var n,o;if(t===y){return e(r)}try{n=e(r);o=t.resolve}catch(i){n=i;o=t.reject}o(n)};var d=function(e,t){var r=e._promise;var n=r.reactionLength;if(n>0){h(r.fulfillReactionHandler0,r.reactionCapability0,t);r.fulfillReactionHandler0=void 0;r.rejectReactions0=void 0;r.reactionCapability0=void 0;if(n>1){for(var o=1,i=0;o<n;o++,i+=3){h(r[i+l],r[i+v],t);e[i+l]=void 0;e[i+p]=void 0;e[i+v]=void 0}}}r.result=t;r.state=s;r.reactionLength=0};var m=function(e,t){var r=e._promise;var n=r.reactionLength;if(n>0){h(r.rejectReactionHandler0,r.reactionCapability0,t);r.fulfillReactionHandler0=void 0;r.rejectReactions0=void 0;r.reactionCapability0=void 0;if(n>1){for(var o=1,i=0;o<n;o++,i+=3){h(r[i+p],r[i+v],t);e[i+l]=void 0;e[i+p]=void 0;e[i+v]=void 0}}}r.result=t;r.state=c;r.reactionLength=0};var O=function(e){var t=false;var r=function(r){var n;if(t){return}t=true;if(r===e){return m(e,new TypeError("Self resolution"))}if(!le.TypeIsObject(r)){return d(e,r)}try{n=r.then}catch(o){return m(e,o)}if(!le.IsCallable(n)){return d(e,r)}i(function(){j(e,r,n)})};var n=function(r){if(t){return}t=true;return m(e,r)};return{resolve:r,reject:n}};var w=function(e,r,n,o){if(e===I){t(e,r,n,o,y)}else{t(e,r,n,o)}};var j=function(e,t,r){var n=O(e);var o=n.resolve;var i=n.reject;try{w(r,t,o,i)}catch(a){i(a)}};var T,I;var E=function(){var e=function Promise(t){if(!(this instanceof e)){throw new TypeError('Constructor Promise requires "new"')}if(this&&this._promise){throw new TypeError("Bad construction")}if(!le.IsCallable(t)){throw new TypeError("not a valid resolver")}var r=Re(this,e,T,{_promise:{result:void 0,state:f,reactionLength:0,fulfillReactionHandler0:void 0,rejectReactionHandler0:void 0,reactionCapability0:void 0}});var n=O(r);var o=n.reject;try{t(n.resolve,o)}catch(i){o(i)}return r};return e}();T=E.prototype;var P=function(e,t,r,n){var o=false;return function(i){if(o){return}o=true;t[e]=i;if(--n.count===0){var a=r.resolve;a(t)}}};var C=function(e,t,r){var n=e.iterator;var o=[];var i={count:1};var a,u;var f=0;while(true){try{a=le.IteratorStep(n);if(a===false){e.done=true;break}u=a.value}catch(s){e.done=true;throw s}o[f]=void 0;var c=t.resolve(u);var l=P(f,o,r,i);i.count+=1;w(c.then,c,l,r.reject);f+=1}if(--i.count===0){var p=r.resolve;p(o)}return r.promise};var x=function(e,t,r){var n=e.iterator;var o,i,a;while(true){try{o=le.IteratorStep(n);if(o===false){e.done=true;break}i=o.value}catch(u){e.done=true;throw u}a=t.resolve(i);w(a.then,a,r.resolve,r.reject)}return r.promise};b(E,{all:function all(e){var t=this;if(!le.TypeIsObject(t)){throw new TypeError("Promise is not object")}var n=new r(t);var o,i;try{o=le.GetIterator(e);i={iterator:o,done:false};return C(i,t,n)}catch(a){var u=a;if(i&&!i.done){try{le.IteratorClose(o,true)}catch(f){u=f}}var s=n.reject;s(u);return n.promise}},race:function race(e){var t=this;if(!le.TypeIsObject(t)){throw new TypeError("Promise is not object")}var n=new r(t);var o,i;try{o=le.GetIterator(e);i={iterator:o,done:false};return x(i,t,n)}catch(a){var u=a;if(i&&!i.done){try{le.IteratorClose(o,true)}catch(f){u=f}}var s=n.reject;s(u);return n.promise}},reject:function reject(e){var t=this;if(!le.TypeIsObject(t)){throw new TypeError("Bad promise constructor")}var n=new r(t);var o=n.reject;o(e);return n.promise},resolve:function resolve(e){var t=this;if(!le.TypeIsObject(t)){throw new TypeError("Bad promise constructor")}if(le.IsPromise(e)){var n=e.constructor;if(n===t){return e}}var o=new r(t);var i=o.resolve;i(e);return o.promise}});b(T,{"catch":function(e){return this.then(null,e)},then:function then(e,t){var n=this;if(!le.IsPromise(n)){throw new TypeError("not a promise")}var o=le.SpeciesConstructor(n,E);var i;var b=arguments.length>2&&arguments[2]===y;if(b&&o===E){i=y}else{i=new r(o)}var g=le.IsCallable(e)?e:a;var d=le.IsCallable(t)?t:u;var m=n._promise;var O;if(m.state===f){if(m.reactionLength===0){m.fulfillReactionHandler0=g;m.rejectReactionHandler0=d;m.reactionCapability0=i}else{var w=3*(m.reactionLength-1);m[w+l]=g;m[w+p]=d;m[w+v]=i}m.reactionLength+=1}else if(m.state===s){O=m.result;h(g,i,O)}else if(m.state===c){O=m.result;h(d,i,O)}else{throw new TypeError("unexpected Promise state")}return i.promise}});y=new r(E);I=T.then;return E}();if(S.Promise){delete S.Promise.accept;delete S.Promise.defer;delete S.Promise.prototype.chain}if(typeof Dr==="function"){b(S,{Promise:Dr});var zr=w(S.Promise,function(e){return e.resolve(42).then(function(){})instanceof e});var qr=!i(function(){return S.Promise.reject(42).then(null,5).then(null,G)});var Wr=i(function(){return S.Promise.call(3,G)});var Gr=function(e){var t=e.resolve(5);t.constructor={};var r=e.resolve(t);try{r.then(null,G).then(null,G)}catch(n){return true}return t===r}(S.Promise);var Hr=s&&function(){var e=0;var t=Object.defineProperty({},"then",{get:function(){e+=1}});Promise.resolve(t);return e===1}();var Vr=function BadResolverPromise(e){var t=new Promise(e);e(3,function(){});this.then=t.then;this.constructor=BadResolverPromise};Vr.prototype=Promise.prototype;Vr.all=Promise.all;var Br=a(function(){return!!Vr.all([1,2])});if(!zr||!qr||!Wr||Gr||!Hr||Br){Promise=Dr;oe(S,"Promise",Dr)}if(Promise.all.length!==1){var Ur=Promise.all;oe(Promise,"all",function all(e){return le.Call(Ur,this,arguments)})}if(Promise.race.length!==1){var $r=Promise.race;oe(Promise,"race",function race(e){return le.Call($r,this,arguments)})}if(Promise.resolve.length!==1){var Jr=Promise.resolve;oe(Promise,"resolve",function resolve(e){return le.Call(Jr,this,arguments)})}if(Promise.reject.length!==1){var Xr=Promise.reject;oe(Promise,"reject",function reject(e){return le.Call(Xr,this,arguments)})}xt(Promise,"all");xt(Promise,"race");xt(Promise,"resolve");xt(Promise,"reject");Me(Promise)}var Kr=function(e){var t=n(p(e,function(e,t){e[t]=true;return e},{}));return e.join(":")===t.join(":")};var Zr=Kr(["z","a","bb"]);var Yr=Kr(["z",1,"a","3",2]);if(s){var Qr=function fastkey(e,t){if(!t&&!Zr){return null}if(ce(e)){return"^"+le.ToString(e)}else if(typeof e==="string"){return"$"+e}else if(typeof e==="number"){if(!Yr){return"n"+e}return e}else if(typeof e==="boolean"){return"b"+e}return null};var en=function emptyObject(){return Object.create?Object.create(null):{}};var tn=function addIterableToMap(e,n,o){if(r(o)||ne.string(o)){l(o,function(e){if(!le.TypeIsObject(e)){throw new TypeError("Iterator value "+e+" is not an entry object")}n.set(e[0],e[1])})}else if(o instanceof e){t(e.prototype.forEach,o,function(e,t){n.set(t,e)})}else{var i,a;if(!ce(o)){a=n.set;if(!le.IsCallable(a)){throw new TypeError("bad map")}i=le.GetIterator(o)}if(typeof i!=="undefined"){while(true){var u=le.IteratorStep(i);if(u===false){break}var f=u.value;try{if(!le.TypeIsObject(f)){throw new TypeError("Iterator value "+f+" is not an entry object")}t(a,n,f[0],f[1])}catch(s){le.IteratorClose(i,true);throw s}}}}};var rn=function addIterableToSet(e,n,o){if(r(o)||ne.string(o)){l(o,function(e){n.add(e)})}else if(o instanceof e){t(e.prototype.forEach,o,function(e){n.add(e)})}else{var i,a;if(!ce(o)){a=n.add;if(!le.IsCallable(a)){throw new TypeError("bad set")}i=le.GetIterator(o)}if(typeof i!=="undefined"){while(true){var u=le.IteratorStep(i);if(u===false){break}var f=u.value;try{t(a,n,f)}catch(s){le.IteratorClose(i,true);throw s}}}}};var nn={Map:function(){var e={};var r=function MapEntry(e,t){this.key=e;this.value=t;this.next=null;this.prev=null};r.prototype.isRemoved=function isRemoved(){return this.key===e};var n=function isMap(e){return!!e._es6map};var o=function requireMapSlot(e,t){if(!le.TypeIsObject(e)||!n(e)){throw new TypeError("Method Map.prototype."+t+" called on incompatible receiver "+le.ToString(e))}};var i=function MapIterator(e,t){o(e,"[[MapIterator]]");this.head=e._head;this.i=this.head;this.kind=t};i.prototype={isMapIterator:true,next:function next(){if(!this.isMapIterator){throw new TypeError("Not a MapIterator")}var e=this.i;var t=this.kind;var r=this.head;if(typeof this.i==="undefined"){return Ze()}while(e.isRemoved()&&e!==r){e=e.prev}var n;while(e.next!==r){e=e.next;if(!e.isRemoved()){if(t==="key"){n=e.key}else if(t==="value"){n=e.value}else{n=[e.key,e.value]}this.i=e;return Ze(n)}}this.i=void 0;return Ze()}};xe(i.prototype);var a;var u=function Map(){if(!(this instanceof Map)){throw new TypeError('Constructor Map requires "new"')}if(this&&this._es6map){throw new TypeError("Bad construction")}var e=Re(this,Map,a,{_es6map:true,_head:null,_map:H?new H:null,_size:0,_storage:en()});var t=new r(null,null);t.next=t.prev=t;e._head=t;if(arguments.length>0){tn(Map,e,arguments[0])}return e};a=u.prototype;m.getter(a,"size",function(){if(typeof this._size==="undefined"){throw new TypeError("size method called on incompatible Map")}return this._size});b(a,{get:function get(e){o(this,"get");var t;var r=Qr(e,true);if(r!==null){t=this._storage[r];if(t){return t.value}else{return}}if(this._map){t=B.call(this._map,e);if(t){return t.value}else{return}}var n=this._head;var i=n;while((i=i.next)!==n){if(le.SameValueZero(i.key,e)){return i.value}}},has:function has(e){o(this,"has");var t=Qr(e,true);if(t!==null){return typeof this._storage[t]!=="undefined"}if(this._map){return U.call(this._map,e)}var r=this._head;var n=r;while((n=n.next)!==r){if(le.SameValueZero(n.key,e)){return true}}return false},set:function set(e,t){o(this,"set");var n=this._head;var i=n;var a;var u=Qr(e,true);if(u!==null){if(typeof this._storage[u]!=="undefined"){this._storage[u].value=t;return this}else{a=this._storage[u]=new r(e,t);i=n.prev}}else if(this._map){if(U.call(this._map,e)){B.call(this._map,e).value=t}else{a=new r(e,t);$.call(this._map,e,a);i=n.prev}}while((i=i.next)!==n){if(le.SameValueZero(i.key,e)){i.value=t;return this}}a=a||new r(e,t);if(le.SameValue(-0,e)){a.key=+0}a.next=this._head;a.prev=this._head.prev;a.prev.next=a;a.next.prev=a;this._size+=1;return this},"delete":function(t){o(this,"delete");var r=this._head;var n=r;var i=Qr(t,true);if(i!==null){if(typeof this._storage[i]==="undefined"){return false}n=this._storage[i].prev;delete this._storage[i]}else if(this._map){if(!U.call(this._map,t)){return false}n=B.call(this._map,t).prev;V.call(this._map,t)}while((n=n.next)!==r){if(le.SameValueZero(n.key,t)){n.key=e;n.value=e;n.prev.next=n.next;n.next.prev=n.prev;this._size-=1;return true}}return false},clear:function clear(){o(this,"clear");this._map=H?new H:null;this._size=0;this._storage=en();var t=this._head;var r=t;var n=r.next;while((r=n)!==t){r.key=e;r.value=e;n=r.next;r.next=r.prev=t}t.next=t.prev=t},keys:function keys(){o(this,"keys");return new i(this,"key")},values:function values(){o(this,"values");return new i(this,"value")},entries:function entries(){o(this,"entries");return new i(this,"key+value")},forEach:function forEach(e){o(this,"forEach");var r=arguments.length>1?arguments[1]:null;var n=this.entries();for(var i=n.next();!i.done;i=n.next()){if(r){t(e,r,i.value[1],i.value[0],this)}else{e(i.value[1],i.value[0],this)}}}});xe(a,a.entries);return u}(),Set:function(){var e=function isSet(e){return e._es6set&&typeof e._storage!=="undefined"};var r=function requireSetSlot(t,r){if(!le.TypeIsObject(t)||!e(t)){throw new TypeError("Set.prototype."+r+" called on incompatible receiver "+le.ToString(t))}};var o;var i=function Set(){if(!(this instanceof Set)){throw new TypeError('Constructor Set requires "new"')}if(this&&this._es6set){throw new TypeError("Bad construction")}var e=Re(this,Set,o,{_es6set:true,"[[SetData]]":null,_storage:en()});if(!e._es6set){throw new TypeError("bad set")}if(arguments.length>0){rn(Set,e,arguments[0])}return e};o=i.prototype;var a=function(e){var t=e;if(t==="^null"){return null}else if(t==="^undefined"){return void 0}else{var r=t.charAt(0);if(r==="$"){return C(t,1)}else if(r==="n"){return+C(t,1)}else if(r==="b"){return t==="btrue"}}return+t};var u=function ensureMap(e){if(!e["[[SetData]]"]){var t=new nn.Map;e["[[SetData]]"]=t;l(n(e._storage),function(e){var r=a(e);t.set(r,r)});e["[[SetData]]"]=t}e._storage=null};m.getter(i.prototype,"size",function(){r(this,"size");if(this._storage){return n(this._storage).length}u(this);return this["[[SetData]]"].size});b(i.prototype,{has:function has(e){r(this,"has");var t;if(this._storage&&(t=Qr(e))!==null){return!!this._storage[t]}u(this);return this["[[SetData]]"].has(e)},add:function add(e){r(this,"add");var t;if(this._storage&&(t=Qr(e))!==null){this._storage[t]=true;return this}u(this);this["[[SetData]]"].set(e,e);return this},"delete":function(e){r(this,"delete");var t;if(this._storage&&(t=Qr(e))!==null){var n=q(this._storage,t);return delete this._storage[t]&&n}u(this);return this["[[SetData]]"]["delete"](e)},clear:function clear(){r(this,"clear");if(this._storage){this._storage=en()}if(this["[[SetData]]"]){this["[[SetData]]"].clear()}},values:function values(){r(this,"values");u(this);return new f(this["[[SetData]]"].values())},entries:function entries(){r(this,"entries");u(this);return new f(this["[[SetData]]"].entries())},forEach:function forEach(e){r(this,"forEach");var n=arguments.length>1?arguments[1]:null;var o=this;u(o);this["[[SetData]]"].forEach(function(r,i){if(n){t(e,n,i,i,o)}else{e(i,i,o)}})}});h(i.prototype,"keys",i.prototype.values,true);xe(i.prototype,i.prototype.values);var f=function SetIterator(e){this.it=e};f.prototype={isSetIterator:true,next:function next(){if(!this.isSetIterator){throw new TypeError("Not a SetIterator")}return this.it.next()}};xe(f.prototype);return i}()};var on=S.Set&&!Set.prototype["delete"]&&Set.prototype.remove&&Set.prototype.items&&Set.prototype.map&&Array.isArray((new Set).keys);if(on){S.Set=nn.Set}if(S.Map||S.Set){var an=a(function(){return new Map([[1,2]]).get(1)===2});if(!an){S.Map=function Map(){if(!(this instanceof Map)){throw new TypeError('Constructor Map requires "new"')}var e=new H;if(arguments.length>0){tn(Map,e,arguments[0])}delete e.constructor;Object.setPrototypeOf(e,S.Map.prototype);return e};S.Map.prototype=O(H.prototype);h(S.Map.prototype,"constructor",S.Map,true);m.preserveToString(S.Map,H)}var un=new Map;var fn=function(){var e=new Map([[1,0],[2,0],[3,0],[4,0]]);e.set(-0,e);return e.get(0)===e&&e.get(-0)===e&&e.has(0)&&e.has(-0)}();var sn=un.set(1,2)===un;if(!fn||!sn){oe(Map.prototype,"set",function set(e,r){t($,this,e===0?0:e,r);return this})}if(!fn){b(Map.prototype,{get:function get(e){return t(B,this,e===0?0:e)},has:function has(e){return t(U,this,e===0?0:e)}},true);m.preserveToString(Map.prototype.get,B);m.preserveToString(Map.prototype.has,U)}var cn=new Set;var ln=Set.prototype["delete"]&&Set.prototype.add&&Set.prototype.has&&function(e){e["delete"](0);e.add(-0);return!e.has(0)}(cn);var pn=cn.add(1)===cn;if(!ln||!pn){var vn=Set.prototype.add;Set.prototype.add=function add(e){t(vn,this,e===0?0:e);return this};m.preserveToString(Set.prototype.add,vn)}if(!ln){var yn=Set.prototype.has;Set.prototype.has=function has(e){return t(yn,this,e===0?0:e)};m.preserveToString(Set.prototype.has,yn);var hn=Set.prototype["delete"];Set.prototype["delete"]=function SetDelete(e){return t(hn,this,e===0?0:e)};m.preserveToString(Set.prototype["delete"],hn)}var bn=w(S.Map,function(e){var t=new e([]);t.set(42,42);return t instanceof e});var gn=Object.setPrototypeOf&&!bn;var dn=function(){try{return!(S.Map()instanceof S.Map)}catch(e){return e instanceof TypeError}}();if(S.Map.length!==0||gn||!dn){S.Map=function Map(){if(!(this instanceof Map)){throw new TypeError('Constructor Map requires "new"')}var e=new H;if(arguments.length>0){tn(Map,e,arguments[0])}delete e.constructor;Object.setPrototypeOf(e,Map.prototype);return e};S.Map.prototype=H.prototype;h(S.Map.prototype,"constructor",S.Map,true);m.preserveToString(S.Map,H)}var mn=w(S.Set,function(e){var t=new e([]);t.add(42,42);return t instanceof e});var On=Object.setPrototypeOf&&!mn;var wn=function(){try{return!(S.Set()instanceof S.Set)}catch(e){return e instanceof TypeError}}();if(S.Set.length!==0||On||!wn){var jn=S.Set;S.Set=function Set(){if(!(this instanceof Set)){throw new TypeError('Constructor Set requires "new"')}var e=new jn;if(arguments.length>0){rn(Set,e,arguments[0])}delete e.constructor;Object.setPrototypeOf(e,Set.prototype);return e};S.Set.prototype=jn.prototype;h(S.Set.prototype,"constructor",S.Set,true);m.preserveToString(S.Set,jn)}var Sn=new S.Map;var Tn=!a(function(){return Sn.keys().next().done});if(typeof S.Map.prototype.clear!=="function"||(new S.Set).size!==0||Sn.size!==0||typeof S.Map.prototype.keys!=="function"||typeof S.Set.prototype.keys!=="function"||typeof S.Map.prototype.forEach!=="function"||typeof S.Set.prototype.forEach!=="function"||u(S.Map)||u(S.Set)||typeof Sn.keys().next!=="function"||Tn||!bn){b(S,{Map:nn.Map,Set:nn.Set},true)}if(S.Set.prototype.keys!==S.Set.prototype.values){h(S.Set.prototype,"keys",S.Set.prototype.values,true)}xe(Object.getPrototypeOf((new S.Map).keys()));xe(Object.getPrototypeOf((new S.Set).keys()));if(c&&S.Set.prototype.has.name!=="has"){var In=S.Set.prototype.has;oe(S.Set.prototype,"has",function has(e){return t(In,this,e)})}}b(S,nn);Me(S.Map);Me(S.Set)}var En=function throwUnlessTargetIsObject(e){if(!le.TypeIsObject(e)){throw new TypeError("target must be an object")}};var Pn={apply:function apply(){return le.Call(le.Call,null,arguments)},construct:function construct(e,t){if(!le.IsConstructor(e)){throw new TypeError("First argument must be a constructor.")}var r=arguments.length>2?arguments[2]:e;if(!le.IsConstructor(r)){throw new TypeError("new.target must be a constructor.")}return le.Construct(e,t,r,"internal")},deleteProperty:function deleteProperty(e,t){En(e);if(s){var r=Object.getOwnPropertyDescriptor(e,t);if(r&&!r.configurable){return false}}return delete e[t]},has:function has(e,t){En(e);return t in e}};if(Object.getOwnPropertyNames){Object.assign(Pn,{ownKeys:function ownKeys(e){En(e);var t=Object.getOwnPropertyNames(e);if(le.IsCallable(Object.getOwnPropertySymbols)){x(t,Object.getOwnPropertySymbols(e))}return t}})}var Cn=function ConvertExceptionToBoolean(e){return!i(e)};if(Object.preventExtensions){Object.assign(Pn,{isExtensible:function isExtensible(e){En(e);return Object.isExtensible(e)},preventExtensions:function preventExtensions(e){En(e);return Cn(function(){return Object.preventExtensions(e)})}})}if(s){var Mn=function get(e,t,r){var n=Object.getOwnPropertyDescriptor(e,t);if(!n){var o=Object.getPrototypeOf(e);if(o===null){return void 0}return Mn(o,t,r)}if("value"in n){return n.value}if(n.get){return le.Call(n.get,r)}return void 0};var xn=function set(e,r,n,o){var i=Object.getOwnPropertyDescriptor(e,r);if(!i){var a=Object.getPrototypeOf(e);if(a!==null){return xn(a,r,n,o)}i={value:void 0,writable:true,enumerable:true,configurable:true}}if("value"in i){if(!i.writable){return false}if(!le.TypeIsObject(o)){return false}var u=Object.getOwnPropertyDescriptor(o,r);if(u){return ue.defineProperty(o,r,{value:n})}else{return ue.defineProperty(o,r,{value:n,writable:true,enumerable:true,configurable:true})}}if(i.set){t(i.set,o,n);return true}return false};Object.assign(Pn,{defineProperty:function defineProperty(e,t,r){En(e);return Cn(function(){return Object.defineProperty(e,t,r)})},getOwnPropertyDescriptor:function getOwnPropertyDescriptor(e,t){En(e);return Object.getOwnPropertyDescriptor(e,t)},get:function get(e,t){En(e);var r=arguments.length>2?arguments[2]:e;return Mn(e,t,r)},set:function set(e,t,r){En(e);var n=arguments.length>3?arguments[3]:e;return xn(e,t,r,n)}})}if(Object.getPrototypeOf){var Nn=Object.getPrototypeOf;Pn.getPrototypeOf=function getPrototypeOf(e){En(e);return Nn(e)}}if(Object.setPrototypeOf&&Pn.getPrototypeOf){var An=function(e,t){var r=t;while(r){if(e===r){return true}r=Pn.getPrototypeOf(r)}return false};Object.assign(Pn,{setPrototypeOf:function setPrototypeOf(e,t){En(e);if(t!==null&&!le.TypeIsObject(t)){throw new TypeError("proto must be an object or null")}if(t===ue.getPrototypeOf(e)){return true}if(ue.isExtensible&&!ue.isExtensible(e)){return false}if(An(e,t)){return false}Object.setPrototypeOf(e,t);return true}})}var Rn=function(e,t){if(!le.IsCallable(S.Reflect[e])){h(S.Reflect,e,t)}else{var r=a(function(){S.Reflect[e](1);S.Reflect[e](NaN);S.Reflect[e](true);return true});if(r){oe(S.Reflect,e,t)}}};Object.keys(Pn).forEach(function(e){Rn(e,Pn[e])});var _n=S.Reflect.getPrototypeOf;if(c&&_n&&_n.name!=="getPrototypeOf"){oe(S.Reflect,"getPrototypeOf",function getPrototypeOf(e){return t(_n,S.Reflect,e)})}if(S.Reflect.setPrototypeOf){if(a(function(){S.Reflect.setPrototypeOf(1,{});return true})){oe(S.Reflect,"setPrototypeOf",Pn.setPrototypeOf)}}if(S.Reflect.defineProperty){if(!a(function(){var e=!S.Reflect.defineProperty(1,"test",{value:1});var t=typeof Object.preventExtensions!=="function"||!S.Reflect.defineProperty(Object.preventExtensions({}),"test",{});return e&&t})){oe(S.Reflect,"defineProperty",Pn.defineProperty)}}if(S.Reflect.construct){if(!a(function(){var e=function F(){};return S.Reflect.construct(function(){},[],e)instanceof e})){oe(S.Reflect,"construct",Pn.construct)}}if(String(new Date(NaN))!=="Invalid Date"){var kn=Date.prototype.toString;var Ln=function toString(){var e=+this;if(e!==e){return"Invalid Date"}return le.Call(kn,this)};oe(Date.prototype,"toString",Ln)}var Fn={anchor:function anchor(e){return le.CreateHTML(this,"a","name",e)},big:function big(){return le.CreateHTML(this,"big","","")},blink:function blink(){return le.CreateHTML(this,"blink","","")},bold:function bold(){return le.CreateHTML(this,"b","","")},fixed:function fixed(){return le.CreateHTML(this,"tt","","")},fontcolor:function fontcolor(e){return le.CreateHTML(this,"font","color",e)},fontsize:function fontsize(e){return le.CreateHTML(this,"font","size",e)},italics:function italics(){return le.CreateHTML(this,"i","","")},link:function link(e){return le.CreateHTML(this,"a","href",e)},small:function small(){return le.CreateHTML(this,"small","","")},strike:function strike(){return le.CreateHTML(this,"strike","","")},sub:function sub(){return le.CreateHTML(this,"sub","","")},sup:function sub(){return le.CreateHTML(this,"sup","","")}};l(Object.keys(Fn),function(e){var r=String.prototype[e];var n=false;if(le.IsCallable(r)){var o=t(r,"",' " ');var i=P([],o.match(/"/g)).length;n=o!==o.toLowerCase()||i>2}else{n=true}if(n){oe(String.prototype,e,Fn[e])}});var Dn=function(){if(!ie){return false}var e=typeof JSON==="object"&&typeof JSON.stringify==="function"?JSON.stringify:null;if(!e){return false}if(typeof e(J())!=="undefined"){return true}if(e([J()])!=="[null]"){return true}var t={a:J()};t[J()]=true;if(e(t)!=="{}"){return true}return false}();var zn=a(function(){if(!ie){return true}return JSON.stringify(Object(J()))==="{}"&&JSON.stringify([Object(J())])==="[{}]"});if(Dn||!zn){var qn=JSON.stringify;oe(JSON,"stringify",function stringify(e){if(typeof e==="symbol"){return}var n;if(arguments.length>1){n=arguments[1]}var o=[e];if(!r(n)){var i=le.IsCallable(n)?n:null;var a=function(e,r){var n=i?t(i,this,e,r):r;if(typeof n!=="symbol"){if(ne.symbol(n)){return At({})(n)}else{return n}}};o.push(a)}else{o.push(n)}if(arguments.length>2){o.push(arguments[2])}return qn.apply(this,o)})}return S});
//# sourceMappingURL=es6-shim.map
;
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
/* Copyright 2012 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/* globals VBArray, PDFJS */
/*
    via https://github.com/mozilla/pdf.js/
    Modified 12/13/2013 *SLR - Removed all code except Uint8Array and btoa definition
    Modified 01/14/2014 *SLR - Added atob definition back in
*/
'use strict';
(function checkTypedArrayCompatibility() {
    if (typeof Uint8Array !== 'undefined') {
        return;
    }
    function subarray(start, end) {
        return TypedArray(this.slice(start, end));
    }
    function setArrayOffset(array, offset) {
        if (arguments.length < 2)
            offset = 0;
        for (var i = 0, n = array.length; i < n; ++i, ++offset)
            this[offset] = array[i] & 0xFF;
    }
    function TypedArray(arg1) {
        var result;
        if (typeof arg1 === 'number') {
            result = [];
            for (var i = 0; i < arg1; ++i)
                result[i] = 0;
        }
        else if ('slice' in arg1) {
            result = arg1.slice(0);
        }
        else {
            result = [];
            for (var i = 0, n = arg1.length; i < n; ++i) {
                result[i] = arg1[i];
            }
        }
        result.subarray = subarray;
        result.buffer = result;
        result.byteLength = result.length;
        result.set = setArrayOffset;
        if (typeof arg1 === 'object' && arg1.buffer)
            result.buffer = arg1.buffer;
        return result;
    }
    window.Uint8Array = TypedArray;
})();
// window.btoa (base64 encode function) ?
(function checkWindowBtoaCompatibility() {
    if ('btoa' in window)
        return;
    var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    window.btoa = function windowBtoa(chars) {
        var buffer = '';
        var i, n;
        for (i = 0, n = chars.length; i < n; i += 3) {
            var b1 = chars.charCodeAt(i) & 0xFF;
            var b2 = chars.charCodeAt(i + 1) & 0xFF;
            var b3 = chars.charCodeAt(i + 2) & 0xFF;
            var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4);
            var d3 = i + 1 < n ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64;
            var d4 = i + 2 < n ? (b3 & 0x3F) : 64;
            buffer += (digits.charAt(d1) + digits.charAt(d2) +
                digits.charAt(d3) + digits.charAt(d4));
        }
        return buffer;
    };
})();
// window.atob (base64 encode function) ?
(function checkWindowAtobCompatibility() {
    if ('atob' in window)
        return;
    // https://github.com/davidchambers/Base64.js
    var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
    window.atob = function (input) {
        input = input.replace(/=+$/, '');
        if (input.length % 4 == 1)
            throw new Error('bad atob input');
        var output = '';
        for (
        // initialize result and counters
        var bc = 0, bs = void 0, buffer = void 0, idx = 0; 
        // get next character
        buffer = input.charAt(idx++); 
        // character found in table?
        // initialize bit storage and add its ascii value
        ~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
            // and if not first of each 4 characters,
            // convert the first 8 bits to one ascii character
            bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0) {
            // try to find character in table (0-63, not found => -1)
            buffer = digits.indexOf(buffer);
        }
        return output;
    };
})();
//# sourceMappingURL=compatibility.js.map;
// source and license: https://github.com/dankogai/js-deflate

(function (GLOBAL) {
    /*
     * Port of script by Masanao Izumo.
     *
     * Wrapped all the variables in a function, created a
     * constructor for interacting with the lib. Everything
     * else was written by M. Izumo.
     *
     * Original code can be found here: http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt
     *
     */

    var zip_WSIZE = 32768;		// Sliding Window size
    var zip_STORED_BLOCK = 0;
    var zip_STATIC_TREES = 1;
    var zip_DYN_TREES    = 2;

    /* for inflate */
    var zip_lbits = 9; 		// bits in base literal/length lookup table
    var zip_dbits = 6; 		// bits in base distance lookup table
    var zip_INBUFSIZ = 32768;	// Input buffer size
    var zip_INBUF_EXTRA = 64;	// Extra buffer

    /* variables (inflate) */
    var zip_slide;
    var zip_wp;			// current position in slide
    var zip_fixed_tl = null;	// inflate static
    var zip_fixed_td;		// inflate static
    var zip_fixed_bl, zip_fixed_bd;	// inflate static //*SLR 1/13/2014 fixed_bd => zip_fixed_bd
    var zip_bit_buf;		// bit buffer
    var zip_bit_len;		// bits in bit buffer
    var zip_method;
    var zip_eof;
    var zip_copy_leng;
    var zip_copy_dist;
    var zip_tl, zip_td;	// literal/length and distance decoder tables
    var zip_bl, zip_bd;	// number of bits decoded by tl and td

    var zip_inflate_data;
    var zip_inflate_pos;


    /* constant tables (inflate) */
    var zip_MASK_BITS = new Array(
        0x0000,
        0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
        0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff);
    // Tables for deflate from PKZIP's appnote.txt.
    var zip_cplens = new Array( // Copy lengths for literal codes 257..285
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0);
    /* note: see note #13 above about the 258 in this list. */
    var zip_cplext = new Array( // Extra bits for literal codes 257..285
        0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
        3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 99, 99); // 99==invalid
    var zip_cpdist = new Array( // Copy offsets for distance codes 0..29
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
        8193, 12289, 16385, 24577);
    var zip_cpdext = new Array( // Extra bits for distance codes
        0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
        7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
        12, 12, 13, 13);
    var zip_border = new Array(  // Order of the bit length code lengths
        16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15);
    /* objects (inflate) */

    function zip_HuftList() {
        this.next = null;
        this.list = null;
    }

    function zip_HuftNode() {
        this.e = 0; // number of extra bits or operation
        this.b = 0; // number of bits in this code or subcode

        // union
        this.n = 0; // literal, length base, or distance base
        this.t = null; // (zip_HuftNode) pointer to next level of table
    }

    function zip_HuftBuild(b,	// code lengths in bits (all assumed <= BMAX)
                           n,	// number of codes (assumed <= N_MAX)
                           s,	// number of simple-valued codes (0..s-1)
                           d,	// list of base values for non-simple codes
                           e,	// list of extra bits for non-simple codes
                           mm	// maximum lookup bits
                          ) {
        this.BMAX = 16;   // maximum bit length of any code
        this.N_MAX = 288; // maximum number of codes in any set
        this.status = 0;	// 0: success, 1: incomplete table, 2: bad input
        this.root = null;	// (zip_HuftList) starting table
        this.m = 0;		// maximum lookup bits, returns actual

        /* Given a list of code lengths and a maximum table size, make a set of
           tables to decode that set of codes.	Return zero on success, one if
           the given code set is incomplete (the tables are still built in this
           case), two if the input is invalid (all zero length codes or an
           oversubscribed set of lengths), and three if not enough memory.
           The code with value 256 is special, and the tables are constructed
           so that no bits beyond that code are fetched when that code is
           decoded. */
        {
            var a;			// counter for codes of length k
            var c = new Array(this.BMAX+1);	// bit length count table
            var el;			// length of EOB code (value 256)
            var f;			// i repeats in table every f entries
            var g;			// maximum code length
            var h;			// table level
            var i;			// counter, current code
            var j;			// counter
            var k;			// number of bits in current code
            var lx = new Array(this.BMAX+1);	// stack of bits per table
            var p;			// pointer into c[], b[], or v[]
            var pidx;		// index of p
            var q;			// (zip_HuftNode) points to current table
            var r = new zip_HuftNode(); // table entry for structure assignment
            var u = new Array(this.BMAX); // zip_HuftNode[BMAX][]  table stack
            var v = new Array(this.N_MAX); // values in order of bit length
            var w;
            var x = new Array(this.BMAX+1);// bit offsets, then code stack
            var xp;			// pointer into x or c
            var y;			// number of dummy codes added
            var z;			// number of entries in current table
            var o;
            var tail;		// (zip_HuftList)

            tail = this.root = null;
            for(i = 0; i < c.length; i++)
                c[i] = 0;
            for(i = 0; i < lx.length; i++)
                lx[i] = 0;
            for(i = 0; i < u.length; i++)
                u[i] = null;
            for(i = 0; i < v.length; i++)
                v[i] = 0;
            for(i = 0; i < x.length; i++)
                x[i] = 0;

            // Generate counts for each bit length
            el = n > 256 ? b[256] : this.BMAX; // set length of EOB code, if any
            p = b; pidx = 0;
            i = n;
            do {
                c[p[pidx]]++;	// assume all entries <= BMAX
                pidx++;
            } while(--i > 0);
            if(c[0] == n) {	// null input--all zero length codes
                this.root = null;
                this.m = 0;
                this.status = 0;
                return;
            }

            // Find minimum and maximum length, bound *m by those
            for(j = 1; j <= this.BMAX; j++)
                if(c[j] != 0)
                    break;
            k = j;			// minimum code length
            if(mm < j)
                mm = j;
            for(i = this.BMAX; i != 0; i--)
                if(c[i] != 0)
                    break;
            g = i;			// maximum code length
            if(mm > i)
                mm = i;

            // Adjust last length count to fill out codes, if needed
            for(y = 1 << j; j < i; j++, y <<= 1)
                if((y -= c[j]) < 0) {
                    this.status = 2;	// bad input: more codes than bits
                    this.m = mm;
                    return;
                }
            if((y -= c[i]) < 0) {
                this.status = 2;
                this.m = mm;
                return;
            }
            c[i] += y;

            // Generate starting offsets into the value table for each length
            x[1] = j = 0;
            p = c;
            pidx = 1;
            xp = 2;
            while(--i > 0)		// note that i == g from above
                x[xp++] = (j += p[pidx++]);

            // Make a table of values in order of bit lengths
            p = b; pidx = 0;
            i = 0;
            do {
                if((j = p[pidx++]) != 0)
                    v[x[j]++] = i;
            } while(++i < n);
            n = x[g];			// set n to length of v

            // Generate the Huffman codes and for each, make the table entries
            x[0] = i = 0;		// first Huffman code is zero
            p = v; pidx = 0;		// grab values in bit order
            h = -1;			// no tables yet--level -1
            w = lx[0] = 0;		// no bits decoded yet
            q = null;			// ditto
            z = 0;			// ditto

            // go through the bit lengths (k already is bits in shortest code)
            for(; k <= g; k++) {
                a = c[k];
                while(a-- > 0) {
                    // here i is the Huffman code of length k bits for value p[pidx]
                    // make tables up to required level
                    while(k > w + lx[1 + h]) {
                        w += lx[1 + h]; // add bits already decoded
                        h++;

                        // compute minimum size table less than or equal to *m bits
                        z = (z = g - w) > mm ? mm : z; // upper limit
                        if((f = 1 << (j = k - w)) > a + 1) { // try a k-w bit table
                            // too few codes for k-w bit table
                            f -= a + 1;	// deduct codes from patterns left
                            xp = k;
                            while(++j < z) { // try smaller tables up to z bits
                                if((f <<= 1) <= c[++xp])
                                    break;	// enough codes to use up j bits
                                f -= c[xp];	// else deduct codes from patterns
                            }
                        }
                        if(w + j > el && w < el)
                            j = el - w;	// make EOB code end at table
                        z = 1 << j;	// table entries for j-bit table
                        lx[1 + h] = j; // set table size in stack

                        // allocate and link in new table
                        q = new Array(z);
                        for(o = 0; o < z; o++) {
                            q[o] = new zip_HuftNode();
                        }

                        if(tail == null)
                            tail = this.root = new zip_HuftList();
                        else
                            tail = tail.next = new zip_HuftList();
                        tail.next = null;
                        tail.list = q;
                        u[h] = q;	// table starts after link

                        /* connect to last table, if there is one */
                        if(h > 0) {
                            x[h] = i;		// save pattern for backing up
                            r.b = lx[h];	// bits to dump before this table
                            r.e = 16 + j;	// bits in this table
                            r.t = q;		// pointer to this table
                            j = (i & ((1 << w) - 1)) >> (w - lx[h]);
                            u[h-1][j].e = r.e;
                            u[h-1][j].b = r.b;
                            u[h-1][j].n = r.n;
                            u[h-1][j].t = r.t;
                        }
                    }

                    // set up table entry in r
                    r.b = k - w;
                    if(pidx >= n)
                        r.e = 99;		// out of values--invalid code
                    else if(p[pidx] < s) {
                        r.e = (p[pidx] < 256 ? 16 : 15); // 256 is end-of-block code
                        r.n = p[pidx++];	// simple code is just the value
                    } else {
                        r.e = e[p[pidx] - s];	// non-simple--look up in lists
                        r.n = d[p[pidx++] - s];
                    }

                    // fill code-like entries with r //
                    f = 1 << (k - w);
                    for(j = i >> w; j < z; j += f) {
                        q[j].e = r.e;
                        q[j].b = r.b;
                        q[j].n = r.n;
                        q[j].t = r.t;
                    }

                    // backwards increment the k-bit code i
                    for(j = 1 << (k - 1); (i & j) != 0; j >>= 1)
                        i ^= j;
                    i ^= j;

                    // backup over finished tables
                    while((i & ((1 << w) - 1)) != x[h]) {
                        w -= lx[h];		// don't need to update q
                        h--;
                    }
                }
            }

            /* return actual size of base table */
            this.m = lx[1];

            /* Return true (1) if we were given an incomplete table */
            this.status = ((y != 0 && g != 1) ? 1 : 0);
        } /* end of constructor */
    }


    /* routines (inflate) */

    function zip_GET_BYTE() {
        if(zip_inflate_data.length == zip_inflate_pos)
            return -1;
        return zip_inflate_data.charCodeAt(zip_inflate_pos++) & 0xff;
    }

    function zip_NEEDBITS(n) {
        while(zip_bit_len < n) {
            zip_bit_buf |= zip_GET_BYTE() << zip_bit_len;
            zip_bit_len += 8;
        }
    }

    function zip_GETBITS(n) {
        return zip_bit_buf & zip_MASK_BITS[n];
    }

    function zip_DUMPBITS(n) {
        zip_bit_buf >>= n;
        zip_bit_len -= n;
    }

    function zip_inflate_codes(buff, off, size) {
        /* inflate (decompress) the codes in a deflated (compressed) block.
           Return an error code or zero if it all goes ok. */
        var e;		// table entry flag/number of extra bits
        var t;		// (zip_HuftNode) pointer to table entry
        var n;

        if(size == 0)
            return 0;

        // inflate the coded data
        n = 0;
        for(;;) {			// do until end of block
            zip_NEEDBITS(zip_bl);
            t = zip_tl.list[zip_GETBITS(zip_bl)];
            e = t.e;
            while(e > 16) {
                if(e == 99)
                    return -1;
                zip_DUMPBITS(t.b);
                e -= 16;
                zip_NEEDBITS(e);
                t = t.t[zip_GETBITS(e)];
                e = t.e;
            }
            zip_DUMPBITS(t.b);

            if(e == 16) {		// then it's a literal
                zip_wp &= zip_WSIZE - 1;
                buff[off + n++] = zip_slide[zip_wp++] = t.n;
                if(n == size)
                    return size;
                continue;
            }

            // exit if end of block
            if(e == 15)
                break;

            // it's an EOB or a length

            // get length of block to copy
            zip_NEEDBITS(e);
            zip_copy_leng = t.n + zip_GETBITS(e);
            zip_DUMPBITS(e);

            // decode distance of block to copy
            zip_NEEDBITS(zip_bd);
            t = zip_td.list[zip_GETBITS(zip_bd)];
            e = t.e;

            while(e > 16) {
                if(e == 99)
                    return -1;
                zip_DUMPBITS(t.b);
                e -= 16;
                zip_NEEDBITS(e);
                t = t.t[zip_GETBITS(e)];
                e = t.e;
            }
            zip_DUMPBITS(t.b);
            zip_NEEDBITS(e);
            zip_copy_dist = zip_wp - t.n - zip_GETBITS(e);
            zip_DUMPBITS(e);

            // do the copy
            while(zip_copy_leng > 0 && n < size) {
                zip_copy_leng--;
                zip_copy_dist &= zip_WSIZE - 1;
                zip_wp &= zip_WSIZE - 1;
                buff[off + n++] = zip_slide[zip_wp++]
                    = zip_slide[zip_copy_dist++];
            }

            if(n == size)
                return size;
        }

        zip_method = -1; // done
        return n;
    }

    function zip_inflate_stored(buff, off, size) {
        /* "decompress" an inflated type 0 (stored) block. */
        var n;

        // go to byte boundary
        n = zip_bit_len & 7;
        zip_DUMPBITS(n);

        // get the length and its complement
        zip_NEEDBITS(16);
        n = zip_GETBITS(16);
        zip_DUMPBITS(16);
        zip_NEEDBITS(16);
        if(n != ((~zip_bit_buf) & 0xffff))
            return -1;			// error in compressed data
        zip_DUMPBITS(16);

        // read and output the compressed data
        zip_copy_leng = n;

        n = 0;
        while(zip_copy_leng > 0 && n < size) {
            zip_copy_leng--;
            zip_wp &= zip_WSIZE - 1;
            zip_NEEDBITS(8);
            buff[off + n++] = zip_slide[zip_wp++] =
                zip_GETBITS(8);
            zip_DUMPBITS(8);
        }

        if(zip_copy_leng == 0)
            zip_method = -1; // done
        return n;
    }

    function zip_inflate_fixed(buff, off, size) {
        /* decompress an inflated type 1 (fixed Huffman codes) block.  We should
           either replace this with a custom decoder, or at least precompute the
           Huffman tables. */

        // if first time, set up tables for fixed blocks
        if(zip_fixed_tl == null) {
            var i;			// temporary variable
            var l = new Array(288);	// length list for huft_build
            var h;	// zip_HuftBuild

            // literal table
            for(i = 0; i < 144; i++)
                l[i] = 8;
            for(; i < 256; i++)
                l[i] = 9;
            for(; i < 280; i++)
                l[i] = 7;
            for(; i < 288; i++)	// make a complete, but wrong code set
                l[i] = 8;
            zip_fixed_bl = 7;

            h = new zip_HuftBuild(l, 288, 257, zip_cplens, zip_cplext,
                                  zip_fixed_bl);
            if(h.status != 0) {
                alert("HufBuild error: "+h.status);
                return -1;
            }
            zip_fixed_tl = h.root;
            zip_fixed_bl = h.m;

            // distance table
            for(i = 0; i < 30; i++)	// make an incomplete code set
                l[i] = 5;
            zip_fixed_bd = 5;

            h = new zip_HuftBuild(l, 30, 0, zip_cpdist, zip_cpdext, zip_fixed_bd);
            if(h.status > 1) {
                zip_fixed_tl = null;
                alert("HufBuild error: "+h.status);
                return -1;
            }
            zip_fixed_td = h.root;
            zip_fixed_bd = h.m;
        }

        zip_tl = zip_fixed_tl;
        zip_td = zip_fixed_td;
        zip_bl = zip_fixed_bl;
        zip_bd = zip_fixed_bd;
        return zip_inflate_codes(buff, off, size);
    }

    function zip_inflate_dynamic(buff, off, size) {
        // decompress an inflated type 2 (dynamic Huffman codes) block.
        var i;		// temporary variables
        var j;
        var l;		// last length
        var n;		// number of lengths to get
        var t;		// (zip_HuftNode) literal/length code table
        var nb;		// number of bit length codes
        var nl;		// number of literal/length codes
        var nd;		// number of distance codes
        var ll = new Array(286+30); // literal/length and distance code lengths
        var h;		// (zip_HuftBuild)

        for(i = 0; i < ll.length; i++)
            ll[i] = 0;

        // read in table lengths
        zip_NEEDBITS(5);
        nl = 257 + zip_GETBITS(5);	// number of literal/length codes
        zip_DUMPBITS(5);
        zip_NEEDBITS(5);
        nd = 1 + zip_GETBITS(5);	// number of distance codes
        zip_DUMPBITS(5);
        zip_NEEDBITS(4);
        nb = 4 + zip_GETBITS(4);	// number of bit length codes
        zip_DUMPBITS(4);
        if(nl > 286 || nd > 30)
            return -1;		// bad lengths

        // read in bit-length-code lengths
        for(j = 0; j < nb; j++)
        {
            zip_NEEDBITS(3);
            ll[zip_border[j]] = zip_GETBITS(3);
            zip_DUMPBITS(3);
        }
        for(; j < 19; j++)
            ll[zip_border[j]] = 0;

        // build decoding table for trees--single level, 7 bit lookup
        zip_bl = 7;
        h = new zip_HuftBuild(ll, 19, 19, null, null, zip_bl);
        if(h.status != 0)
            return -1;	// incomplete code set

        zip_tl = h.root;
        zip_bl = h.m;

        // read in literal and distance code lengths
        n = nl + nd;
        i = l = 0;
        while(i < n) {
            zip_NEEDBITS(zip_bl);
            t = zip_tl.list[zip_GETBITS(zip_bl)];
            j = t.b;
            zip_DUMPBITS(j);
            j = t.n;
            if(j < 16)		// length of code in bits (0..15)
                ll[i++] = l = j;	// save last length in l
            else if(j == 16) {	// repeat last length 3 to 6 times
                zip_NEEDBITS(2);
                j = 3 + zip_GETBITS(2);
                zip_DUMPBITS(2);
                if(i + j > n)
                    return -1;
                while(j-- > 0)
                    ll[i++] = l;
            } else if(j == 17) {	// 3 to 10 zero length codes
                zip_NEEDBITS(3);
                j = 3 + zip_GETBITS(3);
                zip_DUMPBITS(3);
                if(i + j > n)
                    return -1;
                while(j-- > 0)
                    ll[i++] = 0;
                l = 0;
            } else {		// j == 18: 11 to 138 zero length codes
                zip_NEEDBITS(7);
                j = 11 + zip_GETBITS(7);
                zip_DUMPBITS(7);
                if(i + j > n)
                    return -1;
                while(j-- > 0)
                    ll[i++] = 0;
                l = 0;
            }
        }

        // build the decoding tables for literal/length and distance codes
        zip_bl = zip_lbits;
        h = new zip_HuftBuild(ll, nl, 257, zip_cplens, zip_cplext, zip_bl);
        if(zip_bl == 0)	// no literals or lengths
            h.status = 1;
        if(h.status != 0) {
            if(h.status == 1)
                ;// **incomplete literal tree**
            return -1;		// incomplete code set
        }
        zip_tl = h.root;
        zip_bl = h.m;

        for(i = 0; i < nd; i++)
            ll[i] = ll[i + nl];
        zip_bd = zip_dbits;
        h = new zip_HuftBuild(ll, nd, 0, zip_cpdist, zip_cpdext, zip_bd);
        zip_td = h.root;
        zip_bd = h.m;

        if(zip_bd == 0 && nl > 257) {   // lengths but no distances
            // **incomplete distance tree**
            return -1;
        }

        if(h.status == 1) {
            ;// **incomplete distance tree**
        }
        if(h.status != 0)
            return -1;

        // decompress until an end-of-block code
        return zip_inflate_codes(buff, off, size);
    }

    function zip_inflate_start() {
        var i;

        if(zip_slide == null)
            zip_slide = new Array(2 * zip_WSIZE);
        zip_wp = 0;
        zip_bit_buf = 0;
        zip_bit_len = 0;
        zip_method = -1;
        zip_eof = false;
        zip_copy_leng = zip_copy_dist = 0;
        zip_tl = null;
    }

    function zip_inflate_internal(buff, off, size) {
        // decompress an inflated entry
        var n, i;

        n = 0;
        while(n < size) {
            if(zip_eof && zip_method == -1)
                return n;

            if(zip_copy_leng > 0) {
                if(zip_method != zip_STORED_BLOCK) {
                    // STATIC_TREES or DYN_TREES
                    while(zip_copy_leng > 0 && n < size) {
                        zip_copy_leng--;
                        zip_copy_dist &= zip_WSIZE - 1;
                        zip_wp &= zip_WSIZE - 1;
                        buff[off + n++] = zip_slide[zip_wp++] =
                            zip_slide[zip_copy_dist++];
                    }
                } else {
                    while(zip_copy_leng > 0 && n < size) {
                        zip_copy_leng--;
                        zip_wp &= zip_WSIZE - 1;
                        zip_NEEDBITS(8);
                        buff[off + n++] = zip_slide[zip_wp++] = zip_GETBITS(8);
                        zip_DUMPBITS(8);
                    }
                    if(zip_copy_leng == 0)
                        zip_method = -1; // done
                }
                if(n == size)
                    return n;
            }

            if(zip_method == -1) {
                if(zip_eof)
                    break;

                // read in last block bit
                zip_NEEDBITS(1);
                if(zip_GETBITS(1) != 0)
                    zip_eof = true;
                zip_DUMPBITS(1);

                // read in block type
                zip_NEEDBITS(2);
                zip_method = zip_GETBITS(2);
                zip_DUMPBITS(2);
                zip_tl = null;
                zip_copy_leng = 0;
            }

            switch(zip_method) {
            case 0: // zip_STORED_BLOCK
                i = zip_inflate_stored(buff, off + n, size - n);
                break;

            case 1: // zip_STATIC_TREES
                if(zip_tl != null)
                    i = zip_inflate_codes(buff, off + n, size - n);
                else
                    i = zip_inflate_fixed(buff, off + n, size - n);
                break;

            case 2: // zip_DYN_TREES
                if(zip_tl != null)
                    i = zip_inflate_codes(buff, off + n, size - n);
                else
                    i = zip_inflate_dynamic(buff, off + n, size - n);
                break;

            default: // error
                i = -1;
                break;
            }

            if(i == -1) {
                if(zip_eof)
                    return 0;
                return -1;
            }
            n += i;
        }
        return n;
    }


    var JSInflate = {};
    if (typeof(module) == "object") {
        module.exports = JSInflate;
        var fs = require("fs");
    } else {
        GLOBAL.JSInflate = JSInflate;
    }

    JSInflate.inflate = function (data) {
        var out, buff;
        var i, j;

        zip_inflate_start();
        zip_inflate_data = data;
        zip_inflate_pos = 0;

        buff = new Array(1024);
        out = "";
        while((i = zip_inflate_internal(buff, 0, buff.length)) > 0) {
            for(j = 0; j < i; j++)
                out += String.fromCharCode(buff[j]);
        }
        zip_inflate_data = null; // G.C.

        return out;
    };

    function write_inflated_internal(ws, buff) {
        var bytesInflated = zip_inflate_internal(buff, 0, buff.length);
        if (bytesInflated > 0) {
            var out = "";
            var j; //*SLR 1/13/2014 Added variable declaraion
            for(j = 0; j < bytesInflated; j++) {
                out += String.fromCharCode(buff[j]);
            }
            ws.write(out);
        }
        return bytesInflated;
    };

    JSInflate.inflateStream = function(data, unzipFile, callback) {
        var out, buff, bytesWritten;

        zip_inflate_start();
        zip_inflate_data = data;
        zip_inflate_pos = 0;
        bytesWritten = 0;

        var ws = fs.createWriteStream(unzipFile);
        buff = new Array(1024);
        var bytesInflated = 0;

        ws.on('drain', function() {
            bytesInflated = write_inflated_internal(ws, buff);
            if (bytesInflated > 0) {
                bytesWritten += bytesInflated;
            } else {
                zip_inflate_data = null;
                callback(bytesWritten);
            }
        });

        bytesWritten += write_inflated_internal(ws, buff);
    };
}(this));;
/*!
* jQuery Pw0rd Strength plugin for Twitter Bootstrap
*
* Copyright (c) 2008-2013 Tane Piper
* Copyright (c) 2013 Alejandro Blanco
* Dual licensed under the MIT and GPL licenses.
*/

//Source and license: https://github.com/ablanco/jquery.pwstrength.bootstrap/
//*SLR 1/17/2014
//  added options.common.keyUpDelay and options.ui.showProgressBarInPopover
//  turned on validation.wordRepetitions by default
//  rewrote validation.wordRepetitions and validation.wordSequences
//  modified default scores for wordRepetitions and wordSequences
//  added functionality to hide popover when focus lost

(function (jQuery) {
// Source: src/rules.js




var rulesEngine = {};

try {
    if (!jQuery && module && module.exports) {
        var jQuery = require("jquery");
    }
} catch (ignore) {}

(function ($, rulesEngine) {
    "use strict";
    var validation = {};

    rulesEngine.forbiddenSequences = [
        "0123456789", "9876543210", "abcdefghijklmnopqrstuvxywz",
        "qwertyuiop", "asdfghjkl", "zxcvbnm"
    ];

    validation.wordNotEmail = function (options, word, score) {
        if (word.match(/^([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)*[\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+[a-z]{2,6})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)$/i)) {
            options.instances.errors.push(options.ui.spanError(options, "email_as"));
            return score;
        }
    };

    validation.wordLength = function (options, word, score) {
        var wordlen = word.length,
            lenScore = Math.pow(wordlen, options.rules.raisePower);
        if (wordlen < options.common.minChar) {
            lenScore = (lenScore + score);
            options.instances.errors.push(options.ui.spanError(options, "too_short"));
        }
        return lenScore;
    };

    validation.wordSimilarToUsername = function (options, word, score) {
        var username = $(options.common.usernameField).val();
        if (username && word.toLowerCase().match(username.toLowerCase())) {
            options.instances.errors.push(options.ui.spanError(options, "same_as_username"));
            return score;
        }
        return false;
    };

    validation.wordTwoCharacterClasses = function (options, word, score) {
        if (word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) ||
                (word.match(/([a-zA-Z])/) && word.match(/([0-9])/)) ||
                (word.match(/(.[!,@,#,$,%,\^,&,*,?,_,~])/) && word.match(/[a-zA-Z0-9_]/))) {
            return score;
        }
        options.instances.errors.push(options.ui.spanError(options, "two_character_classes"));
        return false;
    };

    //validation.wordRepetitions = function (options, word, score) {
    //    if (word.match(/(.)\1\1/)) {
    //        options.instances.errors.push(options.ui.spanError(options, "repeated_character"));
    //        return score;
    //    }
    //    return false;
    //};

    //*SLR 1/17/2014 - rewrote wordRepetitions to calculate based on length and # of reps
    validation.wordRepetitions = function (options, word, score) {
        var res = word.match(/(.)\1{1,}/g);
        if (res) {
            options.instances.errors.push(options.ui.spanError(options, "repeated_character"));
            var i, calcScore = 0;
            for (i = 0; i < res.length; i++) {
                calcScore += score + ((res[i].length - 3) * (score/2));
            }
            return calcScore;
        }
        return false;
    };

    //validation.wordSequences = function (options, word, score) {
    //    var found = false,
    //        j;
    //    if (word.length > 2) {
    //        $.each(rulesEngine.forbiddenSequences, function (idx, sequence) {
    //            for (j = 0; j < (word.length - 3); j += 1) { //iterate the word trough a sliding window of size 3:
    //                if (sequence.indexOf(word.toLowerCase().substring(j, j + 3)) > -1) {
    //                    found = true;
    //                }
    //            }
    //        });
    //        if (found) {
    //            options.instances.errors.push(options.ui.spanError(options, "sequence_found"));
    //            return score;
    //        }
    //    }
    //    return false;
    //};

    //*SLR 1/17/2014 - rewrote wordSequences to fix bug and return multiples
    validation.wordSequences = function (options, word, score) {
        var found = 0,
            j;
        if (word.length > 2) {
            $.each(rulesEngine.forbiddenSequences, function (idx, sequence) {
                for (j = 0; j < (word.length - 2) ; j += 1) { //iterate the word through a sliding window of size 3:
                    if (sequence.indexOf(word.toLowerCase().substring(j, j + 3)) > -1) {
                        found++;
                    }
                }
            });
            if (found > 0) {
                options.instances.errors.push(options.ui.spanError(options, "sequence_found"));
                return score*found;
            }
        }
        return false;
    };

    validation.wordLowercase = function (options, word, score) {
        return word.match(/[a-z]/) && score;
    };

    validation.wordUppercase = function (options, word, score) {
        return word.match(/[A-Z]/) && score;
    };

    validation.wordOneNumber = function (options, word, score) {
        return word.match(/\d+/) && score;
    };

    validation.wordThreeNumbers = function (options, word, score) {
        return word.match(/(.*[0-9].*[0-9].*[0-9])/) && score;
    };

    validation.wordOneSpecialChar = function (options, word, score) {
        return word.match(/.[!,@,#,$,%,\^,&,*,?,_,~]/) && score;
    };

    validation.wordTwoSpecialChar = function (options, word, score) {
        return word.match(/(.*[!,@,#,$,%,\^,&,*,?,_,~].*[!,@,#,$,%,\^,&,*,?,_,~])/) && score;
    };

    validation.wordUpperLowerCombo = function (options, word, score) {
        return word.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/) && score;
    };

    validation.wordLetterNumberCombo = function (options, word, score) {
        return word.match(/([a-zA-Z])/) && word.match(/([0-9])/) && score;
    };

    validation.wordLetterNumberCharCombo = function (options, word, score) {
        return word.match(/([a-zA-Z0-9].*[!,@,#,$,%,\^,&,*,?,_,~])|([!,@,#,$,%,\^,&,*,?,_,~].*[a-zA-Z0-9])/) && score;
    };

    rulesEngine.validation = validation;

    rulesEngine.executeRules = function (options, word) {
        var totalScore = 0;

        $.each(options.rules.activated, function (rule, active) {
            if (active) {
                var score = options.rules.scores[rule],
                    funct = rulesEngine.validation[rule],
                    result;

                if (!$.isFunction(funct)) {
                    funct = options.rules.extra[rule];
                }
                
                if ($.isFunction(funct)) {
                    result = funct(options, word, score);
                    if (result) {
                        totalScore += result;
                    }
                }
            }
        });

        return totalScore;
    };
}(jQuery, rulesEngine));

try {
    if (module && module.exports) {
        module.exports = rulesEngine;
    }
} catch (ignore) {}

// Source: src/options.js




var defaultOptions = {};

defaultOptions.common = {};
defaultOptions.common.minChar = 6;
defaultOptions.common.usernameField = "#username";
defaultOptions.common.onLoad = undefined;
defaultOptions.common.onKeyUp = undefined;
defaultOptions.common.keyUpDelay = 0; //*SLR 1/17/2014 - added

defaultOptions.rules = {};
defaultOptions.rules.extra = {};
defaultOptions.rules.scores = {
    wordNotEmail: -100,
    wordLength: -50,
    wordSimilarToUsername: -100,
    wordSequences: -6, //-50, *SLR 1/17/2014 - reduced
    wordTwoCharacterClasses: 2,
    wordRepetitions: -6, //-25, *SLR 1/17/2014 - reduced
    wordLowercase: 1,
    wordUppercase: 3,
    wordOneNumber: 3,
    wordThreeNumbers: 5,
    wordOneSpecialChar: 3,
    wordTwoSpecialChar: 5,
    wordUpperLowerCombo: 2,
    wordLetterNumberCombo: 2,
    wordLetterNumberCharCombo: 2
};
defaultOptions.rules.activated = {
    wordNotEmail: true,
    wordLength: true,
    wordSimilarToUsername: true,
    wordSequences: true,
    wordTwoCharacterClasses: false,
    wordRepetitions: true, //*SLR 1/17/2014 - turned on by default
    wordLowercase: true,
    wordUppercase: true,
    wordOneNumber: true,
    wordThreeNumbers: true,
    wordOneSpecialChar: true,
    wordTwoSpecialChar: true,
    wordUpperLowerCombo: true,
    wordLetterNumberCombo: true,
    wordLetterNumberCharCombo: true
};
defaultOptions.rules.raisePower = 1.4;

defaultOptions.ui = {};
defaultOptions.ui.bootstrap2 = false;
defaultOptions.ui.showPopover = false;
defaultOptions.ui.showProgressBarInPopover = false; //*SLR 1/17/2014 - added
defaultOptions.ui.spanError = function (options, key) {
    "use strict";
    var text = options.ui.errorMessages[key];
    return '<span style="color: #d52929">' + text + '</span>';
};
defaultOptions.ui.errorMessages = {
    too_short: "The Password is too short",
    email_as: "Do not use your email as your password",
    same_as_username: "Your password cannot contain your username",
    two_character_classes: "Use different character classes",
    repeated_character: "Too many repetitions",
    sequence_found: "Your password contains sequences"
};
defaultOptions.ui.verdicts = ["Weak", "Normal", "Medium", "Strong", "Very Strong"];
defaultOptions.ui.showVerdicts = true;
defaultOptions.ui.showErrors = false;
defaultOptions.ui.container = undefined;
defaultOptions.ui.viewports = {
    progress: undefined,
    verdict: undefined,
    errors: undefined
};
defaultOptions.ui.scores = [14, 26, 38, 50];

// Source: src/ui.js




var ui = {};

(function ($, ui) {
    "use strict";

    ui.getContainer = function (options, $el) {
        var $container;

        $container = $(options.ui.container);
        if (!($container && $container.length === 1)) {
            $container = $el.parent();
        }
        return $container;
    };

    ui.findElement = function ($container, viewport, cssSelector) {
        if (viewport) {
            return $container.find(viewport).find(cssSelector);
        }
        return $container.find(cssSelector);
    };

    //*SLR 1/17/2014 added
    ui.generateProgressBar = function (options, $el, barCss, barPercentage) {
        var $progressBar = ui.initProgressBar(options, $el);
        ui.updateProgressBar(options, $el, barCss, barPercentage, $progressBar);
        return $progressBar;
    }

    ui.getUIElements = function (options, $el) {
        var $container, result;

        if (options.instances.viewports) {
            return options.instances.viewports;
        }

        result = {};
        $container = ui.getContainer(options, $el);
        if (!options.ui.showPopover || !options.ui.showProgressBarInPopover) { //*SLR 1/17/2014
            result.$progressbar = ui.findElement($container, options.ui.viewports.progress, "div.progress");
        }
        if (!options.ui.showPopover) {
            result.$verdict = ui.findElement($container, options.ui.viewports.verdict, "span.password-verdict");
            result.$errors = ui.findElement($container, options.ui.viewports.errors, "ul.error-list");
        }

        options.instances.viewports = result;
        return result;
    };

    ui.initProgressBar = function (options, $el) {
        var $container = ui.getContainer(options, $el),
            progressbar = "<div class='progress'><div class='";

        if (!options.ui.bootstrap2) {
            progressbar += "progress-";
        }
        progressbar += "bar'></div></div>";

        if (!options.ui.showPopover || !options.ui.showProgressBarInPopover) { //*SLR 1/17/2014
            if (options.ui.viewports.progress) {
                $container.find(options.ui.viewports.progress).append(progressbar);
            } else {
                $(progressbar).insertAfter($el);
            }
        }
        return $(progressbar); //*SLR 1/17/2014
    };

    ui.initHelper = function (options, $el, html, viewport) {
        var $container = ui.getContainer(options, $el);
        if (viewport) {
            $container.find(viewport).append(html);
        } else {
            $(html).insertAfter($el);
        }
    };

    ui.initVerdict = function (options, $el) {
        ui.initHelper(options, $el, "<span class='password-verdict'></span>",
                        options.ui.viewports.verdict);
    };

    ui.initErrorList = function (options, $el) {
        ui.initHelper(options, $el, "<ul class='error-list'></ul>",
                        options.ui.viewports.errors);
    };

    ui.initPopover = function (options, $el, verdictText, $progressBar) {
        var placement = "auto top",
            html = "";

        if (options.ui.bootstrap2) { placement = "top"; }

        if (options.ui.showVerdicts && verdictText.length > 0) {
            html = "<h5><span class='password-verdict'>" + verdictText +
                "</span></h5>";
        }

        if (options.ui.showProgressBarInPopover && $progressBar) { //*SLR 1/17/2014
            html += $('<div />').append($progressBar.clone().css('width', '10em')).html();
        }

        if (options.ui.showErrors) {
            html += "<div><ul class='error-list'>";
            $.each(options.instances.errors, function (idx, err) {
                html += "<li>" + err + "</li>";
            });
            html += "</ul></div>";
        }

        $el.popover("destroy");
        $el.popover({
            html: true,
            placement: placement,
            trigger: "manual",
            content: html
        });
        $el.popover("show");
    };

    ui.initUI = function (options, $el) {
        if (!options.ui.showPopover) {
            if (options.ui.showErrors) { ui.initErrorList(options, $el); }
            if (options.ui.showVerdicts) { ui.initVerdict(options, $el); }
        }
        // The popover can't be initialized here, it requires to be destroyed
        // and recreated every time its content changes, because it calculates
        // its position based on the size of its content

        if (!options.ui.showPopover || !options.ui.showProgressBarInPopover) { //*SLR 1/17/2014
            ui.initProgressBar(options, $el);
        }
    };

    ui.possibleProgressBarClasses = ["danger", "warning", "success"];

    ui.updateProgressBar = function (options, $el, cssClass, percentage, $progressbar) {
        if (!$progressbar) { //*SLR 1/17/2014
            $progressbar = ui.getUIElements(options, $el).$progressbar;
        }
        var $bar = $progressbar.find(".progress-bar"),
            cssPrefix = "progress-";

        if (options.ui.bootstrap2) {
            $bar = $progressbar.find(".bar");
            cssPrefix = "";
        }

        $.each(ui.possibleProgressBarClasses, function (idx, value) {
            $bar.removeClass(cssPrefix + "bar-" + value);
        });
        $bar.addClass(cssPrefix + "bar-" + cssClass);
        $bar.css("width", percentage + '%');
    };

    ui.updateVerdict = function (options, $el, text) {
        var $verdict = ui.getUIElements(options, $el).$verdict;
        $verdict.text(text);
    };

    ui.updateErrors = function (options, $el) {
        var $errors = ui.getUIElements(options, $el).$errors,
            html = "";
        $.each(options.instances.errors, function (idx, err) {
            html += "<li>" + err + "</li>";
        });
        $errors.html(html);
    };

    ui.percentage = function (score, maximun) {
        var result = Math.floor(100 * score / maximun);
        result = result < 0 ? 0 : result;
        result = result > 100 ? 100 : result;
        return result;
    };

    ui.updateUI = function (options, $el, score) {
        var barCss, barPercentage, verdictText,
            word = $el.val();

        barPercentage = ui.percentage(score, options.ui.scores[3]);
        if (score <= 0) {
            barCss = "danger";
            verdictText = options.ui.verdicts[0]; //*SLR 1/20/2014
        } else if (score < options.ui.scores[0]) {
            barCss = "danger";
            verdictText = options.ui.verdicts[0];
        } else if (score < options.ui.scores[1]) {
            barCss = "warning"; //*SLR 1/20/2014 danger->warning
            verdictText = options.ui.verdicts[1];
        } else if (score < options.ui.scores[2]) {
            barCss = "warning";
            verdictText = options.ui.verdicts[2];
        } else if (score < options.ui.scores[3]) {
            barCss = "success"; //*SLR 1/20/2014 warning->success
            verdictText = options.ui.verdicts[3];
        } else {
            barCss = "success";
            verdictText = options.ui.verdicts[4];
        }

        if (!options.ui.showPopover || !options.ui.showProgressBarInPopover) { //*SLR
            ui.updateProgressBar(options, $el, barCss, barPercentage);
        }
        
        if (options.ui.showPopover) {
            // Popover can't be updated, it has to be recreated
            if (word.length == 0) { //*SLR 1/17/2014
                $el.popover('destroy');
            }
            else {
                if (options.ui.showProgressBarInPopover) { //*SLR 1/17/2014
                    var $progressBar = ui.generateProgressBar(options, $el, barCss, barPercentage);
                    ui.initPopover(options, $el, verdictText, $progressBar);
                }
                else {
                    ui.initPopover(options, $el, verdictText);
                }
            }
        } else {
            if (options.ui.showVerdicts) {
                ui.updateVerdict(options, $el, verdictText);
            }
            if (options.ui.showErrors) {
                ui.updateErrors(options, $el);
            }
        }
    };
}(jQuery, ui));

// Source: src/methods.js




var methods = {};

(function ($, methods) {
    "use strict";
    var keyupTimer, onKeyUp, update, onFocusIn, onFocusOut, applyToAll;

    onKeyUp = function (event) {
        if (keyupTimer) { //*SLR 1/17/2014
            clearTimeout(keyupTimer);
        }

        var $el = $(event.target),
            options = $el.data("pwstrength-bootstrap");
        if (options.common.keyUpDelay < 1) {
            update($el);
        }
        else {
            keyupTimer = setTimeout(function () {
                update($el);
            }, options.common.keyUpDelay);
        }
    }

    update = function ($el) {
        var options = $el.data("pwstrength-bootstrap"),
            word = $el.val(),
            score;

        options.instances.errors = [];
        score = rulesEngine.executeRules(options, word);
        ui.updateUI(options, $el, score);

        if ($.isFunction(options.common.onKeyUp)) {
            options.common.onKeyUp(event);
        }
    }

    //*SLR 1/17/2014
    onFocusIn = function (event) {
        var $el = $(event.target),
            options = $el.data("pwstrength-bootstrap");
        update($el);
    }

    //*SLR 1/17/2014
    onFocusOut = function (event) {
        if (keyupTimer) {
            clearTimeout(keyupTimer);
        }

        var $el = $(event.target),
            options = $el.data("pwstrength-bootstrap");
        $el.popover("destroy");
    }

    methods.init = function (settings) {
        this.each(function (idx, el) {
            // Make it deep extend (first param) so it extends too the
            // rules and other inside objects
            var clonedDefaults = $.extend(true, {}, defaultOptions),
                localOptions = $.extend(true, clonedDefaults, settings),
                $el = $(el);

            localOptions.instances = {};
            $el.data("pwstrength-bootstrap", localOptions);
            $el.on("keyup", onKeyUp);
            $el.on("focusin", onFocusIn);
            $el.on("focusout", onFocusOut);
            ui.initUI(localOptions, $el);
            if ($.isFunction(localOptions.common.onLoad)) {
                localOptions.common.onLoad();
            }
        });

        return this;
    };

    methods.destroy = function () {
        this.each(function (idx, el) {
            var $el = $(el),
                options = $el.data("pwstrength-bootstrap"),
                elements = ui.getUIElements(options, $el);
            elements.$progressbar.remove();
            elements.$verdict.remove();
            elements.$errors.remove();
            $el.removeData("pwstrength-bootstrap");
        });
    };

    methods.forceUpdate = function () {
        this.each(function (idx, el) {
            var event = { target: el };
            onKeyUp(event);
        });
    };

    methods.addRule = function (name, method, score, active) {
        this.each(function (idx, el) {
            var options = $(el).data("pwstrength-bootstrap");

            options.rules.activated[name] = active;
            options.rules.scores[name] = score;
            options.rules.extra[name] = method;
        });
    };

    applyToAll = function (rule, prop, value) {
        this.each(function (idx, el) {
            $(el).data("pwstrength-bootstrap").rules[prop][rule] = value;
        });
    };

    methods.changeScore = function (rule, score) {
        applyToAll.call(this, rule, "scores", score);
    };

    methods.ruleActive = function (rule, active) {
        applyToAll.call(this, rule, "activated", active);
    };

    $.fn.pwstrength = function (method) {
        var result;

        if (methods[method]) {
            result = methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === "object" || !method) {
            result = methods.init.apply(this, arguments);
        } else {
            $.error("Method " +  method + " does not exist on jQuery.pwstrength-bootstrap");
        }

        return result;
    };
}(jQuery, methods));
}(jQuery));;
window.DTS = window.DTS || {};
DTS.Responder = DTS.Responder || {};
DTS.Responder.Util = DTS.Responder.Util || {};
// fortify javascript hijacking
var FortifyAjax = {};
FortifyAjax.fortifyAjax = $.ajax;
FortifyAjax.fortifyGet = $.get;
FortifyAjax.fortifyPost = $.post;
DTS.Responder.Util.showChangesSaved = function () {
    var queue = [];
    var animationSpeed = 300;
    var displayLength = 3000;
    var panel = null;
    var template = '<div class="alert alert-success corner-alert"> ' +
        '<span class="fas fa-check"></span>&nbsp;<span></span> ' +
        '</div>';
    var showChangesSavedInternal = function () {
        if (queue.length > 0) {
            if (!panel) {
                var next_1 = queue.shift();
                panel = $(template).appendTo(document.body);
                panel.children('span:last').text(next_1.text);
                panel.show(animationSpeed);
                setTimeout(function () {
                    panel.hide(animationSpeed, function () {
                        panel.remove();
                        panel = null;
                        next_1.deferred.resolve();
                        showChangesSavedInternal(); //show next in queue
                    });
                }, displayLength);
            }
        }
    };
    return function (text) {
        var deferred = $.Deferred();
        queue.push({ text: text ? text : 'Your changes have been saved.', deferred: deferred });
        showChangesSavedInternal();
        return deferred.promise();
    };
}();
DTS.Responder.Util.showFailureMessage = function () {
    var queue = [];
    var animationSpeed = 300;
    var displayLength = 5000;
    var panel = null;
    var template = '<div class="alert alert-danger corner-alert"> ' +
        '<span class="fas fa-times"></span>&nbsp;<span></span> ' +
        '</div>';
    var showFailureMessageInternal = function () {
        if (queue.length > 0) {
            if (!panel) {
                var next_2 = queue.shift();
                panel = $(template).appendTo(document.body);
                panel.on('click', function () {
                    panel.hide(animationSpeed, function () {
                        panel.remove();
                        panel = null;
                        next_2.deferred.resolve();
                        showFailureMessageInternal(); //show next in queue
                    });
                });
                panel.children('span:last').text(next_2.text);
                panel.show(animationSpeed);
            }
        }
    };
    return function (text) {
        var deferred = $.Deferred();
        queue.push({ text: text ? text : 'An error occurred while processing your request. Click to dismiss this message.', deferred: deferred });
        showFailureMessageInternal();
        return deferred.promise();
    };
}();
DTS.Responder.Util.showAlert = function () {
    var domObject = null;
    var currentDeferred = null;
    var currentDeferredDoneFinals = [];
    var forcedClose = false;
    var id = "currentAlertModal";
    var template = '<div id="' + id + '" class="modal fade" data-backdrop="static" data-keyboard="false"> \
                <div class="modal-dialog"> \
                    <div class="modal-content"> \
                        <div class="modal-header"> \
                        <h4 class="modal-title"></h4> \
                        </div> \
                        <div class="modal-body"></div> \
                        <div class="modal-footer"> \
                            <button class="btn btn-default btn-lg" type="button" data-dismiss="modal">Ok</button> \
                        </div> \
                    </div> \
                </div> \
        </div>';
    var func = function (message, title) {
        var alertModal = $("#" + id);
        if (!alertModal.length) {
            alertModal = $(template);
        }
        alertModal.one('show.bs.modal', function () {
            var current = $("#" + id);
            if (!current.length) {
                current = $(template);
            }
            $('.modal:visible').not(current).addClass('below-backdrop');
        }).one('shown.bs.modal', function () {
            var current = $("#" + id);
            if (!current.length) {
                current = $(template);
            }
            current.find('button').focus();
        }).one('hide.bs.modal', function () {
            $('.modal.below-backdrop').removeClass('below-backdrop');
            domObject = null;
        }).one('hidden.bs.modal', function () {
            var current = $("#" + id);
            if (!current.length) {
                current = $(template);
            }
            current.remove();
            if (currentDeferred) {
                var doneFinals = currentDeferredDoneFinals;
                var forced = forcedClose;
                if (!forced && doneFinals.length > 0) {
                    currentDeferred.done(doneFinals);
                    currentDeferredDoneFinals = [];
                }
                currentDeferred.resolve();
                currentDeferred = null;
                forcedClose = false;
            }
            $("a[href*='usernamehref']").attr('tabindex', 6).focus();
        });
        alertModal.appendTo(document.body);
        if (domObject && domObject.is(':visible')) {
            forcedClose = true;
            domObject.removeClass('fade'); //prevent overlapping backdrops
            domObject.modal('hide');
        }
        //attach to the deferred with .doneFinal to execute after a chain of alerts
        currentDeferred = $.Deferred();
        domObject = alertModal;
        domObject.find('.modal-header > *:first-child').text(title || 'FEMA DTS Responder Portal');
        domObject.find('.modal-body').html(message);
        domObject.modal('show');
        return $.extend(currentDeferred.promise(), {
            doneFinal: function (fcn) {
                currentDeferredDoneFinals.push(fcn);
            }
        });
    };
    func.close = function () {
        if (domObject && domObject.is(':visible')) {
            domObject.modal('hide');
        }
    };
    return func;
}();
DTS.Responder.Util.showYesNo = function () {
    var domObject = null;
    var currentDeferred = null;
    var forcedClose = false;
    var id = "defaultYesNoModal";
    var template = '<div id=' + id + ' class="modal fade" data-backdrop="static" data-keyboard="false"> \
                <div class="modal-dialog"> \
                    <div class="modal-content"> \
                        <div class="modal-header"> \
                        <h4 class="modal-title"></h4> \
                        </div> \
                        <div class="modal-body"></div> \
                        <div class="modal-footer"> \
                            <button class="btn btn-default btn-lg js-hook-yes" type="button" data-bind="click: handleYes"></button> \
                            <button class="btn btn-default btn-lg js-hook-no" type="button" data-dismiss="modal" data-bind="click: handleNo"></button> \
                        </div> \
                    </div> \
                </div> \
        </div>';
    var func = function (message, title, yes, no) {
        // no reason to allow more than one of these to be visible at a time
        if (domObject && domObject.is(':visible'))
            return $.Deferred().resolve(false);
        var hideModal = function () {
            $(domObject[0]).modal('hide');
        };
        var vm = {
            handleYes: function () {
                hideModal();
                currentDeferred.resolve(true);
            },
            handleNo: function () {
                hideModal();
                currentDeferred.resolve(false);
            }
        };
        var alertModal = $("#" + id);
        if (!alertModal.length) {
            alertModal = $(template);
        }
        alertModal.one('show.bs.modal', function () {
            var current = $("#" + id);
            if (!current.length) {
                current = $(template);
            }
            $('.modal:visible').not(current).addClass('below-backdrop');
            ko.applyBindings(vm, domObject[0]);
        }).one('shown.bs.modal', function () {
            var current = $("#" + id);
            if (!current.length) {
                current = $(template);
            }
            current.find('button').focus();
        }).one('hide.bs.modal', function () {
            $('.modal.below-backdrop').removeClass('below-backdrop');
            domObject = null;
        }).one('hidden.bs.modal', function () {
            var current = $("#" + id);
            if (!current.length) {
                current = $(template);
            }
            current.remove();
            if (currentDeferred) {
                if (forcedClose)
                    currentDeferred.resolve(false);
                currentDeferred = null;
                forcedClose = false;
            }
        });
        alertModal.appendTo(document.body);
        if (domObject && domObject.is(':visible')) {
            forcedClose = true;
            domObject.removeClass('fade'); //prevent overlapping backdrops
            domObject.modal('hide');
        }
        currentDeferred = $.Deferred();
        domObject = alertModal;
        domObject.find('.modal-header > *:first-child').text(title || 'FEMA DTS Responder Portal');
        domObject.find('.modal-body').html(message);
        domObject.find('.js-hook-yes').text(yes || 'Yes');
        domObject.find('.js-hook-no').text(no || 'No');
        domObject.modal('show');
        return currentDeferred.promise();
    };
    return func;
}();
DTS.Responder.Util.humanizeDateDiff = function (date) {
    if (date) {
        var m = moment.isMoment(date) ? date : moment.dtsDateToLocal(date);
        if (m.isSame(moment(), 'day')) {
            return 'today';
        }
        return moment.duration(m.diff(moment().startOf('day'))).humanize(true);
    }
    return null;
};
DTS.Responder.Util.dateTimeRenderer = function (data, type, row) {
    //Include hidden ISO8601 date to ensure proper sorting.
    return '<span class="sort-data">' + moment.dtsDateTime(data).utc().toISOString() + '</span>' +
        moment.dtsDateTime(data).format('M/D/YYYY h:mm A');
};
//tags start with {0: or {1: indicating 'hide if 0' and 'hide if 1' respectively
//  can have a 'hide result' indicator like {0-: or {1-: to indicate that the time
//  component shouldn't be shown even if the hide condition isn't met
//ex: {1-:show{m}this} will evaluate the number of minutes in the duration, if
//  it is not 1, 'showthis' will be shown, otherwise nothing will be shown
//ex: {0:show{h}this} will evaluate the number of hours in the duration, if
//  it is not 0 (for example, 5), 'show5this' will be shown, otherwise nothing
//tags starting with {-: or {+: will be shown only if the duration is negative or
//  positive, respectfully
DTS.Responder.Util.formatDuration = function () {
    var formatDuration_basic = function (duration, formatString) {
        return formatString
            .replace(/\{d\}/g, Math.floor(Math.abs(duration.asDays())))
            .replace(/\{h\}/g, Math.abs(duration.hours()))
            .replace(/\{m\}/g, Math.abs(duration.minutes()))
            .replace(/\{s\}/g, Math.abs(duration.seconds()))
            .replace(/\{hh\}/g, Math.abs(duration.minutes()).pad(2))
            .replace(/\{mm\}/g, Math.abs(duration.minutes()).pad(2))
            .replace(/\{ss\}/g, Math.abs(duration.seconds()).pad(2));
    };
    return function (duration, formatString) {
        duration = moment.isDuration(duration) ? duration : moment.duration(duration);
        var updatedStr, result, formatCode, op, hide, inner;
        var regexstr = /{[-+]:.*?}/g, arr = formatString.match(regexstr), neg = (duration.asMinutes() < 0);
        if (arr != null) {
            for (var i = 0; i < arr.length; i++) {
                op = arr[i].substring(1, 2);
                if ((op == '-' && neg) || (op == '+' && !neg)) {
                    formatString = formatString.replace(arr[i], arr[i].substring(3, arr[i].length - 1));
                }
                else {
                    formatString = formatString.replace(arr[i], '');
                }
            }
        }
        regexstr = /{[01]-?:[^{}]*?{[^{}]*?}[^{}]*?}/g;
        arr = formatString.match(regexstr);
        while (arr != null) { //can nest tags
            for (var i = 0; i < arr.length; i++) {
                op = arr[i].substring(1, 2);
                formatCode = arr[i].match(/{[^{}]*?}/)[0];
                result = formatDuration_basic(duration, formatCode);
                if (op == '0' && parseInt(result) == 0) {
                    formatString = formatString.replace(arr[i], '');
                }
                else if (op == '1' && parseInt(result) == 1) {
                    formatString = formatString.replace(arr[i], '');
                }
                else {
                    updatedStr = arr[i];
                    hide = (arr[i].substring(2, 3) == '-');
                    if (hide) {
                        result = '';
                    }
                    updatedStr = updatedStr.replace(formatCode, result);
                    updatedStr = updatedStr.substring((hide ? 4 : 3), updatedStr.length - 1);
                    formatString = formatString.replace(arr[i], updatedStr);
                }
            }
            arr = formatString.match(regexstr);
        }
        return formatDuration_basic(duration, formatString);
    };
}();
DTS.Responder.Util.counter = function () {
    var self = this;
    var counterId = null;
    var elements = [];
    var diffUnit = 'seconds';
    var updateDisplay = function (obj, currentMoment) {
        var dur = (currentMoment || moment()).diff(obj.value, diffUnit);
        var mDur = moment.duration(dur, diffUnit);
        if (obj.duration) {
            obj.duration(mDur);
        }
        if (obj.element) {
            var text = DTS.Responder.Util.formatDuration(mDur, obj.format);
            $(obj.element).text(text);
        }
    };
    var updateAll = function () {
        var currentMoment = moment();
        ko.utils.arrayForEach(elements, function (e) {
            updateDisplay(e, currentMoment);
        });
    };
    var findElement = function (element) {
        return ko.utils.arrayFirst(elements, function (e) {
            return e.element && e.element === element;
        });
    };
    this.state = function () {
        return counterId ? 'running' : 'stopped';
    };
    this.start = function (updateEvery) {
        if (counterId) {
            throw 'counter is already running';
        }
        updateAll();
        counterId = setInterval(updateAll, updateEvery * 1000);
        return this;
    };
    this.stop = function () {
        if (!counterId) {
            throw 'counter is already stopped';
        }
        clearInterval(counterId);
        counterId = null;
        return this;
    };
    this.add = function (element, value, format, duration) {
        if (duration && !ko.isObservable(duration)) {
            throw 'provided duration must be an observable';
        }
        if (findElement(element)) {
            throw 'this element has already been added to the counter';
        }
        var e = { element: element, value: value, format: format, duration: duration };
        elements.push(e);
        if (self.state() === 'running') { //update immediately
            updateDisplay(e);
        }
    };
    this.trackDuration = function (duration, value, format) {
        if (!duration || !ko.isObservable(duration)) {
            throw 'provided duration must be an observable';
        }
        var e = { element: null, value: value, format: format, duration: duration };
        elements.push(e);
        if (self.state() === 'running') { //update immediately
            updateDisplay(e);
        }
    };
    this.update = function (element, value, format, duration) {
        if (duration && !ko.isObservable(duration)) {
            throw 'provided duration must be an observable';
        }
        var obj = findElement(element);
        if (!obj) {
            throw 'could not find provided element in counter';
        }
        ;
        obj.value = value;
        obj.format = format;
        obj.duration = duration;
        if (self.state() === 'running') { //update immediately
            updateDisplay(obj);
        }
    };
    this.remove = function (element) {
        var obj = findElement(element);
        if (obj) {
            elements.splice($.inArray(obj, elements), 1); //remove from array
            if (elements.length == 0) {
                self.stop();
            }
        }
    };
};
DTS.Responder.Util.getQueryArgs = function () {
    var args = {}; /*TODO: fix `any` type here - probably just need to move property assignments into the object literal.*/
    if (location.search) {
        var s = location.search.indexOf('?');
        s = s >= 0 ? s + 1 : 0;
        var e = location.search.indexOf('#', s);
        e = e >= 0 ? e : undefined;
        var a = location.search.slice(s, e).split('&');
        $.each(a, function () {
            var i = this.indexOf('=');
            i = i == -1 ? this.length : i;
            args[this.substr(0, i)] = decodeURIComponent(this.substr(i + 1));
        });
    }
    return args;
};
DTS.Responder.Spoof = function () {
    var currentModel = null;
    var showModal = function () {
        currentModel = $.extend(new DTS.Responder.Dialog._default(DTS.Responder.sitePath + 'Account/Spoof'), {
            showUnvalidated: ko.observable(false),
            errorMessage: ko.observable(),
            isLoadingRecentlySpoofed: ko.observable(true),
            recentlySpoofed: ko.observable([])
        });
        $.post(DTS.Responder.sitePath + 'Account/GetRecentPersonnelForSpoof').done(function (jsonResponse) {
            var recentlySpoofed = jsonResponse.recentlySpoofed;
            currentModel.recentlySpoofed(recentlySpoofed);
            currentModel.isLoadingRecentlySpoofed(false);
        });
        currentModel.activate = function () {
            $(document).on('shown.bs.modal', '#spoofModal', function () {
                $('#showUnvalidatedCheckbox').focus();
            });
            $(document).on('keydown', function (e) {
                if (e.keyCode == 9) { //TAB key
                    //If inside the modal dialog:
                    if ($(e.target).parents('[role=dialog]').length) {
                        // Prevent tabbing outside of focused modal by preventing default and cycling through by focusing the first/last element (depending on tab press):
                        var firstElem = $(e.target).closest('[role=dialog]').find('input:visible,select:visible,button:visible,textarea:visible,a:visible').first();
                        var lastElem = $(e.target).closest('[role=dialog]').find('input:visible,select:visible,button:visible,textarea:visible,a:visible').last();
                        var borderElem = e.shiftKey ? firstElem : lastElem;
                        if ($(borderElem).length) {
                            if ($(e.target).is($(borderElem))) {
                                e.preventDefault();
                                e.target.focus();
                                if (borderElem == firstElem)
                                    lastElem.focus();
                                else
                                    firstElem.focus();
                                return false;
                            }
                            else {
                                return true;
                            }
                        }
                    }
                }
                return true;
            });
        };
        currentModel.accept = function () {
            var t = this;
            var $selected = $('#spoofModal').find('input[name="personnelId"]:checked');
            var personnelId = $selected.length == 0 ? null : $selected.val();
            if (!personnelId) {
                t.errorMessage('Please select a personnel record to spoof');
            }
            else {
                $.post_dtsWait(DTS.Responder.sitePath + 'Account/SpoofUser', { personnelId: personnelId }).done(function (jsonResponse) {
                    if (jsonResponse.success) {
                        location.reload();
                    }
                    else {
                        t.errorMessage(jsonResponse.message);
                    }
                });
            }
        };
        currentModel.dataTableOptionsRecent = {
            dom: '<f><"dataTables_childGrid_vis">Rt<"row dataTables_childGrid_foot"<"col-xs-3"l><"col-xs-3"i><"col-xs-6"p><"col-xs-12"r>>',
            ordering: false,
            pageLength: 5,
            searching: false,
            processing: true,
            lengthMenu: [5],
            autoWidth: false,
            columns: [
                {
                    data: 'Personnel_Id',
                    orderable: false,
                    render: function (data, type, row, meta) {
                        return '<input type="radio" name="personnelId" title="' + row['Display_Name'] + '" value="' + data + '" />';
                    }
                },
                { data: 'Last_Name' },
                { data: 'First_Name' },
                { data: 'Username' },
                { data: 'Personnel_Id' },
                {
                    data: 'Validated',
                    render: function (data) {
                        if (data) {
                            return moment.dtsDateTime(data).format('M/D/YYYY h:mm a');
                        }
                        return '';
                    }
                },
            ]
        };
        currentModel.dataTableOptions = {
            dom: '<f><"dataTables_childGrid_vis">Rt<"row dataTables_childGrid_foot"<"col-xs-3"l><"col-xs-3"i><"col-xs-6"p><"col-xs-12"r>>',
            ajax: {
                url: DTS.Responder.sitePath + 'Account/GetPersonnelForSpoof',
                type: 'POST',
                data: function (aoData) {
                    aoData.showUnvalidated = currentModel.showUnvalidated();
                }
            },
            order: [[1, 'asc']],
            pageLength: 10,
            lengthMenu: [5, 10, 20],
            serverSide: true,
            processing: true,
            searching: true,
            searchDelay: 2500,
            autoWidth: false,
            initComplete: function (settings, json) {
                //$('#spoofTable_filter_unvalidated').appendTo($('#spoofModal .dataTables_filter').parent());
            },
            columns: [
                {
                    data: 'Personnel_Id',
                    orderable: false,
                    render: function (data, type, row, meta) {
                        return '<input type="radio" name="personnelId" title="' + row['Display_Name'] + '" value="' + data + '" />';
                    }
                },
                { data: 'Last_Name' },
                { data: 'First_Name' },
                { data: 'Username' },
                { data: 'Personnel_Id' },
                {
                    data: 'Validated',
                    render: function (data) {
                        if (data) {
                            return moment.dtsDateTime(data).format('M/D/YYYY h:mm a');
                        }
                        return '';
                    }
                }
            ]
        };
        DTS.Responder.Dialog.show(currentModel).done(function () {
            currentModel = null;
        }).then(function () {
            $("#spoofButton").click();
            $("#spoofUserButton").focus();
        });
    };
    var end = function () {
        $.post_dtsWait(DTS.Responder.sitePath + 'Account/SpoofEnd').done(function (jsonResponse) {
            if (jsonResponse.success || jsonResponse.message == 'The current user is not in a spoofed session') {
                location.reload();
            }
            else {
                alert('There was an error stopping your spoof session: ' + jsonResponse.message);
            }
        });
    };
    return {
        showModal: showModal,
        end: end
    };
}();
//waitModal on form instructions:
//1) Set attribute data-waitmodalmsg on each form element to the message to display in
//   the wait modal, set it to "default" to use default message.
//2) Set your ajax forms to call DTS.Responder.WaitModal.dismissForForm() when they complete.
//   Non-ajax forms do not need to do this, as the whole page will be replaced, closing
//   the modal.
//3) Call $('form').wireUpWaitModal() on page load. Remember to also call this on all
//   newly loaded forms after the ajax request. Calling wireUpWaitModal multiple times
//   on the same form will have no effect.
DTS.Responder.WaitModal = function () {
    //prototype
    var ModalConfig = function (message) {
        var self = this;
        var modalDOM = null;
        var waitingOn = [];
        self.message = message || 'Please wait...';
        self.parent = null;
        self.timer = null;
        self.dismissed = false;
        self.isComplete = function () {
            return self.dismissed && !_.findWhere(waitingOn, { dismissed: false });
        };
        self.waitOn = function (config) {
            waitingOn.push(config);
            config.parent = self;
        };
        self.show = function () {
            var show_def = $.Deferred();
            modalDOM = $(DTS.Responder.Dialog.loadTemplate('#waitModal'))
                .on('show.bs.modal', function () {
                $('.modal:visible').not(this).addClass('below-backdrop');
            }).on('hide.bs.modal', function () {
                $('.modal.below-backdrop').removeClass('below-backdrop');
            }).on('hidden.bs.modal', function () {
                if ($('.modal:visible').length > 0) {
                    $('body').addClass('modal-open');
                }
                $(this).remove();
                show_def.resolve();
            });
            modalDOM.find('.modal-header :first-child').text(self.message);
            modalDOM.appendTo(document.body).modal('show');
            return show_def.promise();
        };
        self.hide = function () {
            if (!modalDOM) {
                throw 'Wait modal is not being shown, cannot hide.';
            }
            modalDOM.modal('hide');
            modalDOM = null;
        };
        self.dismiss = function () {
            self.dismissed = true;
            return self.parent
                ? (self.parent.isComplete() ? self.parent : false)
                : (self.isComplete() ? self : false);
        };
    };
    var modalQueue = new function () {
        var self = this;
        var showing = null;
        var queue = [];
        var push = function (config) {
            var el = _.findWhere(queue, { message: config.message });
            if (el) {
                el.waitOn(config);
            }
            else {
                queue.push(config);
            }
        };
        var showNext = function () {
            if (!showing) {
                var config = void 0;
                while (config = queue.shift()) {
                    if (!config.isComplete()) {
                        showing = config;
                        config.show().done(showNext);
                        break;
                    }
                    ;
                }
            }
        };
        self.add = function (config, delay) {
            config.timer = setTimeout(function () {
                if (!showing) {
                    showing = config;
                    config.show().done(showNext);
                }
                else if (showing.message === config.message) {
                    showing.waitOn(config);
                }
                else {
                    push(config);
                }
            }, delay || 1000);
        };
        self.dismiss = function (config) {
            clearTimeout(config.timer);
            var completed = config.dismiss();
            if (completed) {
                if (completed === showing) {
                    showing = null;
                    completed.hide();
                }
                else {
                    queue.remove(completed);
                }
            }
        };
    }();
    var _message = null;
    var setMessage = function (msg) {
        _message = msg;
    };
    var show = function (msg, delay) {
        var config = new ModalConfig(msg || _message);
        modalQueue.add(config, delay);
        _message = null;
        return {
            dismiss: function () { modalQueue.dismiss(config); }
        };
    };
    var showForForm = function () {
        var $form = $(this);
        var msg = $form.data('waitmodalmsg');
        if ($form.valid() && msg) {
            var def = show(msg === 'default' ? null : msg); //allow for default msg
            $form.data('waitModal', def);
        }
    };
    var dismissForForm = function () {
        var $form = $(this);
        var def = $form.data('waitModal');
        if (def) {
            $form.data('waitModal', null);
            def.dismiss();
        }
    };
    return {
        show: show,
        setMessage: setMessage,
        showForForm: showForForm,
        dismissForForm: dismissForForm
    };
}();
DTS.Responder.Dialog = function () {
    var loadedTemplates = $.extend([], {
        findTemplate: function (key) {
            return _.findWhere(this, { key: key });
        }
    });
    var activeDialogs = $.extend([], {
        findModel: function (model) {
            return _.findWhere(this, { model: model });
        },
        remove: function (info) {
            this.splice(_.indexOf(this, info), 1);
        }
    });
    var isActive = function (viewLookup) {
        var dialogs = _.findWhere(activeDialogs, { viewLookup: viewLookup });
        return dialogs != null;
    };
    var applyShownHelper = function (model, content) {
        if (_.has(model, 'shown') && $.isFunction(model.shown)) {
            var shown = void 0;
            if (ko.isObservable(model.shown)) {
                if (ko.isWriteableObservable(model.shown)) {
                    shown = function () { model.shown(true); };
                }
            }
            else {
                shown = model.shown;
            }
            if (shown) {
                content.one('shown.bs.modal', shown);
            }
        }
    };
    var loadTemplate = function (selector) {
        if (!selector) {
            throw 'no selector provided to loadTemplate';
        }
        var entry = loadedTemplates.findTemplate(selector), $t;
        if (entry) {
            $t = entry.template;
        }
        else {
            $t = $(selector);
            if ($t.length != 1) {
                throw 'Could not find provided template, or more than one matching template found';
            }
            loadedTemplates.push({ key: selector, template: $t });
        }
        return $t[0].text;
    };
    var loadUrl = function (url) {
        if (!url) {
            throw 'no url provided to loadUrl';
        }
        var def = $.Deferred();
        var entry = loadedTemplates.findTemplate(url), $t;
        if (entry) {
            $t = entry.template;
            def.resolve($t[0].text);
        }
        else {
            FortifyAjax.fortifyGet(url).done(function (viewHtml) {
                $t = $('<script type="text/html"></script>');
                $t[0].text = viewHtml; //cannot append child nodes to script tag in IE8
                $t.appendTo('body');
                loadedTemplates.push({ key: url, template: $t });
                def.resolve($t[0].text);
            }).fail(function () {
                throw 'Error accessing template URL';
                def.reject();
            });
        }
        return def.promise();
    };
    var close = function (model, _unused_) {
        if (!model) {
            throw 'model not provided to DTS.Responder.Dialog.close';
        }
        var info = activeDialogs.findModel(model);
        if (!info) {
            throw 'this model is not active on a dialog';
        }
        ;
        var args = Array.prototype.slice.call(arguments, 1);
        info.$content.one('hidden.bs.modal', function () {
            info.deferred.resolve.apply(model, args);
            ko.removeNode(info.$content[0]);
            //info.$content.remove();
        }).modal('hide');
        activeDialogs.remove(info);
    };
    var _default = function (viewLookup) {
        var self = this;
        self.shown = ko.observable();
        self.getView = function () {
            if (!viewLookup || (typeof viewLookup !== 'string')) {
                throw 'No viewLookup provided to default DTS.Responder.Dialog model';
            }
            if (viewLookup.indexOf('/') > -1) {
                return loadUrl(viewLookup);
            }
            else {
                return loadTemplate(viewLookup);
            }
        };
        self.activate = function () { };
        self.accept = function () { close(self, true); };
        self.cancel = function () { close(self, false); };
    };
    var show = function (model) {
        var activationData = arguments[1];
        var viewLookup = '';
        if (typeof model === 'string') {
            viewLookup = model;
            var extensions = activationData;
            activationData = arguments[2];
            model = $.extend(new _default(viewLookup), (extensions || {}));
        }
        if (!model) {
            throw 'model not provided to DTS.Responder.Dialog.show';
        }
        if (!model.activate || !$.isFunction(model.activate)) {
            throw 'activate does not exist on provided model';
        }
        if (!model.getView || !$.isFunction(model.getView)) {
            throw 'getView does not exist on provided model';
        }
        if (activeDialogs.findModel(model)) {
            throw 'this model is already active on a dialog';
        }
        ;
        var activateDef = model.activate(activationData);
        var info = {};
        info.model = model;
        info.deferred = $.Deferred();
        info.viewLookup = viewLookup; //Have to find by some id
        info.existingFocusId = $(document.activeElement)['uniqueId']().attr("id");
        $.when(model.getView(), activateDef).done(function (viewHtml, activateResult) {
            if (activateResult && activateResult.success === false) {
                info.deferred.reject(activateResult);
                return;
            }
            var $inner = $(viewHtml);
            info.$content = $inner.is('.modal') ? $inner
                : $('<div class="modal fade" role="dialog"></div>').append($inner);
            info.$content.appendTo('body');
            activeDialogs.push(info); //store info
            ko.applyBindings(model, info.$content[0]);
            applyShownHelper(model, info.$content);
            info.$content.on('shown.bs.modal', function (e) {
                // If data-focus-first-selector attribute is set on the modal, attempt to focus that element.
                // Otherwise, focus the first tabbable element
                var focusElement = $(info.$content.data('focus-first-selector'));
                if (focusElement.length) {
                    focusElement.focus();
                }
                else {
                    $('.modal-content :tabbable').first().focus();
                }
                $('.modal-content').on('keydown', function (e) {
                    if (e.which == 9) {
                        var activeElement = $(document.activeElement);
                        var firstElement = $('.modal-content :tabbable').first();
                        var lastElement = $('.modal-content :tabbable').last();
                        // tab-cycling through the modal
                        if (e.shiftKey) {
                            if (activeElement.is(firstElement)) {
                                e.preventDefault();
                                lastElement.focus();
                            }
                        }
                        else {
                            if (activeElement.is(lastElement)) {
                                e.preventDefault();
                                firstElement.focus();
                            }
                        }
                    }
                });
                /* 508 compliance section
                 * on key up, if active element's id of the modal is 'fileupload', it needs to change its visual appearance.
                 * That input type="file" is heavily re-styled and located within a span with an id of #fileuploadContainer.
                 * This code adds border to that span as long as it has id of 'fileuploadContainer'.
                 */
                $('.modal-content').on('keyup', function (e) {
                    if (e.which == 9) {
                        var activeElement = $(document.activeElement);
                        var id = activeElement.attr('id');
                        if (id == 'fileupload') {
                            $('#fileuploadContainer').css({ 'border': '2px dashed black' });
                        }
                        else {
                            $('#fileuploadContainer').css({ 'border': 'none' });
                        }
                    }
                });
            });
            // #46455 - Adding logic for restoring keyboard focus after the modal is closed. This is mostly copied from the Deployer.
            info.$content.on('hidden.bs.modal', function (e) {
                //datepicker events triggering this handler for some reason. ignore them.
                if (e.namespace !== 'bs.modal' || !info.existingFocusId || $('div.modal-dialog.modal-no-focus-restore', e.target).length)
                    return;
                //focus the element that was focused prior to the modal opening
                var $existingFocus = $("#" + info.existingFocusId);
                if (!$existingFocus || !$existingFocus.length) {
                    return;
                }
                $existingFocus.focus();
            });
            activationData && activationData.staticModal ? info.$content.modal({ backdrop: 'static', keyboard: false })
                : info.$content.modal('show');
            // allows parent modal to regain focus after closing nested modal
            $('.modal').on('hidden.bs.modal', function (e) {
                ko.removeNode($(this).get()[0]);
                // this is getting hung up on progress bars and breaking..
                // const located = activeDialogs.findModel(info.model);
                // if (located) ko.cleanNode(located.$content[0]); // if closed by clicking outside the modal..
                if ($('.modal').hasClass('in')) {
                    $('body').addClass('modal-open');
                }
            });
        }).fail(function (suppressException) {
            if (!suppressException) {
                throw 'model failed to activate';
            }
        });
        return info.deferred.promise();
    };
    return {
        loadTemplate: loadTemplate,
        loadUrl: loadUrl,
        show: show,
        close: close,
        _default: _default,
        isActive: isActive
    };
}();
DTS.Responder.Util.newlinesToLineBreaks = function (val) {
    var text = ko.unwrap(val);
    return text ? text.replace(/\n/g, '<br/>') : null;
};
DTS.Responder.Util.extractErrorMessageFromXhrResponseText = (function (existing) {
    if (existing)
        return existing;
    return function (xhr) {
        xhr.responseText = xhr.responseText || '';
        if (xhr.responseJSON)
            return xhr.responseJSON.message;
        var parseMessageResults = xhr.responseText.match('<title>(.*?)<\/title>');
        return (parseMessageResults && parseMessageResults[1]) || 'Failed to parse error message.';
    };
})(DTS.Responder.Util.extractErrorMessageFromXhrResponseText);
//# sourceMappingURL=dtsUtilities.js.map;
var FortifyAjax = {};
FortifyAjax.fortifyAjax = $.ajax;
FortifyAjax.fortifyGet = $.get;
FortifyAjax.fortifyPost = $.post;
String.prototype.format = function () {
    var str = this, i = arguments.length;
    while (i--) {
        str = str.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
    }
    return str;
};
String.prototype.isNullorWhiteSpace = function () {
    return (this === null) || (this.match(/^\s*$/) !== null);
};
String.prototype.startsWith = function (str) {
    return this.lastIndexOf(str, 0) === 0;
};
String.prototype.trunc = function (len) {
    if (!this || this.length <= len) {
        return this;
    }
    return this.substring(0, len - 1) + '…';
};
String.prototype.pluralize = function (number, replace) {
    if (number == 1) {
        return this;
    }
    return replace === undefined ? this + 's' : replace;
};
String.prototype.validateRelativeUrl = function (comesFromServer) {
    //to just bypass for fortify is we are use the server is valid since we built it ourselves on the server
    if (comesFromServer) {
        return this;
    }
    else {
        var pattern = new RegExp('^/[\w~,;\-\./?%&+#=]*$', 'i');
        if (pattern.test(this)) {
            return this;
        }
        else {
            return "/";
        }
    }
};
Number.prototype.pad = function () {
    var str = this + '';
    while (str.length < arguments[0])
        str = '0' + str;
    return str;
};
if (!Array.prototype.hasOwnProperty('remove')) {
    Array.prototype.remove = function (el) {
        var i = $.inArray(el, this);
        if (i > -1) {
            Array.prototype.splice.call(this, i, 1);
        }
    };
}
//use $.ajax_dtsWait, $.post_dtsWait, $.get_dtsWait, $(..).load_dtsWait
//  as replacements for $.ajax, $.post, $.get, and $(..).load that will
//  automatically show and dismiss the Responder Portal wait modal
jQuery.extend({
    ajax_dtsWait: function () {
        var promise = DTS.Responder.WaitModal.show();
        return jQuery.ajax.apply(this, arguments)
            .always(promise.dismiss);
    },
    post_dtsWait: function () {
        var promise = DTS.Responder.WaitModal.show();
        return jQuery.post.apply(this, arguments)
            .always(promise.dismiss);
    },
    get_dtsWait: function () {
        var promise = DTS.Responder.WaitModal.show();
        return jQuery.get_noCache.apply(this, arguments)
            .always(promise.dismiss);
    },
    get_noCache: function (url, data, success, dataType) {
        return FortifyAjax.fortifyAjax({
            type: 'GET',
            url: url,
            data: data,
            success: success,
            dataType: dataType,
            cache: false
        });
    },
    post_go: function (url, input) {
        var form = $('<form />', {
            action: url,
            method: 'POST',
            style: 'display: none;'
        });
        if (input) {
            $.each(input, function (name, value) {
                $('<input />', {
                    type: 'hidden',
                    name: name,
                    value: value
                }).appendTo(form);
            });
        }
        form.appendTo('body').submit();
    }
});
jQuery.fn.extend({
    load_dtsWait: function (url, data, complete) {
        var $jqob = this;
        var $func = $.isPlainObject(data) ? $.post_dtsWait : $.get_dtsWait;
        $func(url, data).done(function (data) {
            $jqob.html(data);
            if (complete && $.isFunction(complete)) {
                complete.apply(this, arguments);
            }
        });
        return this;
    },
    reverse: function () {
        return this.pushStack(this.get().reverse(), arguments);
    },
    saveText: function (key) {
        if (!key) {
            key = 'fmttext';
        }
        ;
        this.each(function () {
            var el = $(this);
            el.data(key, el.text());
        });
        return this;
    },
    saveTextOnce: function (key) {
        if (!key) {
            key = 'fmttext';
        }
        ;
        this.not(this.havingData(key)).saveText(key);
        return this;
    },
    resetText: function (key) {
        if (!key) {
            key = 'fmttext';
        }
        ;
        this.havingData(key).text(function () {
            return $(this).data(key);
        });
        return this;
    },
    dataToText: function (key) {
        this.havingData(key).text(function () {
            return $(this).data(key);
        });
        return this;
    },
    formatText: function () {
        var args = arguments;
        this.saveTextOnce().text(function () {
            var el = $(this);
            return String.prototype.format.apply(el.data('fmttext'), args);
        });
        return this;
    },
    clearInputs: function () {
        this.find('input[type!="hidden"]:not(:checkbox), textarea, select').val('').setDefault();
        this.find('input:checkbox').attr('checked', function () {
            return $(this).data('default') == true;
        });
        return this;
    },
    disableInputs: function (selector) {
        var filter = (selector == null ? '*' : selector);
        this.find('input,textarea,select').filter(filter).prop('disabled', 'disabled');
        return this;
    },
    enableInputs: function (selector) {
        var filter = (selector == null ? '*' : selector);
        this.find('input,textarea,select').filter(filter).prop('disabled', '');
        return this;
    },
    //refreshValidation: function () {
    //    const forms = this.filter('form');
    //    forms.data("unobtrusiveValidation", null);
    //    forms.data("validator", null);
    //    $.validator.unobtrusive.parse(this);
    //    return this;
    //},
    //resetValidation: function () {
    //    const forms = this.filter('form');
    //    let val = forms.validate();
    //    val.resetForm();
    //    forms.find('.field-validation-error, .validation-summary-errors > ul').empty();
    //    return this;
    //},
    //resetValidationItem: function () {
    //    this.find('.input-validation-error').removeClass('input-validation-error');
    //    this.find('.field-validation-error, .validation-summary-errors > ul').empty();
    //    return this;
    //},
    wireUpWaitModal: function () {
        this.filter('form[data-waitmodalmsg]')
            .off('submit', null, DTS.Responder.WaitModal.showForForm)
            .submit(DTS.Responder.WaitModal.showForForm);
        return this;
    },
    hasData: function (name) {
        return this.data(name) != undefined;
    },
    havingData: function (name) {
        return this.filter(function () {
            return $(this).data(name) != undefined;
        });
    },
    setDefault: function () {
        this.havingData('default').val(function () {
            return $(this).data('default');
        });
    },
    copyDataAttrs: function (obj) {
        var $obj = $(obj), $this = $(this);
        var attrs = $obj.prop('attributes');
        $.each(attrs, function () {
            if (this.name.startsWith('data')
                && this.name != 'data-bind') {
                $this.attr(this.name, this.value);
            }
        });
        return this;
    },
    wrapCopyData: function () {
        $.each($(this), function () {
            var w = $('<div></div>').copyDataAttrs(this);
            $(this).wrap(w);
            var x = $('<div></div>').css('display', 'inline-block');
            $(this).parent().wrap(x);
        });
        return this;
    },
    popoverOnDisabled: function (o) {
        var popoverContainer = $(this).wrapCopyData().parent()[0];
        $(popoverContainer).popover(o);
        $(this).data('popoverContainer', popoverContainer);
        return this;
    }
});
//use legacy AJAX server-side processing parameter names
//https://www.datatables.net/upgrade/1.10#Server-side-processing
$.fn.dataTable.ext.legacy.ajax = true;
$.fn.dataTable.ext.classes.sProcessing = "dataTables_processing_new";
$.extend(true, $.fn.dataTable.defaults, {
    language: {
        infoFiltered: '' //no filtered caption in the info
    }
});
(function (moment) {
    var aspNetJsonRegex = /^\/?Date\((\-?\d+)/i;
    moment.dtsDate = function (str) {
        if (!aspNetJsonRegex.test(str)) {
            throw 'Not an ASP.NET JSON datetime string';
        }
        return moment.utc(str);
    };
    moment.dtsDateToLocal = function (str) {
        var mom = moment.isMoment(str) ? moment(str) : moment.dtsDate(str);
        return moment([mom.year(), mom.month(), mom.date()]);
    };
    moment.dtsDateTime = function (str) {
        if (!aspNetJsonRegex.test(str)) {
            throw 'Not an ASP.NET JSON datetime string';
        }
        return moment.utc(str).local();
    };
    moment.dtsTime = function (timeSpan) {
        if (timeSpan == null) {
            return null;
        }
        if (!('Hours' in timeSpan)) {
            throw 'Not an ASP.NET JSON time span: ' + timeSpan;
        }
        return moment(timeSpan.Hours + ":" + timeSpan.Minutes, "HH:mm");
    };
    moment.dtsDateTimeTz = function (str) {
        return moment.dtsDateTime(str).tz('America/New_York');
    };
    //use for UTC date strings
    moment.xutcStringToLocal = function (str) {
        var mom = moment(str);
        if (!mom.isValid()) { //IE 8/9 can't handle microseconds in the string
            mom = moment.utc(str.slice(0, -5));
            mom.local(); //turn local mode on after parsing as utc
        }
        return mom;
    };
    moment.dtsDateTimeTz = function (str) {
        return moment.dtsDateTime(str).tz('America/New_York');
    };
    moment.fn.toASP = function () {
        return '/Date(' + this.valueOf() + this.format('ZZ') + ')/';
    };
}(moment));
ko.validation.init({
    insertMessages: false,
    decorateInputElement: true,
    errorsAsTitle: false,
    errorElementClass: 'has-error'
}, true);
ko.dirtyFlag = function (root, isInitiallyDirty) {
    var result = function () { }, _initialState = ko.observable(ko.toJSON(root)), _isInitiallyDirty = ko.observable(isInitiallyDirty);
    result.isDirty = ko.computed(function () {
        return _isInitiallyDirty() || _initialState() !== ko.toJSON(root);
    });
    result.reset = function () {
        _initialState(ko.toJSON(root));
        _isInitiallyDirty(false);
    };
    return result;
};
ko.modifiedDirtyFlag = function (root, isInitiallyDirty) {
    var result = function () { }, _initialState = ko.observable(ko.toJSON(root, function (key, value) {
        return value || '';
    })), _isInitiallyDirty = ko.observable(isInitiallyDirty);
    result.isDirty = ko.computed(function () {
        return _isInitiallyDirty() || _initialState() !== ko.toJSON(root, function (key, value) {
            return value || '';
        });
    });
    result.reset = function () {
        _initialState(ko.toJSON(root, function (key, value) {
            return value || '';
        }));
        _isInitiallyDirty(false);
    };
    return result;
};
ko.utils.addModifiedDirtyFlags = function (obj) {
    var flags = [];
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop) && ko.isObservable(obj[prop])) {
            var d = new ko.modifiedDirtyFlag(obj[prop]);
            obj[prop].DirtyFlag = d;
            d.propName = prop;
            flags.push(d);
        }
    }
    var returnComputed = ko.computed(function () {
        return !!ko.utils.arrayFirst(flags, function (d) {
            return d.isDirty();
        });
    });
    returnComputed.resetAll = function () {
        flags.forEach(function (flag) {
            if (flag.reset)
                flag.reset();
        });
    };
    return returnComputed;
};
//adds a DirtyFlag property to all properties of obj that are observables
// returns a computed observable indicating if any of the dirty flags are true
ko.utils.addDirtyFlags = function (obj) {
    var flags = [];
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop) && ko.isObservable(obj[prop])) {
            var d = ko.dirtyFlag(obj[prop]);
            obj[prop].DirtyFlag = d;
            flags.push(d);
        }
    }
    return ko.computed(function () {
        return !!ko.utils.arrayFirst(flags, function (d) { return d.isDirty(); });
    });
};
// extends observable objects intelligently
ko.utils.extendObservable = function (target, source, deep) {
    var recurse = function (destVal, sourceVal) {
        var newSrc = (destVal && typeof destVal == 'object') ? destVal : ($.isArray(sourceVal) ? [] : {});
        return ko.utils.extendObservable(newSrc, sourceVal, true);
    };
    for (var prop in source) {
        if (!source.hasOwnProperty(prop)) {
            continue;
        }
        var srcVal = void 0, trgVal = void 0, isObservable = false, isObservableArray = false;
        if (ko.isObservable(source[prop])) {
            if (ko.isComputed(source[prop])) { //computed observable
                continue;
            }
            else if (source[prop].destroyAll !== undefined) { //observableArray
                isObservable = true;
                isObservableArray = true;
                srcVal = source[prop]();
            }
            else { //observable
                isObservable = true;
                srcVal = source[prop]();
            }
        }
        else if ($.isFunction(source[prop])) { //a function
            continue;
        }
        else { //just a regular property
            srcVal = source[prop];
        }
        var goDeep = deep && srcVal && typeof srcVal == 'object';
        //handle cloning moments
        if (goDeep && moment.isMoment(srcVal)) {
            goDeep = false;
            srcVal = moment(srcVal);
        }
        if (ko.isWriteableObservable(target[prop])) {
            srcVal = goDeep ? recurse(target[prop](), srcVal) : srcVal;
            target[prop](srcVal);
        }
        else if (target[prop] === undefined) {
            srcVal = goDeep ? recurse(null, srcVal) : srcVal;
            target[prop] = !isObservable ? srcVal : (isObservableArray ? ko.observableArray(srcVal) : ko.observable(srcVal));
        }
        else if (!$.isFunction(target[prop])) {
            srcVal = goDeep ? recurse(target[prop], srcVal) : srcVal;
            target[prop] = srcVal;
        }
    }
    return target;
};
//ko.utils.isObservableArray = function (obj) {
//    return ko.isObservable(obj) && obj.destroyAll !== undefined;
//};
//ko.utils.findParentObservableArray = function (obj, bindingContext) {
//    if (!$.isPlainObject(obj) && !ko.isObservable(obj)) {
//        throw 'obj must be an object or observable';
//    }
//    if (!bindingContext || !bindingContext.$index) {
//        throw 'no binding context provided, or binding context is not in a foreach binding'
//    };
//    const parent = bindingContext.$parent || { };
//    for (let prop in parent) {
//        if (parent.hasOwnProperty(prop)
//            && ko.utils.isObservableArray(parent[prop])
//            && parent[prop].indexOf(obj) > -1) {
//            return parent[prop];
//        }
//    }
//    return null;
//};
ko.subscribable.fn.subscribeAndFire = function (callback, target) {
    callback.apply(target, [this()]);
    this.subscribe.apply(this, arguments);
};
ko.observableArray.fn.findNameValue = function (valueToMatch, idProp) {
    return ko.utils.arrayFirst(this(), function (item) {
        if (item)
            return item[idProp || 'Value'] === valueToMatch;
        else
            return false;
    });
};
ko.observableArray.fn.selectable = function (selectedValue, idProp, nameProp) {
    this.selectedId = ko.observable();
    this.selectedText = ko.observable();
    this.selectedItem = ko.observable();
    this.selectedId.subscribe(function (newValue) {
        var valueToMatch = parseInt(newValue);
        var nameValueObj = this.findNameValue(valueToMatch, idProp || 'Value');
        var item = ko.toJS(nameValueObj);
        this.selectedItem(item);
        if (item)
            this.selectedText(item[nameProp || 'Name']);
        else
            this.selectedText(null);
    }, this);
    this.selectedId(selectedValue);
    return this;
};
ko.computed.fn.findNameValue = function (valueToMatch, idProp) {
    return ko.utils.arrayFirst(this(), function (item) {
        if (item)
            return item[idProp || 'Value'] === valueToMatch;
        else
            return false;
    });
};
ko.computed.fn.selectable = function (selectedValue, idProp, nameProp) {
    this.selectedId = ko.observable().extend({ notify: 'always' });
    this.selectedText = ko.observable();
    this.selectedItem = ko.observable();
    this.selectedId.subscribe(function (newValue) {
        var valueToMatch = parseInt(newValue);
        var nameValueObj = this.findNameValue(valueToMatch, idProp || 'Value');
        var item = ko.toJS(nameValueObj);
        this.selectedItem(item);
        if (item)
            this.selectedText(item[nameProp || 'Name']);
        else
            this.selectedText(null);
    }, this);
    this.selectedId(selectedValue);
    return this;
};
//allows for a key (number) to be passed into the observable which
//will be looked up in the keyTranslater and the observable will
//be set to the value found
ko.extenders.keyTranslator = function (target, value) {
    target.subscribe(function (newVal) {
        if (typeof newVal === 'number'
            && value.hasOwnProperty(newVal)
            && typeof value[newVal] !== 'number') {
            target(value[newVal]);
        }
    });
    return target;
};
//make an observable persist throughout session
ko.extenders.stateSave = function (target, key) {
    if (window.sessionStorage) {
        var value = window.sessionStorage.getItem(key);
        if (value !== undefined && value !== null) {
            target(JSON.parse(value));
        }
        ;
        target.subscribe(function (data) {
            window.sessionStorage.setItem(key, JSON.stringify(data));
        });
    }
    return target;
};
ko.extenders.characterLimit = function (target, limit) {
    var result = ko.pureComputed({
        read: target,
        write: function (newValue) {
            var current = target();
            var newValueSliced = (newValue || '').slice(0, limit);
            if (newValueSliced !== current) {
                target(newValueSliced);
            }
            else {
                if (newValue !== current) {
                    target.notifySubscribers(newValueSliced);
                }
            }
        }
    }).extend({ notify: 'always' });
    result.displayMessage = ko.computed(function () {
        var currentLength = (ko.unwrap(target) || '').length;
        return (limit - currentLength) + ' characters remaining.';
    }, target);
    result(target());
    return result;
};
ko.bindingHandlers.booleanToYesNo = {
    update: function (element, valueAccessor, allBindingsAccessor, context) {
        var options = valueAccessor();
        var value = ko.unwrap(options);
        var newValueAccessor = function () {
            return value ? 'Yes' : 'No';
        };
        ko.bindingHandlers.text.update(element, newValueAccessor, allBindingsAccessor, context, undefined);
    }
};
ko.bindingHandlers.datepicker = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        //initialize datepicker with some optional options
        var options = allBindingsAccessor().datepickerOptions || {};
        //highlight today's date
        if (options.todayHighlight == undefined) {
            options.todayHighlight = true;
        }
        $(element).datepicker(options);
        //handle the field changing
        ko.utils.registerEventHandler(element, 'change', function () {
            var value = valueAccessor();
            $(element).bind("keydown", function (e) {
                if (e.keyCode !== 13 && e.keyCode !== 9) {
                    var dp = $(element).data('datepicker');
                    dp.show();
                }
            });
            if (ko.isObservable(value)) {
                if (element.value) {
                    value(element.value);
                }
                else {
                    value(null);
                }
            }
        });
        //handle disposal (if KO removes by the template binding)
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).datepicker('destroy');
        });
        ko.bindingHandlers.validationCore.init(element, valueAccessor, allBindingsAccessor, undefined, undefined);
    },
    update: function (element, valueAccessor) {
        //$(element).datepicker({ autoclose: true, language: 'es' });
        //$(elment).datepicker('update', new Date());
        //when the view model is updated, update the widget
        var date = ko.utils.unwrapObservable(valueAccessor());
        if (!date) {
            date = null; //clearing the date
        }
        else if (typeof date == 'string') {
            if (String(date).indexOf('/Date(') == 0) {
                date = moment.dtsDate(date).format('MM/DD/YYYY');
            }
            else {
                date = new Date(date);
                if (isNaN(date.getTime()))
                    date = null;
            }
        }
        //only update the datepicker date if it's changed
        var curval = $(element).datepicker('getDate');
        var hasVal = curval && !isNaN(curval);
        var oneNull = (hasVal && !date) || (!hasVal && date);
        var bothVal = hasVal && date;
        if (oneNull || (bothVal && curval.getTime() != date.getTime())) {
            $(element).datepicker('setDate', date);
        }
    }
};
/**
 * Based on:
 * knockout.bindingHandlers.dataTable.js v1.0
 *
 * Copyright (c) 2011, Josh Buckley (joshbuckley.co.uk).
 * License: MIT (http://www.opensource.org/licenses/mit-license.php)
 *
 */
ko.bindingHandlers.dataTable = {
    init: function (element, valueAccessor) {
        var binding = ko.utils.unwrapObservable(valueAccessor());
        // If the binding is an object with an options field,
        // initialise the dataTable with those options. 
        if (binding.options) {
            var dataTable = $(element).dataTable(binding.options);
            //set api accessors
            if (binding.hasOwnProperty('apiAccessor')) {
                if (ko.isObservable(binding.apiAccessor)) {
                    binding.apiAccessor(dataTable.api());
                }
                else {
                    binding.apiAccessor = dataTable.api();
                }
            }
        }
    },
    update: function (element, valueAccessor) {
        var binding = ko.utils.unwrapObservable(valueAccessor());
        if (binding.data) {
            // Rebuild table from data source specified in binding
            var data = ko.unwrap(binding.data);
            if (!$(element).is(":visible") && $(element).width() == 0) {
                $(element).DataTable().clear().rows.add(data).draw();
                $(element).width("");
                $(element).DataTable().clear().rows.add(data).draw();
            }
            else {
                $(element).DataTable().clear().rows.add(data).draw();
            }
        }
        else {
            $(element).DataTable().draw();
        }
    }
};
// Here's a custom Knockout binding that make elements shown/hidden via jQuery's fadeIn()/fadeOut() methods
// Could be stored in a separate utility library
ko.bindingHandlers.fadeVisible = {
    init: function (element, valueAccessor) {
        // Initially set the element to be instantly visible/hidden depending on the value
        var value = valueAccessor();
        $(element).toggle(ko.unwrap(value)); // Use "unwrapObservable" so we can handle values that may or may not be observable
    },
    update: function (element, valueAccessor) {
        // Whenever the value subsequently changes, slowly fade the element in or out
        var value = valueAccessor();
        ko.unwrap(value) ? $(element).fadeIn() : $(element).fadeOut();
    }
};
// Here's a custom Knockout binding that makes elements shown/hidden via jQuery's fadeIn()/fadeOut() methods
// Could be stored in a separate utility library
ko.bindingHandlers.fadeinVisible = {
    init: function (element, valueAccessor) {
        // Initially set the element to be instantly visible/hidden depending on the value
        var value = valueAccessor();
        $(element).toggle(ko.unwrap(value)); // Use "unwrapObservable" so we can handle values that may or may not be observable
    },
    update: function (element, valueAccessor) {
        // Whenever the value subsequently changes, slowly fade the element in or out
        var value = valueAccessor();
        ko.unwrap(value) ? $(element).fadeIn() : $(element).toggle(false);
    }
};
ko.bindingHandlers.slideVisible = {
    init: function (element, valueAccessor) {
        // Initially set the element to be instantly visible/hidden depending on the value
        var value = valueAccessor();
        $(element).toggle(ko.unwrap(value)); // Use "unwrapObservable" so we can handle values that may or may not be observable
    },
    update: function (element, valueAccessor) {
        // Whenever the value subsequently changes, slowly fade the element in or out
        var value = valueAccessor();
        ko.unwrap(value) ? $(element).show(300) : $(element).hide(300);
    }
};
ko.bindingHandlers.masked = {
    init: function (element, valueAccessor, allBindingsAccessor) {
        var mask = ko.unwrap(allBindingsAccessor().mask || {});
        $(element).mask(mask);
        ko.utils.registerEventHandler(element, 'change', function () {
            var observable = valueAccessor();
            observable($(element).val());
        });
    },
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        $(element).val(value);
    }
};
ko.bindingHandlers.mask = {
    update: function (element, valueAccessor) {
        var mask = ko.unwrap(valueAccessor());
        $(element).mask(mask);
    }
};
ko.bindingHandlers.bootstrapPopover = {
    create: function (element, options) {
        //pull the content of the previous dom element if no content selected
        if (!options.content && !$(element).is("[data-content]")) {
            var $p = $(element).prev().first();
            if ($p.length == 1) {
                //clone options so that we aren't setting the content on the main options object
                options = $.extend({}, options);
                options.content = $p.hide().html();
                if (options.html === undefined || options.html === null) {
                    options.html = true;
                }
            }
        }
        //set onDisabled to true to allow popover on disabled buttons
        if (options.onDisabled) {
            $(element).popoverOnDisabled(options);
        }
        else {
            $(element).popover(options);
        }
    },
    getElement: function (element) {
        //this will pull the element the popover was created on (won't be 'element' if onDisabled is true)
        var $element = $(element);
        if ($element.hasData('popoverContainer')) {
            $element = $($element.data('popoverContainer'));
        }
        return $element;
    },
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var options = ko.unwrap(valueAccessor()) || {};
        //subscribe to recreate observable, and destroy and recreate on change
        if (options.recreate && ko.isObservable(options.recreate)) {
            options.recreate.subscribe(function (newValue) {
                var $element = ko.bindingHandlers.bootstrapPopover.getElement(element);
                $element.popover('destroy');
                if (newValue) { //only recreate if the new recreate value is truthy
                    ko.bindingHandlers.bootstrapPopover.create(element, options);
                }
            });
        }
        ko.bindingHandlers.bootstrapPopover.create(element, options);
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        var options = ko.unwrap(valueAccessor()) || {};
        // Popover can disabled by using the "disable" option.
        var disable = ko.unwrap(options.disable);
        if (disable !== null) {
            var $element = ko.bindingHandlers.bootstrapPopover.getElement(element);
            $element.popover(disable ? 'disable' : 'enable');
        }
    }
};
ko.bindingHandlers.counter = {
    counters: {},
    processOptions: function (valueAccessor) {
        var bindings = ko.unwrap(valueAccessor());
        var options = {
            value: ko.unwrap(bindings.value),
            format: ko.unwrap(bindings.format) || '',
            group: ko.unwrap(bindings.group) || 'default',
            updateEvery: ko.unwrap(bindings.updateEvery) || 1,
            duration: (bindings.duration && ko.isObservable(bindings.duration)) ? bindings.duration : null
        };
        if (!options.value || !moment.isMoment(options.value)) {
            throw 'provided value for counter binding is not a momentjs object';
        }
        return options;
    },
    init: function (element, valueAccessor) {
        var options = ko.bindingHandlers.counter.processOptions(valueAccessor);
        //create the group if one doesn't exist
        var c = ko.bindingHandlers.counter.counters[options.group];
        if (!c) {
            c = ko.bindingHandlers.counter.counters[options.group] = new DTS.Responder.Util.counter();
        }
        //save this element in the list of elements to update
        c.add(element, options.value, options.format, options.duration);
        if (c.state() != 'running') { //start the counter if it's not running
            c.start();
        }
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            c.remove(element);
        });
    },
    update: function (element, valueAccessor) {
        var options = ko.bindingHandlers.counter.processOptions(valueAccessor);
        var c = ko.bindingHandlers.counter.counters[options.group];
        c.update(element, options.value, options.format, options.duration);
        if (c.state() != 'running') { //start the counter if it's not running
            c.start();
        }
    }
};
//adapted from http://stackoverflow.com/a/11536424
ko.bindingHandlers.uniqueId = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var options = ko.bindingHandlers.uniqueId.generateSettings(valueAccessor, bindingContext);
        element.id = ko.bindingHandlers.uniqueId.setGetKey(options.obs, options.key);
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var options = ko.bindingHandlers.uniqueId.generateSettings(valueAccessor, bindingContext);
        element.id = ko.bindingHandlers.uniqueId.setGetKey(options.obs, options.key);
    },
    generateSettings: function (valueAccessor, bindingContext) {
        var value = valueAccessor();
        //handle uniqueId: obsname and uniqueId: { obs: observable, key: 'key_name' }
        if ($.isPlainObject(value)) {
            value = $.extend({ obs: null, key: 0 }, value);
        }
        else {
            value = { obs: value, key: 0 };
        }
        if (!ko.isObservable(value.obs)) {
            throw 'No observable found to store uniqueId/uniqueFor';
        }
        value.key = 'id-' + (bindingContext.$index ? 'ix' + bindingContext.$index() + '-' : '') + (value.key || 0);
        return value;
    },
    setGetKey: function (obs, key) {
        var h = ko.bindingHandlers.uniqueId;
        var keyHolder = obs[h.observableProp] = obs[h.observableProp] || {};
        keyHolder[key] = keyHolder[key] || h.prefix + (++h.counter);
        return keyHolder[key];
    },
    counter: 0,
    prefix: 'unique',
    observableProp: 'unique-ids'
};
ko.bindingHandlers.uniqueFor = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var options = ko.bindingHandlers.uniqueId.generateSettings(valueAccessor, bindingContext);
        element.setAttribute('for', ko.bindingHandlers.uniqueId.setGetKey(options.obs, options.key));
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var options = ko.bindingHandlers.uniqueId.generateSettings(valueAccessor, bindingContext);
        element.setAttribute('for', ko.bindingHandlers.uniqueId.setGetKey(options.obs, options.key));
    }
};
ko.bindingHandlers.accordion = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var options = valueAccessor(), initialState = !!ko.unwrap(options.collapsed);
        var $panel = $(element), $heading = $panel.children('.panel-heading'), $body = $panel.children('.panel-body'), $title = $heading.children('.panel-title');
        if ($panel.length != 1 || $heading.length != 1 || $body.length != 1 || $title.length != 1) {
            throw 'Invalid setup for accordion ko binding handler';
        }
        var idHolder = ko.observable(), titleId = $title.attr('id');
        if (!titleId) {
            titleId = ko.bindingHandlers.uniqueId.setGetKey(idHolder, 'panelTitle');
            $title.attr('id', titleId);
        }
        var collapseId = ko.bindingHandlers.uniqueId.setGetKey(idHolder, 'panelCollapse');
        var $collapse = $('<div></div>').attr({ id: collapseId, role: 'tabpanel', 'aria-labelledby': titleId })
            .addClass('panel-collapse collapse').toggleClass('in', !initialState);
        var $arrow = $('<i></i>').addClass('fas').addClass(initialState ? 'fa-chevron-up' : 'fa-chevron-down').appendTo($title.append('&nbsp;'));
        $collapse.on('show.bs.collapse hide.bs.collapse', function (e) {
            // Need to check if this element is the target of the event,
            // because when accordion panels are nested, the parents get
            // events from their children as well.
            if ($(this).is(e.target)) {
                $arrow.toggleClass('fa-chevron-up', e.type === 'hide').toggleClass('fa-chevron-down', e.type === 'show');
                if (ko.isWriteableObservable(options.collapsed)) {
                    options.collapsed(e.type === 'hide');
                }
            }
        });
        $body.wrap($collapse);
        $heading.addClass('clearfix');
        var $link = $('<a></a>').attr({ 'data-toggle': 'collapse', href: '#' + collapseId, 'aria-expanded': true, 'aria-controls': collapseId });
        $title.css('display', 'inline-block').wrap($link).wrap('<div></div>');
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var options = valueAccessor(), state = !!ko.unwrap(options.collapsed);
        var $panel = $(element), $collapse = $panel.children('.collapse');
        $collapse.collapse(state ? 'hide' : 'show');
    }
};
ko.bindingHandlers.accordion2 = {
    init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var options = valueAccessor(), initialState = !!ko.unwrap(options.collapsed);
        var $panel = $(element), $heading = $panel.children('.panel-heading'), $body = $panel.children('.panel-body'), $title = $heading.children('.panel-title');
        if ($panel.length != 1 || $heading.length != 1 || $body.length != 1 || $title.length != 1) {
            throw 'Invalid setup for accordion ko binding handler';
        }
        var idHolder = ko.observable(), titleId = $title.attr('id');
        if (!titleId) {
            titleId = ko.bindingHandlers.uniqueId.setGetKey(idHolder, 'panelTitle');
            $title.attr('id', titleId);
        }
        var collapseId = ko.bindingHandlers.uniqueId.setGetKey(idHolder, 'panelCollapse');
        var $collapse = $('<div></div>').attr({ id: collapseId, role: 'tabpanel', 'aria-labelledby': titleId })
            .addClass('panel-collapse collapse').toggleClass('in', !initialState);
        var $arrow = $('<i class="pull-right"></i>').addClass('fas').addClass(initialState ? 'fa-chevron-up' : 'fa-chevron-down').appendTo($title.append('&nbsp;'));
        $collapse.on('show.bs.collapse hide.bs.collapse', function (e) {
            $arrow.toggleClass('fa-chevron-up', e.type === 'hide').toggleClass('fa-chevron-down', e.type === 'show');
            if (ko.isWriteableObservable(options.collapsed)) {
                options.collapsed(e.type === 'hide');
            }
        });
        $body.wrap($collapse);
        $heading.addClass('clearfix');
        var $link = $('<a style="text-decoration: none"></a>').attr({ 'data-toggle': 'collapse', href: '#' + collapseId, 'aria-expanded': true, 'aria-controls': collapseId });
        $title.wrap($link).wrap('<div></div>');
    },
    update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
        var options = valueAccessor(), state = !!ko.unwrap(options.collapsed);
        var $panel = $(element), $collapse = $panel.children('.collapse');
        $collapse.collapse(state ? 'hide' : 'show');
    }
};
ko.bindingHandlers.fileupload = {
    init: function (element, valueAccessor) {
        var settings = ko.unwrap(valueAccessor());
        $(element).fileupload(settings);
        // IE doesn't fire correctly on 'enter'
        $(element).keydown(function (e) {
            if (e.which == 13) {
                e.preventDefault();
                $(element).click();
            }
        });
    }
};
ko.bindingHandlers.select2 = {
    //*SLR: for backward compatability--would like to move to using one select2 binding eventually
    generateBinding: function (element, valueAccessor, allBindings) {
        var b = allBindings();
        return {
            options: valueAccessor(),
            text: b.select2Text,
            data: b.select2Data,
            value: (b.select2ValueFilter || {}).value || b.select2ValueInt || b.select2Value,
            int: ko.pureComputed(function () {
                return !!((b.select2ValueFilter || {}).value || b.select2ValueInt);
            }),
            filterDefault: (b.select2ValueFilter || {}).defaultValue,
            enable: b.select2Enabled
        };
    },
    init: function (element, valueAccessor, allBindings) {
        var $el = $(element), obj = ko.bindingHandlers.select2.generateBinding(element, valueAccessor, allBindings);
        if ($el.is('select:not([multiple])') //select element without multiple attribute
            && obj.options.placeholder //has a placeholder
            && allBindings().options //is bound to an options list (not using AJAX/query)
            && allBindings().optionsCaption !== '') {
            throw 'Non-multiple select2s bound to an options list and with a placeholder must have optionsCaption bound to an empty string';
        }
        $el.select2(obj.options);
        // focus the first select when specified
        if ($el.hasClass('first-select')) {
            $el.select2('focus');
        }
        ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
            $(element).select2('destroy');
        });
        $el.on('change', function () {
            if (ko.isObservable(obj.text)) {
                var t = $el.select2('data');
                obj.text((t ? t.text : null));
            }
            if (ko.isObservable(obj.data)) {
                obj.data($el.select2('data'));
            }
            if (ko.isObservable(obj.value)) {
                var val = ko.unwrap(obj.int) ? parseInt($el.select2('val')) : $el.select2('val');
                obj.value(val);
            }
        });
    },
    update: function (element, valueAccessor, allBindings) {
        var $el = $(element), obj = ko.bindingHandlers.select2.generateBinding(element, valueAccessor, allBindings);
        var selData = JSON.stringify($el.select2('data')), selVal = $el.select2('val'), curData = JSON.stringify(ko.unwrap(obj.data));
        var curVal = ko.unwrap(obj.value);
        if (typeof curVal === "number") {
            curVal = curVal.toString();
        }
        // Push any change from the observable to the select2 interface
        //*SLR: do not remove truthiness checks! this prevents calling the
        //  setter when the value is undefined and current is null
        if (ko.isObservable(obj.value) && selVal !== curVal && (!!selVal || !!curVal)) {
            if (obj.filterDefault !== undefined) { //verify the value is in the list if this is set
                var valueString = 'option[value="' + ko.unwrap(obj.value) + '"]';
                if ($el.find(valueString).length === 0) {
                    curVal = ko.unwrap(obj.filterDefault);
                    //not found in list so set to default and change observable
                    obj.value(curVal);
                }
            }
            $el.select2('val', curVal);
        }
        if (ko.isObservable(obj.data) && selData !== curData && (!!selData || !!curData)) {
            $el.select2('data', ko.unwrap(obj.data));
        }
        if (obj.enable !== undefined) {
            $el.select2('enable', ko.unwrap(obj.enable));
        }
    }
};
ko.bindingHandlers.bootstrapButton = {
    init: function (element, valueAccessor, allBindingsAccessor, context) {
        var options = ko.unwrap(valueAccessor()) || {};
        var loading = !!ko.unwrap(options.loading);
        $(element).button();
        if (loading) {
            $(element).button('loading');
        }
        if (ko.isObservable(options.loading)) {
            options.loading.subscribe(function (newVal) {
                $(element).button(newVal ? 'loading' : 'reset');
            });
        }
    }
};
ko.bindingHandlers.tooltip = {
    init: function (element, valueAccessor) {
        var options = ko.unwrap(valueAccessor());
        $(element).tooltip(options);
        if (options && options.visible) {
            $(element).tooltip('disable');
        }
    },
    update: function (element, valueAccessor) {
        var options = ko.unwrap(valueAccessor());
        if (options && options.hasOwnProperty('visible')) {
            if (ko.unwrap(options.visible))
                $(element).tooltip('enable');
            else
                $(element).tooltip('disable');
        }
    }
};
//KNOCKOUT VALIDATION RULES
ko.validation.rules['dtsPasswordPattern'] = {
    validator: function (val, params) {
        var regex = /^.*(?=.*\d)(?=.*[a-zA-Z])(?=.*[!@#$%\^&*()\-_+=[{}\]|\:;'"<>,.?]).*$/;
        return !params || ko.validation.utils.isEmptyVal(val) || val.match(regex) != null;
    },
    message: 'The password must contain a combination of alphabetic, numeric, and special characters'
};
ko.validation.rules['dtsPasswordAllowed'] = {
    async: true,
    validator: function (val, params, callback) {
        if (params) {
            $.ajax({
                url: DTS.Responder.sitePath + 'Account/IsAllowed',
                type: 'POST',
                data: { password: val },
                success: callback
            });
        }
        else {
            callback(true);
        }
    },
    message: 'This password is not allowed due to common usage'
};
ko.validation.rules['dtsPhonePattern'] = {
    validator: function (val, params) {
        var regex = /^(?:1[- \.]?)?(?:\d{3}|\(\d{3}\))[- \.]?\d{3}[- \.]?\d{4}$/;
        return !params || ko.validation.utils.isEmptyVal(val) || val.match(regex) != null;
    },
    message: 'Please enter a valid U.S. phone number with area code'
};
ko.validation.rules['mustEqualTrueIf'] = {
    validator: function (val, expression) {
        return ko.validation.utils.isEmptyVal(val) || !!val || !ko.validation.utils.getValue(expression);
    },
    message: 'You must select at least one option.'
};
ko.validation.rules['minArrayLength'] = {
    validator: function (val, expression) {
        return ko.validation.utils.isEmptyVal(val) || ko.validation.utils.isEmptyVal(expression) ||
            (ko.validation.utils.isArray(val) && val.length >= ko.validation.utils.getValue(expression));
    },
    message: 'You must select at least one option.'
};
// Ian's simplified dirty state tracking..
// equalityComparer allows you to pass a custom equality comparison function for comparing initial and current values
// ALWAYS return true if they're equal
// create an extender as well to affix to selectedIds
ko.observable.fn.trackValueChanged = function (equalityComparer) {
    if (equalityComparer && typeof equalityComparer !== 'function')
        throw Error('parameter \'equalityComparer\' must be a function');
    var initialState = ko.observable(this());
    // flag to indicate the value has mutated from its initial state
    this.valueHasChanged = ko.computed(function () {
        var current = this();
        var initial = initialState();
        // if an equalityComparer function has been provided, use it
        if (equalityComparer)
            return !equalityComparer(initial, current);
        // otherwise, use the default from below
        return !ko.observable.fn.trackValueChanged.defaultEqualityComparer(initial, current);
    }, this);
    // reset the value changed flag by setting the initial state value to be the same as the current value
    this.valueHasChanged.reset = function () {
        initialState(this());
    }.bind(this);
    return this;
};
// default equality comparison for the above fn -- ALWAYS return true if initial and current are loosely equal 
ko.observable.fn.trackValueChanged.defaultEqualityComparer = function (initial, current) {
    return initial == current;
};
(function () {
    var makeValidator = function (comparer) {
        return function (val, otherVal) {
            val = moment(ko.unwrap(val), 'MM/DD/YYYY');
            otherVal = moment(ko.unwrap(otherVal), 'MM/DD/YYYY');
            if (!val.isValid() || !otherVal.isValid()) {
                return true;
            }
            return comparer(val, otherVal);
        };
    };
    ko.validation.rules['dateIsBefore'] = {
        validator: makeValidator(function (val, otherVal) {
            return val.isBefore(otherVal);
        }),
        message: 'Date must be before'
    };
    ko.validation.rules['dateIsNotBefore'] = {
        validator: makeValidator(function (val, otherVal) {
            return !val.isBefore(otherVal);
        }),
        message: 'Date must not be before'
    };
    ko.validation.rules['dateIsAfter'] = {
        validator: makeValidator(function (val, otherVal) {
            return val.isAfter(otherVal);
        }),
        message: 'Date must be after'
    };
    ko.validation.rules['dateIsNotAfter'] = {
        validator: makeValidator(function (val, otherVal) {
            return !val.isAfter(otherVal);
        }),
        message: 'Date must not be after'
    };
    ko.validation.rules['zipCode'] = {
        validator: function (val) {
            var isValidZipCode = true;
            if (val) {
                var regexp = /^[0-9]{5}(?:-[0-9]{4})?$/;
                if (regexp.test(val)) {
                    isValidZipCode = true;
                }
                else {
                    isValidZipCode = false;
                }
            }
            return isValidZipCode;
        },
        message: function (val) {
            return 'Please enter a valid zip code.';
        }
    };
    //only accept dates that are within the acceptable data range for sql datetime type
    //date range changed because FEMA didn't like the extreme date range
    ko.validation.rules['withinSqlDateRange'] = {
        validator: function (val) {
            var currdate = Date.parse(val);
            //  const minDateValue = Date.parse('01/01/1900');
            var minDateValue = Date.parse('01/01/1900');
            var maxDateValue = Date.parse('12/31/2040');
            var isValidSQLDate = true;
            if (val) {
                isValidSQLDate = currdate <= maxDateValue && currdate >= minDateValue;
            }
            return isValidSQLDate;
        },
        message: function (val) {
            return 'The date must be between 1/1/1900 and 12/31/2040.';
        }
    };
}());
ko.validation.registerExtenders();
//# sourceMappingURL=dtsExtensions.js.map;
window.DTS = window.DTS || {};
DTS.Responder = DTS.Responder || {};
DTS.Responder.sitePath = DTS_Responder_sitePath;
DTS.Responder.afToken = DTS_Responder_afToken;
DTS.Responder.maxFileSize = 10 * 1024 * 1024; //10MB
DTS.Responder.maxFileSizeMB = DTS.Responder.maxFileSize / 1024 / 1024 | 0;
DTS.Responder.ajaxPost = $.post;
DTS.Responder.ajaxGet = $.get;
DTS.Responder.ajax = $.ajax;
DTS.Responder.Timeout = function () {
    var timer = null;
    var timeoutDuration = DTS_Responder_Timeout_timeoutDuration;
    var promptDuration = DTS_Responder_Timeout_promptDuration;
    var template = '<div id="SessionLogOffModal" class="modal fade" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-hidden="true"> \
            <div class="modal-dialog"> \
                <div class="modal-content"> \
                    <div class="modal-header"> \
                        <h4 class="modal-title">You\'ve been inactive for a few minutes</h4> \
                    </div> \
                    <div class="modal-body"> \
						<div>You are about to be signed out. Would you like to maintain your session?</div> \
                        <br /> \
                        <div id="logOffModalTimeLeft">Logging out in</div> \
                    </div> \
                    <div class="modal-footer"> \
                            <a role="button" class="btn btn-default" href="/Account/Logout">No</a> \
                            <button type="button" class="btn btn-primary" onclick="DTS.Responder.Timeout.stayAlive()">Yes</button> \
                    </div> \
                </div> \
            </div> \
        </div>';
    var expiredEvent = function () {
        location.reload(); //should direct to login page because the session has expired
    };
    //on expiration of the timer
    var promptEvent = function () {
        clearTimeout(timer);
        timer = setTimeout(expiredEvent, promptDuration * 1000);
        var modalDomObject = $("#SessionLogOffModal");
        if (!modalDomObject.length) {
            modalDomObject = $(template);
            modalDomObject.appendTo(document.body);
            modalDomObject.on('show.bs.modal', function () {
                var otherModals = $('.modal:visible').not(modalDomObject);
                if (otherModals.length) {
                    otherModals.addClass('below-backdrop');
                }
            });
            modalDomObject.on('hide.bs.modal', function () {
                $('.modal.below-backdrop').removeClass('below-backdrop');
            });
            modalDomObject.on('hidden.bs.modal', function () {
                modalDomObject.remove();
                modalDomObject = null;
            });
        }
        var timeLeft = promptDuration;
        var countdownTimer = setInterval(function () {
            timeLeft = timeLeft - 1;
            if (timeLeft > 1) {
                $('#logOffModalTimeLeft').text(' Logging out in ' + timeLeft + ' seconds...');
            }
            else if (timeLeft > 0) {
                $('#logOffModalTimeLeft').text(' Logging out in ' + timeLeft + ' second...');
            }
            else {
                clearInterval(countdownTimer);
                $('#logOffModalTimeLeft').text(' Logging out...');
            }
        }, 1000);
        modalDomObject.modal('show');
    };
    //runs every page load or ajax call
    var process = function () {
        clearTimeout(timer);
        var modalDomObject = $("#SessionLogOffModal");
        if (modalDomObject.length) {
            modalDomObject.modal('hide');
        }
        if (timeoutDuration && promptDuration) {
            var timeout_ms = (timeoutDuration - promptDuration) * 1000;
            if (timeout_ms > 0) {
                timer = setTimeout(promptEvent, timeout_ms);
            }
        }
    };
    var stayAlive = function () {
        $.post(DTS.Responder.sitePath + 'Account/Ping', function () {
            var modalDomObject = $("#SessionLogOffModal");
            if (modalDomObject.length) {
                modalDomObject.modal('hide');
            }
        });
    };
    var clear = function () {
        clearTimeout(timer);
    };
    return {
        process: process,
        stayAlive: stayAlive,
        clear: clear
    };
}();
DTS.Responder.SignalR = DTS.Responder.SignalR || {};
DTS.Responder.SignalR.hub = null;
DTS.Responder.SignalR.triggerAlert = function (alert) {
    var time = moment.dtsDateTime(alert.Date).format('M/D/YYYY h:mm a');
    var title = 'Message from ' + alert.From + ' (' + time + ')';
    DTS.Responder.Util.showAlert(alert.Message, title);
};
$(function () {
    //set up AJAX handlers
    $(document).ajaxError(function (event, jqXHR, ajaxSettings, thrownError) {
        //if the user's session expired, reload to get to the login page
        if (jqXHR.status === 500 && jqXHR.responseText.match(/The provided anti-forgery token was meant for user &quot;\w+&quot;, but the current user is &quot;&quot;\./)) {
            location.reload(true);
        }
        else if (jqXHR.status === 401) {
            try {
                var jsonRsp = JSON.parse(jqXHR.responseText);
                var jsonRspUrl = encodeURIComponent(jsonRsp.Redirect.validateRelativeUrl(true));
                var locationPathName = encodeURIComponent(window.location.pathname);
                var locationSearch = encodeURIComponent(window.location.search);
                window.location.href = jsonRspUrl + '?ReturnUrl=' + locationPathName + locationSearch;
            }
            catch (e) {
                console.log('Redirect failed');
                location.reload(true);
            }
        }
        else {
            console.log('AJAX error');
        }
    }).ajaxStart(function () {
        DTS.Responder.Timeout.clear(); //clear if there's a timer running
    }).ajaxSend(function (event, request, settings) {
        if (DTS.Responder.afToken) {
            request.setRequestHeader('RequestVerificationToken', DTS.Responder.afToken);
        }
    }).ajaxComplete(function () {
        DTS.Responder.Timeout.process();
    });
    //start site timeout timer
    DTS.Responder.Timeout.process();
    //set up signalR listener
    var hub = $.connection.responderPortalHub;
    DTS.Responder.SignalR.hub = hub;
    hub.client.triggerAlert = DTS.Responder.SignalR.triggerAlert;
    //$.connection.hub.logging = true;
    $.connection.hub.start();
});
//fix Select2 fields in modal
$.fn.modal.Constructor.prototype.enforceFocus = function () {
    var that = this;
    $(document).on('focusin.modal', function (e) {
        if ($(e.target).hasClass('select2-input')) {
            return true;
        }
        //if (that.$element[0] !== e.target && !that.$element.has(e.target).length) {
        //    that.$element.focus();
        //}
    });
};
//OWASP CSRF Recomendation
var csrf_token = DTS.Responder.afToken; //document.querySelector("meta[name='csrf-token']").getAttribute("content");
function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("anti-csrf-token", csrf_token);
        }
    }
});
//fix large body padding
if (window.ResizeObserver) {
    var ResizeObserver_1 = window.ResizeObserver;
    $(document).ready(function () {
        setTimeout(function () {
            var navbar = document.querySelector('.navbar.navbar-fixed-top');
            var body = document.querySelector('body');
            var lastHeight = 0;
            new ResizeObserver_1(function (entries) {
                for (var i = 0; i < entries.length; i++) {
                    var entry = entries[i];
                    var height = (entry.contentBoxSize && entry.contentBoxSize.blockSize) ? entry.contentBoxSize.blockSize : entry.contentRect.height;
                    if (height != lastHeight) {
                        lastHeight = height;
                        body.style.paddingTop = Math.max(60, height) + "px";
                    }
                }
            }).observe(navbar);
        }, 0);
    });
}
//# sourceMappingURL=dtsStartup.js.map;
(function ($, window) {
    $.extend({
        fileDownloadWithVerification: function () {
            if (arguments[1].data)
                arguments[1].data.RequestVerificationToken = DTS.Responder.afToken;
            else
                arguments[1].data = { RequestVerificationToken: DTS.Responder.afToken };
            $.fileDownload.apply(this, arguments);
        }
    });
})(jQuery, this);
//# sourceMappingURL=jquery.fileDownloadWIthVerification.js.map;
var Ics;
(function (Ics) {
    function padStart(targetString, targetLength, padWith) {
        targetLength = targetLength >> 0; //truncate if number or convert non-number to 0;
        padWith = String((typeof padWith !== 'undefined' ? padWith : ' '));
        if (targetString.length > targetLength) {
            return String(targetString);
        }
        else {
            targetLength = targetLength - targetString.length;
            if (targetLength > padWith.length) {
                padWith += padWith.repeat(targetLength / padWith.length); //append to original to ensure we are longer than needed
            }
            return padWith.slice(0, targetLength) + String(targetString);
        }
    }
    ;
    function calculateOffset(offset) {
        if (offset > 12 || offset < -12)
            throw new Error('Invalid offset specified.');
        var isNegative = offset < 0;
        var offsetString = padStart((Math.round(offset) * 100).toFixed(0).replace('-', ''), 4, '0');
        return "" + (isNegative ? '-' : '') + offsetString;
    }
    function timezoneTemplate(_a) {
        var Id = _a.Id, OffsetStandard = _a.OffsetStandard, AbbreviationStandard = _a.AbbreviationStandard, OffsetDaylight = _a.OffsetDaylight, AbbreviationDaylight = _a.AbbreviationDaylight;
        return "\n            BEGIN:VTIMEZONE\n            TZID:" + Id + "\n            TZURL:http://tzurl.org/zoneinfo-outlook/" + Id + "\n            X-LIC-LOCATION:" + Id + "\n            " + (OffsetStandard != OffsetDaylight ?
            "BEGIN:DAYLIGHT\n                TZNAME:" + AbbreviationDaylight + "\n                TZOFFSETFROM:" + calculateOffset(OffsetStandard) + "\n                TZOFFSETTO:" + calculateOffset(OffsetDaylight) + "\n                DTSTART:19700308T020000\n                RRULE:FREQ=YEARLY;BYMONTH=3;BYDAY=2SU\n                END:DAYLIGHT" : '') + "\n            BEGIN:STANDARD\n            TZNAME:" + AbbreviationStandard + "\n            TZOFFSETFROM:" + calculateOffset(OffsetDaylight) + "\n            TZOFFSETTO:" + calculateOffset(OffsetStandard) + "\n            DTSTART:19701101T020000\n            RRULE:FREQ=YEARLY;BYMONTH=11;BYDAY=1SU\n            END:STANDARD\n            END:VTIMEZONE\n        ";
    }
    function icsTemplate(_a) {
        var Summary = _a.Summary, Url = _a.Url, Description = _a.Description, Location = _a.Location, Start = _a.Start, End = _a.End, TimezoneInfo = _a.TimezoneInfo;
        return ("\n            BEGIN:VCALENDAR\n            VERSION:2.0\n            PRODID:-//femaresponder.net//ics\n            CALSCALE:GREGORIAN\n            " + timezoneTemplate(TimezoneInfo) + "\n            BEGIN:VEVENT\n            DTSTAMP:" + (moment.utc().format('YYYYMMDDTHHmmss') + 'Z') + "\n            UID:" + (moment.utc().format('YYYYMMDDTHHmmss') + '-' + moment.utc().unix() + '@DTS') + "\n            DTSTART;TZID=" + TimezoneInfo.Id + ":" + Start + "\n            DTEND;TZID=" + TimezoneInfo.Id + ":" + End + "\n            SUMMARY:" + Summary + "\n            URL:" + Url + "\n            X-ALT-DESC;FMTTYPE=text/html:" + Description + "\n            LOCATION:" + Location + "\n            END:VEVENT\n            END:VCALENDAR\n            ").split('\n').filter(function (l) { return l.trim(); }).map(function (l) { return l.trim(); }).join('\n');
    }
    function generateIcsFromSchedule(schedule) {
        return icsTemplate(schedule);
    }
    function createIcsBlob(schedule) {
        var blob = new Blob([generateIcsFromSchedule(schedule)], { type: 'text/calendar' });
        return blob;
    }
    function downloadSchedule(schedule, filename) {
        if (filename === void 0) { filename = 'schedule'; }
        var a = document.createElement('a');
        a.style.display = 'none';
        document.body.appendChild(a);
        var blob = createIcsBlob(schedule);
        if (window.navigator.msSaveOrOpenBlob) {
            a.addEventListener('click', function () { return window.navigator.msSaveOrOpenBlob(blob, filename + ".ics"); });
        }
        else {
            a.href = window.URL.createObjectURL(blob);
            a.setAttribute("download", filename);
        }
        a.click();
        if (!window.navigator.msSaveOrOpenBlob)
            window.URL.revokeObjectURL(a.href);
        document.body.removeChild(a);
    }
    Ics.downloadSchedule = downloadSchedule;
})(Ics || (Ics = {}));
//# sourceMappingURL=ics.js.map;
