/*! jQuery v3.6.1 | (c) OpenJS Foundation and other contributors | jquery.org/license */
!function(e,t){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(C,e){"use strict";var t=[],r=Object.getPrototypeOf,s=t.slice,g=t.flat?function(e){return t.flat.call(e)}:function(e){return t.concat.apply([],e)},u=t.push,i=t.indexOf,n={},o=n.toString,y=n.hasOwnProperty,a=y.toString,l=a.call(Object),v={},m=function(e){return"function"==typeof e&&"number"!=typeof e.nodeType&&"function"!=typeof e.item},x=function(e){return null!=e&&e===e.window},E=C.document,c={type:!0,src:!0,nonce:!0,noModule:!0};function b(e,t,n){var r,i,o=(n=n||E).createElement("script");if(o.text=e,t)for(r in c)(i=t[r]||t.getAttribute&&t.getAttribute(r))&&o.setAttribute(r,i);n.head.appendChild(o).parentNode.removeChild(o)}function w(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?n[o.call(e)]||"object":typeof e}var f="3.6.1",S=function(e,t){return new S.fn.init(e,t)};function p(e){var t=!!e&&"length"in e&&e.length,n=w(e);return!m(e)&&!x(e)&&("array"===n||0===t||"number"==typeof t&&0<t&&t-1 in e)}S.fn=S.prototype={jquery:f,constructor:S,length:0,toArray:function(){return s.call(this)},get:function(e){return null==e?s.call(this):e<0?this[e+this.length]:this[e]},pushStack:function(e){var t=S.merge(this.constructor(),e);return t.prevObject=this,t},each:function(e){return S.each(this,e)},map:function(n){return this.pushStack(S.map(this,function(e,t){return n.call(e,t,e)}))},slice:function(){return this.pushStack(s.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},even:function(){return this.pushStack(S.grep(this,function(e,t){return(t+1)%2}))},odd:function(){return this.pushStack(S.grep(this,function(e,t){return t%2}))},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(0<=n&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:u,sort:t.sort,splice:t.splice},S.extend=S.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,l=!1;for("boolean"==typeof a&&(l=a,a=arguments[s]||{},s++),"object"==typeof a||m(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(e=arguments[s]))for(t in e)r=e[t],"__proto__"!==t&&a!==r&&(l&&r&&(S.isPlainObject(r)||(i=Array.isArray(r)))?(n=a[t],o=i&&!Array.isArray(n)?[]:i||S.isPlainObject(n)?n:{},i=!1,a[t]=S.extend(l,o,r)):void 0!==r&&(a[t]=r));return a},S.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isPlainObject:function(e){var t,n;return!(!e||"[object Object]"!==o.call(e))&&(!(t=r(e))||"function"==typeof(n=y.call(t,"constructor")&&t.constructor)&&a.call(n)===l)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},globalEval:function(e,t,n){b(e,{nonce:t&&t.nonce},n)},each:function(e,t){var n,r=0;if(p(e)){for(n=e.length;r<n;r++)if(!1===t.call(e[r],r,e[r]))break}else for(r in e)if(!1===t.call(e[r],r,e[r]))break;return e},makeArray:function(e,t){var n=t||[];return null!=e&&(p(Object(e))?S.merge(n,"string"==typeof e?[e]:e):u.call(n,e)),n},inArray:function(e,t,n){return null==t?-1:i.call(t,e,n)},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){for(var r=[],i=0,o=e.length,a=!n;i<o;i++)!t(e[i],i)!==a&&r.push(e[i]);return r},map:function(e,t,n){var r,i,o=0,a=[];if(p(e))for(r=e.length;o<r;o++)null!=(i=t(e[o],o,n))&&a.push(i);else for(o in e)null!=(i=t(e[o],o,n))&&a.push(i);return g(a)},guid:1,support:v}),"function"==typeof Symbol&&(S.fn[Symbol.iterator]=t[Symbol.iterator]),S.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){n["[object "+t+"]"]=t.toLowerCase()});var d=function(n){var e,d,b,o,i,h,f,g,w,u,l,T,C,a,E,y,s,c,v,S="sizzle"+1*new Date,p=n.document,k=0,r=0,m=ue(),x=ue(),A=ue(),N=ue(),j=function(e,t){return e===t&&(l=!0),0},D={}.hasOwnProperty,t=[],q=t.pop,L=t.push,H=t.push,O=t.slice,P=function(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},R="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",I="(?:\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\[^\\r\\n\\f]|[\\w-]|[^\0-\\x7f])+",W="\\["+M+"*("+I+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+I+"))|)"+M+"*\\]",F=":("+I+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+W+")*)|.*)\\)|)",$=new RegExp(M+"+","g"),B=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),_=new RegExp("^"+M+"*,"+M+"*"),z=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp(M+"|>"),X=new RegExp(F),V=new RegExp("^"+I+"$"),G={ID:new RegExp("^#("+I+")"),CLASS:new RegExp("^\\.("+I+")"),TAG:new RegExp("^("+I+"|[*])"),ATTR:new RegExp("^"+W),PSEUDO:new RegExp("^"+F),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+R+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/HTML$/i,Q=/^(?:input|select|textarea|button)$/i,J=/^h\d$/i,K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ee=/[+~]/,te=new RegExp("\\\\[\\da-fA-F]{1,6}"+M+"?|\\\\([^\\r\\n\\f])","g"),ne=function(e,t){var n="0x"+e.slice(1)-65536;return t||(n<0?String.fromCharCode(n+65536):String.fromCharCode(n>>10|55296,1023&n|56320))},re=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,ie=function(e,t){return t?"\0"===e?"\ufffd":e.slice(0,-1)+"\\"+e.charCodeAt(e.length-1).toString(16)+" ":"\\"+e},oe=function(){T()},ae=be(function(e){return!0===e.disabled&&"fieldset"===e.nodeName.toLowerCase()},{dir:"parentNode",next:"legend"});try{H.apply(t=O.call(p.childNodes),p.childNodes),t[p.childNodes.length].nodeType}catch(e){H={apply:t.length?function(e,t){L.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function se(t,e,n,r){var i,o,a,s,u,l,c,f=e&&e.ownerDocument,p=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==p&&9!==p&&11!==p)return n;if(!r&&(T(e),e=e||C,E)){if(11!==p&&(u=Z.exec(t)))if(i=u[1]){if(9===p){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(f&&(a=f.getElementById(i))&&v(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return H.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&d.getElementsByClassName&&e.getElementsByClassName)return H.apply(n,e.getElementsByClassName(i)),n}if(d.qsa&&!N[t+" "]&&(!y||!y.test(t))&&(1!==p||"object"!==e.nodeName.toLowerCase())){if(c=t,f=e,1===p&&(U.test(t)||z.test(t))){(f=ee.test(t)&&ve(e.parentNode)||e)===e&&d.scope||((s=e.getAttribute("id"))?s=s.replace(re,ie):e.setAttribute("id",s=S)),o=(l=h(t)).length;while(o--)l[o]=(s?"#"+s:":scope")+" "+xe(l[o]);c=l.join(",")}try{return H.apply(n,f.querySelectorAll(c)),n}catch(e){N(t,!0)}finally{s===S&&e.removeAttribute("id")}}}return g(t.replace(B,"$1"),e,n,r)}function ue(){var r=[];return function e(t,n){return r.push(t+" ")>b.cacheLength&&delete e[r.shift()],e[t+" "]=n}}function le(e){return e[S]=!0,e}function ce(e){var t=C.createElement("fieldset");try{return!!e(t)}catch(e){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function fe(e,t){var n=e.split("|"),r=n.length;while(r--)b.attrHandle[n[r]]=t}function pe(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&e.sourceIndex-t.sourceIndex;if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function de(t){return function(e){return"input"===e.nodeName.toLowerCase()&&e.type===t}}function he(n){return function(e){var t=e.nodeName.toLowerCase();return("input"===t||"button"===t)&&e.type===n}}function ge(t){return function(e){return"form"in e?e.parentNode&&!1===e.disabled?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&ae(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function ye(a){return le(function(o){return o=+o,le(function(e,t){var n,r=a([],e.length,o),i=r.length;while(i--)e[n=r[i]]&&(e[n]=!(t[n]=e[n]))})})}function ve(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}for(e in d=se.support={},i=se.isXML=function(e){var t=e&&e.namespaceURI,n=e&&(e.ownerDocument||e).documentElement;return!Y.test(t||n&&n.nodeName||"HTML")},T=se.setDocument=function(e){var t,n,r=e?e.ownerDocument||e:p;return r!=C&&9===r.nodeType&&r.documentElement&&(a=(C=r).documentElement,E=!i(C),p!=C&&(n=C.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",oe,!1):n.attachEvent&&n.attachEvent("onunload",oe)),d.scope=ce(function(e){return a.appendChild(e).appendChild(C.createElement("div")),"undefined"!=typeof e.querySelectorAll&&!e.querySelectorAll(":scope fieldset div").length}),d.attributes=ce(function(e){return e.className="i",!e.getAttribute("className")}),d.getElementsByTagName=ce(function(e){return e.appendChild(C.createComment("")),!e.getElementsByTagName("*").length}),d.getElementsByClassName=K.test(C.getElementsByClassName),d.getById=ce(function(e){return a.appendChild(e).id=S,!C.getElementsByName||!C.getElementsByName(S).length}),d.getById?(b.filter.ID=function(e){var t=e.replace(te,ne);return function(e){return e.getAttribute("id")===t}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n=t.getElementById(e);return n?[n]:[]}}):(b.filter.ID=function(e){var n=e.replace(te,ne);return function(e){var t="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return t&&t.value===n}},b.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&E){var n,r,i,o=t.getElementById(e);if(o){if((n=o.getAttributeNode("id"))&&n.value===e)return[o];i=t.getElementsByName(e),r=0;while(o=i[r++])if((n=o.getAttributeNode("id"))&&n.value===e)return[o]}return[]}}),b.find.TAG=d.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):d.qsa?t.querySelectorAll(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},b.find.CLASS=d.getElementsByClassName&&function(e,t){if("undefined"!=typeof t.getElementsByClassName&&E)return t.getElementsByClassName(e)},s=[],y=[],(d.qsa=K.test(C.querySelectorAll))&&(ce(function(e){var t;a.appendChild(e).innerHTML="<a id='"+S+"'></a><select id='"+S+"-\r\\' msallowcapture=''><option selected=''></option></select>",e.querySelectorAll("[msallowcapture^='']").length&&y.push("[*^$]="+M+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||y.push("\\["+M+"*(?:value|"+R+")"),e.querySelectorAll("[id~="+S+"-]").length||y.push("~="),(t=C.createElement("input")).setAttribute("name",""),e.appendChild(t),e.querySelectorAll("[name='']").length||y.push("\\["+M+"*name"+M+"*="+M+"*(?:''|\"\")"),e.querySelectorAll(":checked").length||y.push(":checked"),e.querySelectorAll("a#"+S+"+*").length||y.push(".#.+[+~]"),e.querySelectorAll("\\\f"),y.push("[\\r\\n\\f]")}),ce(function(e){e.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var t=C.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&y.push("name"+M+"*[*^$|!~]?="),2!==e.querySelectorAll(":enabled").length&&y.push(":enabled",":disabled"),a.appendChild(e).disabled=!0,2!==e.querySelectorAll(":disabled").length&&y.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),y.push(",.*:")})),(d.matchesSelector=K.test(c=a.matches||a.webkitMatchesSelector||a.mozMatchesSelector||a.oMatchesSelector||a.msMatchesSelector))&&ce(function(e){d.disconnectedMatch=c.call(e,"*"),c.call(e,"[s!='']:x"),s.push("!=",F)}),y=y.length&&new RegExp(y.join("|")),s=s.length&&new RegExp(s.join("|")),t=K.test(a.compareDocumentPosition),v=t||K.test(a.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},j=t?function(e,t){if(e===t)return l=!0,0;var n=!e.compareDocumentPosition-!t.compareDocumentPosition;return n||(1&(n=(e.ownerDocument||e)==(t.ownerDocument||t)?e.compareDocumentPosition(t):1)||!d.sortDetached&&t.compareDocumentPosition(e)===n?e==C||e.ownerDocument==p&&v(p,e)?-1:t==C||t.ownerDocument==p&&v(p,t)?1:u?P(u,e)-P(u,t):0:4&n?-1:1)}:function(e,t){if(e===t)return l=!0,0;var n,r=0,i=e.parentNode,o=t.parentNode,a=[e],s=[t];if(!i||!o)return e==C?-1:t==C?1:i?-1:o?1:u?P(u,e)-P(u,t):0;if(i===o)return pe(e,t);n=e;while(n=n.parentNode)a.unshift(n);n=t;while(n=n.parentNode)s.unshift(n);while(a[r]===s[r])r++;return r?pe(a[r],s[r]):a[r]==p?-1:s[r]==p?1:0}),C},se.matches=function(e,t){return se(e,null,null,t)},se.matchesSelector=function(e,t){if(T(e),d.matchesSelector&&E&&!N[t+" "]&&(!s||!s.test(t))&&(!y||!y.test(t)))try{var n=c.call(e,t);if(n||d.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(e){N(t,!0)}return 0<se(t,C,null,[e]).length},se.contains=function(e,t){return(e.ownerDocument||e)!=C&&T(e),v(e,t)},se.attr=function(e,t){(e.ownerDocument||e)!=C&&T(e);var n=b.attrHandle[t.toLowerCase()],r=n&&D.call(b.attrHandle,t.toLowerCase())?n(e,t,!E):void 0;return void 0!==r?r:d.attributes||!E?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},se.escape=function(e){return(e+"").replace(re,ie)},se.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},se.uniqueSort=function(e){var t,n=[],r=0,i=0;if(l=!d.detectDuplicates,u=!d.sortStable&&e.slice(0),e.sort(j),l){while(t=e[i++])t===e[i]&&(r=n.push(i));while(r--)e.splice(n[r],1)}return u=null,e},o=se.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else while(t=e[r++])n+=o(t);return n},(b=se.selectors={cacheLength:50,createPseudo:le,match:G,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(te,ne),e[3]=(e[3]||e[4]||e[5]||"").replace(te,ne),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||se.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&se.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return G.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&X.test(n)&&(t=h(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(te,ne).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=m[e+" "];return t||(t=new RegExp("(^|"+M+")"+e+"("+M+"|$)"))&&m(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(n,r,i){return function(e){var t=se.attr(e,n);return null==t?"!="===r:!r||(t+="","="===r?t===i:"!="===r?t!==i:"^="===r?i&&0===t.indexOf(i):"*="===r?i&&-1<t.indexOf(i):"$="===r?i&&t.slice(-i.length)===i:"~="===r?-1<(" "+t.replace($," ")+" ").indexOf(i):"|="===r&&(t===i||t.slice(0,i.length+1)===i+"-"))}},CHILD:function(h,e,t,g,y){var v="nth"!==h.slice(0,3),m="last"!==h.slice(-4),x="of-type"===e;return 1===g&&0===y?function(e){return!!e.parentNode}:function(e,t,n){var r,i,o,a,s,u,l=v!==m?"nextSibling":"previousSibling",c=e.parentNode,f=x&&e.nodeName.toLowerCase(),p=!n&&!x,d=!1;if(c){if(v){while(l){a=e;while(a=a[l])if(x?a.nodeName.toLowerCase()===f:1===a.nodeType)return!1;u=l="only"===h&&!u&&"nextSibling"}return!0}if(u=[m?c.firstChild:c.lastChild],m&&p){d=(s=(r=(i=(o=(a=c)[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===k&&r[1])&&r[2],a=s&&c.childNodes[s];while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if(1===a.nodeType&&++d&&a===e){i[h]=[k,s,d];break}}else if(p&&(d=s=(r=(i=(o=(a=e)[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]||[])[0]===k&&r[1]),!1===d)while(a=++s&&a&&a[l]||(d=s=0)||u.pop())if((x?a.nodeName.toLowerCase()===f:1===a.nodeType)&&++d&&(p&&((i=(o=a[S]||(a[S]={}))[a.uniqueID]||(o[a.uniqueID]={}))[h]=[k,d]),a===e))break;return(d-=y)===g||d%g==0&&0<=d/g}}},PSEUDO:function(e,o){var t,a=b.pseudos[e]||b.setFilters[e.toLowerCase()]||se.error("unsupported pseudo: "+e);return a[S]?a(o):1<a.length?(t=[e,e,"",o],b.setFilters.hasOwnProperty(e.toLowerCase())?le(function(e,t){var n,r=a(e,o),i=r.length;while(i--)e[n=P(e,r[i])]=!(t[n]=r[i])}):function(e){return a(e,0,t)}):a}},pseudos:{not:le(function(e){var r=[],i=[],s=f(e.replace(B,"$1"));return s[S]?le(function(e,t,n,r){var i,o=s(e,null,r,[]),a=e.length;while(a--)(i=o[a])&&(e[a]=!(t[a]=i))}):function(e,t,n){return r[0]=e,s(r,null,n,i),r[0]=null,!i.pop()}}),has:le(function(t){return function(e){return 0<se(t,e).length}}),contains:le(function(t){return t=t.replace(te,ne),function(e){return-1<(e.textContent||o(e)).indexOf(t)}}),lang:le(function(n){return V.test(n||"")||se.error("unsupported lang: "+n),n=n.replace(te,ne).toLowerCase(),function(e){var t;do{if(t=E?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return(t=t.toLowerCase())===n||0===t.indexOf(n+"-")}while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var t=n.location&&n.location.hash;return t&&t.slice(1)===e.id},root:function(e){return e===a},focus:function(e){return e===C.activeElement&&(!C.hasFocus||C.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:ge(!1),disabled:ge(!0),checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,!0===e.selected},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!b.pseudos.empty(e)},header:function(e){return J.test(e.nodeName)},input:function(e){return Q.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:ye(function(){return[0]}),last:ye(function(e,t){return[t-1]}),eq:ye(function(e,t,n){return[n<0?n+t:n]}),even:ye(function(e,t){for(var n=0;n<t;n+=2)e.push(n);return e}),odd:ye(function(e,t){for(var n=1;n<t;n+=2)e.push(n);return e}),lt:ye(function(e,t,n){for(var r=n<0?n+t:t<n?t:n;0<=--r;)e.push(r);return e}),gt:ye(function(e,t,n){for(var r=n<0?n+t:n;++r<t;)e.push(r);return e})}}).pseudos.nth=b.pseudos.eq,{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})b.pseudos[e]=de(e);for(e in{submit:!0,reset:!0})b.pseudos[e]=he(e);function me(){}function xe(e){for(var t=0,n=e.length,r="";t<n;t++)r+=e[t].value;return r}function be(s,e,t){var u=e.dir,l=e.next,c=l||u,f=t&&"parentNode"===c,p=r++;return e.first?function(e,t,n){while(e=e[u])if(1===e.nodeType||f)return s(e,t,n);return!1}:function(e,t,n){var r,i,o,a=[k,p];if(n){while(e=e[u])if((1===e.nodeType||f)&&s(e,t,n))return!0}else while(e=e[u])if(1===e.nodeType||f)if(i=(o=e[S]||(e[S]={}))[e.uniqueID]||(o[e.uniqueID]={}),l&&l===e.nodeName.toLowerCase())e=e[u]||e;else{if((r=i[c])&&r[0]===k&&r[1]===p)return a[2]=r[2];if((i[c]=a)[2]=s(e,t,n))return!0}return!1}}function we(i){return 1<i.length?function(e,t,n){var r=i.length;while(r--)if(!i[r](e,t,n))return!1;return!0}:i[0]}function Te(e,t,n,r,i){for(var o,a=[],s=0,u=e.length,l=null!=t;s<u;s++)(o=e[s])&&(n&&!n(o,r,i)||(a.push(o),l&&t.push(s)));return a}function Ce(d,h,g,y,v,e){return y&&!y[S]&&(y=Ce(y)),v&&!v[S]&&(v=Ce(v,e)),le(function(e,t,n,r){var i,o,a,s=[],u=[],l=t.length,c=e||function(e,t,n){for(var r=0,i=t.length;r<i;r++)se(e,t[r],n);return n}(h||"*",n.nodeType?[n]:n,[]),f=!d||!e&&h?c:Te(c,s,d,n,r),p=g?v||(e?d:l||y)?[]:t:f;if(g&&g(f,p,n,r),y){i=Te(p,u),y(i,[],n,r),o=i.length;while(o--)(a=i[o])&&(p[u[o]]=!(f[u[o]]=a))}if(e){if(v||d){if(v){i=[],o=p.length;while(o--)(a=p[o])&&i.push(f[o]=a);v(null,p=[],i,r)}o=p.length;while(o--)(a=p[o])&&-1<(i=v?P(e,a):s[o])&&(e[i]=!(t[i]=a))}}else p=Te(p===t?p.splice(l,p.length):p),v?v(null,t,p,r):H.apply(t,p)})}function Ee(e){for(var i,t,n,r=e.length,o=b.relative[e[0].type],a=o||b.relative[" "],s=o?1:0,u=be(function(e){return e===i},a,!0),l=be(function(e){return-1<P(i,e)},a,!0),c=[function(e,t,n){var r=!o&&(n||t!==w)||((i=t).nodeType?u(e,t,n):l(e,t,n));return i=null,r}];s<r;s++)if(t=b.relative[e[s].type])c=[be(we(c),t)];else{if((t=b.filter[e[s].type].apply(null,e[s].matches))[S]){for(n=++s;n<r;n++)if(b.relative[e[n].type])break;return Ce(1<s&&we(c),1<s&&xe(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(B,"$1"),t,s<n&&Ee(e.slice(s,n)),n<r&&Ee(e=e.slice(n)),n<r&&xe(e))}c.push(t)}return we(c)}return me.prototype=b.filters=b.pseudos,b.setFilters=new me,h=se.tokenize=function(e,t){var n,r,i,o,a,s,u,l=x[e+" "];if(l)return t?0:l.slice(0);a=e,s=[],u=b.preFilter;while(a){for(o in n&&!(r=_.exec(a))||(r&&(a=a.slice(r[0].length)||a),s.push(i=[])),n=!1,(r=z.exec(a))&&(n=r.shift(),i.push({value:n,type:r[0].replace(B," ")}),a=a.slice(n.length)),b.filter)!(r=G[o].exec(a))||u[o]&&!(r=u[o](r))||(n=r.shift(),i.push({value:n,type:o,matches:r}),a=a.slice(n.length));if(!n)break}return t?a.length:a?se.error(e):x(e,s).slice(0)},f=se.compile=function(e,t){var n,y,v,m,x,r,i=[],o=[],a=A[e+" "];if(!a){t||(t=h(e)),n=t.length;while(n--)(a=Ee(t[n]))[S]?i.push(a):o.push(a);(a=A(e,(y=o,m=0<(v=i).length,x=0<y.length,r=function(e,t,n,r,i){var o,a,s,u=0,l="0",c=e&&[],f=[],p=w,d=e||x&&b.find.TAG("*",i),h=k+=null==p?1:Math.random()||.1,g=d.length;for(i&&(w=t==C||t||i);l!==g&&null!=(o=d[l]);l++){if(x&&o){a=0,t||o.ownerDocument==C||(T(o),n=!E);while(s=y[a++])if(s(o,t||C,n)){r.push(o);break}i&&(k=h)}m&&((o=!s&&o)&&u--,e&&c.push(o))}if(u+=l,m&&l!==u){a=0;while(s=v[a++])s(c,f,t,n);if(e){if(0<u)while(l--)c[l]||f[l]||(f[l]=q.call(r));f=Te(f)}H.apply(r,f),i&&!e&&0<f.length&&1<u+v.length&&se.uniqueSort(r)}return i&&(k=h,w=p),c},m?le(r):r))).selector=e}return a},g=se.select=function(e,t,n,r){var i,o,a,s,u,l="function"==typeof e&&e,c=!r&&h(e=l.selector||e);if(n=n||[],1===c.length){if(2<(o=c[0]=c[0].slice(0)).length&&"ID"===(a=o[0]).type&&9===t.nodeType&&E&&b.relative[o[1].type]){if(!(t=(b.find.ID(a.matches[0].replace(te,ne),t)||[])[0]))return n;l&&(t=t.parentNode),e=e.slice(o.shift().value.length)}i=G.needsContext.test(e)?0:o.length;while(i--){if(a=o[i],b.relative[s=a.type])break;if((u=b.find[s])&&(r=u(a.matches[0].replace(te,ne),ee.test(o[0].type)&&ve(t.parentNode)||t))){if(o.splice(i,1),!(e=r.length&&xe(o)))return H.apply(n,r),n;break}}}return(l||f(e,c))(r,t,!E,n,!t||ee.test(e)&&ve(t.parentNode)||t),n},d.sortStable=S.split("").sort(j).join("")===S,d.detectDuplicates=!!l,T(),d.sortDetached=ce(function(e){return 1&e.compareDocumentPosition(C.createElement("fieldset"))}),ce(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||fe("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),d.attributes&&ce(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||fe("value",function(e,t,n){if(!n&&"input"===e.nodeName.toLowerCase())return e.defaultValue}),ce(function(e){return null==e.getAttribute("disabled")})||fe(R,function(e,t,n){var r;if(!n)return!0===e[t]?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),se}(C);S.find=d,S.expr=d.selectors,S.expr[":"]=S.expr.pseudos,S.uniqueSort=S.unique=d.uniqueSort,S.text=d.getText,S.isXMLDoc=d.isXML,S.contains=d.contains,S.escapeSelector=d.escape;var h=function(e,t,n){var r=[],i=void 0!==n;while((e=e[t])&&9!==e.nodeType)if(1===e.nodeType){if(i&&S(e).is(n))break;r.push(e)}return r},T=function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n},k=S.expr.match.needsContext;function A(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()}var N=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i;function j(e,n,r){return m(n)?S.grep(e,function(e,t){return!!n.call(e,t,e)!==r}):n.nodeType?S.grep(e,function(e){return e===n!==r}):"string"!=typeof n?S.grep(e,function(e){return-1<i.call(n,e)!==r}):S.filter(n,e,r)}S.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?S.find.matchesSelector(r,e)?[r]:[]:S.find.matches(e,S.grep(t,function(e){return 1===e.nodeType}))},S.fn.extend({find:function(e){var t,n,r=this.length,i=this;if("string"!=typeof e)return this.pushStack(S(e).filter(function(){for(t=0;t<r;t++)if(S.contains(i[t],this))return!0}));for(n=this.pushStack([]),t=0;t<r;t++)S.find(e,i[t],n);return 1<r?S.uniqueSort(n):n},filter:function(e){return this.pushStack(j(this,e||[],!1))},not:function(e){return this.pushStack(j(this,e||[],!0))},is:function(e){return!!j(this,"string"==typeof e&&k.test(e)?S(e):e||[],!1).length}});var D,q=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/;(S.fn.init=function(e,t,n){var r,i;if(!e)return this;if(n=n||D,"string"==typeof e){if(!(r="<"===e[0]&&">"===e[e.length-1]&&3<=e.length?[null,e,null]:q.exec(e))||!r[1]&&t)return!t||t.jquery?(t||n).find(e):this.constructor(t).find(e);if(r[1]){if(t=t instanceof S?t[0]:t,S.merge(this,S.parseHTML(r[1],t&&t.nodeType?t.ownerDocument||t:E,!0)),N.test(r[1])&&S.isPlainObject(t))for(r in t)m(this[r])?this[r](t[r]):this.attr(r,t[r]);return this}return(i=E.getElementById(r[2]))&&(this[0]=i,this.length=1),this}return e.nodeType?(this[0]=e,this.length=1,this):m(e)?void 0!==n.ready?n.ready(e):e(S):S.makeArray(e,this)}).prototype=S.fn,D=S(E);var L=/^(?:parents|prev(?:Until|All))/,H={children:!0,contents:!0,next:!0,prev:!0};function O(e,t){while((e=e[t])&&1!==e.nodeType);return e}S.fn.extend({has:function(e){var t=S(e,this),n=t.length;return this.filter(function(){for(var e=0;e<n;e++)if(S.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,o=[],a="string"!=typeof e&&S(e);if(!k.test(e))for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?-1<a.index(n):1===n.nodeType&&S.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(1<o.length?S.uniqueSort(o):o)},index:function(e){return e?"string"==typeof e?i.call(S(e),this[0]):i.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(S.uniqueSort(S.merge(this.get(),S(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),S.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return h(e,"parentNode")},parentsUntil:function(e,t,n){return h(e,"parentNode",n)},next:function(e){return O(e,"nextSibling")},prev:function(e){return O(e,"previousSibling")},nextAll:function(e){return h(e,"nextSibling")},prevAll:function(e){return h(e,"previousSibling")},nextUntil:function(e,t,n){return h(e,"nextSibling",n)},prevUntil:function(e,t,n){return h(e,"previousSibling",n)},siblings:function(e){return T((e.parentNode||{}).firstChild,e)},children:function(e){return T(e.firstChild)},contents:function(e){return null!=e.contentDocument&&r(e.contentDocument)?e.contentDocument:(A(e,"template")&&(e=e.content||e),S.merge([],e.childNodes))}},function(r,i){S.fn[r]=function(e,t){var n=S.map(this,i,e);return"Until"!==r.slice(-5)&&(t=e),t&&"string"==typeof t&&(n=S.filter(t,n)),1<this.length&&(H[r]||S.uniqueSort(n),L.test(r)&&n.reverse()),this.pushStack(n)}});var P=/[^\x20\t\r\n\f]+/g;function R(e){return e}function M(e){throw e}function I(e,t,n,r){var i;try{e&&m(i=e.promise)?i.call(e).done(t).fail(n):e&&m(i=e.then)?i.call(e,t,n):t.apply(void 0,[e].slice(r))}catch(e){n.apply(void 0,[e])}}S.Callbacks=function(r){var e,n;r="string"==typeof r?(e=r,n={},S.each(e.match(P)||[],function(e,t){n[t]=!0}),n):S.extend({},r);var i,t,o,a,s=[],u=[],l=-1,c=function(){for(a=a||r.once,o=i=!0;u.length;l=-1){t=u.shift();while(++l<s.length)!1===s[l].apply(t[0],t[1])&&r.stopOnFalse&&(l=s.length,t=!1)}r.memory||(t=!1),i=!1,a&&(s=t?[]:"")},f={add:function(){return s&&(t&&!i&&(l=s.length-1,u.push(t)),function n(e){S.each(e,function(e,t){m(t)?r.unique&&f.has(t)||s.push(t):t&&t.length&&"string"!==w(t)&&n(t)})}(arguments),t&&!i&&c()),this},remove:function(){return S.each(arguments,function(e,t){var n;while(-1<(n=S.inArray(t,s,n)))s.splice(n,1),n<=l&&l--}),this},has:function(e){return e?-1<S.inArray(e,s):0<s.length},empty:function(){return s&&(s=[]),this},disable:function(){return a=u=[],s=t="",this},disabled:function(){return!s},lock:function(){return a=u=[],t||i||(s=t=""),this},locked:function(){return!!a},fireWith:function(e,t){return a||(t=[e,(t=t||[]).slice?t.slice():t],u.push(t),i||c()),this},fire:function(){return f.fireWith(this,arguments),this},fired:function(){return!!o}};return f},S.extend({Deferred:function(e){var o=[["notify","progress",S.Callbacks("memory"),S.Callbacks("memory"),2],["resolve","done",S.Callbacks("once memory"),S.Callbacks("once memory"),0,"resolved"],["reject","fail",S.Callbacks("once memory"),S.Callbacks("once memory"),1,"rejected"]],i="pending",a={state:function(){return i},always:function(){return s.done(arguments).fail(arguments),this},"catch":function(e){return a.then(null,e)},pipe:function(){var i=arguments;return S.Deferred(function(r){S.each(o,function(e,t){var n=m(i[t[4]])&&i[t[4]];s[t[1]](function(){var e=n&&n.apply(this,arguments);e&&m(e.promise)?e.promise().progress(r.notify).done(r.resolve).fail(r.reject):r[t[0]+"With"](this,n?[e]:arguments)})}),i=null}).promise()},then:function(t,n,r){var u=0;function l(i,o,a,s){return function(){var n=this,r=arguments,e=function(){var e,t;if(!(i<u)){if((e=a.apply(n,r))===o.promise())throw new TypeError("Thenable self-resolution");t=e&&("object"==typeof e||"function"==typeof e)&&e.then,m(t)?s?t.call(e,l(u,o,R,s),l(u,o,M,s)):(u++,t.call(e,l(u,o,R,s),l(u,o,M,s),l(u,o,R,o.notifyWith))):(a!==R&&(n=void 0,r=[e]),(s||o.resolveWith)(n,r))}},t=s?e:function(){try{e()}catch(e){S.Deferred.exceptionHook&&S.Deferred.exceptionHook(e,t.stackTrace),u<=i+1&&(a!==M&&(n=void 0,r=[e]),o.rejectWith(n,r))}};i?t():(S.Deferred.getStackHook&&(t.stackTrace=S.Deferred.getStackHook()),C.setTimeout(t))}}return S.Deferred(function(e){o[0][3].add(l(0,e,m(r)?r:R,e.notifyWith)),o[1][3].add(l(0,e,m(t)?t:R)),o[2][3].add(l(0,e,m(n)?n:M))}).promise()},promise:function(e){return null!=e?S.extend(e,a):a}},s={};return S.each(o,function(e,t){var n=t[2],r=t[5];a[t[1]]=n.add,r&&n.add(function(){i=r},o[3-e][2].disable,o[3-e][3].disable,o[0][2].lock,o[0][3].lock),n.add(t[3].fire),s[t[0]]=function(){return s[t[0]+"With"](this===s?void 0:this,arguments),this},s[t[0]+"With"]=n.fireWith}),a.promise(s),e&&e.call(s,s),s},when:function(e){var n=arguments.length,t=n,r=Array(t),i=s.call(arguments),o=S.Deferred(),a=function(t){return function(e){r[t]=this,i[t]=1<arguments.length?s.call(arguments):e,--n||o.resolveWith(r,i)}};if(n<=1&&(I(e,o.done(a(t)).resolve,o.reject,!n),"pending"===o.state()||m(i[t]&&i[t].then)))return o.then();while(t--)I(i[t],a(t),o.reject);return o.promise()}});var W=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;S.Deferred.exceptionHook=function(e,t){C.console&&C.console.warn&&e&&W.test(e.name)&&C.console.warn("jQuery.Deferred exception: "+e.message,e.stack,t)},S.readyException=function(e){C.setTimeout(function(){throw e})};var F=S.Deferred();function $(){E.removeEventListener("DOMContentLoaded",$),C.removeEventListener("load",$),S.ready()}S.fn.ready=function(e){return F.then(e)["catch"](function(e){S.readyException(e)}),this},S.extend({isReady:!1,readyWait:1,ready:function(e){(!0===e?--S.readyWait:S.isReady)||(S.isReady=!0)!==e&&0<--S.readyWait||F.resolveWith(E,[S])}}),S.ready.then=F.then,"complete"===E.readyState||"loading"!==E.readyState&&!E.documentElement.doScroll?C.setTimeout(S.ready):(E.addEventListener("DOMContentLoaded",$),C.addEventListener("load",$));var B=function(e,t,n,r,i,o,a){var s=0,u=e.length,l=null==n;if("object"===w(n))for(s in i=!0,n)B(e,t,s,n[s],!0,o,a);else if(void 0!==r&&(i=!0,m(r)||(a=!0),l&&(a?(t.call(e,r),t=null):(l=t,t=function(e,t,n){return l.call(S(e),n)})),t))for(;s<u;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:l?t.call(e):u?t(e[0],n):o},_=/^-ms-/,z=/-([a-z])/g;function U(e,t){return t.toUpperCase()}function X(e){return e.replace(_,"ms-").replace(z,U)}var V=function(e){return 1===e.nodeType||9===e.nodeType||!+e.nodeType};function G(){this.expando=S.expando+G.uid++}G.uid=1,G.prototype={cache:function(e){var t=e[this.expando];return t||(t={},V(e)&&(e.nodeType?e[this.expando]=t:Object.defineProperty(e,this.expando,{value:t,configurable:!0}))),t},set:function(e,t,n){var r,i=this.cache(e);if("string"==typeof t)i[X(t)]=n;else for(r in t)i[X(r)]=t[r];return i},get:function(e,t){return void 0===t?this.cache(e):e[this.expando]&&e[this.expando][X(t)]},access:function(e,t,n){return void 0===t||t&&"string"==typeof t&&void 0===n?this.get(e,t):(this.set(e,t,n),void 0!==n?n:t)},remove:function(e,t){var n,r=e[this.expando];if(void 0!==r){if(void 0!==t){n=(t=Array.isArray(t)?t.map(X):(t=X(t))in r?[t]:t.match(P)||[]).length;while(n--)delete r[t[n]]}(void 0===t||S.isEmptyObject(r))&&(e.nodeType?e[this.expando]=void 0:delete e[this.expando])}},hasData:function(e){var t=e[this.expando];return void 0!==t&&!S.isEmptyObject(t)}};var Y=new G,Q=new G,J=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,K=/[A-Z]/g;function Z(e,t,n){var r,i;if(void 0===n&&1===e.nodeType)if(r="data-"+t.replace(K,"-$&").toLowerCase(),"string"==typeof(n=e.getAttribute(r))){try{n="true"===(i=n)||"false"!==i&&("null"===i?null:i===+i+""?+i:J.test(i)?JSON.parse(i):i)}catch(e){}Q.set(e,t,n)}else n=void 0;return n}S.extend({hasData:function(e){return Q.hasData(e)||Y.hasData(e)},data:function(e,t,n){return Q.access(e,t,n)},removeData:function(e,t){Q.remove(e,t)},_data:function(e,t,n){return Y.access(e,t,n)},_removeData:function(e,t){Y.remove(e,t)}}),S.fn.extend({data:function(n,e){var t,r,i,o=this[0],a=o&&o.attributes;if(void 0===n){if(this.length&&(i=Q.get(o),1===o.nodeType&&!Y.get(o,"hasDataAttrs"))){t=a.length;while(t--)a[t]&&0===(r=a[t].name).indexOf("data-")&&(r=X(r.slice(5)),Z(o,r,i[r]));Y.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof n?this.each(function(){Q.set(this,n)}):B(this,function(e){var t;if(o&&void 0===e)return void 0!==(t=Q.get(o,n))?t:void 0!==(t=Z(o,n))?t:void 0;this.each(function(){Q.set(this,n,e)})},null,e,1<arguments.length,null,!0)},removeData:function(e){return this.each(function(){Q.remove(this,e)})}}),S.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=Y.get(e,t),n&&(!r||Array.isArray(n)?r=Y.access(e,t,S.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=S.queue(e,t),r=n.length,i=n.shift(),o=S._queueHooks(e,t);"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,function(){S.dequeue(e,t)},o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return Y.get(e,n)||Y.access(e,n,{empty:S.Callbacks("once memory").add(function(){Y.remove(e,[t+"queue",n])})})}}),S.fn.extend({queue:function(t,n){var e=2;return"string"!=typeof t&&(n=t,t="fx",e--),arguments.length<e?S.queue(this[0],t):void 0===n?this:this.each(function(){var e=S.queue(this,t,n);S._queueHooks(this,t),"fx"===t&&"inprogress"!==e[0]&&S.dequeue(this,t)})},dequeue:function(e){return this.each(function(){S.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=S.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};"string"!=typeof e&&(t=e,e=void 0),e=e||"fx";while(a--)(n=Y.get(o[a],e+"queueHooks"))&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var ee=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,te=new RegExp("^(?:([+-])=|)("+ee+")([a-z%]*)$","i"),ne=["Top","Right","Bottom","Left"],re=E.documentElement,ie=function(e){return S.contains(e.ownerDocument,e)},oe={composed:!0};re.getRootNode&&(ie=function(e){return S.contains(e.ownerDocument,e)||e.getRootNode(oe)===e.ownerDocument});var ae=function(e,t){return"none"===(e=t||e).style.display||""===e.style.display&&ie(e)&&"none"===S.css(e,"display")};function se(e,t,n,r){var i,o,a=20,s=r?function(){return r.cur()}:function(){return S.css(e,t,"")},u=s(),l=n&&n[3]||(S.cssNumber[t]?"":"px"),c=e.nodeType&&(S.cssNumber[t]||"px"!==l&&+u)&&te.exec(S.css(e,t));if(c&&c[3]!==l){u/=2,l=l||c[3],c=+u||1;while(a--)S.style(e,t,c+l),(1-o)*(1-(o=s()/u||.5))<=0&&(a=0),c/=o;c*=2,S.style(e,t,c+l),n=n||[]}return n&&(c=+c||+u||0,i=n[1]?c+(n[1]+1)*n[2]:+n[2],r&&(r.unit=l,r.start=c,r.end=i)),i}var ue={};function le(e,t){for(var n,r,i,o,a,s,u,l=[],c=0,f=e.length;c<f;c++)(r=e[c]).style&&(n=r.style.display,t?("none"===n&&(l[c]=Y.get(r,"display")||null,l[c]||(r.style.display="")),""===r.style.display&&ae(r)&&(l[c]=(u=a=o=void 0,a=(i=r).ownerDocument,s=i.nodeName,(u=ue[s])||(o=a.body.appendChild(a.createElement(s)),u=S.css(o,"display"),o.parentNode.removeChild(o),"none"===u&&(u="block"),ue[s]=u)))):"none"!==n&&(l[c]="none",Y.set(r,"display",n)));for(c=0;c<f;c++)null!=l[c]&&(e[c].style.display=l[c]);return e}S.fn.extend({show:function(){return le(this,!0)},hide:function(){return le(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){ae(this)?S(this).show():S(this).hide()})}});var ce,fe,pe=/^(?:checkbox|radio)$/i,de=/<([a-z][^\/\0>\x20\t\r\n\f]*)/i,he=/^$|^module$|\/(?:java|ecma)script/i;ce=E.createDocumentFragment().appendChild(E.createElement("div")),(fe=E.createElement("input")).setAttribute("type","radio"),fe.setAttribute("checked","checked"),fe.setAttribute("name","t"),ce.appendChild(fe),v.checkClone=ce.cloneNode(!0).cloneNode(!0).lastChild.checked,ce.innerHTML="<textarea>x</textarea>",v.noCloneChecked=!!ce.cloneNode(!0).lastChild.defaultValue,ce.innerHTML="<option></option>",v.option=!!ce.lastChild;var ge={thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};function ye(e,t){var n;return n="undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t||"*"):"undefined"!=typeof e.querySelectorAll?e.querySelectorAll(t||"*"):[],void 0===t||t&&A(e,t)?S.merge([e],n):n}function ve(e,t){for(var n=0,r=e.length;n<r;n++)Y.set(e[n],"globalEval",!t||Y.get(t[n],"globalEval"))}ge.tbody=ge.tfoot=ge.colgroup=ge.caption=ge.thead,ge.th=ge.td,v.option||(ge.optgroup=ge.option=[1,"<select multiple='multiple'>","</select>"]);var me=/<|&#?\w+;/;function xe(e,t,n,r,i){for(var o,a,s,u,l,c,f=t.createDocumentFragment(),p=[],d=0,h=e.length;d<h;d++)if((o=e[d])||0===o)if("object"===w(o))S.merge(p,o.nodeType?[o]:o);else if(me.test(o)){a=a||f.appendChild(t.createElement("div")),s=(de.exec(o)||["",""])[1].toLowerCase(),u=ge[s]||ge._default,a.innerHTML=u[1]+S.htmlPrefilter(o)+u[2],c=u[0];while(c--)a=a.lastChild;S.merge(p,a.childNodes),(a=f.firstChild).textContent=""}else p.push(t.createTextNode(o));f.textContent="",d=0;while(o=p[d++])if(r&&-1<S.inArray(o,r))i&&i.push(o);else if(l=ie(o),a=ye(f.appendChild(o),"script"),l&&ve(a),n){c=0;while(o=a[c++])he.test(o.type||"")&&n.push(o)}return f}var be=/^([^.]*)(?:\.(.+)|)/;function we(){return!0}function Te(){return!1}function Ce(e,t){return e===function(){try{return E.activeElement}catch(e){}}()==("focus"===t)}function Ee(e,t,n,r,i,o){var a,s;if("object"==typeof t){for(s in"string"!=typeof n&&(r=r||n,n=void 0),t)Ee(e,s,n,r,t[s],o);return e}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),!1===i)i=Te;else if(!i)return e;return 1===o&&(a=i,(i=function(e){return S().off(e),a.apply(this,arguments)}).guid=a.guid||(a.guid=S.guid++)),e.each(function(){S.event.add(this,t,i,r,n)})}function Se(e,i,o){o?(Y.set(e,i,!1),S.event.add(e,i,{namespace:!1,handler:function(e){var t,n,r=Y.get(this,i);if(1&e.isTrigger&&this[i]){if(r.length)(S.event.special[i]||{}).delegateType&&e.stopPropagation();else if(r=s.call(arguments),Y.set(this,i,r),t=o(this,i),this[i](),r!==(n=Y.get(this,i))||t?Y.set(this,i,!1):n={},r!==n)return e.stopImmediatePropagation(),e.preventDefault(),n&&n.value}else r.length&&(Y.set(this,i,{value:S.event.trigger(S.extend(r[0],S.Event.prototype),r.slice(1),this)}),e.stopImmediatePropagation())}})):void 0===Y.get(e,i)&&S.event.add(e,i,we)}S.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=Y.get(t);if(V(t)){n.handler&&(n=(o=n).handler,i=o.selector),i&&S.find.matchesSelector(re,i),n.guid||(n.guid=S.guid++),(u=y.events)||(u=y.events=Object.create(null)),(a=y.handle)||(a=y.handle=function(e){return"undefined"!=typeof S&&S.event.triggered!==e.type?S.event.dispatch.apply(t,arguments):void 0}),l=(e=(e||"").match(P)||[""]).length;while(l--)d=g=(s=be.exec(e[l])||[])[1],h=(s[2]||"").split(".").sort(),d&&(f=S.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=S.event.special[d]||{},c=S.extend({type:d,origType:g,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&S.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||((p=u[d]=[]).delegateCount=0,f.setup&&!1!==f.setup.call(t,r,h,a)||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,c),c.handler.guid||(c.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,c):p.push(c),S.event.global[d]=!0)}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,f,p,d,h,g,y=Y.hasData(e)&&Y.get(e);if(y&&(u=y.events)){l=(t=(t||"").match(P)||[""]).length;while(l--)if(d=g=(s=be.exec(t[l])||[])[1],h=(s[2]||"").split(".").sort(),d){f=S.event.special[d]||{},p=u[d=(r?f.delegateType:f.bindType)||d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;while(o--)c=p[o],!i&&g!==c.origType||n&&n.guid!==c.guid||s&&!s.test(c.namespace)||r&&r!==c.selector&&("**"!==r||!c.selector)||(p.splice(o,1),c.selector&&p.delegateCount--,f.remove&&f.remove.call(e,c));a&&!p.length&&(f.teardown&&!1!==f.teardown.call(e,h,y.handle)||S.removeEvent(e,d,y.handle),delete u[d])}else for(d in u)S.event.remove(e,d+t[l],n,r,!0);S.isEmptyObject(u)&&Y.remove(e,"handle events")}},dispatch:function(e){var t,n,r,i,o,a,s=new Array(arguments.length),u=S.event.fix(e),l=(Y.get(this,"events")||Object.create(null))[u.type]||[],c=S.event.special[u.type]||{};for(s[0]=u,t=1;t<arguments.length;t++)s[t]=arguments[t];if(u.delegateTarget=this,!c.preDispatch||!1!==c.preDispatch.call(this,u)){a=S.event.handlers.call(this,u,l),t=0;while((i=a[t++])&&!u.isPropagationStopped()){u.currentTarget=i.elem,n=0;while((o=i.handlers[n++])&&!u.isImmediatePropagationStopped())u.rnamespace&&!1!==o.namespace&&!u.rnamespace.test(o.namespace)||(u.handleObj=o,u.data=o.data,void 0!==(r=((S.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,s))&&!1===(u.result=r)&&(u.preventDefault(),u.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,u),u.result}},handlers:function(e,t){var n,r,i,o,a,s=[],u=t.delegateCount,l=e.target;if(u&&l.nodeType&&!("click"===e.type&&1<=e.button))for(;l!==this;l=l.parentNode||this)if(1===l.nodeType&&("click"!==e.type||!0!==l.disabled)){for(o=[],a={},n=0;n<u;n++)void 0===a[i=(r=t[n]).selector+" "]&&(a[i]=r.needsContext?-1<S(i,this).index(l):S.find(i,this,null,[l]).length),a[i]&&o.push(r);o.length&&s.push({elem:l,handlers:o})}return l=this,u<t.length&&s.push({elem:l,handlers:t.slice(u)}),s},addProp:function(t,e){Object.defineProperty(S.Event.prototype,t,{enumerable:!0,configurable:!0,get:m(e)?function(){if(this.originalEvent)return e(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[t]},set:function(e){Object.defineProperty(this,t,{enumerable:!0,configurable:!0,writable:!0,value:e})}})},fix:function(e){return e[S.expando]?e:new S.Event(e)},special:{load:{noBubble:!0},click:{setup:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&Se(t,"click",we),!1},trigger:function(e){var t=this||e;return pe.test(t.type)&&t.click&&A(t,"input")&&Se(t,"click"),!0},_default:function(e){var t=e.target;return pe.test(t.type)&&t.click&&A(t,"input")&&Y.get(t,"click")||A(t,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}}},S.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n)},S.Event=function(e,t){if(!(this instanceof S.Event))return new S.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&!1===e.returnValue?we:Te,this.target=e.target&&3===e.target.nodeType?e.target.parentNode:e.target,this.currentTarget=e.currentTarget,this.relatedTarget=e.relatedTarget):this.type=e,t&&S.extend(this,t),this.timeStamp=e&&e.timeStamp||Date.now(),this[S.expando]=!0},S.Event.prototype={constructor:S.Event,isDefaultPrevented:Te,isPropagationStopped:Te,isImmediatePropagationStopped:Te,isSimulated:!1,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=we,e&&!this.isSimulated&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=we,e&&!this.isSimulated&&e.stopPropagation()},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=we,e&&!this.isSimulated&&e.stopImmediatePropagation(),this.stopPropagation()}},S.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,code:!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:!0},S.event.addProp),S.each({focus:"focusin",blur:"focusout"},function(t,e){S.event.special[t]={setup:function(){return Se(this,t,Ce),!1},trigger:function(){return Se(this,t),!0},_default:function(e){return Y.get(e.target,t)},delegateType:e}}),S.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,i){S.event.special[e]={delegateType:i,bindType:i,handle:function(e){var t,n=e.relatedTarget,r=e.handleObj;return n&&(n===this||S.contains(this,n))||(e.type=r.origType,t=r.handler.apply(this,arguments),e.type=i),t}}}),S.fn.extend({on:function(e,t,n,r){return Ee(this,e,t,n,r)},one:function(e,t,n,r){return Ee(this,e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,S(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return!1!==t&&"function"!=typeof t||(n=t,t=void 0),!1===n&&(n=Te),this.each(function(){S.event.remove(this,e,n,t)})}});var ke=/<script|<style|<link/i,Ae=/checked\s*(?:[^=]|=\s*.checked.)/i,Ne=/^\s*<!\[CDATA\[|\]\]>\s*$/g;function je(e,t){return A(e,"table")&&A(11!==t.nodeType?t:t.firstChild,"tr")&&S(e).children("tbody")[0]||e}function De(e){return e.type=(null!==e.getAttribute("type"))+"/"+e.type,e}function qe(e){return"true/"===(e.type||"").slice(0,5)?e.type=e.type.slice(5):e.removeAttribute("type"),e}function Le(e,t){var n,r,i,o,a,s;if(1===t.nodeType){if(Y.hasData(e)&&(s=Y.get(e).events))for(i in Y.remove(t,"handle events"),s)for(n=0,r=s[i].length;n<r;n++)S.event.add(t,i,s[i][n]);Q.hasData(e)&&(o=Q.access(e),a=S.extend({},o),Q.set(t,a))}}function He(n,r,i,o){r=g(r);var e,t,a,s,u,l,c=0,f=n.length,p=f-1,d=r[0],h=m(d);if(h||1<f&&"string"==typeof d&&!v.checkClone&&Ae.test(d))return n.each(function(e){var t=n.eq(e);h&&(r[0]=d.call(this,e,t.html())),He(t,r,i,o)});if(f&&(t=(e=xe(r,n[0].ownerDocument,!1,n,o)).firstChild,1===e.childNodes.length&&(e=t),t||o)){for(s=(a=S.map(ye(e,"script"),De)).length;c<f;c++)u=e,c!==p&&(u=S.clone(u,!0,!0),s&&S.merge(a,ye(u,"script"))),i.call(n[c],u,c);if(s)for(l=a[a.length-1].ownerDocument,S.map(a,qe),c=0;c<s;c++)u=a[c],he.test(u.type||"")&&!Y.access(u,"globalEval")&&S.contains(l,u)&&(u.src&&"module"!==(u.type||"").toLowerCase()?S._evalUrl&&!u.noModule&&S._evalUrl(u.src,{nonce:u.nonce||u.getAttribute("nonce")},l):b(u.textContent.replace(Ne,""),u,l))}return n}function Oe(e,t,n){for(var r,i=t?S.filter(t,e):e,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||S.cleanData(ye(r)),r.parentNode&&(n&&ie(r)&&ve(ye(r,"script")),r.parentNode.removeChild(r));return e}S.extend({htmlPrefilter:function(e){return e},clone:function(e,t,n){var r,i,o,a,s,u,l,c=e.cloneNode(!0),f=ie(e);if(!(v.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||S.isXMLDoc(e)))for(a=ye(c),r=0,i=(o=ye(e)).length;r<i;r++)s=o[r],u=a[r],void 0,"input"===(l=u.nodeName.toLowerCase())&&pe.test(s.type)?u.checked=s.checked:"input"!==l&&"textarea"!==l||(u.defaultValue=s.defaultValue);if(t)if(n)for(o=o||ye(e),a=a||ye(c),r=0,i=o.length;r<i;r++)Le(o[r],a[r]);else Le(e,c);return 0<(a=ye(c,"script")).length&&ve(a,!f&&ye(e,"script")),c},cleanData:function(e){for(var t,n,r,i=S.event.special,o=0;void 0!==(n=e[o]);o++)if(V(n)){if(t=n[Y.expando]){if(t.events)for(r in t.events)i[r]?S.event.remove(n,r):S.removeEvent(n,r,t.handle);n[Y.expando]=void 0}n[Q.expando]&&(n[Q.expando]=void 0)}}}),S.fn.extend({detach:function(e){return Oe(this,e,!0)},remove:function(e){return Oe(this,e)},text:function(e){return B(this,function(e){return void 0===e?S.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=e)})},null,e,arguments.length)},append:function(){return He(this,arguments,function(e){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||je(this,e).appendChild(e)})},prepend:function(){return He(this,arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=je(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return He(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return He(this,arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},empty:function(){for(var e,t=0;null!=(e=this[t]);t++)1===e.nodeType&&(S.cleanData(ye(e,!1)),e.textContent="");return this},clone:function(e,t){return e=null!=e&&e,t=null==t?e:t,this.map(function(){return S.clone(this,e,t)})},html:function(e){return B(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e&&1===t.nodeType)return t.innerHTML;if("string"==typeof e&&!ke.test(e)&&!ge[(de.exec(e)||["",""])[1].toLowerCase()]){e=S.htmlPrefilter(e);try{for(;n<r;n++)1===(t=this[n]||{}).nodeType&&(S.cleanData(ye(t,!1)),t.innerHTML=e);t=0}catch(e){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var n=[];return He(this,arguments,function(e){var t=this.parentNode;S.inArray(this,n)<0&&(S.cleanData(ye(this)),t&&t.replaceChild(e,this))},n)}}),S.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,a){S.fn[e]=function(e){for(var t,n=[],r=S(e),i=r.length-1,o=0;o<=i;o++)t=o===i?this:this.clone(!0),S(r[o])[a](t),u.apply(n,t.get());return this.pushStack(n)}});var Pe=new RegExp("^("+ee+")(?!px)[a-z%]+$","i"),Re=/^--/,Me=function(e){var t=e.ownerDocument.defaultView;return t&&t.opener||(t=C),t.getComputedStyle(e)},Ie=function(e,t,n){var r,i,o={};for(i in t)o[i]=e.style[i],e.style[i]=t[i];for(i in r=n.call(e),t)e.style[i]=o[i];return r},We=new RegExp(ne.join("|"),"i"),Fe="[\\x20\\t\\r\\n\\f]",$e=new RegExp("^"+Fe+"+|((?:^|[^\\\\])(?:\\\\.)*)"+Fe+"+$","g");function Be(e,t,n){var r,i,o,a,s=Re.test(t),u=e.style;return(n=n||Me(e))&&(a=n.getPropertyValue(t)||n[t],s&&(a=a.replace($e,"$1")),""!==a||ie(e)||(a=S.style(e,t)),!v.pixelBoxStyles()&&Pe.test(a)&&We.test(t)&&(r=u.width,i=u.minWidth,o=u.maxWidth,u.minWidth=u.maxWidth=u.width=a,a=n.width,u.width=r,u.minWidth=i,u.maxWidth=o)),void 0!==a?a+"":a}function _e(e,t){return{get:function(){if(!e())return(this.get=t).apply(this,arguments);delete this.get}}}!function(){function e(){if(l){u.style.cssText="position:absolute;left:-11111px;width:60px;margin-top:1px;padding:0;border:0",l.style.cssText="position:relative;display:block;box-sizing:border-box;overflow:scroll;margin:auto;border:1px;padding:1px;width:60%;top:1%",re.appendChild(u).appendChild(l);var e=C.getComputedStyle(l);n="1%"!==e.top,s=12===t(e.marginLeft),l.style.right="60%",o=36===t(e.right),r=36===t(e.width),l.style.position="absolute",i=12===t(l.offsetWidth/3),re.removeChild(u),l=null}}function t(e){return Math.round(parseFloat(e))}var n,r,i,o,a,s,u=E.createElement("div"),l=E.createElement("div");l.style&&(l.style.backgroundClip="content-box",l.cloneNode(!0).style.backgroundClip="",v.clearCloneStyle="content-box"===l.style.backgroundClip,S.extend(v,{boxSizingReliable:function(){return e(),r},pixelBoxStyles:function(){return e(),o},pixelPosition:function(){return e(),n},reliableMarginLeft:function(){return e(),s},scrollboxSize:function(){return e(),i},reliableTrDimensions:function(){var e,t,n,r;return null==a&&(e=E.createElement("table"),t=E.createElement("tr"),n=E.createElement("div"),e.style.cssText="position:absolute;left:-11111px;border-collapse:separate",t.style.cssText="border:1px solid",t.style.height="1px",n.style.height="9px",n.style.display="block",re.appendChild(e).appendChild(t).appendChild(n),r=C.getComputedStyle(t),a=parseInt(r.height,10)+parseInt(r.borderTopWidth,10)+parseInt(r.borderBottomWidth,10)===t.offsetHeight,re.removeChild(e)),a}}))}();var ze=["Webkit","Moz","ms"],Ue=E.createElement("div").style,Xe={};function Ve(e){var t=S.cssProps[e]||Xe[e];return t||(e in Ue?e:Xe[e]=function(e){var t=e[0].toUpperCase()+e.slice(1),n=ze.length;while(n--)if((e=ze[n]+t)in Ue)return e}(e)||e)}var Ge=/^(none|table(?!-c[ea]).+)/,Ye={position:"absolute",visibility:"hidden",display:"block"},Qe={letterSpacing:"0",fontWeight:"400"};function Je(e,t,n){var r=te.exec(t);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):t}function Ke(e,t,n,r,i,o){var a="width"===t?1:0,s=0,u=0;if(n===(r?"border":"content"))return 0;for(;a<4;a+=2)"margin"===n&&(u+=S.css(e,n+ne[a],!0,i)),r?("content"===n&&(u-=S.css(e,"padding"+ne[a],!0,i)),"margin"!==n&&(u-=S.css(e,"border"+ne[a]+"Width",!0,i))):(u+=S.css(e,"padding"+ne[a],!0,i),"padding"!==n?u+=S.css(e,"border"+ne[a]+"Width",!0,i):s+=S.css(e,"border"+ne[a]+"Width",!0,i));return!r&&0<=o&&(u+=Math.max(0,Math.ceil(e["offset"+t[0].toUpperCase()+t.slice(1)]-o-u-s-.5))||0),u}function Ze(e,t,n){var r=Me(e),i=(!v.boxSizingReliable()||n)&&"border-box"===S.css(e,"boxSizing",!1,r),o=i,a=Be(e,t,r),s="offset"+t[0].toUpperCase()+t.slice(1);if(Pe.test(a)){if(!n)return a;a="auto"}return(!v.boxSizingReliable()&&i||!v.reliableTrDimensions()&&A(e,"tr")||"auto"===a||!parseFloat(a)&&"inline"===S.css(e,"display",!1,r))&&e.getClientRects().length&&(i="border-box"===S.css(e,"boxSizing",!1,r),(o=s in e)&&(a=e[s])),(a=parseFloat(a)||0)+Ke(e,t,n||(i?"border":"content"),o,r,a)+"px"}function et(e,t,n,r,i){return new et.prototype.init(e,t,n,r,i)}S.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Be(e,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=X(t),u=Re.test(t),l=e.style;if(u||(t=Ve(s)),a=S.cssHooks[t]||S.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];"string"===(o=typeof n)&&(i=te.exec(n))&&i[1]&&(n=se(e,t,i),o="number"),null!=n&&n==n&&("number"!==o||u||(n+=i&&i[3]||(S.cssNumber[s]?"":"px")),v.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),a&&"set"in a&&void 0===(n=a.set(e,n,r))||(u?l.setProperty(t,n):l[t]=n))}},css:function(e,t,n,r){var i,o,a,s=X(t);return Re.test(t)||(t=Ve(s)),(a=S.cssHooks[t]||S.cssHooks[s])&&"get"in a&&(i=a.get(e,!0,n)),void 0===i&&(i=Be(e,t,r)),"normal"===i&&t in Qe&&(i=Qe[t]),""===n||n?(o=parseFloat(i),!0===n||isFinite(o)?o||0:i):i}}),S.each(["height","width"],function(e,u){S.cssHooks[u]={get:function(e,t,n){if(t)return!Ge.test(S.css(e,"display"))||e.getClientRects().length&&e.getBoundingClientRect().width?Ze(e,u,n):Ie(e,Ye,function(){return Ze(e,u,n)})},set:function(e,t,n){var r,i=Me(e),o=!v.scrollboxSize()&&"absolute"===i.position,a=(o||n)&&"border-box"===S.css(e,"boxSizing",!1,i),s=n?Ke(e,u,n,a,i):0;return a&&o&&(s-=Math.ceil(e["offset"+u[0].toUpperCase()+u.slice(1)]-parseFloat(i[u])-Ke(e,u,"border",!1,i)-.5)),s&&(r=te.exec(t))&&"px"!==(r[3]||"px")&&(e.style[u]=t,t=S.css(e,u)),Je(0,t,s)}}}),S.cssHooks.marginLeft=_e(v.reliableMarginLeft,function(e,t){if(t)return(parseFloat(Be(e,"marginLeft"))||e.getBoundingClientRect().left-Ie(e,{marginLeft:0},function(){return e.getBoundingClientRect().left}))+"px"}),S.each({margin:"",padding:"",border:"Width"},function(i,o){S.cssHooks[i+o]={expand:function(e){for(var t=0,n={},r="string"==typeof e?e.split(" "):[e];t<4;t++)n[i+ne[t]+o]=r[t]||r[t-2]||r[0];return n}},"margin"!==i&&(S.cssHooks[i+o].set=Je)}),S.fn.extend({css:function(e,t){return B(this,function(e,t,n){var r,i,o={},a=0;if(Array.isArray(t)){for(r=Me(e),i=t.length;a<i;a++)o[t[a]]=S.css(e,t[a],!1,r);return o}return void 0!==n?S.style(e,t,n):S.css(e,t)},e,t,1<arguments.length)}}),((S.Tween=et).prototype={constructor:et,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||S.easing._default,this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(S.cssNumber[n]?"":"px")},cur:function(){var e=et.propHooks[this.prop];return e&&e.get?e.get(this):et.propHooks._default.get(this)},run:function(e){var t,n=et.propHooks[this.prop];return this.options.duration?this.pos=t=S.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):et.propHooks._default.set(this),this}}).init.prototype=et.prototype,(et.propHooks={_default:{get:function(e){var t;return 1!==e.elem.nodeType||null!=e.elem[e.prop]&&null==e.elem.style[e.prop]?e.elem[e.prop]:(t=S.css(e.elem,e.prop,""))&&"auto"!==t?t:0},set:function(e){S.fx.step[e.prop]?S.fx.step[e.prop](e):1!==e.elem.nodeType||!S.cssHooks[e.prop]&&null==e.elem.style[Ve(e.prop)]?e.elem[e.prop]=e.now:S.style(e.elem,e.prop,e.now+e.unit)}}}).scrollTop=et.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},S.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2},_default:"swing"},S.fx=et.prototype.init,S.fx.step={};var tt,nt,rt,it,ot=/^(?:toggle|show|hide)$/,at=/queueHooks$/;function st(){nt&&(!1===E.hidden&&C.requestAnimationFrame?C.requestAnimationFrame(st):C.setTimeout(st,S.fx.interval),S.fx.tick())}function ut(){return C.setTimeout(function(){tt=void 0}),tt=Date.now()}function lt(e,t){var n,r=0,i={height:e};for(t=t?1:0;r<4;r+=2-t)i["margin"+(n=ne[r])]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function ct(e,t,n){for(var r,i=(ft.tweeners[t]||[]).concat(ft.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,t,e))return r}function ft(o,e,t){var n,a,r=0,i=ft.prefilters.length,s=S.Deferred().always(function(){delete u.elem}),u=function(){if(a)return!1;for(var e=tt||ut(),t=Math.max(0,l.startTime+l.duration-e),n=1-(t/l.duration||0),r=0,i=l.tweens.length;r<i;r++)l.tweens[r].run(n);return s.notifyWith(o,[l,n,t]),n<1&&i?t:(i||s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l]),!1)},l=s.promise({elem:o,props:S.extend({},e),opts:S.extend(!0,{specialEasing:{},easing:S.easing._default},t),originalProperties:e,originalOptions:t,startTime:tt||ut(),duration:t.duration,tweens:[],createTween:function(e,t){var n=S.Tween(o,l.opts,e,t,l.opts.specialEasing[e]||l.opts.easing);return l.tweens.push(n),n},stop:function(e){var t=0,n=e?l.tweens.length:0;if(a)return this;for(a=!0;t<n;t++)l.tweens[t].run(1);return e?(s.notifyWith(o,[l,1,0]),s.resolveWith(o,[l,e])):s.rejectWith(o,[l,e]),this}}),c=l.props;for(!function(e,t){var n,r,i,o,a;for(n in e)if(i=t[r=X(n)],o=e[n],Array.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),(a=S.cssHooks[r])&&"expand"in a)for(n in o=a.expand(o),delete e[r],o)n in e||(e[n]=o[n],t[n]=i);else t[r]=i}(c,l.opts.specialEasing);r<i;r++)if(n=ft.prefilters[r].call(l,o,c,l.opts))return m(n.stop)&&(S._queueHooks(l.elem,l.opts.queue).stop=n.stop.bind(n)),n;return S.map(c,ct,l),m(l.opts.start)&&l.opts.start.call(o,l),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always),S.fx.timer(S.extend(u,{elem:o,anim:l,queue:l.opts.queue})),l}S.Animation=S.extend(ft,{tweeners:{"*":[function(e,t){var n=this.createTween(e,t);return se(n.elem,e,te.exec(t),n),n}]},tweener:function(e,t){m(e)?(t=e,e=["*"]):e=e.match(P);for(var n,r=0,i=e.length;r<i;r++)n=e[r],ft.tweeners[n]=ft.tweeners[n]||[],ft.tweeners[n].unshift(t)},prefilters:[function(e,t,n){var r,i,o,a,s,u,l,c,f="width"in t||"height"in t,p=this,d={},h=e.style,g=e.nodeType&&ae(e),y=Y.get(e,"fxshow");for(r in n.queue||(null==(a=S._queueHooks(e,"fx")).unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,p.always(function(){p.always(function(){a.unqueued--,S.queue(e,"fx").length||a.empty.fire()})})),t)if(i=t[r],ot.test(i)){if(delete t[r],o=o||"toggle"===i,i===(g?"hide":"show")){if("show"!==i||!y||void 0===y[r])continue;g=!0}d[r]=y&&y[r]||S.style(e,r)}if((u=!S.isEmptyObject(t))||!S.isEmptyObject(d))for(r in f&&1===e.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],null==(l=y&&y.display)&&(l=Y.get(e,"display")),"none"===(c=S.css(e,"display"))&&(l?c=l:(le([e],!0),l=e.style.display||l,c=S.css(e,"display"),le([e]))),("inline"===c||"inline-block"===c&&null!=l)&&"none"===S.css(e,"float")&&(u||(p.done(function(){h.display=l}),null==l&&(c=h.display,l="none"===c?"":c)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1,d)u||(y?"hidden"in y&&(g=y.hidden):y=Y.access(e,"fxshow",{display:l}),o&&(y.hidden=!g),g&&le([e],!0),p.done(function(){for(r in g||le([e]),Y.remove(e,"fxshow"),d)S.style(e,r,d[r])})),u=ct(g?y[r]:0,r,p),r in y||(y[r]=u.start,g&&(u.end=u.start,u.start=0))}],prefilter:function(e,t){t?ft.prefilters.unshift(e):ft.prefilters.push(e)}}),S.speed=function(e,t,n){var r=e&&"object"==typeof e?S.extend({},e):{complete:n||!n&&t||m(e)&&e,duration:e,easing:n&&t||t&&!m(t)&&t};return S.fx.off?r.duration=0:"number"!=typeof r.duration&&(r.duration in S.fx.speeds?r.duration=S.fx.speeds[r.duration]:r.duration=S.fx.speeds._default),null!=r.queue&&!0!==r.queue||(r.queue="fx"),r.old=r.complete,r.complete=function(){m(r.old)&&r.old.call(this),r.queue&&S.dequeue(this,r.queue)},r},S.fn.extend({fadeTo:function(e,t,n,r){return this.filter(ae).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(t,e,n,r){var i=S.isEmptyObject(t),o=S.speed(e,n,r),a=function(){var e=ft(this,S.extend({},t),o);(i||Y.get(this,"finish"))&&e.stop(!0)};return a.finish=a,i||!1===o.queue?this.each(a):this.queue(o.queue,a)},stop:function(i,e,o){var a=function(e){var t=e.stop;delete e.stop,t(o)};return"string"!=typeof i&&(o=e,e=i,i=void 0),e&&this.queue(i||"fx",[]),this.each(function(){var e=!0,t=null!=i&&i+"queueHooks",n=S.timers,r=Y.get(this);if(t)r[t]&&r[t].stop&&a(r[t]);else for(t in r)r[t]&&r[t].stop&&at.test(t)&&a(r[t]);for(t=n.length;t--;)n[t].elem!==this||null!=i&&n[t].queue!==i||(n[t].anim.stop(o),e=!1,n.splice(t,1));!e&&o||S.dequeue(this,i)})},finish:function(a){return!1!==a&&(a=a||"fx"),this.each(function(){var e,t=Y.get(this),n=t[a+"queue"],r=t[a+"queueHooks"],i=S.timers,o=n?n.length:0;for(t.finish=!0,S.queue(this,a,[]),r&&r.stop&&r.stop.call(this,!0),e=i.length;e--;)i[e].elem===this&&i[e].queue===a&&(i[e].anim.stop(!0),i.splice(e,1));for(e=0;e<o;e++)n[e]&&n[e].finish&&n[e].finish.call(this);delete t.finish})}}),S.each(["toggle","show","hide"],function(e,r){var i=S.fn[r];S.fn[r]=function(e,t,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(lt(r,!0),e,t,n)}}),S.each({slideDown:lt("show"),slideUp:lt("hide"),slideToggle:lt("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,r){S.fn[e]=function(e,t,n){return this.animate(r,e,t,n)}}),S.timers=[],S.fx.tick=function(){var e,t=0,n=S.timers;for(tt=Date.now();t<n.length;t++)(e=n[t])()||n[t]!==e||n.splice(t--,1);n.length||S.fx.stop(),tt=void 0},S.fx.timer=function(e){S.timers.push(e),S.fx.start()},S.fx.interval=13,S.fx.start=function(){nt||(nt=!0,st())},S.fx.stop=function(){nt=null},S.fx.speeds={slow:600,fast:200,_default:400},S.fn.delay=function(r,e){return r=S.fx&&S.fx.speeds[r]||r,e=e||"fx",this.queue(e,function(e,t){var n=C.setTimeout(e,r);t.stop=function(){C.clearTimeout(n)}})},rt=E.createElement("input"),it=E.createElement("select").appendChild(E.createElement("option")),rt.type="checkbox",v.checkOn=""!==rt.value,v.optSelected=it.selected,(rt=E.createElement("input")).value="t",rt.type="radio",v.radioValue="t"===rt.value;var pt,dt=S.expr.attrHandle;S.fn.extend({attr:function(e,t){return B(this,S.attr,e,t,1<arguments.length)},removeAttr:function(e){return this.each(function(){S.removeAttr(this,e)})}}),S.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof e.getAttribute?S.prop(e,t,n):(1===o&&S.isXMLDoc(e)||(i=S.attrHooks[t.toLowerCase()]||(S.expr.match.bool.test(t)?pt:void 0)),void 0!==n?null===n?void S.removeAttr(e,t):i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:(e.setAttribute(t,n+""),n):i&&"get"in i&&null!==(r=i.get(e,t))?r:null==(r=S.find.attr(e,t))?void 0:r)},attrHooks:{type:{set:function(e,t){if(!v.radioValue&&"radio"===t&&A(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},removeAttr:function(e,t){var n,r=0,i=t&&t.match(P);if(i&&1===e.nodeType)while(n=i[r++])e.removeAttribute(n)}}),pt={set:function(e,t,n){return!1===t?S.removeAttr(e,n):e.setAttribute(n,n),n}},S.each(S.expr.match.bool.source.match(/\w+/g),function(e,t){var a=dt[t]||S.find.attr;dt[t]=function(e,t,n){var r,i,o=t.toLowerCase();return n||(i=dt[o],dt[o]=r,r=null!=a(e,t,n)?o:null,dt[o]=i),r}});var ht=/^(?:input|select|textarea|button)$/i,gt=/^(?:a|area)$/i;function yt(e){return(e.match(P)||[]).join(" ")}function vt(e){return e.getAttribute&&e.getAttribute("class")||""}function mt(e){return Array.isArray(e)?e:"string"==typeof e&&e.match(P)||[]}S.fn.extend({prop:function(e,t){return B(this,S.prop,e,t,1<arguments.length)},removeProp:function(e){return this.each(function(){delete this[S.propFix[e]||e]})}}),S.extend({prop:function(e,t,n){var r,i,o=e.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&S.isXMLDoc(e)||(t=S.propFix[t]||t,i=S.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=S.find.attr(e,"tabindex");return t?parseInt(t,10):ht.test(e.nodeName)||gt.test(e.nodeName)&&e.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),v.optSelected||(S.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null},set:function(e){var t=e.parentNode;t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex)}}),S.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){S.propFix[this.toLowerCase()]=this}),S.fn.extend({addClass:function(t){var e,n,r,i,o,a;return m(t)?this.each(function(e){S(this).addClass(t.call(this,e,vt(this)))}):(e=mt(t)).length?this.each(function(){if(r=vt(this),n=1===this.nodeType&&" "+yt(r)+" "){for(o=0;o<e.length;o++)i=e[o],n.indexOf(" "+i+" ")<0&&(n+=i+" ");a=yt(n),r!==a&&this.setAttribute("class",a)}}):this},removeClass:function(t){var e,n,r,i,o,a;return m(t)?this.each(function(e){S(this).removeClass(t.call(this,e,vt(this)))}):arguments.length?(e=mt(t)).length?this.each(function(){if(r=vt(this),n=1===this.nodeType&&" "+yt(r)+" "){for(o=0;o<e.length;o++){i=e[o];while(-1<n.indexOf(" "+i+" "))n=n.replace(" "+i+" "," ")}a=yt(n),r!==a&&this.setAttribute("class",a)}}):this:this.attr("class","")},toggleClass:function(t,n){var e,r,i,o,a=typeof t,s="string"===a||Array.isArray(t);return m(t)?this.each(function(e){S(this).toggleClass(t.call(this,e,vt(this),n),n)}):"boolean"==typeof n&&s?n?this.addClass(t):this.removeClass(t):(e=mt(t),this.each(function(){if(s)for(o=S(this),i=0;i<e.length;i++)r=e[i],o.hasClass(r)?o.removeClass(r):o.addClass(r);else void 0!==t&&"boolean"!==a||((r=vt(this))&&Y.set(this,"__className__",r),this.setAttribute&&this.setAttribute("class",r||!1===t?"":Y.get(this,"__className__")||""))}))},hasClass:function(e){var t,n,r=0;t=" "+e+" ";while(n=this[r++])if(1===n.nodeType&&-1<(" "+yt(vt(n))+" ").indexOf(t))return!0;return!1}});var xt=/\r/g;S.fn.extend({val:function(n){var r,e,i,t=this[0];return arguments.length?(i=m(n),this.each(function(e){var t;1===this.nodeType&&(null==(t=i?n.call(this,e,S(this).val()):n)?t="":"number"==typeof t?t+="":Array.isArray(t)&&(t=S.map(t,function(e){return null==e?"":e+""})),(r=S.valHooks[this.type]||S.valHooks[this.nodeName.toLowerCase()])&&"set"in r&&void 0!==r.set(this,t,"value")||(this.value=t))})):t?(r=S.valHooks[t.type]||S.valHooks[t.nodeName.toLowerCase()])&&"get"in r&&void 0!==(e=r.get(t,"value"))?e:"string"==typeof(e=t.value)?e.replace(xt,""):null==e?"":e:void 0}}),S.extend({valHooks:{option:{get:function(e){var t=S.find.attr(e,"value");return null!=t?t:yt(S.text(e))}},select:{get:function(e){var t,n,r,i=e.options,o=e.selectedIndex,a="select-one"===e.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r<u;r++)if(((n=i[r]).selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!A(n.parentNode,"optgroup"))){if(t=S(n).val(),a)return t;s.push(t)}return s},set:function(e,t){var n,r,i=e.options,o=S.makeArray(t),a=i.length;while(a--)((r=i[a]).selected=-1<S.inArray(S.valHooks.option.get(r),o))&&(n=!0);return n||(e.selectedIndex=-1),o}}}}),S.each(["radio","checkbox"],function(){S.valHooks[this]={set:function(e,t){if(Array.isArray(t))return e.checked=-1<S.inArray(S(e).val(),t)}},v.checkOn||(S.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})}),v.focusin="onfocusin"in C;var bt=/^(?:focusinfocus|focusoutblur)$/,wt=function(e){e.stopPropagation()};S.extend(S.event,{trigger:function(e,t,n,r){var i,o,a,s,u,l,c,f,p=[n||E],d=y.call(e,"type")?e.type:e,h=y.call(e,"namespace")?e.namespace.split("."):[];if(o=f=a=n=n||E,3!==n.nodeType&&8!==n.nodeType&&!bt.test(d+S.event.triggered)&&(-1<d.indexOf(".")&&(d=(h=d.split(".")).shift(),h.sort()),u=d.indexOf(":")<0&&"on"+d,(e=e[S.expando]?e:new S.Event(d,"object"==typeof e&&e)).isTrigger=r?2:3,e.namespace=h.join("."),e.rnamespace=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=void 0,e.target||(e.target=n),t=null==t?[e]:S.makeArray(t,[e]),c=S.event.special[d]||{},r||!c.trigger||!1!==c.trigger.apply(n,t))){if(!r&&!c.noBubble&&!x(n)){for(s=c.delegateType||d,bt.test(s+d)||(o=o.parentNode);o;o=o.parentNode)p.push(o),a=o;a===(n.ownerDocument||E)&&p.push(a.defaultView||a.parentWindow||C)}i=0;while((o=p[i++])&&!e.isPropagationStopped())f=o,e.type=1<i?s:c.bindType||d,(l=(Y.get(o,"events")||Object.create(null))[e.type]&&Y.get(o,"handle"))&&l.apply(o,t),(l=u&&o[u])&&l.apply&&V(o)&&(e.result=l.apply(o,t),!1===e.result&&e.preventDefault());return e.type=d,r||e.isDefaultPrevented()||c._default&&!1!==c._default.apply(p.pop(),t)||!V(n)||u&&m(n[d])&&!x(n)&&((a=n[u])&&(n[u]=null),S.event.triggered=d,e.isPropagationStopped()&&f.addEventListener(d,wt),n[d](),e.isPropagationStopped()&&f.removeEventListener(d,wt),S.event.triggered=void 0,a&&(n[u]=a)),e.result}},simulate:function(e,t,n){var r=S.extend(new S.Event,n,{type:e,isSimulated:!0});S.event.trigger(r,null,t)}}),S.fn.extend({trigger:function(e,t){return this.each(function(){S.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return S.event.trigger(e,t,n,!0)}}),v.focusin||S.each({focus:"focusin",blur:"focusout"},function(n,r){var i=function(e){S.event.simulate(r,e.target,S.event.fix(e))};S.event.special[r]={setup:function(){var e=this.ownerDocument||this.document||this,t=Y.access(e,r);t||e.addEventListener(n,i,!0),Y.access(e,r,(t||0)+1)},teardown:function(){var e=this.ownerDocument||this.document||this,t=Y.access(e,r)-1;t?Y.access(e,r,t):(e.removeEventListener(n,i,!0),Y.remove(e,r))}}});var Tt=C.location,Ct={guid:Date.now()},Et=/\?/;S.parseXML=function(e){var t,n;if(!e||"string"!=typeof e)return null;try{t=(new C.DOMParser).parseFromString(e,"text/xml")}catch(e){}return n=t&&t.getElementsByTagName("parsererror")[0],t&&!n||S.error("Invalid XML: "+(n?S.map(n.childNodes,function(e){return e.textContent}).join("\n"):e)),t};var St=/\[\]$/,kt=/\r?\n/g,At=/^(?:submit|button|image|reset|file)$/i,Nt=/^(?:input|select|textarea|keygen)/i;function jt(n,e,r,i){var t;if(Array.isArray(e))S.each(e,function(e,t){r||St.test(n)?i(n,t):jt(n+"["+("object"==typeof t&&null!=t?e:"")+"]",t,r,i)});else if(r||"object"!==w(e))i(n,e);else for(t in e)jt(n+"["+t+"]",e[t],r,i)}S.param=function(e,t){var n,r=[],i=function(e,t){var n=m(t)?t():t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(null==n?"":n)};if(null==e)return"";if(Array.isArray(e)||e.jquery&&!S.isPlainObject(e))S.each(e,function(){i(this.name,this.value)});else for(n in e)jt(n,e[n],t,i);return r.join("&")},S.fn.extend({serialize:function(){return S.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=S.prop(this,"elements");return e?S.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!S(this).is(":disabled")&&Nt.test(this.nodeName)&&!At.test(e)&&(this.checked||!pe.test(e))}).map(function(e,t){var n=S(this).val();return null==n?null:Array.isArray(n)?S.map(n,function(e){return{name:t.name,value:e.replace(kt,"\r\n")}}):{name:t.name,value:n.replace(kt,"\r\n")}}).get()}});var Dt=/%20/g,qt=/#.*$/,Lt=/([?&])_=[^&]*/,Ht=/^(.*?):[ \t]*([^\r\n]*)$/gm,Ot=/^(?:GET|HEAD)$/,Pt=/^\/\//,Rt={},Mt={},It="*/".concat("*"),Wt=E.createElement("a");function Ft(o){return function(e,t){"string"!=typeof e&&(t=e,e="*");var n,r=0,i=e.toLowerCase().match(P)||[];if(m(t))while(n=i[r++])"+"===n[0]?(n=n.slice(1)||"*",(o[n]=o[n]||[]).unshift(t)):(o[n]=o[n]||[]).push(t)}}function $t(t,i,o,a){var s={},u=t===Mt;function l(e){var r;return s[e]=!0,S.each(t[e]||[],function(e,t){var n=t(i,o,a);return"string"!=typeof n||u||s[n]?u?!(r=n):void 0:(i.dataTypes.unshift(n),l(n),!1)}),r}return l(i.dataTypes[0])||!s["*"]&&l("*")}function Bt(e,t){var n,r,i=S.ajaxSettings.flatOptions||{};for(n in t)void 0!==t[n]&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&S.extend(!0,e,r),e}Wt.href=Tt.href,S.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Tt.href,type:"GET",isLocal:/^(?:about|app|app-storage|.+-extension|file|res|widget):$/.test(Tt.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":It,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":S.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Bt(Bt(e,S.ajaxSettings),t):Bt(S.ajaxSettings,e)},ajaxPrefilter:Ft(Rt),ajaxTransport:Ft(Mt),ajax:function(e,t){"object"==typeof e&&(t=e,e=void 0),t=t||{};var c,f,p,n,d,r,h,g,i,o,y=S.ajaxSetup({},t),v=y.context||y,m=y.context&&(v.nodeType||v.jquery)?S(v):S.event,x=S.Deferred(),b=S.Callbacks("once memory"),w=y.statusCode||{},a={},s={},u="canceled",T={readyState:0,getResponseHeader:function(e){var t;if(h){if(!n){n={};while(t=Ht.exec(p))n[t[1].toLowerCase()+" "]=(n[t[1].toLowerCase()+" "]||[]).concat(t[2])}t=n[e.toLowerCase()+" "]}return null==t?null:t.join(", ")},getAllResponseHeaders:function(){return h?p:null},setRequestHeader:function(e,t){return null==h&&(e=s[e.toLowerCase()]=s[e.toLowerCase()]||e,a[e]=t),this},overrideMimeType:function(e){return null==h&&(y.mimeType=e),this},statusCode:function(e){var t;if(e)if(h)T.always(e[T.status]);else for(t in e)w[t]=[w[t],e[t]];return this},abort:function(e){var t=e||u;return c&&c.abort(t),l(0,t),this}};if(x.promise(T),y.url=((e||y.url||Tt.href)+"").replace(Pt,Tt.protocol+"//"),y.type=t.method||t.type||y.method||y.type,y.dataTypes=(y.dataType||"*").toLowerCase().match(P)||[""],null==y.crossDomain){r=E.createElement("a");try{r.href=y.url,r.href=r.href,y.crossDomain=Wt.protocol+"//"+Wt.host!=r.protocol+"//"+r.host}catch(e){y.crossDomain=!0}}if(y.data&&y.processData&&"string"!=typeof y.data&&(y.data=S.param(y.data,y.traditional)),$t(Rt,y,t,T),h)return T;for(i in(g=S.event&&y.global)&&0==S.active++&&S.event.trigger("ajaxStart"),y.type=y.type.toUpperCase(),y.hasContent=!Ot.test(y.type),f=y.url.replace(qt,""),y.hasContent?y.data&&y.processData&&0===(y.contentType||"").indexOf("application/x-www-form-urlencoded")&&(y.data=y.data.replace(Dt,"+")):(o=y.url.slice(f.length),y.data&&(y.processData||"string"==typeof y.data)&&(f+=(Et.test(f)?"&":"?")+y.data,delete y.data),!1===y.cache&&(f=f.replace(Lt,"$1"),o=(Et.test(f)?"&":"?")+"_="+Ct.guid+++o),y.url=f+o),y.ifModified&&(S.lastModified[f]&&T.setRequestHeader("If-Modified-Since",S.lastModified[f]),S.etag[f]&&T.setRequestHeader("If-None-Match",S.etag[f])),(y.data&&y.hasContent&&!1!==y.contentType||t.contentType)&&T.setRequestHeader("Content-Type",y.contentType),T.setRequestHeader("Accept",y.dataTypes[0]&&y.accepts[y.dataTypes[0]]?y.accepts[y.dataTypes[0]]+("*"!==y.dataTypes[0]?", "+It+"; q=0.01":""):y.accepts["*"]),y.headers)T.setRequestHeader(i,y.headers[i]);if(y.beforeSend&&(!1===y.beforeSend.call(v,T,y)||h))return T.abort();if(u="abort",b.add(y.complete),T.done(y.success),T.fail(y.error),c=$t(Mt,y,t,T)){if(T.readyState=1,g&&m.trigger("ajaxSend",[T,y]),h)return T;y.async&&0<y.timeout&&(d=C.setTimeout(function(){T.abort("timeout")},y.timeout));try{h=!1,c.send(a,l)}catch(e){if(h)throw e;l(-1,e)}}else l(-1,"No Transport");function l(e,t,n,r){var i,o,a,s,u,l=t;h||(h=!0,d&&C.clearTimeout(d),c=void 0,p=r||"",T.readyState=0<e?4:0,i=200<=e&&e<300||304===e,n&&(s=function(e,t,n){var r,i,o,a,s=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),void 0===r&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||e.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}(y,T,n)),!i&&-1<S.inArray("script",y.dataTypes)&&S.inArray("json",y.dataTypes)<0&&(y.converters["text script"]=function(){}),s=function(e,t,n,r){var i,o,a,s,u,l={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)l[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!u&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u=o,o=c.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(!(a=l[u+" "+o]||l["* "+o]))for(i in l)if((s=i.split(" "))[1]===o&&(a=l[u+" "+s[0]]||l["* "+s[0]])){!0===a?a=l[i]:!0!==l[i]&&(o=s[0],c.unshift(s[1]));break}if(!0!==a)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(e){return{state:"parsererror",error:a?e:"No conversion from "+u+" to "+o}}}return{state:"success",data:t}}(y,s,T,i),i?(y.ifModified&&((u=T.getResponseHeader("Last-Modified"))&&(S.lastModified[f]=u),(u=T.getResponseHeader("etag"))&&(S.etag[f]=u)),204===e||"HEAD"===y.type?l="nocontent":304===e?l="notmodified":(l=s.state,o=s.data,i=!(a=s.error))):(a=l,!e&&l||(l="error",e<0&&(e=0))),T.status=e,T.statusText=(t||l)+"",i?x.resolveWith(v,[o,l,T]):x.rejectWith(v,[T,l,a]),T.statusCode(w),w=void 0,g&&m.trigger(i?"ajaxSuccess":"ajaxError",[T,y,i?o:a]),b.fireWith(v,[T,l]),g&&(m.trigger("ajaxComplete",[T,y]),--S.active||S.event.trigger("ajaxStop")))}return T},getJSON:function(e,t,n){return S.get(e,t,n,"json")},getScript:function(e,t){return S.get(e,void 0,t,"script")}}),S.each(["get","post"],function(e,i){S[i]=function(e,t,n,r){return m(t)&&(r=r||n,n=t,t=void 0),S.ajax(S.extend({url:e,type:i,dataType:r,data:t,success:n},S.isPlainObject(e)&&e))}}),S.ajaxPrefilter(function(e){var t;for(t in e.headers)"content-type"===t.toLowerCase()&&(e.contentType=e.headers[t]||"")}),S._evalUrl=function(e,t,n){return S.ajax({url:e,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,converters:{"text script":function(){}},dataFilter:function(e){S.globalEval(e,t,n)}})},S.fn.extend({wrapAll:function(e){var t;return this[0]&&(m(e)&&(e=e.call(this[0])),t=S(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this},wrapInner:function(n){return m(n)?this.each(function(e){S(this).wrapInner(n.call(this,e))}):this.each(function(){var e=S(this),t=e.contents();t.length?t.wrapAll(n):e.append(n)})},wrap:function(t){var n=m(t);return this.each(function(e){S(this).wrapAll(n?t.call(this,e):t)})},unwrap:function(e){return this.parent(e).not("body").each(function(){S(this).replaceWith(this.childNodes)}),this}}),S.expr.pseudos.hidden=function(e){return!S.expr.pseudos.visible(e)},S.expr.pseudos.visible=function(e){return!!(e.offsetWidth||e.offsetHeight||e.getClientRects().length)},S.ajaxSettings.xhr=function(){try{return new C.XMLHttpRequest}catch(e){}};var _t={0:200,1223:204},zt=S.ajaxSettings.xhr();v.cors=!!zt&&"withCredentials"in zt,v.ajax=zt=!!zt,S.ajaxTransport(function(i){var o,a;if(v.cors||zt&&!i.crossDomain)return{send:function(e,t){var n,r=i.xhr();if(r.open(i.type,i.url,i.async,i.username,i.password),i.xhrFields)for(n in i.xhrFields)r[n]=i.xhrFields[n];for(n in i.mimeType&&r.overrideMimeType&&r.overrideMimeType(i.mimeType),i.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest"),e)r.setRequestHeader(n,e[n]);o=function(e){return function(){o&&(o=a=r.onload=r.onerror=r.onabort=r.ontimeout=r.onreadystatechange=null,"abort"===e?r.abort():"error"===e?"number"!=typeof r.status?t(0,"error"):t(r.status,r.statusText):t(_t[r.status]||r.status,r.statusText,"text"!==(r.responseType||"text")||"string"!=typeof r.responseText?{binary:r.response}:{text:r.responseText},r.getAllResponseHeaders()))}},r.onload=o(),a=r.onerror=r.ontimeout=o("error"),void 0!==r.onabort?r.onabort=a:r.onreadystatechange=function(){4===r.readyState&&C.setTimeout(function(){o&&a()})},o=o("abort");try{r.send(i.hasContent&&i.data||null)}catch(e){if(o)throw e}},abort:function(){o&&o()}}}),S.ajaxPrefilter(function(e){e.crossDomain&&(e.contents.script=!1)}),S.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(e){return S.globalEval(e),e}}}),S.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),S.ajaxTransport("script",function(n){var r,i;if(n.crossDomain||n.scriptAttrs)return{send:function(e,t){r=S("<script>").attr(n.scriptAttrs||{}).prop({charset:n.scriptCharset,src:n.url}).on("load error",i=function(e){r.remove(),i=null,e&&t("error"===e.type?404:200,e.type)}),E.head.appendChild(r[0])},abort:function(){i&&i()}}});var Ut,Xt=[],Vt=/(=)\?(?=&|$)|\?\?/;S.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Xt.pop()||S.expando+"_"+Ct.guid++;return this[e]=!0,e}}),S.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,o,a=!1!==e.jsonp&&(Vt.test(e.url)?"url":"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&Vt.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0])return r=e.jsonpCallback=m(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,a?e[a]=e[a].replace(Vt,"$1"+r):!1!==e.jsonp&&(e.url+=(Et.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return o||S.error(r+" was not called"),o[0]},e.dataTypes[0]="json",i=C[r],C[r]=function(){o=arguments},n.always(function(){void 0===i?S(C).removeProp(r):C[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,Xt.push(r)),o&&m(i)&&i(o[0]),o=i=void 0}),"script"}),v.createHTMLDocument=((Ut=E.implementation.createHTMLDocument("").body).innerHTML="<form></form><form></form>",2===Ut.childNodes.length),S.parseHTML=function(e,t,n){return"string"!=typeof e?[]:("boolean"==typeof t&&(n=t,t=!1),t||(v.createHTMLDocument?((r=(t=E.implementation.createHTMLDocument("")).createElement("base")).href=E.location.href,t.head.appendChild(r)):t=E),o=!n&&[],(i=N.exec(e))?[t.createElement(i[1])]:(i=xe([e],t,o),o&&o.length&&S(o).remove(),S.merge([],i.childNodes)));var r,i,o},S.fn.load=function(e,t,n){var r,i,o,a=this,s=e.indexOf(" ");return-1<s&&(r=yt(e.slice(s)),e=e.slice(0,s)),m(t)?(n=t,t=void 0):t&&"object"==typeof t&&(i="POST"),0<a.length&&S.ajax({url:e,type:i||"GET",dataType:"html",data:t}).done(function(e){o=arguments,a.html(r?S("<div>").append(S.parseHTML(e)).find(r):e)}).always(n&&function(e,t){a.each(function(){n.apply(this,o||[e.responseText,t,e])})}),this},S.expr.pseudos.animated=function(t){return S.grep(S.timers,function(e){return t===e.elem}).length},S.offset={setOffset:function(e,t,n){var r,i,o,a,s,u,l=S.css(e,"position"),c=S(e),f={};"static"===l&&(e.style.position="relative"),s=c.offset(),o=S.css(e,"top"),u=S.css(e,"left"),("absolute"===l||"fixed"===l)&&-1<(o+u).indexOf("auto")?(a=(r=c.position()).top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),m(t)&&(t=t.call(e,n,S.extend({},s))),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):c.css(f)}},S.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){S.offset.setOffset(this,t,e)});var e,n,r=this[0];return r?r.getClientRects().length?(e=r.getBoundingClientRect(),n=r.ownerDocument.defaultView,{top:e.top+n.pageYOffset,left:e.left+n.pageXOffset}):{top:0,left:0}:void 0},position:function(){if(this[0]){var e,t,n,r=this[0],i={top:0,left:0};if("fixed"===S.css(r,"position"))t=r.getBoundingClientRect();else{t=this.offset(),n=r.ownerDocument,e=r.offsetParent||n.documentElement;while(e&&(e===n.body||e===n.documentElement)&&"static"===S.css(e,"position"))e=e.parentNode;e&&e!==r&&1===e.nodeType&&((i=S(e).offset()).top+=S.css(e,"borderTopWidth",!0),i.left+=S.css(e,"borderLeftWidth",!0))}return{top:t.top-i.top-S.css(r,"marginTop",!0),left:t.left-i.left-S.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent;while(e&&"static"===S.css(e,"position"))e=e.offsetParent;return e||re})}}),S.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,i){var o="pageYOffset"===i;S.fn[t]=function(e){return B(this,function(e,t,n){var r;if(x(e)?r=e:9===e.nodeType&&(r=e.defaultView),void 0===n)return r?r[i]:e[t];r?r.scrollTo(o?r.pageXOffset:n,o?n:r.pageYOffset):e[t]=n},t,e,arguments.length)}}),S.each(["top","left"],function(e,n){S.cssHooks[n]=_e(v.pixelPosition,function(e,t){if(t)return t=Be(e,n),Pe.test(t)?S(e).position()[n]+"px":t})}),S.each({Height:"height",Width:"width"},function(a,s){S.each({padding:"inner"+a,content:s,"":"outer"+a},function(r,o){S.fn[o]=function(e,t){var n=arguments.length&&(r||"boolean"!=typeof e),i=r||(!0===e||!0===t?"margin":"border");return B(this,function(e,t,n){var r;return x(e)?0===o.indexOf("outer")?e["inner"+a]:e.document.documentElement["client"+a]:9===e.nodeType?(r=e.documentElement,Math.max(e.body["scroll"+a],r["scroll"+a],e.body["offset"+a],r["offset"+a],r["client"+a])):void 0===n?S.css(e,t,i):S.style(e,t,n,i)},s,n?e:void 0,n)}})}),S.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){S.fn[t]=function(e){return this.on(t,e)}}),S.fn.extend({bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)}}),S.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,n){S.fn[n]=function(e,t){return 0<arguments.length?this.on(n,null,e,t):this.trigger(n)}});var Gt=/^[\s\uFEFF\xA0]+|([^\s\uFEFF\xA0])[\s\uFEFF\xA0]+$/g;S.proxy=function(e,t){var n,r,i;if("string"==typeof t&&(n=e[t],t=e,e=n),m(e))return r=s.call(arguments,2),(i=function(){return e.apply(t||this,r.concat(s.call(arguments)))}).guid=e.guid=e.guid||S.guid++,i},S.holdReady=function(e){e?S.readyWait++:S.ready(!0)},S.isArray=Array.isArray,S.parseJSON=JSON.parse,S.nodeName=A,S.isFunction=m,S.isWindow=x,S.camelCase=X,S.type=w,S.now=Date.now,S.isNumeric=function(e){var t=S.type(e);return("number"===t||"string"===t)&&!isNaN(e-parseFloat(e))},S.trim=function(e){return null==e?"":(e+"").replace(Gt,"$1")},"function"==typeof define&&define.amd&&define("jquery",[],function(){return S});var Yt=C.jQuery,Qt=C.$;return S.noConflict=function(e){return C.$===S&&(C.$=Qt),e&&C.jQuery===S&&(C.jQuery=Yt),S},"undefined"==typeof e&&(C.jQuery=C.$=S),S});

/*! jQuery Migrate v3.4.0 | (c) OpenJS Foundation and other contributors | jquery.org/license */
"undefined"==typeof jQuery.migrateMute&&(jQuery.migrateMute=!0),function(t){"use strict";"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e,window)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery"),window):t(jQuery,window)}(function(s,n){"use strict";function e(e){return 0<=function(e,t){for(var r=/^(\d+)\.(\d+)\.(\d+)/,n=r.exec(e)||[],o=r.exec(t)||[],a=1;a<=3;a++){if(+n[a]>+o[a])return 1;if(+n[a]<+o[a])return-1}return 0}(s.fn.jquery,e)}s.migrateVersion="3.4.0";var t=Object.create(null),o=(s.migrateDisablePatches=function(){for(var e=0;e<arguments.length;e++)t[arguments[e]]=!0},s.migrateEnablePatches=function(){for(var e=0;e<arguments.length;e++)delete t[arguments[e]]},s.migrateIsPatchEnabled=function(e){return!t[e]},n.console&&n.console.log&&(s&&e("3.0.0")||n.console.log("JQMIGRATE: jQuery 3.0.0+ REQUIRED"),s.migrateWarnings&&n.console.log("JQMIGRATE: Migrate plugin loaded multiple times"),n.console.log("JQMIGRATE: Migrate is installed"+(s.migrateMute?"":" with logging active")+", version "+s.migrateVersion)),{});function i(e,t){var r=n.console;!s.migrateIsPatchEnabled(e)||s.migrateDeduplicateWarnings&&o[t]||(o[t]=!0,s.migrateWarnings.push(t+" ["+e+"]"),r&&r.warn&&!s.migrateMute&&(r.warn("JQMIGRATE: "+t),s.migrateTrace&&r.trace&&r.trace()))}function r(e,t,r,n,o){Object.defineProperty(e,t,{configurable:!0,enumerable:!0,get:function(){return i(n,o),r},set:function(e){i(n,o),r=e}})}function a(e,t,r,n,o){var a=e[t];e[t]=function(){return o&&i(n,o),(s.migrateIsPatchEnabled(n)?r:a||s.noop).apply(this,arguments)}}function u(e,t,r,n,o){if(!o)throw new Error("No warning message provided");a(e,t,r,n,o)}function d(e,t,r,n){a(e,t,r,n)}s.migrateDeduplicateWarnings=!0,s.migrateWarnings=[],void 0===s.migrateTrace&&(s.migrateTrace=!0),s.migrateReset=function(){o={},s.migrateWarnings.length=0},"BackCompat"===n.document.compatMode&&i("quirks","jQuery is not compatible with Quirks Mode");var c,l,p,f={},m=s.fn.init,y=s.find,h=/\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/,g=/\[(\s*[-\w]+\s*)([~|^$*]?=)\s*([-\w#]*?#[-\w#]*)\s*\]/g,v=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;for(c in d(s.fn,"init",function(e){var t=Array.prototype.slice.call(arguments);return s.migrateIsPatchEnabled("selector-empty-id")&&"string"==typeof e&&"#"===e&&(i("selector-empty-id","jQuery( '#' ) is not a valid selector"),t[0]=[]),m.apply(this,t)},"selector-empty-id"),s.fn.init.prototype=s.fn,d(s,"find",function(t){var r=Array.prototype.slice.call(arguments);if("string"==typeof t&&h.test(t))try{n.document.querySelector(t)}catch(e){t=t.replace(g,function(e,t,r,n){return"["+t+r+'"'+n+'"]'});try{n.document.querySelector(t),i("selector-hash","Attribute selector with '#' must be quoted: "+r[0]),r[0]=t}catch(e){i("selector-hash","Attribute selector with '#' was not fixed: "+r[0])}}return y.apply(this,r)},"selector-hash"),y)Object.prototype.hasOwnProperty.call(y,c)&&(s.find[c]=y[c]);u(s.fn,"size",function(){return this.length},"size","jQuery.fn.size() is deprecated and removed; use the .length property"),u(s,"parseJSON",function(){return JSON.parse.apply(null,arguments)},"parseJSON","jQuery.parseJSON is deprecated; use JSON.parse"),u(s,"holdReady",s.holdReady,"holdReady","jQuery.holdReady is deprecated"),u(s,"unique",s.uniqueSort,"unique","jQuery.unique is deprecated; use jQuery.uniqueSort"),r(s.expr,"filters",s.expr.pseudos,"expr-pre-pseudos","jQuery.expr.filters is deprecated; use jQuery.expr.pseudos"),r(s.expr,":",s.expr.pseudos,"expr-pre-pseudos","jQuery.expr[':'] is deprecated; use jQuery.expr.pseudos"),e("3.1.1")&&u(s,"trim",function(e){return null==e?"":(e+"").replace(v,"")},"trim","jQuery.trim is deprecated; use String.prototype.trim"),e("3.2.0")&&(u(s,"nodeName",function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},"nodeName","jQuery.nodeName is deprecated"),u(s,"isArray",Array.isArray,"isArray","jQuery.isArray is deprecated; use Array.isArray")),e("3.3.0")&&(u(s,"isNumeric",function(e){var t=typeof e;return("number"==t||"string"==t)&&!isNaN(e-parseFloat(e))},"isNumeric","jQuery.isNumeric() is deprecated"),s.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(e,t){f["[object "+t+"]"]=t.toLowerCase()}),u(s,"type",function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?f[Object.prototype.toString.call(e)]||"object":typeof e},"type","jQuery.type is deprecated"),u(s,"isFunction",function(e){return"function"==typeof e},"isFunction","jQuery.isFunction() is deprecated"),u(s,"isWindow",function(e){return null!=e&&e===e.window},"isWindow","jQuery.isWindow() is deprecated")),s.ajax&&(l=s.ajax,p=/(=)\?(?=&|$)|\?\?/,d(s,"ajax",function(){var e=l.apply(this,arguments);return e.promise&&(u(e,"success",e.done,"jqXHR-methods","jQXHR.success is deprecated and removed"),u(e,"error",e.fail,"jqXHR-methods","jQXHR.error is deprecated and removed"),u(e,"complete",e.always,"jqXHR-methods","jQXHR.complete is deprecated and removed")),e},"jqXHR-methods"),e("4.0.0")||s.ajaxPrefilter("+json",function(e){!1!==e.jsonp&&(p.test(e.url)||"string"==typeof e.data&&0===(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&p.test(e.data))&&i("jsonp-promotion","JSON-to-JSONP auto-promotion is deprecated")}));var j=s.fn.removeAttr,b=s.fn.toggleClass,w=/\S+/g;function Q(e){return e.replace(/-([a-z])/g,function(e,t){return t.toUpperCase()})}d(s.fn,"removeAttr",function(e){var r=this;return s.each(e.match(w),function(e,t){s.expr.match.bool.test(t)&&(i("removeAttr-bool","jQuery.fn.removeAttr no longer sets boolean properties: "+t),r.prop(t,!1))}),j.apply(this,arguments)},"removeAttr-bool"),d(s.fn,"toggleClass",function(t){return void 0!==t&&"boolean"!=typeof t?b.apply(this,arguments):(i("toggleClass-bool","jQuery.fn.toggleClass( boolean ) is deprecated"),this.each(function(){var e=this.getAttribute&&this.getAttribute("class")||"";e&&s.data(this,"__className__",e),this.setAttribute&&this.setAttribute("class",!e&&!1!==t&&s.data(this,"__className__")||"")}))},"toggleClass-bool");var x,A=!1,R=/^[a-z]/,T=/^(?:Border(?:Top|Right|Bottom|Left)?(?:Width|)|(?:Margin|Padding)?(?:Top|Right|Bottom|Left)?|(?:Min|Max)?(?:Width|Height))$/;s.swap&&s.each(["height","width","reliableMarginRight"],function(e,t){var r=s.cssHooks[t]&&s.cssHooks[t].get;r&&(s.cssHooks[t].get=function(){var e;return A=!0,e=r.apply(this,arguments),A=!1,e})}),d(s,"swap",function(e,t,r,n){var o,a={};for(o in A||i("swap","jQuery.swap() is undocumented and deprecated"),t)a[o]=e.style[o],e.style[o]=t[o];for(o in r=r.apply(e,n||[]),t)e.style[o]=a[o];return r},"swap"),e("3.4.0")&&"undefined"!=typeof Proxy&&(s.cssProps=new Proxy(s.cssProps||{},{set:function(){return i("cssProps","jQuery.cssProps is deprecated"),Reflect.set.apply(this,arguments)}})),e("4.0.0")&&"undefined"!=typeof Proxy&&(s.cssNumber=new Proxy({animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,gridArea:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnStart:!0,gridRow:!0,gridRowEnd:!0,gridRowStart:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},{get:function(){return i("css-number","jQuery.cssNumber is deprecated"),Reflect.get.apply(this,arguments)},set:function(){return i("css-number","jQuery.cssNumber is deprecated"),Reflect.set.apply(this,arguments)}})),x=s.fn.css,d(s.fn,"css",function(e,t){var r,n=this;return e&&"object"==typeof e&&!Array.isArray(e)?(s.each(e,function(e,t){s.fn.css.call(n,e,t)}),this):("number"==typeof t&&(t=Q(e),r=t,R.test(r)&&T.test(r[0].toUpperCase()+r.slice(1))||s.cssNumber[t]||i("css-number",'Number-typed values are deprecated for jQuery.fn.css( "'+e+'", value )')),x.apply(this,arguments))},"css-number");function C(e){var t=n.document.implementation.createHTMLDocument("");return t.body.innerHTML=e,t.body&&t.body.innerHTML}var S,N,P,k,H,E,M,q=s.data,D=(d(s,"data",function(e,t,r){var n,o,a;if(t&&"object"==typeof t&&2===arguments.length){for(a in n=s.hasData(e)&&q.call(this,e),o={},t)a!==Q(a)?(i("data-camelCase","jQuery.data() always sets/gets camelCased names: "+a),n[a]=t[a]):o[a]=t[a];return q.call(this,e,o),t}return t&&"string"==typeof t&&t!==Q(t)&&(n=s.hasData(e)&&q.call(this,e))&&t in n?(i("data-camelCase","jQuery.data() always sets/gets camelCased names: "+t),2<arguments.length&&(n[t]=r),n[t]):q.apply(this,arguments)},"data-camelCase"),s.fx&&(P=s.Tween.prototype.run,k=function(e){return e},d(s.Tween.prototype,"run",function(){1<s.easing[this.easing].length&&(i("easing-one-arg","'jQuery.easing."+this.easing.toString()+"' should use only one argument"),s.easing[this.easing]=k),P.apply(this,arguments)},"easing-one-arg"),S=s.fx.interval,N="jQuery.fx.interval is deprecated",n.requestAnimationFrame&&Object.defineProperty(s.fx,"interval",{configurable:!0,enumerable:!0,get:function(){return n.document.hidden||i("fx-interval",N),s.migrateIsPatchEnabled("fx-interval")&&void 0===S?13:S},set:function(e){i("fx-interval",N),S=e}})),s.fn.load),F=s.event.add,W=s.event.fix,O=(s.event.props=[],s.event.fixHooks={},r(s.event.props,"concat",s.event.props.concat,"event-old-patch","jQuery.event.props.concat() is deprecated and removed"),d(s.event,"fix",function(e){var t=e.type,r=this.fixHooks[t],n=s.event.props;if(n.length){i("event-old-patch","jQuery.event.props are deprecated and removed: "+n.join());while(n.length)s.event.addProp(n.pop())}if(r&&!r._migrated_&&(r._migrated_=!0,i("event-old-patch","jQuery.event.fixHooks are deprecated and removed: "+t),(n=r.props)&&n.length))while(n.length)s.event.addProp(n.pop());return t=W.call(this,e),r&&r.filter?r.filter(t,e):t},"event-old-patch"),d(s.event,"add",function(e,t){return e===n&&"load"===t&&"complete"===n.document.readyState&&i("load-after-event","jQuery(window).on('load'...) called after load event occurred"),F.apply(this,arguments)},"load-after-event"),s.each(["load","unload","error"],function(e,t){d(s.fn,t,function(){var e=Array.prototype.slice.call(arguments,0);return"load"===t&&"string"==typeof e[0]?D.apply(this,e):(i("shorthand-removed-v3","jQuery.fn."+t+"() is deprecated"),e.splice(0,0,t),arguments.length?this.on.apply(this,e):(this.triggerHandler.apply(this,e),this))},"shorthand-removed-v3")}),s.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(e,r){u(s.fn,r,function(e,t){return 0<arguments.length?this.on(r,null,e,t):this.trigger(r)},"shorthand-deprecated-v3","jQuery.fn."+r+"() event shorthand is deprecated")}),s(function(){s(n.document).triggerHandler("ready")}),s.event.special.ready={setup:function(){this===n.document&&i("ready-event","'ready' event is deprecated")}},u(s.fn,"bind",function(e,t,r){return this.on(e,null,t,r)},"pre-on-methods","jQuery.fn.bind() is deprecated"),u(s.fn,"unbind",function(e,t){return this.off(e,null,t)},"pre-on-methods","jQuery.fn.unbind() is deprecated"),u(s.fn,"delegate",function(e,t,r,n){return this.on(t,e,r,n)},"pre-on-methods","jQuery.fn.delegate() is deprecated"),u(s.fn,"undelegate",function(e,t,r){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",r)},"pre-on-methods","jQuery.fn.undelegate() is deprecated"),u(s.fn,"hover",function(e,t){return this.on("mouseenter",e).on("mouseleave",t||e)},"pre-on-methods","jQuery.fn.hover() is deprecated"),/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi),_=(s.UNSAFE_restoreLegacyHtmlPrefilter=function(){s.migrateEnablePatches("self-closed-tags")},d(s,"htmlPrefilter",function(e){var t,r;return(r=(t=e).replace(O,"<$1></$2>"))!==t&&C(t)!==C(r)&&i("self-closed-tags","HTML tags must be properly nested and closed: "+t),e.replace(O,"<$1></$2>")},"self-closed-tags"),s.migrateDisablePatches("self-closed-tags"),s.fn.offset);return d(s.fn,"offset",function(){var e=this[0];return!e||e.nodeType&&e.getBoundingClientRect?_.apply(this,arguments):(i("offset-valid-elem","jQuery.fn.offset() requires a valid DOM element"),arguments.length?this:void 0)},"offset-valid-elem"),s.ajax&&(H=s.param,d(s,"param",function(e,t){var r=s.ajaxSettings&&s.ajaxSettings.traditional;return void 0===t&&r&&(i("param-ajax-traditional","jQuery.param() no longer uses jQuery.ajaxSettings.traditional"),t=r),H.call(this,e,t)},"param-ajax-traditional")),u(s.fn,"andSelf",s.fn.addBack,"andSelf","jQuery.fn.andSelf() is deprecated and removed, use jQuery.fn.addBack()"),s.Deferred&&(E=s.Deferred,M=[["resolve","done",s.Callbacks("once memory"),s.Callbacks("once memory"),"resolved"],["reject","fail",s.Callbacks("once memory"),s.Callbacks("once memory"),"rejected"],["notify","progress",s.Callbacks("memory"),s.Callbacks("memory")]],d(s,"Deferred",function(e){var a=E(),i=a.promise();function t(){var o=arguments;return s.Deferred(function(n){s.each(M,function(e,t){var r="function"==typeof o[e]&&o[e];a[t[1]](function(){var e=r&&r.apply(this,arguments);e&&"function"==typeof e.promise?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[t[0]+"With"](this===i?n.promise():this,r?[e]:arguments)})}),o=null}).promise()}return u(a,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),u(i,"pipe",t,"deferred-pipe","deferred.pipe() is deprecated"),e&&e.call(a,a),a},"deferred-pipe"),s.Deferred.exceptionHook=E.exceptionHook),s});

/*! jQuery Validation Plugin - v1.19.5 - 7/1/2022
 * https://jqueryvalidation.org/
 * Copyright (c) 2022 Jörn Zaefferer; Licensed MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){a.extend(a.fn,{validate:function(b){if(!this.length)return void(b&&b.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing."));var c=a.data(this[0],"validator");return c?c:(this.attr("novalidate","novalidate"),c=new a.validator(b,this[0]),a.data(this[0],"validator",c),c.settings.onsubmit&&(this.on("click.validate",":submit",function(b){c.submitButton=b.currentTarget,a(this).hasClass("cancel")&&(c.cancelSubmit=!0),void 0!==a(this).attr("formnovalidate")&&(c.cancelSubmit=!0)}),this.on("submit.validate",function(b){function d(){var d,e;return c.submitButton&&(c.settings.submitHandler||c.formSubmitted)&&(d=a("<input type='hidden'/>").attr("name",c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)),!(c.settings.submitHandler&&!c.settings.debug)||(e=c.settings.submitHandler.call(c,c.currentForm,b),d&&d.remove(),void 0!==e&&e)}return c.settings.debug&&b.preventDefault(),c.cancelSubmit?(c.cancelSubmit=!1,d()):c.form()?c.pendingRequest?(c.formSubmitted=!0,!1):d():(c.focusInvalid(),!1)})),c)},valid:function(){var b,c,d;return a(this[0]).is("form")?b=this.validate().form():(d=[],b=!0,c=a(this[0].form).validate(),this.each(function(){b=c.element(this)&&b,b||(d=d.concat(c.errorList))}),c.errorList=d),b},rules:function(b,c){var d,e,f,g,h,i,j=this[0],k="undefined"!=typeof this.attr("contenteditable")&&"false"!==this.attr("contenteditable");if(null!=j&&(!j.form&&k&&(j.form=this.closest("form")[0],j.name=this.attr("name")),null!=j.form)){if(b)switch(d=a.data(j.form,"validator").settings,e=d.rules,f=a.validator.staticRules(j),b){case"add":a.extend(f,a.validator.normalizeRule(c)),delete f.messages,e[j.name]=f,c.messages&&(d.messages[j.name]=a.extend(d.messages[j.name],c.messages));break;case"remove":return c?(i={},a.each(c.split(/\s/),function(a,b){i[b]=f[b],delete f[b]}),i):(delete e[j.name],f)}return g=a.validator.normalizeRules(a.extend({},a.validator.classRules(j),a.validator.attributeRules(j),a.validator.dataRules(j),a.validator.staticRules(j)),j),g.required&&(h=g.required,delete g.required,g=a.extend({required:h},g)),g.remote&&(h=g.remote,delete g.remote,g=a.extend(g,{remote:h})),g}}});var b=function(a){return a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")};a.extend(a.expr.pseudos||a.expr[":"],{blank:function(c){return!b(""+a(c).val())},filled:function(c){var d=a(c).val();return null!==d&&!!b(""+d)},unchecked:function(b){return!a(b).prop("checked")}}),a.validator=function(b,c){this.settings=a.extend(!0,{},a.validator.defaults,b),this.currentForm=c,this.init()},a.validator.format=function(b,c){return 1===arguments.length?function(){var c=a.makeArray(arguments);return c.unshift(b),a.validator.format.apply(this,c)}:void 0===c?b:(arguments.length>2&&c.constructor!==Array&&(c=a.makeArray(arguments).slice(1)),c.constructor!==Array&&(c=[c]),a.each(c,function(a,c){b=b.replace(new RegExp("\\{"+a+"\\}","g"),function(){return c})}),b)},a.extend(a.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",pendingClass:"pending",validClass:"valid",errorElement:"label",focusCleanup:!1,focusInvalid:!0,errorContainer:a([]),errorLabelContainer:a([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(a){this.lastActive=a,this.settings.focusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass),this.hideThese(this.errorsFor(a)))},onfocusout:function(a){this.checkable(a)||!(a.name in this.submitted)&&this.optional(a)||this.element(a)},onkeyup:function(b,c){var d=[16,17,18,20,35,36,37,38,39,40,45,144,225];9===c.which&&""===this.elementValue(b)||a.inArray(c.keyCode,d)!==-1||(b.name in this.submitted||b.name in this.invalid)&&this.element(b)},onclick:function(a){a.name in this.submitted?this.element(a):a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).addClass(c).removeClass(d):a(b).addClass(c).removeClass(d)},unhighlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).removeClass(c).addClass(d):a(b).removeClass(c).addClass(d)}},setDefaults:function(b){a.extend(a.validator.defaults,b)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date (ISO).",number:"Please enter a valid number.",digits:"Please enter only digits.",equalTo:"Please enter the same value again.",maxlength:a.validator.format("Please enter no more than {0} characters."),minlength:a.validator.format("Please enter at least {0} characters."),rangelength:a.validator.format("Please enter a value between {0} and {1} characters long."),range:a.validator.format("Please enter a value between {0} and {1}."),max:a.validator.format("Please enter a value less than or equal to {0}."),min:a.validator.format("Please enter a value greater than or equal to {0}."),step:a.validator.format("Please enter a multiple of {0}.")},autoCreateRanges:!1,prototype:{init:function(){function b(b){var c="undefined"!=typeof a(this).attr("contenteditable")&&"false"!==a(this).attr("contenteditable");if(!this.form&&c&&(this.form=a(this).closest("form")[0],this.name=a(this).attr("name")),d===this.form){var e=a.data(this.form,"validator"),f="on"+b.type.replace(/^validate/,""),g=e.settings;g[f]&&!a(this).is(g.ignore)&&g[f].call(e,this,b)}}this.labelContainer=a(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||a(this.currentForm),this.containers=a(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var c,d=this.currentForm,e=this.groups={};a.each(this.settings.groups,function(b,c){"string"==typeof c&&(c=c.split(/\s/)),a.each(c,function(a,c){e[c]=b})}),c=this.settings.rules,a.each(c,function(b,d){c[b]=a.validator.normalizeRule(d)}),a(this.currentForm).on("focusin.validate focusout.validate keyup.validate",":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], [type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox'], [contenteditable], [type='button']",b).on("click.validate","select, option, [type='radio'], [type='checkbox']",b),this.settings.invalidHandler&&a(this.currentForm).on("invalid-form.validate",this.settings.invalidHandler)},form:function(){return this.checkForm(),a.extend(this.submitted,this.errorMap),this.invalid=a.extend({},this.errorMap),this.valid()||a(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(b){var c,d,e=this.clean(b),f=this.validationTargetFor(e),g=this,h=!0;return void 0===f?delete this.invalid[e.name]:(this.prepareElement(f),this.currentElements=a(f),d=this.groups[f.name],d&&a.each(this.groups,function(a,b){b===d&&a!==f.name&&(e=g.validationTargetFor(g.clean(g.findByName(a))),e&&e.name in g.invalid&&(g.currentElements.push(e),h=g.check(e)&&h))}),c=this.check(f)!==!1,h=h&&c,c?this.invalid[f.name]=!1:this.invalid[f.name]=!0,this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),a(b).attr("aria-invalid",!c)),h},showErrors:function(b){if(b){var c=this;a.extend(this.errorMap,b),this.errorList=a.map(this.errorMap,function(a,b){return{message:a,element:c.findByName(b)[0]}}),this.successList=a.grep(this.successList,function(a){return!(a.name in b)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){a.fn.resetForm&&a(this.currentForm).resetForm(),this.invalid={},this.submitted={},this.prepareForm(),this.hideErrors();var b=this.elements().removeData("previousValue").removeAttr("aria-invalid");this.resetElements(b)},resetElements:function(a){var b;if(this.settings.unhighlight)for(b=0;a[b];b++)this.settings.unhighlight.call(this,a[b],this.settings.errorClass,""),this.findByName(a[b].name).removeClass(this.settings.validClass);else a.removeClass(this.settings.errorClass).removeClass(this.settings.validClass)},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b,c=0;for(b in a)void 0!==a[b]&&null!==a[b]&&a[b]!==!1&&c++;return c},hideErrors:function(){this.hideThese(this.toHide)},hideThese:function(a){a.not(this.containers).text(""),this.addWrapper(a).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{a(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").trigger("focus").trigger("focusin")}catch(b){}},findLastActive:function(){var b=this.lastActive;return b&&1===a.grep(this.errorList,function(a){return a.element.name===b.name}).length&&b},elements:function(){var b=this,c={};return a(this.currentForm).find("input, select, textarea, [contenteditable]").not(":submit, :reset, :image, :disabled").not(this.settings.ignore).filter(function(){var d=this.name||a(this).attr("name"),e="undefined"!=typeof a(this).attr("contenteditable")&&"false"!==a(this).attr("contenteditable");return!d&&b.settings.debug&&window.console&&console.error("%o has no name assigned",this),e&&(this.form=a(this).closest("form")[0],this.name=d),this.form===b.currentForm&&(!(d in c||!b.objectLength(a(this).rules()))&&(c[d]=!0,!0))})},clean:function(b){return a(b)[0]},errors:function(){var b=this.settings.errorClass.split(" ").join(".");return a(this.settings.errorElement+"."+b,this.errorContext)},resetInternals:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=a([]),this.toHide=a([])},reset:function(){this.resetInternals(),this.currentElements=a([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset(),this.toHide=this.errorsFor(a)},elementValue:function(b){var c,d,e=a(b),f=b.type,g="undefined"!=typeof e.attr("contenteditable")&&"false"!==e.attr("contenteditable");return"radio"===f||"checkbox"===f?this.findByName(b.name).filter(":checked").val():"number"===f&&"undefined"!=typeof b.validity?b.validity.badInput?"NaN":e.val():(c=g?e.text():e.val(),"file"===f?"C:\\fakepath\\"===c.substr(0,12)?c.substr(12):(d=c.lastIndexOf("/"),d>=0?c.substr(d+1):(d=c.lastIndexOf("\\"),d>=0?c.substr(d+1):c)):"string"==typeof c?c.replace(/\r/g,""):c)},check:function(b){b=this.validationTargetFor(this.clean(b));var c,d,e,f,g=a(b).rules(),h=a.map(g,function(a,b){return b}).length,i=!1,j=this.elementValue(b);"function"==typeof g.normalizer?f=g.normalizer:"function"==typeof this.settings.normalizer&&(f=this.settings.normalizer),f&&(j=f.call(b,j),delete g.normalizer);for(d in g){e={method:d,parameters:g[d]};try{if(c=a.validator.methods[d].call(this,j,b,e.parameters),"dependency-mismatch"===c&&1===h){i=!0;continue}if(i=!1,"pending"===c)return void(this.toHide=this.toHide.not(this.errorsFor(b)));if(!c)return this.formatAndAdd(b,e),!1}catch(k){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+b.id+", check the '"+e.method+"' method.",k),k instanceof TypeError&&(k.message+=".  Exception occurred when checking element "+b.id+", check the '"+e.method+"' method."),k}}if(!i)return this.objectLength(g)&&this.successList.push(b),!0},customDataMessage:function(b,c){return a(b).data("msg"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase())||a(b).data("msg")},customMessage:function(a,b){var c=this.settings.messages[a];return c&&(c.constructor===String?c:c[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(void 0!==arguments[a])return arguments[a]},defaultMessage:function(b,c){"string"==typeof c&&(c={method:c});var d=this.findDefined(this.customMessage(b.name,c.method),this.customDataMessage(b,c.method),!this.settings.ignoreTitle&&b.title||void 0,a.validator.messages[c.method],"<strong>Warning: No message defined for "+b.name+"</strong>"),e=/\$?\{(\d+)\}/g;return"function"==typeof d?d=d.call(this,c.parameters,b):e.test(d)&&(d=a.validator.format(d.replace(e,"{$1}"),c.parameters)),d},formatAndAdd:function(a,b){var c=this.defaultMessage(a,b);this.errorList.push({message:c,element:a,method:b.method}),this.errorMap[a.name]=c,this.submitted[a.name]=c},addWrapper:function(a){return this.settings.wrapper&&(a=a.add(a.parent(this.settings.wrapper))),a},defaultShowErrors:function(){var a,b,c;for(a=0;this.errorList[a];a++)c=this.errorList[a],this.settings.highlight&&this.settings.highlight.call(this,c.element,this.settings.errorClass,this.settings.validClass),this.showLabel(c.element,c.message);if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight)for(a=0,b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return a(this.errorList).map(function(){return this.element})},showLabel:function(b,c){var d,e,f,g,h=this.errorsFor(b),i=this.idOrName(b),j=a(b).attr("aria-describedby");h.length?(h.removeClass(this.settings.validClass).addClass(this.settings.errorClass),h.html(c)):(h=a("<"+this.settings.errorElement+">").attr("id",i+"-error").addClass(this.settings.errorClass).html(c||""),d=h,this.settings.wrapper&&(d=h.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.length?this.labelContainer.append(d):this.settings.errorPlacement?this.settings.errorPlacement.call(this,d,a(b)):d.insertAfter(b),h.is("label")?h.attr("for",i):0===h.parents("label[for='"+this.escapeCssMeta(i)+"']").length&&(f=h.attr("id"),j?j.match(new RegExp("\\b"+this.escapeCssMeta(f)+"\\b"))||(j+=" "+f):j=f,a(b).attr("aria-describedby",j),e=this.groups[b.name],e&&(g=this,a.each(g.groups,function(b,c){c===e&&a("[name='"+g.escapeCssMeta(b)+"']",g.currentForm).attr("aria-describedby",h.attr("id"))})))),!c&&this.settings.success&&(h.text(""),"string"==typeof this.settings.success?h.addClass(this.settings.success):this.settings.success(h,b)),this.toShow=this.toShow.add(h)},errorsFor:function(b){var c=this.escapeCssMeta(this.idOrName(b)),d=a(b).attr("aria-describedby"),e="label[for='"+c+"'], label[for='"+c+"'] *";return d&&(e=e+", #"+this.escapeCssMeta(d).replace(/\s+/g,", #")),this.errors().filter(e)},escapeCssMeta:function(a){return void 0===a?"":a.replace(/([\\!"#$%&'()*+,./:;<=>?@\[\]^`{|}~])/g,"\\$1")},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(b){return this.checkable(b)&&(b=this.findByName(b.name)),a(b).not(this.settings.ignore)[0]},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(b){return a(this.currentForm).find("[name='"+this.escapeCssMeta(b)+"']")},getLength:function(b,c){switch(c.nodeName.toLowerCase()){case"select":return a("option:selected",c).length;case"input":if(this.checkable(c))return this.findByName(c.name).filter(":checked").length}return b.length},depend:function(a,b){return!this.dependTypes[typeof a]||this.dependTypes[typeof a](a,b)},dependTypes:{"boolean":function(a){return a},string:function(b,c){return!!a(b,c.form).length},"function":function(a,b){return a(b)}},optional:function(b){var c=this.elementValue(b);return!a.validator.methods.required.call(this,c,b)&&"dependency-mismatch"},startRequest:function(b){this.pending[b.name]||(this.pendingRequest++,a(b).addClass(this.settings.pendingClass),this.pending[b.name]=!0)},stopRequest:function(b,c){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[b.name],a(b).removeClass(this.settings.pendingClass),c&&0===this.pendingRequest&&this.formSubmitted&&this.form()&&0===this.pendingRequest?(a(this.currentForm).trigger("submit"),this.submitButton&&a("input:hidden[name='"+this.submitButton.name+"']",this.currentForm).remove(),this.formSubmitted=!1):!c&&0===this.pendingRequest&&this.formSubmitted&&(a(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(b,c){return c="string"==typeof c&&c||"remote",a.data(b,"previousValue")||a.data(b,"previousValue",{old:null,valid:!0,message:this.defaultMessage(b,{method:c})})},destroy:function(){this.resetForm(),a(this.currentForm).off(".validate").removeData("validator").find(".validate-equalTo-blur").off(".validate-equalTo").removeClass("validate-equalTo-blur").find(".validate-lessThan-blur").off(".validate-lessThan").removeClass("validate-lessThan-blur").find(".validate-lessThanEqual-blur").off(".validate-lessThanEqual").removeClass("validate-lessThanEqual-blur").find(".validate-greaterThanEqual-blur").off(".validate-greaterThanEqual").removeClass("validate-greaterThanEqual-blur").find(".validate-greaterThan-blur").off(".validate-greaterThan").removeClass("validate-greaterThan-blur")}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(b,c){b.constructor===String?this.classRuleSettings[b]=c:a.extend(this.classRuleSettings,b)},classRules:function(b){var c={},d=a(b).attr("class");return d&&a.each(d.split(" "),function(){this in a.validator.classRuleSettings&&a.extend(c,a.validator.classRuleSettings[this])}),c},normalizeAttributeRule:function(a,b,c,d){/min|max|step/.test(c)&&(null===b||/number|range|text/.test(b))&&(d=Number(d),isNaN(d)&&(d=void 0)),d||0===d?a[c]=d:b===c&&"range"!==b&&(a["date"===b?"dateISO":c]=!0)},attributeRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)"required"===c?(d=b.getAttribute(c),""===d&&(d=!0),d=!!d):d=f.attr(c),this.normalizeAttributeRule(e,g,c,d);return e.maxlength&&/-1|2147483647|524288/.test(e.maxlength)&&delete e.maxlength,e},dataRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)d=f.data("rule"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase()),""===d&&(d=!0),this.normalizeAttributeRule(e,g,c,d);return e},staticRules:function(b){var c={},d=a.data(b.form,"validator");return d.settings.rules&&(c=a.validator.normalizeRule(d.settings.rules[b.name])||{}),c},normalizeRules:function(b,c){return a.each(b,function(d,e){if(e===!1)return void delete b[d];if(e.param||e.depends){var f=!0;switch(typeof e.depends){case"string":f=!!a(e.depends,c.form).length;break;case"function":f=e.depends.call(c,c)}f?b[d]=void 0===e.param||e.param:(a.data(c.form,"validator").resetElements(a(c)),delete b[d])}}),a.each(b,function(a,d){b[a]="function"==typeof d&&"normalizer"!==a?d(c):d}),a.each(["minlength","maxlength"],function(){b[this]&&(b[this]=Number(b[this]))}),a.each(["rangelength","range"],function(){var a;b[this]&&(Array.isArray(b[this])?b[this]=[Number(b[this][0]),Number(b[this][1])]:"string"==typeof b[this]&&(a=b[this].replace(/[\[\]]/g,"").split(/[\s,]+/),b[this]=[Number(a[0]),Number(a[1])]))}),a.validator.autoCreateRanges&&(null!=b.min&&null!=b.max&&(b.range=[b.min,b.max],delete b.min,delete b.max),null!=b.minlength&&null!=b.maxlength&&(b.rangelength=[b.minlength,b.maxlength],delete b.minlength,delete b.maxlength)),b},normalizeRule:function(b){if("string"==typeof b){var c={};a.each(b.split(/\s/),function(){c[this]=!0}),b=c}return b},addMethod:function(b,c,d){a.validator.methods[b]=c,a.validator.messages[b]=void 0!==d?d:a.validator.messages[b],c.length<3&&a.validator.addClassRules(b,a.validator.normalizeRule(b))},methods:{required:function(b,c,d){if(!this.depend(d,c))return"dependency-mismatch";if("select"===c.nodeName.toLowerCase()){var e=a(c).val();return e&&e.length>0}return this.checkable(c)?this.getLength(b,c)>0:void 0!==b&&null!==b&&b.length>0},email:function(a,b){return this.optional(b)||/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test(a)},url:function(a,b){return this.optional(b)||/^(?:(?:(?:https?|ftp):)?\/\/)(?:(?:[^\]\[?\/<~#`!@$^&*()+=}|:";',>{ ]|%[0-9A-Fa-f]{2})+(?::(?:[^\]\[?\/<~#`!@$^&*()+=}|:";',>{ ]|%[0-9A-Fa-f]{2})*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u00a1-\uffff][a-z0-9\u00a1-\uffff_-]{0,62})?[a-z0-9\u00a1-\uffff]\.)+(?:[a-z\u00a1-\uffff]{2,}\.?))(?::\d{2,5})?(?:[/?#]\S*)?$/i.test(a)},date:function(){var a=!1;return function(b,c){return a||(a=!0,this.settings.debug&&window.console&&console.warn("The `date` method is deprecated and will be removed in version '2.0.0'.\nPlease don't use it, since it relies on the Date constructor, which\nbehaves very differently across browsers and locales. Use `dateISO`\ninstead or one of the locale specific methods in `localizations/`\nand `additional-methods.js`.")),this.optional(c)||!/Invalid|NaN/.test(new Date(b).toString())}}(),dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a)},number:function(a,b){return this.optional(b)||/^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},minlength:function(a,b,c){var d=Array.isArray(a)?a.length:this.getLength(a,b);return this.optional(b)||d>=c},maxlength:function(a,b,c){var d=Array.isArray(a)?a.length:this.getLength(a,b);return this.optional(b)||d<=c},rangelength:function(a,b,c){var d=Array.isArray(a)?a.length:this.getLength(a,b);return this.optional(b)||d>=c[0]&&d<=c[1]},min:function(a,b,c){return this.optional(b)||a>=c},max:function(a,b,c){return this.optional(b)||a<=c},range:function(a,b,c){return this.optional(b)||a>=c[0]&&a<=c[1]},step:function(b,c,d){var e,f=a(c).attr("type"),g="Step attribute on input type "+f+" is not supported.",h=["text","number","range"],i=new RegExp("\\b"+f+"\\b"),j=f&&!i.test(h.join()),k=function(a){var b=(""+a).match(/(?:\.(\d+))?$/);return b&&b[1]?b[1].length:0},l=function(a){return Math.round(a*Math.pow(10,e))},m=!0;if(j)throw new Error(g);return e=k(d),(k(b)>e||l(b)%l(d)!==0)&&(m=!1),this.optional(c)||m},equalTo:function(b,c,d){var e=a(d);return this.settings.onfocusout&&e.not(".validate-equalTo-blur").length&&e.addClass("validate-equalTo-blur").on("blur.validate-equalTo",function(){a(c).valid()}),b===e.val()},remote:function(b,c,d,e){if(this.optional(c))return"dependency-mismatch";e="string"==typeof e&&e||"remote";var f,g,h,i=this.previousValue(c,e);return this.settings.messages[c.name]||(this.settings.messages[c.name]={}),i.originalMessage=i.originalMessage||this.settings.messages[c.name][e],this.settings.messages[c.name][e]=i.message,d="string"==typeof d&&{url:d}||d,h=a.param(a.extend({data:b},d.data)),i.old===h?i.valid:(i.old=h,f=this,this.startRequest(c),g={},g[c.name]=b,a.ajax(a.extend(!0,{mode:"abort",port:"validate"+c.name,dataType:"json",data:g,context:f.currentForm,success:function(a){var d,g,h,j=a===!0||"true"===a;f.settings.messages[c.name][e]=i.originalMessage,j?(h=f.formSubmitted,f.resetInternals(),f.toHide=f.errorsFor(c),f.formSubmitted=h,f.successList.push(c),f.invalid[c.name]=!1,f.showErrors()):(d={},g=a||f.defaultMessage(c,{method:e,parameters:b}),d[c.name]=i.message=g,f.invalid[c.name]=!0,f.showErrors(d)),i.valid=j,f.stopRequest(c,j)}},d)),"pending")}}});var c,d={};return a.ajaxPrefilter?a.ajaxPrefilter(function(a,b,c){var e=a.port;"abort"===a.mode&&(d[e]&&d[e].abort(),d[e]=c)}):(c=a.ajax,a.ajax=function(b){var e=("mode"in b?b:a.ajaxSettings).mode,f=("port"in b?b:a.ajaxSettings).port;return"abort"===e?(d[f]&&d[f].abort(),d[f]=c.apply(this,arguments),d[f]):c.apply(this,arguments)}),a});
/*! jQuery Validation Plugin - v1.19.5 - 7/1/2022
 * https://jqueryvalidation.org/
 * Copyright (c) 2022 Jörn Zaefferer; Licensed MIT */
!function(a){"function"==typeof define&&define.amd?define(["jquery","jquery.validate.min"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery")):a(jQuery)}(function(a){return a.extend(a.validator.messages,{required:"Detta f&auml;lt &auml;r obligatoriskt.",remote:"Var snäll och åtgärda detta fält.",maxlength:a.validator.format("Du f&aring;r ange h&ouml;gst {0} tecken."),minlength:a.validator.format("Du m&aring;ste ange minst {0} tecken."),rangelength:a.validator.format("Ange minst {0} och max {1} tecken."),email:"Ange en korrekt e-postadress.",url:"Ange en korrekt URL.",date:"Ange ett korrekt datum.",dateISO:"Ange ett korrekt datum (&Aring;&Aring;&Aring;&Aring;-MM-DD).",number:"Använd endast siffror.",digits:"Ange endast siffror.",equalTo:"Ange samma v&auml;rde igen.",range:a.validator.format("Ange ett v&auml;rde mellan {0} och {1}."),max:a.validator.format("Ange ett v&auml;rde som &auml;r mindre eller lika med {0}."),min:a.validator.format("Ange ett v&auml;rde som &auml;r st&ouml;rre eller lika med {0}."),creditcard:"Ange ett korrekt kreditkortsnummer.",pattern:"Ogiltigt format."}),a});
// wrap in UMD - see https://github.com/umdjs/umd/blob/master/jqueryPlugin.js
(function(factory) {
	if (typeof define === "function" && define.amd) {
		define([ "jquery" ], function($) {
			factory($, window, document);
		});
	} else if (typeof module === "object" && module.exports) {
		module.exports = factory(require("jquery"), window, document);
	} else {
		factory(jQuery, window, document);
	}
})(function($, window, document, undefined) {
	"use strict";
	var pluginName = "countrySelect", id = 1, // give each instance its own ID for namespaced event handling
	defaults = {
		// Default country
		defaultCountry: "",
		// Position the selected flag inside or outside of the input
		defaultStyling: "inside",
		// don't display these countries
		excludeCountries: [],
		// Display only these countries
		onlyCountries: [],
		// The countries at the top of the list. Defaults to United States and United Kingdom
		preferredCountries: [ "us", "gb" ],
		// localized country names e.g. { 'de': 'Deutschland' }
		localizedCountries: null,
		// Set the dropdown's width to be the same as the input. This is automatically enabled for small screens.
		responsiveDropdown: ($(window).width() < 768 ? true : false),
	}, keys = {
		UP: 38,
		DOWN: 40,
		ENTER: 13,
		ESC: 27,
		BACKSPACE: 8,
		PLUS: 43,
		SPACE: 32,
		A: 65,
		Z: 90
	}, windowLoaded = false;
	// keep track of if the window.load event has fired as impossible to check after the fact
	$(window).on('load', function() {
		windowLoaded = true;
	});
	function Plugin(element, options) {
		this.element = element;
		this.options = $.extend({}, defaults, options);
		this._defaults = defaults;
		// event namespace
		this.ns = "." + pluginName + id++;
		this._name = pluginName;
		this.init();
	}
	Plugin.prototype = {
		init: function() {
			// Process all the data: onlyCountries, excludeCountries, preferredCountries, defaultCountry etc
			this._processCountryData();
			// Generate the markup
			this._generateMarkup();
			// Set the initial state of the input value and the selected flag
			this._setInitialState();
			// Start all of the event listeners: input keyup, selectedFlag click
			this._initListeners();
			// Return this when the auto country is resolved.
			this.autoCountryDeferred = new $.Deferred();
			// Get auto country.
			this._initAutoCountry();
			// Keep track as the user types
		        this.typedLetters = "";

			return this.autoCountryDeferred;
		},
		/********************
		 *  PRIVATE METHODS
		 ********************/
		// prepare all of the country data, including onlyCountries, excludeCountries, preferredCountries and
		// defaultCountry options
		_processCountryData: function() {
			// set the instances country data objects
			this._setInstanceCountryData();
			// set the preferredCountries property
			this._setPreferredCountries();
			// translate countries according to localizedCountries option
			if (this.options.localizedCountries) this._translateCountriesByLocale();
			// sort countries by name
			//if (this.options.onlyCountries.length || this.options.localizedCountries) {
			//	this.countries.sort(this._countryNameSort);
			//}
			this.countries.sort(this._countryNameSort);
		},
		// process onlyCountries array if present
		_setInstanceCountryData: function() {
			var that = this;
			if (this.options.onlyCountries.length) {
				var newCountries = [];
				$.each(this.options.onlyCountries, function(i, countryCode) {
					var countryData = that._getCountryData(countryCode, true);
					if (countryData) {
						newCountries.push(countryData);
					}
				});
				this.countries = newCountries;
			} else if (this.options.excludeCountries.length) {
                var lowerCaseExcludeCountries = this.options.excludeCountries.map(function(country) {
                    return country.toLowerCase();
                });
                this.countries = allCountries.filter(function(country) {
                    return lowerCaseExcludeCountries.indexOf(country.iso2) === -1;
                });
            } else {
				this.countries = allCountries;
			}
		},
		// Process preferred countries - iterate through the preferences,
		// fetching the country data for each one
		_setPreferredCountries: function() {
			var that = this;
			this.preferredCountries = [];
			$.each(this.options.preferredCountries, function(i, countryCode) {
				var countryData = that._getCountryData(countryCode, false);
				if (countryData) {
					that.preferredCountries.push(countryData);
				}
			});
		},
		// Translate Countries by object literal provided on config
		_translateCountriesByLocale() {
			for (let i = 0; i < this.countries.length; i++) {
				const iso = this.countries[i].iso2.toLowerCase();
				if (this.options.localizedCountries.hasOwnProperty(iso)) {
					this.countries[i].name = this.options.localizedCountries[iso];
				}
			}
		},
		// sort by country name
		_countryNameSort(a, b) {
			return a.name.localeCompare(b.name);
		},
		// generate all of the markup for the plugin: the selected flag overlay, and the dropdown
		_generateMarkup: function() {
			// Country input
			this.countryInput = $(this.element);
			// containers (mostly for positioning)
			var mainClass = "country-select";
			if (this.options.defaultStyling) {
				mainClass += " " + this.options.defaultStyling;
			}
			this.countryInput.wrap($("<div>", {
				"class": mainClass
			}));
			var flagsContainer = $("<div>", {
				"class": "flag-dropdown"
			}).insertAfter(this.countryInput);
			// currently selected flag (displayed to left of input)
			var selectedFlag = $("<div>", {
				"class": "selected-flag"
			}).appendTo(flagsContainer);
			this.selectedFlagInner = $("<div>", {
				"class": "flag"
			}).appendTo(selectedFlag);
			// CSS triangle
			//$("<div>", {
			//	"class": "arrow"
			//}).appendTo(selectedFlag);
			// country list contains: preferred countries, then divider, then all countries
			this.countryList = $("<ul>", {
				"class": "country-list v-hide"
			}).appendTo(flagsContainer);
			if (this.preferredCountries.length) {
				this._appendListItems(this.preferredCountries, "preferred");
				$("<li>", {
					"class": "divider"
				}).appendTo(this.countryList);
			}
			this._appendListItems(this.countries, "");
			// Add the hidden input for the country code
			this.countryCodeInput = $("#"+this.countryInput.attr("id")+"_code");
			if (!this.countryCodeInput) {
				this.countryCodeInput = $('<input type="hidden" id="'+this.countryInput.attr("id")+'_code" name="'+this.countryInput.attr("name")+'_code" value="" />');
				this.countryCodeInput.insertAfter(this.countryInput);
			}
			// now we can grab the dropdown height, and hide it properly
			this.dropdownHeight = this.countryList.outerHeight();
			// set the dropdown width according to the input if responsiveDropdown option is present or if it's a small screen
			if (this.options.responsiveDropdown) {
				//$(window).resize(function() {
				//	$('.country-select').each(function() {
				//		var dropdownWidth = this.offsetWidth;
				//		$(this).find('.country-list').css("width", dropdownWidth + "px");
				//	});
				//}).resize();
			}
			this.countryList.removeClass("v-hide").addClass("hide");
			// this is useful in lots of places
			this.countryListItems = this.countryList.children(".country");
		},
		// add a country <li> to the countryList <ul> container
		_appendListItems: function(countries, className) {
			// Generate DOM elements as a large temp string, so that there is only
			// one DOM insert event
			var tmp = "";
			// for each country
			$.each(countries, function(i, c) {
				// open the list item
				tmp += '<li class="country ' + className + '" data-country-code="' + c.iso2 + '">';
				// add the flag
				tmp += '<div class="flag ' + c.iso2 + '"></div>';
				// and the country name
				tmp += '<span class="country-name">' + c.name + ' (' + c.code + ')' + '</span>';
				// close the list item
				tmp += '</li>';
			});
			this.countryList.append(tmp);
		},
		// set the initial state of the input value and the selected flag
		_setInitialState: function() {
			var flagIsSet = false;
			// If the input is pre-populated, then just update the selected flag
			if (this.countryInput.val()) {
				flagIsSet = this._updateFlagFromInputVal();
			}
			// If the country code input is pre-populated, update the name and the selected flag
			var selectedCode = this.countryCodeInput.val();
			if (selectedCode) {
				this.selectCountry(selectedCode);
			}
			if (!flagIsSet) {
				// flag is not set, so set to the default country
				var defaultCountry;
				// check the defaultCountry option, else fall back to the first in the list
				if (this.options.defaultCountry) {
					defaultCountry = this._getCountryData(this.options.defaultCountry, false);
					// Did we not find the requested default country?
					if (!defaultCountry) {
						defaultCountry = this.preferredCountries.length ? this.preferredCountries[0] : this.countries[0];
					}
				} else {
					defaultCountry = this.preferredCountries.length ? this.preferredCountries[0] : this.countries[0];
				}
				this.defaultCountry = defaultCountry.iso2;
			}
		},
		// initialise the main event listeners: input keyup, and click selected flag
		_initListeners: function() {
			var that = this;
			// Update flag on keyup.
			// Use keyup instead of keypress because we want to update on backspace
			// and instead of keydown because the value hasn't updated when that
			// event is fired.
			// NOTE: better to have this one listener all the time instead of
			// starting it on focus and stopping it on blur, because then you've
			// got two listeners (focus and blur)
			this.countryInput.on("keyup" + this.ns, function() {
				that._updateFlagFromInputVal();
			});
			// toggle country dropdown on click
			/*var selectedFlag = this.selectedFlagInner.parent();*/
			this.countryInput.on("click" + this.ns, function(e) {
				// only intercept this event if we're opening the dropdown
				// else let it bubble up to the top ("click-off-to-close" listener)
				// we cannot just stopPropagation as it may be needed to close another instance
				if (that.countryList.hasClass("hide") && !that.countryInput.prop("disabled")) {
					that._showDropdown();
				}
			});
			// Despite above note, added blur to ensure partially spelled country
			// with correctly chosen flag is spelled out on blur. Also, correctly
			// selects flag when field is autofilled
			this.countryInput.on("blur" + this.ns, function() {
				if (that.countryInput.val() != that.getSelectedCountryData().name) {
					that.setCountry(that.countryInput.val());
				}
				that.countryInput.val(that.getSelectedCountryData().code);
			});
		},
		_initAutoCountry: function() {
			if (this.options.initialCountry === "auto") {
				this._loadAutoCountry();
			} else {
				if (this.defaultCountry) {
					this.selectCountry(this.defaultCountry);
				}
				this.autoCountryDeferred.resolve();
			}
		},
		// perform the geo ip lookup
		_loadAutoCountry: function() {
			var that = this;

			// 3 options:
			// 1) already loaded (we're done)
			// 2) not already started loading (start)
			// 3) already started loading (do nothing - just wait for loading callback to fire)
			if ($.fn[pluginName].autoCountry) {
				this.handleAutoCountry();
			} else if (!$.fn[pluginName].startedLoadingAutoCountry) {
				// don't do this twice!
				$.fn[pluginName].startedLoadingAutoCountry = true;

				if (typeof this.options.geoIpLookup === 'function') {
					this.options.geoIpLookup(function(countryCode) {
						$.fn[pluginName].autoCountry = countryCode.toLowerCase();
						// tell all instances the auto country is ready
						// TODO: this should just be the current instances
						// UPDATE: use setTimeout in case their geoIpLookup function calls this callback straight away (e.g. if they have already done the geo ip lookup somewhere else). Using setTimeout means that the current thread of execution will finish before executing this, which allows the plugin to finish initialising.
						setTimeout(function() {
							$(".country-select input").countrySelect("handleAutoCountry");
						});
					});
				}
			}
		},
		// Focus input and put the cursor at the end
		_focus: function() {
			this.countryInput.focus();
			var input = this.countryInput[0];
			// works for Chrome, FF, Safari, IE9+
			if (input.setSelectionRange) {
				var len = this.countryInput.val().length;
				input.setSelectionRange(len, len);
			}
		},
		// Show the dropdown
		_showDropdown: function() {
			this._setDropdownPosition();
			// update highlighting and scroll to active list item
			var activeListItem = this.countryList.children(".active");
			this._highlightListItem(activeListItem);
			// show it
			this.countryList.removeClass("hide");
			this._scrollTo(activeListItem);
			// bind all the dropdown-related listeners: mouseover, click, click-off, keydown
			this._bindDropdownListeners();
			// update the arrow
			this.selectedFlagInner.parent().children(".arrow").addClass("up");
		},
		// decide where to position dropdown (depends on position within viewport, and scroll)
		_setDropdownPosition: function() {
			var inputTop = this.countryInput.offset().top, windowTop = $(window).scrollTop(),
			dropdownFitsBelow = inputTop + this.countryInput.outerHeight() + this.dropdownHeight < windowTop + $(window).height(), dropdownFitsAbove = inputTop - this.dropdownHeight > windowTop;
			// dropdownHeight - 1 for border
			var cssTop = !dropdownFitsBelow && dropdownFitsAbove ? "-" + (this.dropdownHeight - 1) + "px" : "";
			this.countryList.css("top", cssTop);
		},
		// we only bind dropdown listeners when the dropdown is open
		_bindDropdownListeners: function() {
			var that = this;
			// when mouse over a list item, just highlight that one
			// we add the class "highlight", so if they hit "enter" we know which one to select
			this.countryList.on("mouseover" + this.ns, ".country", function(e) {
				that._highlightListItem($(this));
			});
			// listen for country selection
			this.countryList.on("click" + this.ns, ".country", function(e) {
				that._selectListItem($(this));
			});
			// click off to close
			// (except when this initial opening click is bubbling up)
			// we cannot just stopPropagation as it may be needed to close another instance
			var isOpening = true;
			$("html").on("click" + this.ns, function(e) {
				e.preventDefault();
				if (!isOpening) {
					that._closeDropdown();
				}
				isOpening = false;
			});
			// Listen for up/down scrolling, enter to select, or letters to jump to country name.
			// Use keydown as keypress doesn't fire for non-char keys and we want to catch if they
			// just hit down and hold it to scroll down (no keyup event).
			// Listen on the document because that's where key events are triggered if no input has focus
			$(document).on("keydown" + this.ns, function(e) {
				// prevent down key from scrolling the whole page,
				// and enter key from submitting a form etc
				e.preventDefault();
				if (e.which == keys.UP || e.which == keys.DOWN) {
					// up and down to navigate
					that._handleUpDownKey(e.which);
				} else if (e.which == keys.ENTER) {
					// enter to select
					that._handleEnterKey();
				} else if (e.which == keys.ESC) {
					// esc to close
					that._closeDropdown();
				} else if (e.which >= keys.A && e.which <= keys.Z || e.which === keys.SPACE) {
					that.typedLetters += String.fromCharCode(e.which);
					that._filterCountries(that.typedLetters);
				} else if (e.which === keys.BACKSPACE) {
					that.typedLetters = that.typedLetters.slice(0, -1);
					that._filterCountries(that.typedLetters);
				}
			});
		},
		// Highlight the next/prev item in the list (and ensure it is visible)
		_handleUpDownKey: function(key) {
			var current = this.countryList.children(".highlight").first();
			var next = key == keys.UP ? current.prev() : current.next();
			if (next.length) {
				// skip the divider
				if (next.hasClass("divider")) {
					next = key == keys.UP ? next.prev() : next.next();
				}
				this._highlightListItem(next);
				this._scrollTo(next);
			}
		},
		// select the currently highlighted item
		_handleEnterKey: function() {
			var currentCountry = this.countryList.children(".highlight").first();
			if (currentCountry.length) {
				this._selectListItem(currentCountry);
			}
		},
		_filterCountries: function(letters) {
			var countries = this.countryListItems.filter(function() {
				return $(this).text().toUpperCase().indexOf(letters) === 0 && !$(this).hasClass("preferred");
			});
			if (countries.length) {
				// if one is already highlighted, then we want the next one
				var highlightedCountry = countries.filter(".highlight").first(), listItem;
				if (highlightedCountry && highlightedCountry.next() && highlightedCountry.next().text().toUpperCase().indexOf(letters) === 0) {
					listItem = highlightedCountry.next();
				} else {
					listItem = countries.first();
				}
				// update highlighting and scroll
				this._highlightListItem(listItem);
				this._scrollTo(listItem);
			}
		},
		// Update the selected flag using the input's current value
		_updateFlagFromInputVal: function() {
			var that = this;
			// try and extract valid country from input
			var value = this.countryInput.val(); // Escape + .replace(/[+](?=[() ])/g, '\\+')
			
			if (value) {
				var countryCodes = [];
				/*var matcher = new RegExp(value, "i");*/
				// Check for ISO codes only
				if(value.length <= 2) {
					for (var i = 0; i < this.countries.length; i++) {
						if (this.countries[i].iso2 == value) {
							countryCodes.push(this.countries[i].iso2);
						}
					}
				}
				// If no previous matches / larger than 2 chars, then search country name
				if(countryCodes.length == 0) {
					for (var i = 0; i < this.countries.length; i++) {
						if (this.countries[i].code == value) {
							countryCodes.push(this.countries[i].iso2);
						}
					}
				}
				//if (countryCodes.length == 0) {
				//	value = "+46";
				//	this.countryInput.val(value);
				//	for (var i = 0; i < this.countries.length; i++) {
				//		if (this.countries[i].code == value) {
				//			countryCodes.push(this.countries[i].iso2);
				//		}
				//	}
				//}
				// Check if one of the matching countries is already selected
				var alreadySelected = false;
				$.each(countryCodes, function(i, c) {
					if (that.selectedFlagInner.hasClass(c)) {
						alreadySelected = true;
					}
				});
				if (!alreadySelected) {
					this._selectFlag(countryCodes[0]);
					this.countryCodeInput.val(countryCodes[0]).trigger("change");
				}
				// Matching country found
				return true;
			}
			// No match found
			return false;
		},
		// remove highlighting from other list items and highlight the given item
		_highlightListItem: function(listItem) {
			this.countryListItems.removeClass("highlight");
			listItem.addClass("highlight");
		},
		// find the country data for the given country code
		// the ignoreOnlyCountriesOption is only used during init() while parsing the onlyCountries array
		_getCountryData: function(countryCode, ignoreOnlyCountriesOption) {
			var countryList = ignoreOnlyCountriesOption ? allCountries : this.countries;
			for (var i = 0; i < countryList.length; i++) {
				if (countryList[i].iso2 == countryCode) {
					return countryList[i];
				}
			}
			return null;
		},
		// update the selected flag and the active list item
		_selectFlag: function(countryCode) {
			if (! countryCode) {
				return false;
			}
			this.selectedFlagInner.attr("class", "flag " + countryCode);
			// update the title attribute
			var countryData = this._getCountryData(countryCode);
			this.selectedFlagInner.parent().attr("title", countryData.name);
			// update the active list item
			var listItem = this.countryListItems.children(".flag." + countryCode).first().parent();
			this.countryListItems.removeClass("active");
			listItem.addClass("active");
		},
		// called when the user selects a list item from the dropdown
		_selectListItem: function(listItem) {
			// update selected flag and active list item
			var countryCode = listItem.attr("data-country-code");
			this._selectFlag(countryCode);
			this._closeDropdown();
			// update input value
			this._updateName(countryCode);
			this.countryInput.trigger("change");
			this.countryCodeInput.trigger("change");
			// focus the input
			this._focus();
		},
		// close the dropdown and unbind any listeners
		_closeDropdown: function() {
			this.countryList.addClass("hide");
			// update the arrow
			this.selectedFlagInner.parent().children(".arrow").removeClass("up");
			// unbind event listeners
			$(document).off("keydown" + this.ns);
			$("html").off("click" + this.ns);
			// unbind both hover and click listeners
			this.countryList.off(this.ns);
			this.typedLetters = "";
		},
		// check if an element is visible within its container, else scroll until it is
		_scrollTo: function(element) {
			if (!element || !element.offset()) {
				return;
			}
			var container = this.countryList, containerHeight = container.height(), containerTop = container.offset().top, containerBottom = containerTop + containerHeight, elementHeight = element.outerHeight(), elementTop = element.offset().top, elementBottom = elementTop + elementHeight, newScrollTop = elementTop - containerTop + container.scrollTop();
			if (elementTop < containerTop) {
				// scroll up
				container.scrollTop(newScrollTop);
			} else if (elementBottom > containerBottom) {
				// scroll down
				var heightDifference = containerHeight - elementHeight;
				container.scrollTop(newScrollTop - heightDifference);
			}
		},
		// Replace any existing country name with the new one
		_updateName: function(countryCode) {
			this.countryCodeInput.val(countryCode).trigger("change");
			this.countryInput.val(this._getCountryData(countryCode).code);
		},
		/********************
		 *  PUBLIC METHODS
		 ********************/
		// this is called when the geoip call returns
		handleAutoCountry: function() {
			if (this.options.initialCountry === "auto") {
				// we must set this even if there is an initial val in the input: in case the initial val is invalid and they delete it - they should see their auto country
				this.defaultCountry = $.fn[pluginName].autoCountry;
				// if there's no initial value in the input, then update the flag
				if (!this.countryInput.val()) {
					this.selectCountry(this.defaultCountry);
				}
				this.autoCountryDeferred.resolve();
			}
		},
		// get the country data for the currently selected flag
		getSelectedCountryData: function() {
			// rely on the fact that we only set 2 classes on the selected flag element:
			// the first is "flag" and the second is the 2-char country code
			var countryCode = this.selectedFlagInner.attr("class").split(" ")[1];
			return this._getCountryData(countryCode);
		},
		// update the selected flag
		selectCountry: function(countryCode) {
			countryCode = countryCode.toLowerCase();
			// check if already selected
			if (!this.selectedFlagInner.hasClass(countryCode)) {
				this._selectFlag(countryCode);
				this._updateName(countryCode);
			}
		},
		// set the input value and update the flag
		setCountry: function(country) {
			this.countryInput.val(country);
			this._updateFlagFromInputVal();
		},
		// remove plugin
		destroy: function() {
			// stop listeners
			this.countryInput.off(this.ns);
			this.selectedFlagInner.parent().off(this.ns);
			// remove markup
			var container = this.countryInput.parent();
			container.before(this.countryInput).remove();
		}
	};
	// adapted to allow public functions
	// using https://github.com/jquery-boilerplate/jquery-boilerplate/wiki/Extending-jQuery-Boilerplate
	$.fn[pluginName] = function(options) {
		var args = arguments;
		// Is the first parameter an object (options), or was omitted,
		// instantiate a new instance of the plugin.
		if (options === undefined || typeof options === "object") {
			return this.each(function() {
				if (!$.data(this, "plugin_" + pluginName)) {
					$.data(this, "plugin_" + pluginName, new Plugin(this, options));
				}
			});
		} else if (typeof options === "string" && options[0] !== "_" && options !== "init") {
			// If the first parameter is a string and it doesn't start
			// with an underscore or "contains" the `init`-function,
			// treat this as a call to a public method.
			// Cache the method call to make it possible to return a value
			var returns;
			this.each(function() {
				var instance = $.data(this, "plugin_" + pluginName);
				// Tests that there's already a plugin-instance
				// and checks that the requested public method exists
				if (instance instanceof Plugin && typeof instance[options] === "function") {
					// Call the method of our plugin instance,
					// and pass it the supplied arguments.
					returns = instance[options].apply(instance, Array.prototype.slice.call(args, 1));
				}
				// Allow instances to be destroyed via the 'destroy' method
				if (options === "destroy") {
					$.data(this, "plugin_" + pluginName, null);
				}
			});
			// If the earlier cached method gives a value back return the value,
			// otherwise return this to preserve chainability.
			return returns !== undefined ? returns : this;
		}
	};
	/********************
   *  STATIC METHODS
   ********************/
	// get the country data object
	$.fn[pluginName].getCountryData = function() {
		return allCountries;
	};
	// set the country data object
	$.fn[pluginName].setCountryData = function(obj) {
		allCountries = obj;
	};
	// Tell JSHint to ignore this warning: "character may get silently deleted by one or more browsers"
	// jshint -W100
	// Array of country objects for the flag dropdown.
	// Each contains a name and country code (ISO 3166-1 alpha-2).
	//
	// Note: using single char property names to keep filesize down
	// n = name
	// i = iso2 (2-char country code)
	var allCountries = $.each([{ n: "Afghanistan", i: "af", c: "+93" },
		{ n: "Ålandsöarna", i: "ax", c: "+358" },
		{ n: "Albanien", i: "al", c: "+355" },
		{ n: "Algeriet", i: "dz", c: "+213" },
		{ n: "Amerikanska Samoa", i: "as", c: "+1" },
		{ n: "Andorra", i: "ad", c: "+376" },
		{ n: "Angola", i: "ao", c: "+244" },
		{ n: "Anguilla", i: "ai", c: "+1" },
		{ n: "Antarktis", i: "aq", c: "+672" },
		{ n: "Antigua och Barbuda", i: "ag", c: "+1" },
		{ n: "Argentina", i: "ar", c: "+54" },
		{ n: "Armenien", i: "am", c: "+374" },
		{ n: "Aruba", i: "aw", c: "+297" },
		{ n: "Australien", i: "au", c: "+61" },
		{ n: "Österrike", i: "at", c: "+43" },
		{ n: "Azerbajdzjan", i: "az", c: "+994" },
		{ n: "Bahamas", i: "bs", c: "+1" },
		{ n: "Bahrain", i: "bh", c: "+973" },
		{ n: "Bangladesh", i: "bd", c: "+880" },
		{ n: "Barbados", i: "bb", c: "+1" },
		{ n: "Vitryssland", i: "by", c: "+375" },
		{ n: "Belgien", i: "be", c: "+32" },
		{ n: "Belize", i: "bz", c: "+501" },
		{ n: "Benin", i: "bj", c: "+229" },
		{ n: "Bermuda", i: "bm", c: "+1" },
		{ n: "Bhutan", i: "bt", c: "+975" },
		{ n: "Bolivia", i: "bo", c: "+591" },
		{ n: "Bosnien och Hercegovina", i: "ba", c: "+387" },
		{ n: "Botswana", i: "bw", c: "+267" },
		/*{ n: "Bouvetön", i: "bv", c: "" },*/
		{ n: "Brasilien", i: "br", c: "+55" },
		{ n: "Brittiska Indiska oceanöarna", i: "io", c: "+246" },
		{ n: "Brittiska Jungfruöarna", i: "vg", c: "+1" },
		{ n: "Brunei", i: "bn", c: "+673" },
		{ n: "Bulgarien", i: "bg", c: "+359" },
		{ n: "Burkina Faso", i: "bf", c: "+226" },
		{ n: "Burundi", i: "bi", c: "+257" },
		{ n: "Kambodja", i: "kh", c: "+855" },
		{ n: "Kamerun", i: "cm", c: "+237" },
		{ n: "Kanada", i: "ca", c: "+1" },
		{ n: "Kap Verde", i: "cv", c: "+238" },
		{ n: "Karibiska Nederländerna", i: "bq", c: "+599" },
		{ n: "Caymanöarna", i: "ky", c: "+1" },
		{ n: "Centralafrikanska republiken", i: "cf", c: "+236" },
		{ n: "Chad", i: "td", c: "+235" },
		{ n: "Chile", i: "cl", c: "+56" },
		{ n: "Kina", i: "cn", c: "+86" },
		{ n: "Julön", i: "cx", c: "+61" },
		{ n: "Kokosöarna", i: "cc", c: "+61" },
		{ n: "Colombia", i: "co", c: "+57" },
		{ n: "Komorerna", i: "km", c: "+269" },
		{ n: "Kongo-Kinshasa", i: "cd", c: "+243" },
		{ n: "Kongo-Brazzaville", i: "cg", c: "+242" },
		{ n: "Cooköarna", i: "ck", c: "+682" },
		{ n: "Costa Rica", i: "cr", c: "+506" },
		{ n: "Elfenbenskusten", i: "ci", c: "+225" },
		{ n: "Kroatien", i: "hr", c: "+385" },
		{ n: "Kuba", i: "cu", c: "+53" },
		{ n: "Curaçao", i: "cw", c: "+599" },
		{ n: "Cypern", i: "cy", c: "+357" },
		{ n: "Tjeckien", i: "cz", c: "+420" },
		{ n: "Danmark", i: "dk", c: "+45" },
		{ n: "Djibouti", i: "dj", c: "+253" },
		{ n: "Dominica", i: "dm", c: "+1" },
		{ n: "Dominikanska republiken", i: "do", c: "+1" },
		{ n: "Ecuador", i: "ec", c: "+593" },
		{ n: "Egypten", i: "eg", c: "+20" },
		{ n: "El Salvador", i: "sv", c: "+503" },
		{ n: "Ekvatorialguinea", i: "gq", c: "+240" },
		{ n: "Eritrea", i: "er", c: "+291" },
		{ n: "Estland", i: "ee", c: "+372" },
		{ n: "Eswatini", i: "sz", c: "+268" },
		{ n: "Etiopien", i: "et", c: "+251" },
		{ n: "Falklandsöarna", i: "fk", c: "+500" },
		{ n: "Färöarna", i: "fo", c: "+298" },
		{ n: "Fiji", i: "fj", c: "+679" },
		{ n: "Finland", i: "fi", c: "+358" },
		{ n: "Frankrike", i: "fr", c: "+33" },
		{ n: "Franska Guyana", i: "gf", c: "+594" },
		{ n: "Franska Polynesien", i: "pf", c: "+689" },
		{ n: "Franska sydterritorierna", i: "tf", c: "+262" },
		{ n: "Gabon", i: "ga", c: "+241" },
		{ n: "Gambia", i: "gm", c: "+220" },
		{ n: "Georgien", i: "ge", c: "+995" },
		{ n: "Tyskland", i: "de", c: "+49" },
		{ n: "Ghana", i: "gh", c: "+233" },
		{ n: "Gibraltar", i: "gi", c: "+350" },
		{ n: "Grekland", i: "gr", c: "+30" },
		{ n: "Grönland", i: "gl", c: "+299" },
		{ n: "Grenada", i: "gd", c: "+1" },
		{ n: "Guadeloupe", i: "gp", c: "+590" },
		{ n: "Guam", i: "gu", c: "+1" },
		{ n: "Guatemala", i: "gt", c: "+502" },
		{ n: "Guernsey", i: "gg", c: "+44" },
		{ n: "Guinea", i: "gn", c: "+224" },
		{ n: "Guinea-Bissau", i: "gw", c: "+245" },
		{ n: "Guyana", i: "gy", c: "+592" },
		{ n: "Haiti", i: "ht", c: "+509" },
		/*{ n: "Heardön och McDonaldöarna", i: "hm", c: "" },*/
		{ n: "Honduras", i: "hn", c: "+504" },
		{ n: "Hongkong", i: "hk", c: "+852" },
		{ n: "Ungern", i: "hu", c: "+36" },
		{ n: "Island", i: "is", c: "+354" },
		{ n: "Indien", i: "in", c: "+91" },
		{ n: "Indonesien", i: "id", c: "+62" },
		{ n: "Iran", i: "ir", c: "+98" },
		{ n: "Irak", i: "iq", c: "+964" },
		{ n: "Irland", i: "ie", c: "+353" },
		{ n: "Isle of Man", i: "im", c: "+44" },
		{ n: "Israel", i: "il", c: "+972" },
		{ n: "Italien", i: "it", c: "+39" },
		{ n: "Jamaica", i: "jm", c: "+1" },
		{ n: "Japan", i: "jp", c: "+81" },
		{ n: "Jersey", i: "je", c: "+44" },
		{ n: "Jordanien", i: "jo", c: "+962" },
		{ n: "Kazakstan", i: "kz", c: "+7" },
		{ n: "Kenya", i: "ke", c: "+254" },
		{ n: "Kiribati", i: "ki", c: "+686" },
		{ n: "Kuwait", i: "kw", c: "+965" },
		{ n: "Kirgizistan", i: "kg", c: "+996" },
		{ n: "Laos", i: "la", c: "+856" },
		{ n: "Lettland", i: "lv", c: "+371" },
		{ n: "Libanon", i: "lb", c: "+961" },
		{ n: "Lesotho", i: "ls", c: "+266" },
		{ n: "Liberia", i: "lr", c: "+231" },
		{ n: "Libyen", i: "ly", c: "+218" },
		{ n: "Liechtenstein", i: "li", c: "+423" },
		{ n: "Litauen", i: "lt", c: "+370" },
		{ n: "Luxemburg", i: "lu", c: "+352" },
		{ n: "Macao", i: "mo", c: "+853" },
		{ n: "Madagaskar", i: "mg", c: "+261" },
		{ n: "Malawi", i: "mw", c: "+265" },
		{ n: "Malaysia", i: "my", c: "+60" },
		{ n: "Maldiverna", i: "mv", c: "+960" },
		{ n: "Mali", i: "ml", c: "+223" },
		{ n: "Malta", i: "mt", c: "+356" },
		{ n: "Marshallöarna", i: "mh", c: "+692" },
		{ n: "Martinique", i: "mq", c: "+596" },
		{ n: "Mauretanien", i: "mr", c: "+222" },
		{ n: "Mauritius", i: "mu", c: "+230" },
		{ n: "Mayotte", i: "yt", c: "+262" },
		{ n: "Mexiko", i: "mx", c: "+52" },
		{ n: "Mikronesien", i: "fm", c: "+691" },
		{ n: "Moldavien", i: "md", c: "+373" },
		{ n: "Monaco", i: "mc", c: "+377" },
		{ n: "Mongoliet", i: "mn", c: "+976" },
		{ n: "Montenegro", i: "me", c: "+382" },
		{ n: "Montserrat", i: "ms", c: "+1" },
		{ n: "Marocko", i: "ma", c: "+212" },
		{ n: "Moçambique", i: "mz", c: "+258" },
		{ n: "Myanmar (Burma)", i: "mm", c: "+95" },
		{ n: "Namibia", i: "na", c: "+264" },
		{ n: "Nauru", i: "nr", c: "+674" },
		{ n: "Nepal", i: "np", c: "+977" },
		{ n: "Nederländerna", i: "nl", c: "+31" },
		{ n: "Nya Kaledonien", i: "nc", c: "+687" },
		{ n: "Nya Zeeland", i: "nz", c: "+64" },
		{ n: "Nicaragua", i: "ni", c: "+505" },
		{ n: "Niger", i: "ne", c: "+227" },
		{ n: "Nigeria", i: "ng", c: "+234" },
		{ n: "Niue", i: "nu", c: "+683" },
		{ n: "Norfolkön", i: "nf", c: "+672" },
		{ n: "Nordkorea", i: "kp", c: "+850" },
		{ n: "Nordmakedonien", i: "mk", c: "+389" },
		{ n: "Nordmarianerna", i: "mp", c: "+1" },
		{ n: "Norge", i: "no", c: "+47" },
		{ n: "Oman", i: "om", c: "+968" },
		{ n: "Pakistan", i: "pk", c: "+92" },
		{ n: "Palau", i: "pw", c: "+680" },
		{ n: "Palestina", i: "ps", c: "+970" },
		{ n: "Panama", i: "pa", c: "+507" },
		{ n: "Papua Nya Guinea", i: "pg", c: "+675" },
		{ n: "Paraguay", i: "py", c: "+595" },
		{ n: "Peru", i: "pe", c: "+51" },
		{ n: "Filippinerna", i: "ph", c: "+63" },
		{ n: "Pitcairnöarna", i: "pn", c: "+64" },
		{ n: "Polen", i: "pl", c: "+48" },
		{ n: "Portugal", i: "pt", c: "+351" },
		{ n: "Puerto Rico", i: "pr", c: "+1" },
		{ n: "Qatar", i: "qa", c: "+974" },
		{ n: "Réunion", i: "re", c: "+262" },
		{ n: "Rumänien", i: "ro", c: "+40" },
		{ n: "Ryssland", i: "ru", c: "+7" },
		{ n: "Rwanda", i: "rw", c: "+250" },
		{ n: "S:t Kitts och Nevis", i: "kn", c: "+1" },
		{ n: "S:t Lucia", i: "lc", c: "+1" },
		{ n: "S:t Vincent och Grenadinerna", i: "vc", c: "+1" },
		{ n: "Samoa", i: "ws", c: "+685" },
		{ n: "San Marino", i: "sm", c: "+378" },
		{ n: "São Tomé och Príncipe", i: "st", c: "+239" },
		{ n: "Saudiarabien", i: "sa", c: "+966" },
		{ n: "Senegal", i: "sn", c: "+221" },
		{ n: "Serbien", i: "rs", c: "+381" },
		{ n: "Seychellerna", i: "sc", c: "+248" },
		{ n: "Sierra Leone", i: "sl", c: "+232" },
		{ n: "Singapore", i: "sg", c: "+65" },
		{ n: "Sint Maarten", i: "sx", c: "+1" },
		{ n: "Slovakien", i: "sk", c: "+421" },
		{ n: "Slovenien", i: "si", c: "+386" },
		{ n: "Salomonöarna", i: "sb", c: "+677" },
		{ n: "Somalia", i: "so", c: "+252" },
		{ n: "Sydafrika", i: "za", c: "+27" },
		{ n: "Sydgeorgien och Sydsandwichöarna", i: "gs", c: "+500" },
		{ n: "Sydkorea", i: "kr", c: "+82" },
		{ n: "Sydsudan", i: "ss", c: "+211" },
		{ n: "Spanien", i: "es", c: "+34" },
		{ n: "Sri Lanka", i: "lk", c: "+94" },
		{ n: "Sudan", i: "sd", c: "+249" },
		{ n: "Surinam", i: "sr", c: "+597" },
		{ n: "Svalbard och Jan Mayen", i: "sj", c: "+47" },
		{ n: "Sverige", i: "se", c: "+46" },
		{ n: "Schweiz", i: "ch", c: "+41" },
		{ n: "Syrien", i: "sy", c: "+963" },
		{ n: "Taiwan", i: "tw", c: "+886" },
		{ n: "Tadzjikistan", i: "tj", c: "+992" },
		{ n: "Tanzania", i: "tz", c: "+255" },
		{ n: "Thailand", i: "th", c: "+66" },
		{ n: "Östtimor", i: "tl", c: "+670" },
		{ n: "Togo", i: "tg", c: "+228" },
		{ n: "Tokelau", i: "tk", c: "+690" },
		{ n: "Tonga", i: "to", c: "+676" },
		{ n: "Trinidad och Tobago", i: "tt", c: "+1" },
		{ n: "Tunisien", i: "tn", c: "+216" },
		{ n: "Turkiet", i: "tr", c: "+90" },
		{ n: "Turkmenistan", i: "tm", c: "+993" },
		{ n: "Turks- och Caicosöarna", i: "tc", c: "+1" },
		{ n: "Tuvalu", i: "tv", c: "+688" },
		{ n: "USA", i: "us", c: "+1" },
		/*{ n: "USA:s yttre öar", i: "um", c: "" },*/
		{ n: "Amerikas Jungfruöar", i: "vi", c: "+1" },
		{ n: "Uganda", i: "ug", c: "+256" },
		{ n: "Ukraina", i: "ua", c: "+380" },
		{ n: "Förenade Arabemiraten", i: "ae", c: "+971" },
		{ n: "Storbritannien", i: "gb", c: "+44" },
		{ n: "Uruguay", i: "uy", c: "+598" },
		{ n: "Uzbekistan", i: "uz", c: "+998" },
		{ n: "Vanuatu", i: "vu", c: "+678" },
		{ n: "Vatikanstaten", i: "va", c: "+39" },
		{ n: "Venezuela", i: "ve", c: "+58" },
		{ n: "Vietnam", i: "vn", c: "+84" },
		{ n: "Wallis och Futuna", i: "wf", c: "+681" },
		{ n: "Västsahara", i: "eh", c: "+212" },
		{ n: "Jemen", i: "ye", c: "+967" },
		{ n: "Zambia", i: "zm", c: "+260" },
		{ n: "Zimbabwe", i: "zw", c: "+263" }], function(i, c) {
		c.name = c.n;
		c.iso2 = c.i;
		c.code = c.c;
		delete c.n;
		delete c.i;
		delete c.c;
	});
});

/*!
  * Bootstrap v5.2.2 (https://getbootstrap.com/)
  * Copyright 2011-2022 The Bootstrap Authors (https://github.com/twbs/bootstrap/graphs/contributors)
  * Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
  */
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e(require("@popperjs/core")):"function"==typeof define&&define.amd?define(["@popperjs/core"],e):(t="undefined"!=typeof globalThis?globalThis:t||self).bootstrap=e(t.Popper)}(this,(function(t){"use strict";function e(t){if(t&&t.__esModule)return t;const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t)for(const i in t)if("default"!==i){const s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:()=>t[i]})}return e.default=t,Object.freeze(e)}const i=e(t),s="transitionend",n=t=>{let e=t.getAttribute("data-bs-target");if(!e||"#"===e){let i=t.getAttribute("href");if(!i||!i.includes("#")&&!i.startsWith("."))return null;i.includes("#")&&!i.startsWith("#")&&(i=`#${i.split("#")[1]}`),e=i&&"#"!==i?i.trim():null}return e},o=t=>{const e=n(t);return e&&document.querySelector(e)?e:null},r=t=>{const e=n(t);return e?document.querySelector(e):null},a=t=>{t.dispatchEvent(new Event(s))},l=t=>!(!t||"object"!=typeof t)&&(void 0!==t.jquery&&(t=t[0]),void 0!==t.nodeType),c=t=>l(t)?t.jquery?t[0]:t:"string"==typeof t&&t.length>0?document.querySelector(t):null,h=t=>{if(!l(t)||0===t.getClientRects().length)return!1;const e="visible"===getComputedStyle(t).getPropertyValue("visibility"),i=t.closest("details:not([open])");if(!i)return e;if(i!==t){const e=t.closest("summary");if(e&&e.parentNode!==i)return!1;if(null===e)return!1}return e},d=t=>!t||t.nodeType!==Node.ELEMENT_NODE||!!t.classList.contains("disabled")||(void 0!==t.disabled?t.disabled:t.hasAttribute("disabled")&&"false"!==t.getAttribute("disabled")),u=t=>{if(!document.documentElement.attachShadow)return null;if("function"==typeof t.getRootNode){const e=t.getRootNode();return e instanceof ShadowRoot?e:null}return t instanceof ShadowRoot?t:t.parentNode?u(t.parentNode):null},_=()=>{},g=t=>{t.offsetHeight},f=()=>window.jQuery&&!document.body.hasAttribute("data-bs-no-jquery")?window.jQuery:null,p=[],m=()=>"rtl"===document.documentElement.dir,b=t=>{var e;e=()=>{const e=f();if(e){const i=t.NAME,s=e.fn[i];e.fn[i]=t.jQueryInterface,e.fn[i].Constructor=t,e.fn[i].noConflict=()=>(e.fn[i]=s,t.jQueryInterface)}},"loading"===document.readyState?(p.length||document.addEventListener("DOMContentLoaded",(()=>{for(const t of p)t()})),p.push(e)):e()},v=t=>{"function"==typeof t&&t()},y=(t,e,i=!0)=>{if(!i)return void v(t);const n=(t=>{if(!t)return 0;let{transitionDuration:e,transitionDelay:i}=window.getComputedStyle(t);const s=Number.parseFloat(e),n=Number.parseFloat(i);return s||n?(e=e.split(",")[0],i=i.split(",")[0],1e3*(Number.parseFloat(e)+Number.parseFloat(i))):0})(e)+5;let o=!1;const r=({target:i})=>{i===e&&(o=!0,e.removeEventListener(s,r),v(t))};e.addEventListener(s,r),setTimeout((()=>{o||a(e)}),n)},w=(t,e,i,s)=>{const n=t.length;let o=t.indexOf(e);return-1===o?!i&&s?t[n-1]:t[0]:(o+=i?1:-1,s&&(o=(o+n)%n),t[Math.max(0,Math.min(o,n-1))])},A=/[^.]*(?=\..*)\.|.*/,E=/\..*/,C=/::\d+$/,T={};let k=1;const L={mouseenter:"mouseover",mouseleave:"mouseout"},O=new Set(["click","dblclick","mouseup","mousedown","contextmenu","mousewheel","DOMMouseScroll","mouseover","mouseout","mousemove","selectstart","selectend","keydown","keypress","keyup","orientationchange","touchstart","touchmove","touchend","touchcancel","pointerdown","pointermove","pointerup","pointerleave","pointercancel","gesturestart","gesturechange","gestureend","focus","blur","change","reset","select","submit","focusin","focusout","load","unload","beforeunload","resize","move","DOMContentLoaded","readystatechange","error","abort","scroll"]);function I(t,e){return e&&`${e}::${k++}`||t.uidEvent||k++}function S(t){const e=I(t);return t.uidEvent=e,T[e]=T[e]||{},T[e]}function D(t,e,i=null){return Object.values(t).find((t=>t.callable===e&&t.delegationSelector===i))}function N(t,e,i){const s="string"==typeof e,n=s?i:e||i;let o=j(t);return O.has(o)||(o=t),[s,n,o]}function P(t,e,i,s,n){if("string"!=typeof e||!t)return;let[o,r,a]=N(e,i,s);if(e in L){const t=t=>function(e){if(!e.relatedTarget||e.relatedTarget!==e.delegateTarget&&!e.delegateTarget.contains(e.relatedTarget))return t.call(this,e)};r=t(r)}const l=S(t),c=l[a]||(l[a]={}),h=D(c,r,o?i:null);if(h)return void(h.oneOff=h.oneOff&&n);const d=I(r,e.replace(A,"")),u=o?function(t,e,i){return function s(n){const o=t.querySelectorAll(e);for(let{target:r}=n;r&&r!==this;r=r.parentNode)for(const a of o)if(a===r)return F(n,{delegateTarget:r}),s.oneOff&&$.off(t,n.type,e,i),i.apply(r,[n])}}(t,i,r):function(t,e){return function i(s){return F(s,{delegateTarget:t}),i.oneOff&&$.off(t,s.type,e),e.apply(t,[s])}}(t,r);u.delegationSelector=o?i:null,u.callable=r,u.oneOff=n,u.uidEvent=d,c[d]=u,t.addEventListener(a,u,o)}function x(t,e,i,s,n){const o=D(e[i],s,n);o&&(t.removeEventListener(i,o,Boolean(n)),delete e[i][o.uidEvent])}function M(t,e,i,s){const n=e[i]||{};for(const o of Object.keys(n))if(o.includes(s)){const s=n[o];x(t,e,i,s.callable,s.delegationSelector)}}function j(t){return t=t.replace(E,""),L[t]||t}const $={on(t,e,i,s){P(t,e,i,s,!1)},one(t,e,i,s){P(t,e,i,s,!0)},off(t,e,i,s){if("string"!=typeof e||!t)return;const[n,o,r]=N(e,i,s),a=r!==e,l=S(t),c=l[r]||{},h=e.startsWith(".");if(void 0===o){if(h)for(const i of Object.keys(l))M(t,l,i,e.slice(1));for(const i of Object.keys(c)){const s=i.replace(C,"");if(!a||e.includes(s)){const e=c[i];x(t,l,r,e.callable,e.delegationSelector)}}}else{if(!Object.keys(c).length)return;x(t,l,r,o,n?i:null)}},trigger(t,e,i){if("string"!=typeof e||!t)return null;const s=f();let n=null,o=!0,r=!0,a=!1;e!==j(e)&&s&&(n=s.Event(e,i),s(t).trigger(n),o=!n.isPropagationStopped(),r=!n.isImmediatePropagationStopped(),a=n.isDefaultPrevented());let l=new Event(e,{bubbles:o,cancelable:!0});return l=F(l,i),a&&l.preventDefault(),r&&t.dispatchEvent(l),l.defaultPrevented&&n&&n.preventDefault(),l}};function F(t,e){for(const[i,s]of Object.entries(e||{}))try{t[i]=s}catch(e){Object.defineProperty(t,i,{configurable:!0,get:()=>s})}return t}const z=new Map,H={set(t,e,i){z.has(t)||z.set(t,new Map);const s=z.get(t);s.has(e)||0===s.size?s.set(e,i):console.error(`Bootstrap doesn't allow more than one instance per element. Bound instance: ${Array.from(s.keys())[0]}.`)},get:(t,e)=>z.has(t)&&z.get(t).get(e)||null,remove(t,e){if(!z.has(t))return;const i=z.get(t);i.delete(e),0===i.size&&z.delete(t)}};function q(t){if("true"===t)return!0;if("false"===t)return!1;if(t===Number(t).toString())return Number(t);if(""===t||"null"===t)return null;if("string"!=typeof t)return t;try{return JSON.parse(decodeURIComponent(t))}catch(e){return t}}function B(t){return t.replace(/[A-Z]/g,(t=>`-${t.toLowerCase()}`))}const W={setDataAttribute(t,e,i){t.setAttribute(`data-bs-${B(e)}`,i)},removeDataAttribute(t,e){t.removeAttribute(`data-bs-${B(e)}`)},getDataAttributes(t){if(!t)return{};const e={},i=Object.keys(t.dataset).filter((t=>t.startsWith("bs")&&!t.startsWith("bsConfig")));for(const s of i){let i=s.replace(/^bs/,"");i=i.charAt(0).toLowerCase()+i.slice(1,i.length),e[i]=q(t.dataset[s])}return e},getDataAttribute:(t,e)=>q(t.getAttribute(`data-bs-${B(e)}`))};class R{static get Default(){return{}}static get DefaultType(){return{}}static get NAME(){throw new Error('You have to implement the static method "NAME", for each component!')}_getConfig(t){return t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t}_mergeConfigObj(t,e){const i=l(e)?W.getDataAttribute(e,"config"):{};return{...this.constructor.Default,..."object"==typeof i?i:{},...l(e)?W.getDataAttributes(e):{},..."object"==typeof t?t:{}}}_typeCheckConfig(t,e=this.constructor.DefaultType){for(const s of Object.keys(e)){const n=e[s],o=t[s],r=l(o)?"element":null==(i=o)?`${i}`:Object.prototype.toString.call(i).match(/\s([a-z]+)/i)[1].toLowerCase();if(!new RegExp(n).test(r))throw new TypeError(`${this.constructor.NAME.toUpperCase()}: Option "${s}" provided type "${r}" but expected type "${n}".`)}var i}}class V extends R{constructor(t,e){super(),(t=c(t))&&(this._element=t,this._config=this._getConfig(e),H.set(this._element,this.constructor.DATA_KEY,this))}dispose(){H.remove(this._element,this.constructor.DATA_KEY),$.off(this._element,this.constructor.EVENT_KEY);for(const t of Object.getOwnPropertyNames(this))this[t]=null}_queueCallback(t,e,i=!0){y(t,e,i)}_getConfig(t){return t=this._mergeConfigObj(t,this._element),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}static getInstance(t){return H.get(c(t),this.DATA_KEY)}static getOrCreateInstance(t,e={}){return this.getInstance(t)||new this(t,"object"==typeof e?e:null)}static get VERSION(){return"5.2.2"}static get DATA_KEY(){return`bs.${this.NAME}`}static get EVENT_KEY(){return`.${this.DATA_KEY}`}static eventName(t){return`${t}${this.EVENT_KEY}`}}const K=(t,e="hide")=>{const i=`click.dismiss${t.EVENT_KEY}`,s=t.NAME;$.on(document,i,`[data-bs-dismiss="${s}"]`,(function(i){if(["A","AREA"].includes(this.tagName)&&i.preventDefault(),d(this))return;const n=r(this)||this.closest(`.${s}`);t.getOrCreateInstance(n)[e]()}))};class Q extends V{static get NAME(){return"alert"}close(){if($.trigger(this._element,"close.bs.alert").defaultPrevented)return;this._element.classList.remove("show");const t=this._element.classList.contains("fade");this._queueCallback((()=>this._destroyElement()),this._element,t)}_destroyElement(){this._element.remove(),$.trigger(this._element,"closed.bs.alert"),this.dispose()}static jQueryInterface(t){return this.each((function(){const e=Q.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}K(Q,"close"),b(Q);const X='[data-bs-toggle="button"]';class Y extends V{static get NAME(){return"button"}toggle(){this._element.setAttribute("aria-pressed",this._element.classList.toggle("active"))}static jQueryInterface(t){return this.each((function(){const e=Y.getOrCreateInstance(this);"toggle"===t&&e[t]()}))}}$.on(document,"click.bs.button.data-api",X,(t=>{t.preventDefault();const e=t.target.closest(X);Y.getOrCreateInstance(e).toggle()})),b(Y);const U={find:(t,e=document.documentElement)=>[].concat(...Element.prototype.querySelectorAll.call(e,t)),findOne:(t,e=document.documentElement)=>Element.prototype.querySelector.call(e,t),children:(t,e)=>[].concat(...t.children).filter((t=>t.matches(e))),parents(t,e){const i=[];let s=t.parentNode.closest(e);for(;s;)i.push(s),s=s.parentNode.closest(e);return i},prev(t,e){let i=t.previousElementSibling;for(;i;){if(i.matches(e))return[i];i=i.previousElementSibling}return[]},next(t,e){let i=t.nextElementSibling;for(;i;){if(i.matches(e))return[i];i=i.nextElementSibling}return[]},focusableChildren(t){const e=["a","button","input","textarea","select","details","[tabindex]",'[contenteditable="true"]'].map((t=>`${t}:not([tabindex^="-"])`)).join(",");return this.find(e,t).filter((t=>!d(t)&&h(t)))}},G={endCallback:null,leftCallback:null,rightCallback:null},J={endCallback:"(function|null)",leftCallback:"(function|null)",rightCallback:"(function|null)"};class Z extends R{constructor(t,e){super(),this._element=t,t&&Z.isSupported()&&(this._config=this._getConfig(e),this._deltaX=0,this._supportPointerEvents=Boolean(window.PointerEvent),this._initEvents())}static get Default(){return G}static get DefaultType(){return J}static get NAME(){return"swipe"}dispose(){$.off(this._element,".bs.swipe")}_start(t){this._supportPointerEvents?this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX):this._deltaX=t.touches[0].clientX}_end(t){this._eventIsPointerPenTouch(t)&&(this._deltaX=t.clientX-this._deltaX),this._handleSwipe(),v(this._config.endCallback)}_move(t){this._deltaX=t.touches&&t.touches.length>1?0:t.touches[0].clientX-this._deltaX}_handleSwipe(){const t=Math.abs(this._deltaX);if(t<=40)return;const e=t/this._deltaX;this._deltaX=0,e&&v(e>0?this._config.rightCallback:this._config.leftCallback)}_initEvents(){this._supportPointerEvents?($.on(this._element,"pointerdown.bs.swipe",(t=>this._start(t))),$.on(this._element,"pointerup.bs.swipe",(t=>this._end(t))),this._element.classList.add("pointer-event")):($.on(this._element,"touchstart.bs.swipe",(t=>this._start(t))),$.on(this._element,"touchmove.bs.swipe",(t=>this._move(t))),$.on(this._element,"touchend.bs.swipe",(t=>this._end(t))))}_eventIsPointerPenTouch(t){return this._supportPointerEvents&&("pen"===t.pointerType||"touch"===t.pointerType)}static isSupported(){return"ontouchstart"in document.documentElement||navigator.maxTouchPoints>0}}const tt="next",et="prev",it="left",st="right",nt="slid.bs.carousel",ot="carousel",rt="active",at={ArrowLeft:st,ArrowRight:it},lt={interval:5e3,keyboard:!0,pause:"hover",ride:!1,touch:!0,wrap:!0},ct={interval:"(number|boolean)",keyboard:"boolean",pause:"(string|boolean)",ride:"(boolean|string)",touch:"boolean",wrap:"boolean"};class ht extends V{constructor(t,e){super(t,e),this._interval=null,this._activeElement=null,this._isSliding=!1,this.touchTimeout=null,this._swipeHelper=null,this._indicatorsElement=U.findOne(".carousel-indicators",this._element),this._addEventListeners(),this._config.ride===ot&&this.cycle()}static get Default(){return lt}static get DefaultType(){return ct}static get NAME(){return"carousel"}next(){this._slide(tt)}nextWhenVisible(){!document.hidden&&h(this._element)&&this.next()}prev(){this._slide(et)}pause(){this._isSliding&&a(this._element),this._clearInterval()}cycle(){this._clearInterval(),this._updateInterval(),this._interval=setInterval((()=>this.nextWhenVisible()),this._config.interval)}_maybeEnableCycle(){this._config.ride&&(this._isSliding?$.one(this._element,nt,(()=>this.cycle())):this.cycle())}to(t){const e=this._getItems();if(t>e.length-1||t<0)return;if(this._isSliding)return void $.one(this._element,nt,(()=>this.to(t)));const i=this._getItemIndex(this._getActive());if(i===t)return;const s=t>i?tt:et;this._slide(s,e[t])}dispose(){this._swipeHelper&&this._swipeHelper.dispose(),super.dispose()}_configAfterMerge(t){return t.defaultInterval=t.interval,t}_addEventListeners(){this._config.keyboard&&$.on(this._element,"keydown.bs.carousel",(t=>this._keydown(t))),"hover"===this._config.pause&&($.on(this._element,"mouseenter.bs.carousel",(()=>this.pause())),$.on(this._element,"mouseleave.bs.carousel",(()=>this._maybeEnableCycle()))),this._config.touch&&Z.isSupported()&&this._addTouchEventListeners()}_addTouchEventListeners(){for(const t of U.find(".carousel-item img",this._element))$.on(t,"dragstart.bs.carousel",(t=>t.preventDefault()));const t={leftCallback:()=>this._slide(this._directionToOrder(it)),rightCallback:()=>this._slide(this._directionToOrder(st)),endCallback:()=>{"hover"===this._config.pause&&(this.pause(),this.touchTimeout&&clearTimeout(this.touchTimeout),this.touchTimeout=setTimeout((()=>this._maybeEnableCycle()),500+this._config.interval))}};this._swipeHelper=new Z(this._element,t)}_keydown(t){if(/input|textarea/i.test(t.target.tagName))return;const e=at[t.key];e&&(t.preventDefault(),this._slide(this._directionToOrder(e)))}_getItemIndex(t){return this._getItems().indexOf(t)}_setActiveIndicatorElement(t){if(!this._indicatorsElement)return;const e=U.findOne(".active",this._indicatorsElement);e.classList.remove(rt),e.removeAttribute("aria-current");const i=U.findOne(`[data-bs-slide-to="${t}"]`,this._indicatorsElement);i&&(i.classList.add(rt),i.setAttribute("aria-current","true"))}_updateInterval(){const t=this._activeElement||this._getActive();if(!t)return;const e=Number.parseInt(t.getAttribute("data-bs-interval"),10);this._config.interval=e||this._config.defaultInterval}_slide(t,e=null){if(this._isSliding)return;const i=this._getActive(),s=t===tt,n=e||w(this._getItems(),i,s,this._config.wrap);if(n===i)return;const o=this._getItemIndex(n),r=e=>$.trigger(this._element,e,{relatedTarget:n,direction:this._orderToDirection(t),from:this._getItemIndex(i),to:o});if(r("slide.bs.carousel").defaultPrevented)return;if(!i||!n)return;const a=Boolean(this._interval);this.pause(),this._isSliding=!0,this._setActiveIndicatorElement(o),this._activeElement=n;const l=s?"carousel-item-start":"carousel-item-end",c=s?"carousel-item-next":"carousel-item-prev";n.classList.add(c),g(n),i.classList.add(l),n.classList.add(l),this._queueCallback((()=>{n.classList.remove(l,c),n.classList.add(rt),i.classList.remove(rt,c,l),this._isSliding=!1,r(nt)}),i,this._isAnimated()),a&&this.cycle()}_isAnimated(){return this._element.classList.contains("slide")}_getActive(){return U.findOne(".active.carousel-item",this._element)}_getItems(){return U.find(".carousel-item",this._element)}_clearInterval(){this._interval&&(clearInterval(this._interval),this._interval=null)}_directionToOrder(t){return m()?t===it?et:tt:t===it?tt:et}_orderToDirection(t){return m()?t===et?it:st:t===et?st:it}static jQueryInterface(t){return this.each((function(){const e=ht.getOrCreateInstance(this,t);if("number"!=typeof t){if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}else e.to(t)}))}}$.on(document,"click.bs.carousel.data-api","[data-bs-slide], [data-bs-slide-to]",(function(t){const e=r(this);if(!e||!e.classList.contains(ot))return;t.preventDefault();const i=ht.getOrCreateInstance(e),s=this.getAttribute("data-bs-slide-to");return s?(i.to(s),void i._maybeEnableCycle()):"next"===W.getDataAttribute(this,"slide")?(i.next(),void i._maybeEnableCycle()):(i.prev(),void i._maybeEnableCycle())})),$.on(window,"load.bs.carousel.data-api",(()=>{const t=U.find('[data-bs-ride="carousel"]');for(const e of t)ht.getOrCreateInstance(e)})),b(ht);const dt="show",ut="collapse",_t="collapsing",gt='[data-bs-toggle="collapse"]',ft={parent:null,toggle:!0},pt={parent:"(null|element)",toggle:"boolean"};class mt extends V{constructor(t,e){super(t,e),this._isTransitioning=!1,this._triggerArray=[];const i=U.find(gt);for(const t of i){const e=o(t),i=U.find(e).filter((t=>t===this._element));null!==e&&i.length&&this._triggerArray.push(t)}this._initializeChildren(),this._config.parent||this._addAriaAndCollapsedClass(this._triggerArray,this._isShown()),this._config.toggle&&this.toggle()}static get Default(){return ft}static get DefaultType(){return pt}static get NAME(){return"collapse"}toggle(){this._isShown()?this.hide():this.show()}show(){if(this._isTransitioning||this._isShown())return;let t=[];if(this._config.parent&&(t=this._getFirstLevelChildren(".collapse.show, .collapse.collapsing").filter((t=>t!==this._element)).map((t=>mt.getOrCreateInstance(t,{toggle:!1})))),t.length&&t[0]._isTransitioning)return;if($.trigger(this._element,"show.bs.collapse").defaultPrevented)return;for(const e of t)e.hide();const e=this._getDimension();this._element.classList.remove(ut),this._element.classList.add(_t),this._element.style[e]=0,this._addAriaAndCollapsedClass(this._triggerArray,!0),this._isTransitioning=!0;const i=`scroll${e[0].toUpperCase()+e.slice(1)}`;this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(_t),this._element.classList.add(ut,dt),this._element.style[e]="",$.trigger(this._element,"shown.bs.collapse")}),this._element,!0),this._element.style[e]=`${this._element[i]}px`}hide(){if(this._isTransitioning||!this._isShown())return;if($.trigger(this._element,"hide.bs.collapse").defaultPrevented)return;const t=this._getDimension();this._element.style[t]=`${this._element.getBoundingClientRect()[t]}px`,g(this._element),this._element.classList.add(_t),this._element.classList.remove(ut,dt);for(const t of this._triggerArray){const e=r(t);e&&!this._isShown(e)&&this._addAriaAndCollapsedClass([t],!1)}this._isTransitioning=!0,this._element.style[t]="",this._queueCallback((()=>{this._isTransitioning=!1,this._element.classList.remove(_t),this._element.classList.add(ut),$.trigger(this._element,"hidden.bs.collapse")}),this._element,!0)}_isShown(t=this._element){return t.classList.contains(dt)}_configAfterMerge(t){return t.toggle=Boolean(t.toggle),t.parent=c(t.parent),t}_getDimension(){return this._element.classList.contains("collapse-horizontal")?"width":"height"}_initializeChildren(){if(!this._config.parent)return;const t=this._getFirstLevelChildren(gt);for(const e of t){const t=r(e);t&&this._addAriaAndCollapsedClass([e],this._isShown(t))}}_getFirstLevelChildren(t){const e=U.find(":scope .collapse .collapse",this._config.parent);return U.find(t,this._config.parent).filter((t=>!e.includes(t)))}_addAriaAndCollapsedClass(t,e){if(t.length)for(const i of t)i.classList.toggle("collapsed",!e),i.setAttribute("aria-expanded",e)}static jQueryInterface(t){const e={};return"string"==typeof t&&/show|hide/.test(t)&&(e.toggle=!1),this.each((function(){const i=mt.getOrCreateInstance(this,e);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t]()}}))}}$.on(document,"click.bs.collapse.data-api",gt,(function(t){("A"===t.target.tagName||t.delegateTarget&&"A"===t.delegateTarget.tagName)&&t.preventDefault();const e=o(this),i=U.find(e);for(const t of i)mt.getOrCreateInstance(t,{toggle:!1}).toggle()})),b(mt);const bt="dropdown",vt="ArrowUp",yt="ArrowDown",wt="click.bs.dropdown.data-api",At="keydown.bs.dropdown.data-api",Et="show",Ct='[data-bs-toggle="dropdown"]:not(.disabled):not(:disabled)',Tt=`${Ct}.show`,kt=".dropdown-menu",Lt=m()?"top-end":"top-start",Ot=m()?"top-start":"top-end",It=m()?"bottom-end":"bottom-start",St=m()?"bottom-start":"bottom-end",Dt=m()?"left-start":"right-start",Nt=m()?"right-start":"left-start",Pt={autoClose:!0,boundary:"clippingParents",display:"dynamic",offset:[0,2],popperConfig:null,reference:"toggle"},xt={autoClose:"(boolean|string)",boundary:"(string|element)",display:"string",offset:"(array|string|function)",popperConfig:"(null|object|function)",reference:"(string|element|object)"};class Mt extends V{constructor(t,e){super(t,e),this._popper=null,this._parent=this._element.parentNode,this._menu=U.next(this._element,kt)[0]||U.prev(this._element,kt)[0]||U.findOne(kt,this._parent),this._inNavbar=this._detectNavbar()}static get Default(){return Pt}static get DefaultType(){return xt}static get NAME(){return bt}toggle(){return this._isShown()?this.hide():this.show()}show(){if(d(this._element)||this._isShown())return;const t={relatedTarget:this._element};if(!$.trigger(this._element,"show.bs.dropdown",t).defaultPrevented){if(this._createPopper(),"ontouchstart"in document.documentElement&&!this._parent.closest(".navbar-nav"))for(const t of[].concat(...document.body.children))$.on(t,"mouseover",_);this._element.focus(),this._element.setAttribute("aria-expanded",!0),this._menu.classList.add(Et),this._element.classList.add(Et),$.trigger(this._element,"shown.bs.dropdown",t)}}hide(){if(d(this._element)||!this._isShown())return;const t={relatedTarget:this._element};this._completeHide(t)}dispose(){this._popper&&this._popper.destroy(),super.dispose()}update(){this._inNavbar=this._detectNavbar(),this._popper&&this._popper.update()}_completeHide(t){if(!$.trigger(this._element,"hide.bs.dropdown",t).defaultPrevented){if("ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))$.off(t,"mouseover",_);this._popper&&this._popper.destroy(),this._menu.classList.remove(Et),this._element.classList.remove(Et),this._element.setAttribute("aria-expanded","false"),W.removeDataAttribute(this._menu,"popper"),$.trigger(this._element,"hidden.bs.dropdown",t)}}_getConfig(t){if("object"==typeof(t=super._getConfig(t)).reference&&!l(t.reference)&&"function"!=typeof t.reference.getBoundingClientRect)throw new TypeError(`${bt.toUpperCase()}: Option "reference" provided type "object" without a required "getBoundingClientRect" method.`);return t}_createPopper(){if(void 0===i)throw new TypeError("Bootstrap's dropdowns require Popper (https://popper.js.org)");let t=this._element;"parent"===this._config.reference?t=this._parent:l(this._config.reference)?t=c(this._config.reference):"object"==typeof this._config.reference&&(t=this._config.reference);const e=this._getPopperConfig();this._popper=i.createPopper(t,this._menu,e)}_isShown(){return this._menu.classList.contains(Et)}_getPlacement(){const t=this._parent;if(t.classList.contains("dropend"))return Dt;if(t.classList.contains("dropstart"))return Nt;if(t.classList.contains("dropup-center"))return"top";if(t.classList.contains("dropdown-center"))return"bottom";const e="end"===getComputedStyle(this._menu).getPropertyValue("--bs-position").trim();return t.classList.contains("dropup")?e?Ot:Lt:e?St:It}_detectNavbar(){return null!==this._element.closest(".navbar")}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map((t=>Number.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_getPopperConfig(){const t={placement:this._getPlacement(),modifiers:[{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"offset",options:{offset:this._getOffset()}}]};return(this._inNavbar||"static"===this._config.display)&&(W.setDataAttribute(this._menu,"popper","static"),t.modifiers=[{name:"applyStyles",enabled:!1}]),{...t,..."function"==typeof this._config.popperConfig?this._config.popperConfig(t):this._config.popperConfig}}_selectMenuItem({key:t,target:e}){const i=U.find(".dropdown-menu .dropdown-item:not(.disabled):not(:disabled)",this._menu).filter((t=>h(t)));i.length&&w(i,e,t===yt,!i.includes(e)).focus()}static jQueryInterface(t){return this.each((function(){const e=Mt.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}static clearMenus(t){if(2===t.button||"keyup"===t.type&&"Tab"!==t.key)return;const e=U.find(Tt);for(const i of e){const e=Mt.getInstance(i);if(!e||!1===e._config.autoClose)continue;const s=t.composedPath(),n=s.includes(e._menu);if(s.includes(e._element)||"inside"===e._config.autoClose&&!n||"outside"===e._config.autoClose&&n)continue;if(e._menu.contains(t.target)&&("keyup"===t.type&&"Tab"===t.key||/input|select|option|textarea|form/i.test(t.target.tagName)))continue;const o={relatedTarget:e._element};"click"===t.type&&(o.clickEvent=t),e._completeHide(o)}}static dataApiKeydownHandler(t){const e=/input|textarea/i.test(t.target.tagName),i="Escape"===t.key,s=[vt,yt].includes(t.key);if(!s&&!i)return;if(e&&!i)return;t.preventDefault();const n=this.matches(Ct)?this:U.prev(this,Ct)[0]||U.next(this,Ct)[0]||U.findOne(Ct,t.delegateTarget.parentNode),o=Mt.getOrCreateInstance(n);if(s)return t.stopPropagation(),o.show(),void o._selectMenuItem(t);o._isShown()&&(t.stopPropagation(),o.hide(),n.focus())}}$.on(document,At,Ct,Mt.dataApiKeydownHandler),$.on(document,At,kt,Mt.dataApiKeydownHandler),$.on(document,wt,Mt.clearMenus),$.on(document,"keyup.bs.dropdown.data-api",Mt.clearMenus),$.on(document,wt,Ct,(function(t){t.preventDefault(),Mt.getOrCreateInstance(this).toggle()})),b(Mt);const jt=".fixed-top, .fixed-bottom, .is-fixed, .sticky-top",$t=".sticky-top",Ft="padding-right",zt="margin-right";class Ht{constructor(){this._element=document.body}getWidth(){const t=document.documentElement.clientWidth;return Math.abs(window.innerWidth-t)}hide(){const t=this.getWidth();this._disableOverFlow(),this._setElementAttributes(this._element,Ft,(e=>e+t)),this._setElementAttributes(jt,Ft,(e=>e+t)),this._setElementAttributes($t,zt,(e=>e-t))}reset(){this._resetElementAttributes(this._element,"overflow"),this._resetElementAttributes(this._element,Ft),this._resetElementAttributes(jt,Ft),this._resetElementAttributes($t,zt)}isOverflowing(){return this.getWidth()>0}_disableOverFlow(){this._saveInitialAttribute(this._element,"overflow"),this._element.style.overflow="hidden"}_setElementAttributes(t,e,i){const s=this.getWidth();this._applyManipulationCallback(t,(t=>{if(t!==this._element&&window.innerWidth>t.clientWidth+s)return;this._saveInitialAttribute(t,e);const n=window.getComputedStyle(t).getPropertyValue(e);t.style.setProperty(e,`${i(Number.parseFloat(n))}px`)}))}_saveInitialAttribute(t,e){const i=t.style.getPropertyValue(e);i&&W.setDataAttribute(t,e,i)}_resetElementAttributes(t,e){this._applyManipulationCallback(t,(t=>{const i=W.getDataAttribute(t,e);null!==i?(W.removeDataAttribute(t,e),t.style.setProperty(e,i)):t.style.removeProperty(e)}))}_applyManipulationCallback(t,e){if(l(t))e(t);else for(const i of U.find(t,this._element))e(i)}}const qt="show",Bt="mousedown.bs.backdrop",Wt={className:"modal-backdrop",clickCallback:null,isAnimated:!1,isVisible:!0,rootElement:"body"},Rt={className:"string",clickCallback:"(function|null)",isAnimated:"boolean",isVisible:"boolean",rootElement:"(element|string)"};class Vt extends R{constructor(t){super(),this._config=this._getConfig(t),this._isAppended=!1,this._element=null}static get Default(){return Wt}static get DefaultType(){return Rt}static get NAME(){return"backdrop"}show(t){if(!this._config.isVisible)return void v(t);this._append();const e=this._getElement();this._config.isAnimated&&g(e),e.classList.add(qt),this._emulateAnimation((()=>{v(t)}))}hide(t){this._config.isVisible?(this._getElement().classList.remove(qt),this._emulateAnimation((()=>{this.dispose(),v(t)}))):v(t)}dispose(){this._isAppended&&($.off(this._element,Bt),this._element.remove(),this._isAppended=!1)}_getElement(){if(!this._element){const t=document.createElement("div");t.className=this._config.className,this._config.isAnimated&&t.classList.add("fade"),this._element=t}return this._element}_configAfterMerge(t){return t.rootElement=c(t.rootElement),t}_append(){if(this._isAppended)return;const t=this._getElement();this._config.rootElement.append(t),$.on(t,Bt,(()=>{v(this._config.clickCallback)})),this._isAppended=!0}_emulateAnimation(t){y(t,this._getElement(),this._config.isAnimated)}}const Kt=".bs.focustrap",Qt="backward",Xt={autofocus:!0,trapElement:null},Yt={autofocus:"boolean",trapElement:"element"};class Ut extends R{constructor(t){super(),this._config=this._getConfig(t),this._isActive=!1,this._lastTabNavDirection=null}static get Default(){return Xt}static get DefaultType(){return Yt}static get NAME(){return"focustrap"}activate(){this._isActive||(this._config.autofocus&&this._config.trapElement.focus(),$.off(document,Kt),$.on(document,"focusin.bs.focustrap",(t=>this._handleFocusin(t))),$.on(document,"keydown.tab.bs.focustrap",(t=>this._handleKeydown(t))),this._isActive=!0)}deactivate(){this._isActive&&(this._isActive=!1,$.off(document,Kt))}_handleFocusin(t){const{trapElement:e}=this._config;if(t.target===document||t.target===e||e.contains(t.target))return;const i=U.focusableChildren(e);0===i.length?e.focus():this._lastTabNavDirection===Qt?i[i.length-1].focus():i[0].focus()}_handleKeydown(t){"Tab"===t.key&&(this._lastTabNavDirection=t.shiftKey?Qt:"forward")}}const Gt="hidden.bs.modal",Jt="show.bs.modal",Zt="modal-open",te="show",ee="modal-static",ie={backdrop:!0,focus:!0,keyboard:!0},se={backdrop:"(boolean|string)",focus:"boolean",keyboard:"boolean"};class ne extends V{constructor(t,e){super(t,e),this._dialog=U.findOne(".modal-dialog",this._element),this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._isShown=!1,this._isTransitioning=!1,this._scrollBar=new Ht,this._addEventListeners()}static get Default(){return ie}static get DefaultType(){return se}static get NAME(){return"modal"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||this._isTransitioning||$.trigger(this._element,Jt,{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._isTransitioning=!0,this._scrollBar.hide(),document.body.classList.add(Zt),this._adjustDialog(),this._backdrop.show((()=>this._showElement(t))))}hide(){this._isShown&&!this._isTransitioning&&($.trigger(this._element,"hide.bs.modal").defaultPrevented||(this._isShown=!1,this._isTransitioning=!0,this._focustrap.deactivate(),this._element.classList.remove(te),this._queueCallback((()=>this._hideModal()),this._element,this._isAnimated())))}dispose(){for(const t of[window,this._dialog])$.off(t,".bs.modal");this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}handleUpdate(){this._adjustDialog()}_initializeBackDrop(){return new Vt({isVisible:Boolean(this._config.backdrop),isAnimated:this._isAnimated()})}_initializeFocusTrap(){return new Ut({trapElement:this._element})}_showElement(t){document.body.contains(this._element)||document.body.append(this._element),this._element.style.display="block",this._element.removeAttribute("aria-hidden"),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.scrollTop=0;const e=U.findOne(".modal-body",this._dialog);e&&(e.scrollTop=0),g(this._element),this._element.classList.add(te),this._queueCallback((()=>{this._config.focus&&this._focustrap.activate(),this._isTransitioning=!1,$.trigger(this._element,"shown.bs.modal",{relatedTarget:t})}),this._dialog,this._isAnimated())}_addEventListeners(){$.on(this._element,"keydown.dismiss.bs.modal",(t=>{if("Escape"===t.key)return this._config.keyboard?(t.preventDefault(),void this.hide()):void this._triggerBackdropTransition()})),$.on(window,"resize.bs.modal",(()=>{this._isShown&&!this._isTransitioning&&this._adjustDialog()})),$.on(this._element,"mousedown.dismiss.bs.modal",(t=>{$.one(this._element,"click.dismiss.bs.modal",(e=>{this._element===t.target&&this._element===e.target&&("static"!==this._config.backdrop?this._config.backdrop&&this.hide():this._triggerBackdropTransition())}))}))}_hideModal(){this._element.style.display="none",this._element.setAttribute("aria-hidden",!0),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._isTransitioning=!1,this._backdrop.hide((()=>{document.body.classList.remove(Zt),this._resetAdjustments(),this._scrollBar.reset(),$.trigger(this._element,Gt)}))}_isAnimated(){return this._element.classList.contains("fade")}_triggerBackdropTransition(){if($.trigger(this._element,"hidePrevented.bs.modal").defaultPrevented)return;const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._element.style.overflowY;"hidden"===e||this._element.classList.contains(ee)||(t||(this._element.style.overflowY="hidden"),this._element.classList.add(ee),this._queueCallback((()=>{this._element.classList.remove(ee),this._queueCallback((()=>{this._element.style.overflowY=e}),this._dialog)}),this._dialog),this._element.focus())}_adjustDialog(){const t=this._element.scrollHeight>document.documentElement.clientHeight,e=this._scrollBar.getWidth(),i=e>0;if(i&&!t){const t=m()?"paddingLeft":"paddingRight";this._element.style[t]=`${e}px`}if(!i&&t){const t=m()?"paddingRight":"paddingLeft";this._element.style[t]=`${e}px`}}_resetAdjustments(){this._element.style.paddingLeft="",this._element.style.paddingRight=""}static jQueryInterface(t,e){return this.each((function(){const i=ne.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===i[t])throw new TypeError(`No method named "${t}"`);i[t](e)}}))}}$.on(document,"click.bs.modal.data-api",'[data-bs-toggle="modal"]',(function(t){const e=r(this);["A","AREA"].includes(this.tagName)&&t.preventDefault(),$.one(e,Jt,(t=>{t.defaultPrevented||$.one(e,Gt,(()=>{h(this)&&this.focus()}))}));const i=U.findOne(".modal.show");i&&ne.getInstance(i).hide(),ne.getOrCreateInstance(e).toggle(this)})),K(ne),b(ne);const oe="show",re="showing",ae="hiding",le=".offcanvas.show",ce="hidePrevented.bs.offcanvas",he="hidden.bs.offcanvas",de={backdrop:!0,keyboard:!0,scroll:!1},ue={backdrop:"(boolean|string)",keyboard:"boolean",scroll:"boolean"};class _e extends V{constructor(t,e){super(t,e),this._isShown=!1,this._backdrop=this._initializeBackDrop(),this._focustrap=this._initializeFocusTrap(),this._addEventListeners()}static get Default(){return de}static get DefaultType(){return ue}static get NAME(){return"offcanvas"}toggle(t){return this._isShown?this.hide():this.show(t)}show(t){this._isShown||$.trigger(this._element,"show.bs.offcanvas",{relatedTarget:t}).defaultPrevented||(this._isShown=!0,this._backdrop.show(),this._config.scroll||(new Ht).hide(),this._element.setAttribute("aria-modal",!0),this._element.setAttribute("role","dialog"),this._element.classList.add(re),this._queueCallback((()=>{this._config.scroll&&!this._config.backdrop||this._focustrap.activate(),this._element.classList.add(oe),this._element.classList.remove(re),$.trigger(this._element,"shown.bs.offcanvas",{relatedTarget:t})}),this._element,!0))}hide(){this._isShown&&($.trigger(this._element,"hide.bs.offcanvas").defaultPrevented||(this._focustrap.deactivate(),this._element.blur(),this._isShown=!1,this._element.classList.add(ae),this._backdrop.hide(),this._queueCallback((()=>{this._element.classList.remove(oe,ae),this._element.removeAttribute("aria-modal"),this._element.removeAttribute("role"),this._config.scroll||(new Ht).reset(),$.trigger(this._element,he)}),this._element,!0)))}dispose(){this._backdrop.dispose(),this._focustrap.deactivate(),super.dispose()}_initializeBackDrop(){const t=Boolean(this._config.backdrop);return new Vt({className:"offcanvas-backdrop",isVisible:t,isAnimated:!0,rootElement:this._element.parentNode,clickCallback:t?()=>{"static"!==this._config.backdrop?this.hide():$.trigger(this._element,ce)}:null})}_initializeFocusTrap(){return new Ut({trapElement:this._element})}_addEventListeners(){$.on(this._element,"keydown.dismiss.bs.offcanvas",(t=>{"Escape"===t.key&&(this._config.keyboard?this.hide():$.trigger(this._element,ce))}))}static jQueryInterface(t){return this.each((function(){const e=_e.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}$.on(document,"click.bs.offcanvas.data-api",'[data-bs-toggle="offcanvas"]',(function(t){const e=r(this);if(["A","AREA"].includes(this.tagName)&&t.preventDefault(),d(this))return;$.one(e,he,(()=>{h(this)&&this.focus()}));const i=U.findOne(le);i&&i!==e&&_e.getInstance(i).hide(),_e.getOrCreateInstance(e).toggle(this)})),$.on(window,"load.bs.offcanvas.data-api",(()=>{for(const t of U.find(le))_e.getOrCreateInstance(t).show()})),$.on(window,"resize.bs.offcanvas",(()=>{for(const t of U.find("[aria-modal][class*=show][class*=offcanvas-]"))"fixed"!==getComputedStyle(t).position&&_e.getOrCreateInstance(t).hide()})),K(_e),b(_e);const ge=new Set(["background","cite","href","itemtype","longdesc","poster","src","xlink:href"]),fe=/^(?:(?:https?|mailto|ftp|tel|file|sms):|[^#&/:?]*(?:[#/?]|$))/i,pe=/^data:(?:image\/(?:bmp|gif|jpeg|jpg|png|tiff|webp)|video\/(?:mpeg|mp4|ogg|webm)|audio\/(?:mp3|oga|ogg|opus));base64,[\d+/a-z]+=*$/i,me=(t,e)=>{const i=t.nodeName.toLowerCase();return e.includes(i)?!ge.has(i)||Boolean(fe.test(t.nodeValue)||pe.test(t.nodeValue)):e.filter((t=>t instanceof RegExp)).some((t=>t.test(i)))},be={"*":["class","dir","id","lang","role",/^aria-[\w-]*$/i],a:["target","href","title","rel"],area:[],b:[],br:[],col:[],code:[],div:[],em:[],hr:[],h1:[],h2:[],h3:[],h4:[],h5:[],h6:[],i:[],img:["src","srcset","alt","title","width","height"],li:[],ol:[],p:[],pre:[],s:[],small:[],span:[],sub:[],sup:[],strong:[],u:[],ul:[]},ve={allowList:be,content:{},extraClass:"",html:!1,sanitize:!0,sanitizeFn:null,template:"<div></div>"},ye={allowList:"object",content:"object",extraClass:"(string|function)",html:"boolean",sanitize:"boolean",sanitizeFn:"(null|function)",template:"string"},we={entry:"(string|element|function|null)",selector:"(string|element)"};class Ae extends R{constructor(t){super(),this._config=this._getConfig(t)}static get Default(){return ve}static get DefaultType(){return ye}static get NAME(){return"TemplateFactory"}getContent(){return Object.values(this._config.content).map((t=>this._resolvePossibleFunction(t))).filter(Boolean)}hasContent(){return this.getContent().length>0}changeContent(t){return this._checkContent(t),this._config.content={...this._config.content,...t},this}toHtml(){const t=document.createElement("div");t.innerHTML=this._maybeSanitize(this._config.template);for(const[e,i]of Object.entries(this._config.content))this._setContent(t,i,e);const e=t.children[0],i=this._resolvePossibleFunction(this._config.extraClass);return i&&e.classList.add(...i.split(" ")),e}_typeCheckConfig(t){super._typeCheckConfig(t),this._checkContent(t.content)}_checkContent(t){for(const[e,i]of Object.entries(t))super._typeCheckConfig({selector:e,entry:i},we)}_setContent(t,e,i){const s=U.findOne(i,t);s&&((e=this._resolvePossibleFunction(e))?l(e)?this._putElementInTemplate(c(e),s):this._config.html?s.innerHTML=this._maybeSanitize(e):s.textContent=e:s.remove())}_maybeSanitize(t){return this._config.sanitize?function(t,e,i){if(!t.length)return t;if(i&&"function"==typeof i)return i(t);const s=(new window.DOMParser).parseFromString(t,"text/html"),n=[].concat(...s.body.querySelectorAll("*"));for(const t of n){const i=t.nodeName.toLowerCase();if(!Object.keys(e).includes(i)){t.remove();continue}const s=[].concat(...t.attributes),n=[].concat(e["*"]||[],e[i]||[]);for(const e of s)me(e,n)||t.removeAttribute(e.nodeName)}return s.body.innerHTML}(t,this._config.allowList,this._config.sanitizeFn):t}_resolvePossibleFunction(t){return"function"==typeof t?t(this):t}_putElementInTemplate(t,e){if(this._config.html)return e.innerHTML="",void e.append(t);e.textContent=t.textContent}}const Ee=new Set(["sanitize","allowList","sanitizeFn"]),Ce="fade",Te="show",ke=".modal",Le="hide.bs.modal",Oe="hover",Ie="focus",Se={AUTO:"auto",TOP:"top",RIGHT:m()?"left":"right",BOTTOM:"bottom",LEFT:m()?"right":"left"},De={allowList:be,animation:!0,boundary:"clippingParents",container:!1,customClass:"",delay:0,fallbackPlacements:["top","right","bottom","left"],html:!1,offset:[0,0],placement:"top",popperConfig:null,sanitize:!0,sanitizeFn:null,selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',title:"",trigger:"hover focus"},Ne={allowList:"object",animation:"boolean",boundary:"(string|element)",container:"(string|element|boolean)",customClass:"(string|function)",delay:"(number|object)",fallbackPlacements:"array",html:"boolean",offset:"(array|string|function)",placement:"(string|function)",popperConfig:"(null|object|function)",sanitize:"boolean",sanitizeFn:"(null|function)",selector:"(string|boolean)",template:"string",title:"(string|element|function)",trigger:"string"};class Pe extends V{constructor(t,e){if(void 0===i)throw new TypeError("Bootstrap's tooltips require Popper (https://popper.js.org)");super(t,e),this._isEnabled=!0,this._timeout=0,this._isHovered=null,this._activeTrigger={},this._popper=null,this._templateFactory=null,this._newContent=null,this.tip=null,this._setListeners(),this._config.selector||this._fixTitle()}static get Default(){return De}static get DefaultType(){return Ne}static get NAME(){return"tooltip"}enable(){this._isEnabled=!0}disable(){this._isEnabled=!1}toggleEnabled(){this._isEnabled=!this._isEnabled}toggle(){this._isEnabled&&(this._activeTrigger.click=!this._activeTrigger.click,this._isShown()?this._leave():this._enter())}dispose(){clearTimeout(this._timeout),$.off(this._element.closest(ke),Le,this._hideModalHandler),this.tip&&this.tip.remove(),this._element.getAttribute("data-bs-original-title")&&this._element.setAttribute("title",this._element.getAttribute("data-bs-original-title")),this._disposePopper(),super.dispose()}show(){if("none"===this._element.style.display)throw new Error("Please use show on visible elements");if(!this._isWithContent()||!this._isEnabled)return;const t=$.trigger(this._element,this.constructor.eventName("show")),e=(u(this._element)||this._element.ownerDocument.documentElement).contains(this._element);if(t.defaultPrevented||!e)return;this.tip&&(this.tip.remove(),this.tip=null);const i=this._getTipElement();this._element.setAttribute("aria-describedby",i.getAttribute("id"));const{container:s}=this._config;if(this._element.ownerDocument.documentElement.contains(this.tip)||(s.append(i),$.trigger(this._element,this.constructor.eventName("inserted"))),this._popper?this._popper.update():this._popper=this._createPopper(i),i.classList.add(Te),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))$.on(t,"mouseover",_);this._queueCallback((()=>{$.trigger(this._element,this.constructor.eventName("shown")),!1===this._isHovered&&this._leave(),this._isHovered=!1}),this.tip,this._isAnimated())}hide(){if(!this._isShown())return;if($.trigger(this._element,this.constructor.eventName("hide")).defaultPrevented)return;const t=this._getTipElement();if(t.classList.remove(Te),"ontouchstart"in document.documentElement)for(const t of[].concat(...document.body.children))$.off(t,"mouseover",_);this._activeTrigger.click=!1,this._activeTrigger.focus=!1,this._activeTrigger.hover=!1,this._isHovered=null,this._queueCallback((()=>{this._isWithActiveTrigger()||(this._isHovered||t.remove(),this._element.removeAttribute("aria-describedby"),$.trigger(this._element,this.constructor.eventName("hidden")),this._disposePopper())}),this.tip,this._isAnimated())}update(){this._popper&&this._popper.update()}_isWithContent(){return Boolean(this._getTitle())}_getTipElement(){return this.tip||(this.tip=this._createTipElement(this._newContent||this._getContentForTemplate())),this.tip}_createTipElement(t){const e=this._getTemplateFactory(t).toHtml();if(!e)return null;e.classList.remove(Ce,Te),e.classList.add(`bs-${this.constructor.NAME}-auto`);const i=(t=>{do{t+=Math.floor(1e6*Math.random())}while(document.getElementById(t));return t})(this.constructor.NAME).toString();return e.setAttribute("id",i),this._isAnimated()&&e.classList.add(Ce),e}setContent(t){this._newContent=t,this._isShown()&&(this._disposePopper(),this.show())}_getTemplateFactory(t){return this._templateFactory?this._templateFactory.changeContent(t):this._templateFactory=new Ae({...this._config,content:t,extraClass:this._resolvePossibleFunction(this._config.customClass)}),this._templateFactory}_getContentForTemplate(){return{".tooltip-inner":this._getTitle()}}_getTitle(){return this._resolvePossibleFunction(this._config.title)||this._element.getAttribute("data-bs-original-title")}_initializeOnDelegatedTarget(t){return this.constructor.getOrCreateInstance(t.delegateTarget,this._getDelegateConfig())}_isAnimated(){return this._config.animation||this.tip&&this.tip.classList.contains(Ce)}_isShown(){return this.tip&&this.tip.classList.contains(Te)}_createPopper(t){const e="function"==typeof this._config.placement?this._config.placement.call(this,t,this._element):this._config.placement,s=Se[e.toUpperCase()];return i.createPopper(this._element,t,this._getPopperConfig(s))}_getOffset(){const{offset:t}=this._config;return"string"==typeof t?t.split(",").map((t=>Number.parseInt(t,10))):"function"==typeof t?e=>t(e,this._element):t}_resolvePossibleFunction(t){return"function"==typeof t?t.call(this._element):t}_getPopperConfig(t){const e={placement:t,modifiers:[{name:"flip",options:{fallbackPlacements:this._config.fallbackPlacements}},{name:"offset",options:{offset:this._getOffset()}},{name:"preventOverflow",options:{boundary:this._config.boundary}},{name:"arrow",options:{element:`.${this.constructor.NAME}-arrow`}},{name:"preSetPlacement",enabled:!0,phase:"beforeMain",fn:t=>{this._getTipElement().setAttribute("data-popper-placement",t.state.placement)}}]};return{...e,..."function"==typeof this._config.popperConfig?this._config.popperConfig(e):this._config.popperConfig}}_setListeners(){const t=this._config.trigger.split(" ");for(const e of t)if("click"===e)$.on(this._element,this.constructor.eventName("click"),this._config.selector,(t=>{this._initializeOnDelegatedTarget(t).toggle()}));else if("manual"!==e){const t=e===Oe?this.constructor.eventName("mouseenter"):this.constructor.eventName("focusin"),i=e===Oe?this.constructor.eventName("mouseleave"):this.constructor.eventName("focusout");$.on(this._element,t,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusin"===t.type?Ie:Oe]=!0,e._enter()})),$.on(this._element,i,this._config.selector,(t=>{const e=this._initializeOnDelegatedTarget(t);e._activeTrigger["focusout"===t.type?Ie:Oe]=e._element.contains(t.relatedTarget),e._leave()}))}this._hideModalHandler=()=>{this._element&&this.hide()},$.on(this._element.closest(ke),Le,this._hideModalHandler)}_fixTitle(){const t=this._element.getAttribute("title");t&&(this._element.getAttribute("aria-label")||this._element.textContent.trim()||this._element.setAttribute("aria-label",t),this._element.setAttribute("data-bs-original-title",t),this._element.removeAttribute("title"))}_enter(){this._isShown()||this._isHovered?this._isHovered=!0:(this._isHovered=!0,this._setTimeout((()=>{this._isHovered&&this.show()}),this._config.delay.show))}_leave(){this._isWithActiveTrigger()||(this._isHovered=!1,this._setTimeout((()=>{this._isHovered||this.hide()}),this._config.delay.hide))}_setTimeout(t,e){clearTimeout(this._timeout),this._timeout=setTimeout(t,e)}_isWithActiveTrigger(){return Object.values(this._activeTrigger).includes(!0)}_getConfig(t){const e=W.getDataAttributes(this._element);for(const t of Object.keys(e))Ee.has(t)&&delete e[t];return t={...e,..."object"==typeof t&&t?t:{}},t=this._mergeConfigObj(t),t=this._configAfterMerge(t),this._typeCheckConfig(t),t}_configAfterMerge(t){return t.container=!1===t.container?document.body:c(t.container),"number"==typeof t.delay&&(t.delay={show:t.delay,hide:t.delay}),"number"==typeof t.title&&(t.title=t.title.toString()),"number"==typeof t.content&&(t.content=t.content.toString()),t}_getDelegateConfig(){const t={};for(const e in this._config)this.constructor.Default[e]!==this._config[e]&&(t[e]=this._config[e]);return t.selector=!1,t.trigger="manual",t}_disposePopper(){this._popper&&(this._popper.destroy(),this._popper=null)}static jQueryInterface(t){return this.each((function(){const e=Pe.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}b(Pe);const xe={...Pe.Default,content:"",offset:[0,8],placement:"right",template:'<div class="popover" role="tooltip"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>',trigger:"click"},Me={...Pe.DefaultType,content:"(null|string|element|function)"};class je extends Pe{static get Default(){return xe}static get DefaultType(){return Me}static get NAME(){return"popover"}_isWithContent(){return this._getTitle()||this._getContent()}_getContentForTemplate(){return{".popover-header":this._getTitle(),".popover-body":this._getContent()}}_getContent(){return this._resolvePossibleFunction(this._config.content)}static jQueryInterface(t){return this.each((function(){const e=je.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t]()}}))}}b(je);const $e="click.bs.scrollspy",Fe="active",ze="[href]",He={offset:null,rootMargin:"0px 0px -25%",smoothScroll:!1,target:null,threshold:[.1,.5,1]},qe={offset:"(number|null)",rootMargin:"string",smoothScroll:"boolean",target:"element",threshold:"array"};class Be extends V{constructor(t,e){super(t,e),this._targetLinks=new Map,this._observableSections=new Map,this._rootElement="visible"===getComputedStyle(this._element).overflowY?null:this._element,this._activeTarget=null,this._observer=null,this._previousScrollData={visibleEntryTop:0,parentScrollTop:0},this.refresh()}static get Default(){return He}static get DefaultType(){return qe}static get NAME(){return"scrollspy"}refresh(){this._initializeTargetsAndObservables(),this._maybeEnableSmoothScroll(),this._observer?this._observer.disconnect():this._observer=this._getNewObserver();for(const t of this._observableSections.values())this._observer.observe(t)}dispose(){this._observer.disconnect(),super.dispose()}_configAfterMerge(t){return t.target=c(t.target)||document.body,t.rootMargin=t.offset?`${t.offset}px 0px -30%`:t.rootMargin,"string"==typeof t.threshold&&(t.threshold=t.threshold.split(",").map((t=>Number.parseFloat(t)))),t}_maybeEnableSmoothScroll(){this._config.smoothScroll&&($.off(this._config.target,$e),$.on(this._config.target,$e,ze,(t=>{const e=this._observableSections.get(t.target.hash);if(e){t.preventDefault();const i=this._rootElement||window,s=e.offsetTop-this._element.offsetTop;if(i.scrollTo)return void i.scrollTo({top:s,behavior:"smooth"});i.scrollTop=s}})))}_getNewObserver(){const t={root:this._rootElement,threshold:this._config.threshold,rootMargin:this._config.rootMargin};return new IntersectionObserver((t=>this._observerCallback(t)),t)}_observerCallback(t){const e=t=>this._targetLinks.get(`#${t.target.id}`),i=t=>{this._previousScrollData.visibleEntryTop=t.target.offsetTop,this._process(e(t))},s=(this._rootElement||document.documentElement).scrollTop,n=s>=this._previousScrollData.parentScrollTop;this._previousScrollData.parentScrollTop=s;for(const o of t){if(!o.isIntersecting){this._activeTarget=null,this._clearActiveClass(e(o));continue}const t=o.target.offsetTop>=this._previousScrollData.visibleEntryTop;if(n&&t){if(i(o),!s)return}else n||t||i(o)}}_initializeTargetsAndObservables(){this._targetLinks=new Map,this._observableSections=new Map;const t=U.find(ze,this._config.target);for(const e of t){if(!e.hash||d(e))continue;const t=U.findOne(e.hash,this._element);h(t)&&(this._targetLinks.set(e.hash,e),this._observableSections.set(e.hash,t))}}_process(t){this._activeTarget!==t&&(this._clearActiveClass(this._config.target),this._activeTarget=t,t.classList.add(Fe),this._activateParents(t),$.trigger(this._element,"activate.bs.scrollspy",{relatedTarget:t}))}_activateParents(t){if(t.classList.contains("dropdown-item"))U.findOne(".dropdown-toggle",t.closest(".dropdown")).classList.add(Fe);else for(const e of U.parents(t,".nav, .list-group"))for(const t of U.prev(e,".nav-link, .nav-item > .nav-link, .list-group-item"))t.classList.add(Fe)}_clearActiveClass(t){t.classList.remove(Fe);const e=U.find("[href].active",t);for(const t of e)t.classList.remove(Fe)}static jQueryInterface(t){return this.each((function(){const e=Be.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}$.on(window,"load.bs.scrollspy.data-api",(()=>{for(const t of U.find('[data-bs-spy="scroll"]'))Be.getOrCreateInstance(t)})),b(Be);const We="ArrowLeft",Re="ArrowRight",Ve="ArrowUp",Ke="ArrowDown",Qe="active",Xe="fade",Ye="show",Ue='[data-bs-toggle="tab"], [data-bs-toggle="pill"], [data-bs-toggle="list"]',Ge=`.nav-link:not(.dropdown-toggle), .list-group-item:not(.dropdown-toggle), [role="tab"]:not(.dropdown-toggle), ${Ue}`;class Je extends V{constructor(t){super(t),this._parent=this._element.closest('.list-group, .nav, [role="tablist"]'),this._parent&&(this._setInitialAttributes(this._parent,this._getChildren()),$.on(this._element,"keydown.bs.tab",(t=>this._keydown(t))))}static get NAME(){return"tab"}show(){const t=this._element;if(this._elemIsActive(t))return;const e=this._getActiveElem(),i=e?$.trigger(e,"hide.bs.tab",{relatedTarget:t}):null;$.trigger(t,"show.bs.tab",{relatedTarget:e}).defaultPrevented||i&&i.defaultPrevented||(this._deactivate(e,t),this._activate(t,e))}_activate(t,e){t&&(t.classList.add(Qe),this._activate(r(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.removeAttribute("tabindex"),t.setAttribute("aria-selected",!0),this._toggleDropDown(t,!0),$.trigger(t,"shown.bs.tab",{relatedTarget:e})):t.classList.add(Ye)}),t,t.classList.contains(Xe)))}_deactivate(t,e){t&&(t.classList.remove(Qe),t.blur(),this._deactivate(r(t)),this._queueCallback((()=>{"tab"===t.getAttribute("role")?(t.setAttribute("aria-selected",!1),t.setAttribute("tabindex","-1"),this._toggleDropDown(t,!1),$.trigger(t,"hidden.bs.tab",{relatedTarget:e})):t.classList.remove(Ye)}),t,t.classList.contains(Xe)))}_keydown(t){if(![We,Re,Ve,Ke].includes(t.key))return;t.stopPropagation(),t.preventDefault();const e=[Re,Ke].includes(t.key),i=w(this._getChildren().filter((t=>!d(t))),t.target,e,!0);i&&(i.focus({preventScroll:!0}),Je.getOrCreateInstance(i).show())}_getChildren(){return U.find(Ge,this._parent)}_getActiveElem(){return this._getChildren().find((t=>this._elemIsActive(t)))||null}_setInitialAttributes(t,e){this._setAttributeIfNotExists(t,"role","tablist");for(const t of e)this._setInitialAttributesOnChild(t)}_setInitialAttributesOnChild(t){t=this._getInnerElement(t);const e=this._elemIsActive(t),i=this._getOuterElement(t);t.setAttribute("aria-selected",e),i!==t&&this._setAttributeIfNotExists(i,"role","presentation"),e||t.setAttribute("tabindex","-1"),this._setAttributeIfNotExists(t,"role","tab"),this._setInitialAttributesOnTargetPanel(t)}_setInitialAttributesOnTargetPanel(t){const e=r(t);e&&(this._setAttributeIfNotExists(e,"role","tabpanel"),t.id&&this._setAttributeIfNotExists(e,"aria-labelledby",`#${t.id}`))}_toggleDropDown(t,e){const i=this._getOuterElement(t);if(!i.classList.contains("dropdown"))return;const s=(t,s)=>{const n=U.findOne(t,i);n&&n.classList.toggle(s,e)};s(".dropdown-toggle",Qe),s(".dropdown-menu",Ye),i.setAttribute("aria-expanded",e)}_setAttributeIfNotExists(t,e,i){t.hasAttribute(e)||t.setAttribute(e,i)}_elemIsActive(t){return t.classList.contains(Qe)}_getInnerElement(t){return t.matches(Ge)?t:U.findOne(Ge,t)}_getOuterElement(t){return t.closest(".nav-item, .list-group-item")||t}static jQueryInterface(t){return this.each((function(){const e=Je.getOrCreateInstance(this);if("string"==typeof t){if(void 0===e[t]||t.startsWith("_")||"constructor"===t)throw new TypeError(`No method named "${t}"`);e[t]()}}))}}$.on(document,"click.bs.tab",Ue,(function(t){["A","AREA"].includes(this.tagName)&&t.preventDefault(),d(this)||Je.getOrCreateInstance(this).show()})),$.on(window,"load.bs.tab",(()=>{for(const t of U.find('.active[data-bs-toggle="tab"], .active[data-bs-toggle="pill"], .active[data-bs-toggle="list"]'))Je.getOrCreateInstance(t)})),b(Je);const Ze="hide",ti="show",ei="showing",ii={animation:"boolean",autohide:"boolean",delay:"number"},si={animation:!0,autohide:!0,delay:5e3};class ni extends V{constructor(t,e){super(t,e),this._timeout=null,this._hasMouseInteraction=!1,this._hasKeyboardInteraction=!1,this._setListeners()}static get Default(){return si}static get DefaultType(){return ii}static get NAME(){return"toast"}show(){$.trigger(this._element,"show.bs.toast").defaultPrevented||(this._clearTimeout(),this._config.animation&&this._element.classList.add("fade"),this._element.classList.remove(Ze),g(this._element),this._element.classList.add(ti,ei),this._queueCallback((()=>{this._element.classList.remove(ei),$.trigger(this._element,"shown.bs.toast"),this._maybeScheduleHide()}),this._element,this._config.animation))}hide(){this.isShown()&&($.trigger(this._element,"hide.bs.toast").defaultPrevented||(this._element.classList.add(ei),this._queueCallback((()=>{this._element.classList.add(Ze),this._element.classList.remove(ei,ti),$.trigger(this._element,"hidden.bs.toast")}),this._element,this._config.animation)))}dispose(){this._clearTimeout(),this.isShown()&&this._element.classList.remove(ti),super.dispose()}isShown(){return this._element.classList.contains(ti)}_maybeScheduleHide(){this._config.autohide&&(this._hasMouseInteraction||this._hasKeyboardInteraction||(this._timeout=setTimeout((()=>{this.hide()}),this._config.delay)))}_onInteraction(t,e){switch(t.type){case"mouseover":case"mouseout":this._hasMouseInteraction=e;break;case"focusin":case"focusout":this._hasKeyboardInteraction=e}if(e)return void this._clearTimeout();const i=t.relatedTarget;this._element===i||this._element.contains(i)||this._maybeScheduleHide()}_setListeners(){$.on(this._element,"mouseover.bs.toast",(t=>this._onInteraction(t,!0))),$.on(this._element,"mouseout.bs.toast",(t=>this._onInteraction(t,!1))),$.on(this._element,"focusin.bs.toast",(t=>this._onInteraction(t,!0))),$.on(this._element,"focusout.bs.toast",(t=>this._onInteraction(t,!1)))}_clearTimeout(){clearTimeout(this._timeout),this._timeout=null}static jQueryInterface(t){return this.each((function(){const e=ni.getOrCreateInstance(this,t);if("string"==typeof t){if(void 0===e[t])throw new TypeError(`No method named "${t}"`);e[t](this)}}))}}return K(ni),b(ni),{Alert:Q,Button:Y,Carousel:ht,Collapse:mt,Dropdown:Mt,Modal:ne,Offcanvas:_e,Popover:je,ScrollSpy:Be,Tab:Je,Toast:ni,Tooltip:Pe}}));
//# sourceMappingURL=bootstrap.min.js.map
// name: sammy
// version: 0.7.6

// Sammy.js / http://sammyjs.org

(function (factory) {
    // Support module loading scenarios
    if (typeof define === 'function' && define.amd) {
        // AMD Anonymous Module
        define(['jquery'], factory);
    } else {
        // No module loader (plain <script> tag) - put directly in global namespace
        jQuery.sammy = window.Sammy = factory(jQuery);
    }
})(function ($) {

    var Sammy,
        PATH_REPLACER = "([^\/]+)",
        PATH_NAME_MATCHER = /:([\w\d]+)/g,
        QUERY_STRING_MATCHER = /\?([^#]*)?$/,
        // mainly for making `arguments` an Array
        _makeArray = function (nonarray) { return Array.prototype.slice.call(nonarray); },
        // borrowed from jQuery
        _isFunction = function (obj) { return Object.prototype.toString.call(obj) === "[object Function]"; },
        _isArray = function (obj) { return Object.prototype.toString.call(obj) === "[object Array]"; },
        _isRegExp = function (obj) { return Object.prototype.toString.call(obj) === "[object RegExp]"; },
        _decode = function (str) { return decodeURIComponent((str || '').replace(/\+/g, ' ')); },
        _encode = encodeURIComponent,
        _escapeHTML = function (s) {
            return String(s).replace(/&(?!\w+;)/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
        },
        _routeWrapper = function (verb) {
            return function () {
                return this.route.apply(this, [verb].concat(Array.prototype.slice.call(arguments)));
            };
        },
        _template_cache = {},
        _has_history = !!(window.history && history.pushState),
        loggers = [];


    // `Sammy` (also aliased as $.sammy) is not only the namespace for a
    // number of prototypes, its also a top level method that allows for easy
    // creation/management of `Sammy.Application` instances. There are a
    // number of different forms for `Sammy()` but each returns an instance
    // of `Sammy.Application`. When a new instance is created using
    // `Sammy` it is added to an Object called `Sammy.apps`. This
    // provides for an easy way to get at existing Sammy applications. Only one
    // instance is allowed per `element_selector` so when calling
    // `Sammy('selector')` multiple times, the first time will create
    // the application and the following times will extend the application
    // already added to that selector.
    //
    // ### Example
    //
    //      // returns the app at #main or a new app
    //      Sammy('#main')
    //
    //      // equivalent to "new Sammy.Application", except appends to apps
    //      Sammy();
    //      Sammy(function() { ... });
    //
    //      // extends the app at '#main' with function.
    //      Sammy('#main', function() { ... });
    //
    Sammy = function (selector) {
        //var args = _makeArray(arguments),
        //    app, selector;
        Sammy.apps = Sammy.apps || {};
        //if (args.length === 0 || args[0] && _isFunction(args[0])) { // Sammy()
        //    return Sammy.apply(Sammy, ['body'].concat(args));
        //} else if (typeof (selector = args.shift()) == 'string')        { // Sammy('#main')
        if (selector) {
            app = Sammy.apps[selector] || new Sammy.Application();
            app.element_selector = selector;
            //if (args.length > 0) {
            //    $.each(args, function (i, plugin) {
            //        app.use(plugin);
            //    });
            //}
            // if the selector changes make sure the reference in Sammy.apps changes
            if (app.element_selector != selector) {
                delete Sammy.apps[selector];
            }
            Sammy.apps[app.element_selector] = app;
            return app;
        }
    };

    Sammy.VERSION = '0.7.6';

    // Add to the global logger pool. Takes a function that accepts an
    // unknown number of arguments and should print them or send them somewhere
    // The first argument is always a timestamp.
    Sammy.addLogger = function (logger) {
        loggers.push(logger);
    };

    // Sends a log message to each logger listed in the global
    // loggers pool. Can take any number of arguments.
    // Also prefixes the arguments with a timestamp.
    Sammy.log = function () {
        var args = _makeArray(arguments);
        args.unshift("[" + Date() + "]");
        $.each(loggers, function (i, logger) {
            logger.apply(Sammy, args);
        });
    };

    if (typeof window.console != 'undefined') {
        if (typeof window.console.log === 'function' && _isFunction(window.console.log.apply)) {
            Sammy.addLogger(function () {
                window.console.log.apply(window.console, arguments);
            });
        } else {
            Sammy.addLogger(function () {
                window.console.log(arguments);
            });
        }
    } else if (typeof console != 'undefined') {
        Sammy.addLogger(function () {
            console.log.apply(console, arguments);
        });
    }

    $.extend(Sammy, {
        makeArray: _makeArray,
        isFunction: _isFunction,
        isArray: _isArray
    });

    // Sammy.Object is the base for all other Sammy classes. It provides some useful
    // functionality, including cloning, iterating, etc.
    Sammy.Object = function (obj) { // constructor
        return $.extend(this, obj || {});
    };

    $.extend(Sammy.Object.prototype, {

        // Escape HTML in string, use in templates to prevent script injection.
        // Also aliased as `h()`
        escapeHTML: _escapeHTML,
        h: _escapeHTML,

        // Returns a copy of the object with Functions removed.
        toHash: function () {
            var json = {};
            $.each(this, function (k, v) {
                if (!_isFunction(v)) {
                    json[k] = v;
                }
            });
            return json;
        },

        // Renders a simple HTML version of this Objects attributes.
        // Does not render functions.
        // For example. Given this Sammy.Object:
        //
        //     var s = new Sammy.Object({first_name: 'Sammy', last_name: 'Davis Jr.'});
        //     s.toHTML()
        //     //=> '<strong>first_name</strong> Sammy<br /><strong>last_name</strong> Davis Jr.<br />'
        //
        toHTML: function () {
            var display = "";
            $.each(this, function (k, v) {
                if (!_isFunction(v)) {
                    display += "<strong>" + k + "</strong> " + v + "<br />";
                }
            });
            return display;
        },

        // Returns an array of keys for this object. If `attributes_only`
        // is true will not return keys that map to a `function()`
        keys: function (attributes_only) {
            var keys = [];
            for (var property in this) {
                if (!_isFunction(this[property]) || !attributes_only) {
                    keys.push(property);
                }
            }
            return keys;
        },

        // Checks if the object has a value at `key` and that the value is not empty
        has: function (key) {
            return this[key] && $.trim(this[key].toString()) !== '';
        },

        // convenience method to join as many arguments as you want
        // by the first argument - useful for making paths
        join: function () {
            var args = _makeArray(arguments);
            var delimiter = args.shift();
            return args.join(delimiter);
        },

        // Shortcut to Sammy.log
        log: function () {
            Sammy.log.apply(Sammy, arguments);
        },

        // Returns a string representation of this object.
        // if `include_functions` is true, it will also toString() the
        // methods of this object. By default only prints the attributes.
        toString: function (include_functions) {
            var s = [];
            $.each(this, function (k, v) {
                if (!_isFunction(v) || include_functions) {
                    s.push('"' + k + '": ' + v.toString());
                }
            });
            return "Sammy.Object: {" + s.join(',') + "}";
        }
    });


    // Return whether the event targets this window.
    Sammy.targetIsThisWindow = function targetIsThisWindow(event, tagName) {
        var targetElement = $(event.target).closest(tagName);
        if (targetElement.length === 0) { return true; }

        var targetWindow = targetElement.attr('target');
        if (!targetWindow || targetWindow === window.name || targetWindow === '_self') { return true; }
        if (targetWindow === '_blank') { return false; }
        if (targetWindow === 'top' && window === window.top) { return true; }
        return false;
    };


    // The DefaultLocationProxy is the default location proxy for all Sammy applications.
    // A location proxy is a prototype that conforms to a simple interface. The purpose
    // of a location proxy is to notify the Sammy.Application its bound to when the location
    // or 'external state' changes.
    //
    // The `DefaultLocationProxy` watches for changes to the path of the current window and
    // is also able to set the path based on changes in the application. It does this by
    // using different methods depending on what is available in the current browser. In
    // the latest and greatest browsers it used the HTML5 History API and the `pushState`
    // `popState` events/methods. This allows you to use Sammy to serve a site behind normal
    // URI paths as opposed to the older default of hash (#) based routing. Because the server
    // can interpret the changed path on a refresh or re-entry, though, it requires additional
    // support on the server side. If you'd like to force disable HTML5 history support, please
    // use the `disable_push_state` setting on `Sammy.Application`. If pushState support
    // is enabled, `DefaultLocationProxy` also binds to all links on the page. If a link is clicked
    // that matches the current set of routes, the URL is changed using pushState instead of
    // fully setting the location and the app is notified of the change.
    //
    // If the browser does not have support for HTML5 History, `DefaultLocationProxy` automatically
    // falls back to the older hash based routing. The newest browsers (IE, Safari > 4, FF >= 3.6)
    // support a 'onhashchange' DOM event, thats fired whenever the location.hash changes.
    // In this situation the DefaultLocationProxy just binds to this event and delegates it to
    // the application. In the case of older browsers a poller is set up to track changes to the
    // hash.
    Sammy.DefaultLocationProxy = function (app, run_interval_every) {
        this.app = app;
        // set is native to false and start the poller immediately
        this.is_native = false;
        this.has_history = _has_history;
        this._startPolling(run_interval_every);
    };

    Sammy.DefaultLocationProxy.fullPath = function (location_obj) {
        // Bypass the `window.location.hash` attribute.  If a question mark
        // appears in the hash IE6 will strip it and all of the following
        // characters from `window.location.hash`.
        var matches = location_obj.toString().match(/^[^#]*(#.+)$/);
        var hash = matches ? matches[1] : '';
        return [location_obj.pathname, location_obj.search, hash].join('');
    };
    $.extend(Sammy.DefaultLocationProxy.prototype, {
        // bind the proxy events to the current app.
        bind: function () {
            var proxy = this, app = this.app, lp = Sammy.DefaultLocationProxy;
            $(window).bind('hashchange.' + this.app.eventNamespace(), function (e, non_native) {
                // if we receive a native hash change event, set the proxy accordingly
                // and stop polling
                if (proxy.is_native === false && !non_native) {
                    proxy.is_native = true;
                    window.clearInterval(lp._interval);
                    lp._interval = null;
                }
                app.trigger('location-changed');
            });
            if (_has_history && !app.disable_push_state) {
                // bind to popstate
                $(window).bind('popstate.' + this.app.eventNamespace(), function (e) {
                    app.trigger('location-changed');
                });
                // bind to link clicks that have routes
                $(document).delegate('a', 'click.history-' + this.app.eventNamespace(), function (e) {
                    if (e.isDefaultPrevented() || e.metaKey || e.ctrlKey) {
                        return;
                    }
                    var full_path = lp.fullPath(this),
                        // Get anchor's host name in a cross browser compatible way.
                        // IE looses hostname property when setting href in JS
                        // with a relative URL, e.g. a.setAttribute('href',"/whatever").
                        // Circumvent this problem by creating a new link with given URL and
                        // querying that for a hostname.
                        hostname = this.hostname ? this.hostname : function (a) {
                            var l = document.createElement("a");
                            l.href = a.href;
                            return l.hostname;
                        }(this);

                    if (hostname == window.location.hostname &&
                        app.lookupRoute('get', full_path) &&
                        Sammy.targetIsThisWindow(e, 'a')) {
                        e.preventDefault();
                        proxy.setLocation(full_path);
                        return false;
                    }
                });
            }
            if (!lp._bindings) {
                lp._bindings = 0;
            }
            lp._bindings++;
        },

        // unbind the proxy events from the current app
        unbind: function () {
            $(window).unbind('hashchange.' + this.app.eventNamespace());
            $(window).unbind('popstate.' + this.app.eventNamespace());
            $(document).undelegate('a', 'click.history-' + this.app.eventNamespace());
            Sammy.DefaultLocationProxy._bindings--;
            if (Sammy.DefaultLocationProxy._bindings <= 0) {
                window.clearInterval(Sammy.DefaultLocationProxy._interval);
                Sammy.DefaultLocationProxy._interval = null;
            }
        },

        // get the current location from the hash.
        getLocation: function () {
            return Sammy.DefaultLocationProxy.fullPath(window.location);
        },

        // set the current location to `new_location`
        setLocation: function (new_location) {
            if (/^([^#\/]|$)/.test(new_location)) { // non-prefixed url
                if (_has_history && !this.app.disable_push_state) {
                    new_location = '/' + new_location;
                } else {
                    new_location = '#!/' + new_location;
                }
            }
            if (new_location != this.getLocation()) {
                // HTML5 History exists and new_location is a full path
                if (_has_history && !this.app.disable_push_state && /^\//.test(new_location)) {
                    history.pushState({ path: new_location }, window.title, new_location);
                    this.app.trigger('location-changed');
                } else {
                    return (window.location = new_location);
                }
            }
        },

        _startPolling: function (every) {
            // set up interval
            var proxy = this;
            if (!Sammy.DefaultLocationProxy._interval) {
                if (!every) { every = 10; }
                var hashCheck = function () {
                    var current_location = proxy.getLocation();
                    if (typeof Sammy.DefaultLocationProxy._last_location == 'undefined' ||
                        current_location != Sammy.DefaultLocationProxy._last_location) {
                        window.setTimeout(function () {
                            $(window).trigger('hashchange', [true]);
                        }, 0);
                    }
                    Sammy.DefaultLocationProxy._last_location = current_location;
                };
                hashCheck();
                Sammy.DefaultLocationProxy._interval = window.setInterval(hashCheck, every);
            }
        }
    });


    // Sammy.Application is the Base prototype for defining 'applications'.
    // An 'application' is a collection of 'routes' and bound events that is
    // attached to an element when `run()` is called.
    // The only argument an 'app_function' is evaluated within the context of the application.
    Sammy.Application = function (app_function) {
        var app = this;
        this.routes = {};
        this.listeners = new Sammy.Object({});
        this.arounds = [];
        this.befores = [];
        // generate a unique namespace
        this.namespace = (new Date()).getTime() + '-' + parseInt(Math.random() * 1000, 10);
        this.context_prototype = function () { Sammy.EventContext.apply(this, arguments); };
        this.context_prototype.prototype = new Sammy.EventContext();

        if (_isFunction(app_function)) {
            app_function.apply(this, [this]);
        }
        // set the location proxy if not defined to the default (DefaultLocationProxy)
        if (!this._location_proxy) {
            this.setLocationProxy(new Sammy.DefaultLocationProxy(this, this.run_interval_every));
        }
        if (this.debug) {
            this.bindToAllEvents(function (e, data) {
                app.log(app.toString(), e.cleaned_type, data || {});
            });
        }
    };

    Sammy.Application.prototype = $.extend({}, Sammy.Object.prototype, {

        // the four route verbs
        ROUTE_VERBS: ['get', 'post', 'put', 'delete'],

        // An array of the default events triggered by the
        // application during its lifecycle
        APP_EVENTS: ['run', 'unload', 'lookup-route', 'run-route', 'route-found', 'event-context-before', 'event-context-after', 'changed', 'error', 'check-form-submission', 'redirect', 'location-changed'],

        _last_route: null,
        _location_proxy: null,
        _running: false,

        // Defines what element the application is bound to. Provide a selector
        // (parseable by `jQuery()`) and this will be used by `$element()`
        element_selector: 'body',

        // When set to true, logs all of the default events using `log()`
        debug: false,

        // When set to true, and the error() handler is not overridden, will actually
        // raise JS errors in routes (500) and when routes can't be found (404)
        raise_errors: false,

        // The time in milliseconds that the URL is queried for changes
        run_interval_every: 50,

        // if using the `DefaultLocationProxy` setting this to true will force the app to use
        // traditional hash based routing as opposed to the new HTML5 PushState support
        disable_push_state: false,

        // The default template engine to use when using `partial()` in an
        // `EventContext`. `template_engine` can either be a string that
        // corresponds to the name of a method/helper on EventContext or it can be a function
        // that takes two arguments, the content of the unrendered partial and an optional
        // JS object that contains interpolation data. Template engine is only called/referred
        // to if the extension of the partial is null or unknown. See `partial()`
        // for more information
        template_engine: null,

        // //=> Sammy.Application: body
        toString: function () {
            return 'Sammy.Application:' + this.element_selector;
        },

        // returns a jQuery object of the Applications bound element.
        $element: function (selector) {
            return selector ? $(this.element_selector).find(selector) : $(this.element_selector);
        },

        // `use()` is the entry point for including Sammy plugins.
        // The first argument to use should be a function() that is evaluated
        // in the context of the current application, just like the `app_function`
        // argument to the `Sammy.Application` constructor.
        //
        // Any additional arguments are passed to the app function sequentially.
        //
        // For much more detail about plugins, check out:
        // [http://sammyjs.org/docs/plugins](http://sammyjs.org/docs/plugins)
        //
        // ### Example
        //
        //      var MyPlugin = function(app, prepend) {
        //
        //        this.helpers({
        //          myhelper: function(text) {
        //            alert(prepend + " " + text);
        //          }
        //        });
        //
        //      };
        //
        //      var app = $.sammy(function() {
        //
        //        this.use(MyPlugin, 'This is my plugin');
        //
        //        this.get('#/', function() {
        //          this.myhelper('and dont you forget it!');
        //          //=> Alerts: This is my plugin and dont you forget it!
        //        });
        //
        //      });
        //
        // If plugin is passed as a string it assumes your are trying to load
        // Sammy."Plugin". This is the preferred way of loading core Sammy plugins
        // as it allows for better error-messaging.
        //
        // ### Example
        //
        //      $.sammy(function() {
        //        this.use('Mustache'); //=> Sammy.Mustache
        //        this.use('Storage'); //=> Sammy.Storage
        //      });
        //
        use: function () {
            // flatten the arguments
            var args = _makeArray(arguments),
                plugin = args.shift(),
                plugin_name = plugin || '';
            try {
                args.unshift(this);
                if (typeof plugin == 'string') {
                    plugin_name = 'Sammy.' + plugin;
                    plugin = Sammy[plugin];
                }
                plugin.apply(this, args);
            } catch (e) {
                if (typeof plugin === 'undefined') {
                    this.error("Plugin Error: called use() but plugin (" + plugin_name.toString() + ") is not defined", e);
                } else if (!_isFunction(plugin)) {
                    this.error("Plugin Error: called use() but '" + plugin_name.toString() + "' is not a function", e);
                } else {
                    this.error("Plugin Error", e);
                }
            }
            return this;
        },

        // Sets the location proxy for the current app. By default this is set to
        // a new `Sammy.DefaultLocationProxy` on initialization. However, you can set
        // the location_proxy inside you're app function to give your app a custom
        // location mechanism. See `Sammy.DefaultLocationProxy` and `Sammy.DataLocationProxy`
        // for examples.
        //
        // `setLocationProxy()` takes an initialized location proxy.
        //
        // ### Example
        //
        //        // to bind to data instead of the default hash;
        //        var app = $.sammy(function() {
        //          this.setLocationProxy(new Sammy.DataLocationProxy(this));
        //        });
        //
        setLocationProxy: function (new_proxy) {
            var original_proxy = this._location_proxy;
            this._location_proxy = new_proxy;
            if (this.isRunning()) {
                if (original_proxy) {
                    // if there is already a location proxy, unbind it.
                    original_proxy.unbind();
                }
                this._location_proxy.bind();
            }
        },

        // provide log() override for inside an app that includes the relevant application element_selector
        log: function () {
            Sammy.log.apply(Sammy, Array.prototype.concat.apply([this.element_selector], arguments));
        },


        // `route()` is the main method for defining routes within an application.
        // For great detail on routes, check out:
        // [http://sammyjs.org/docs/routes](http://sammyjs.org/docs/routes)
        //
        // This method also has aliases for each of the different verbs (eg. `get()`, `post()`, etc.)
        //
        // ### Arguments
        //
        // * `verb` A String in the set of ROUTE_VERBS or 'any'. 'any' will add routes for each
        //    of the ROUTE_VERBS. If only two arguments are passed,
        //    the first argument is the path, the second is the callback and the verb
        //    is assumed to be 'any'.
        // * `path` A Regexp or a String representing the path to match to invoke this verb.
        // * `callback` A Function that is called/evaluated when the route is run see: `runRoute()`.
        //    It is also possible to pass a string as the callback, which is looked up as the name
        //    of a method on the application.
        //
        route: function (verb, path) {
            var app = this, param_names = [], add_route, path_match, callback = Array.prototype.slice.call(arguments, 2);

            // if the method signature is just (path, callback)
            // assume the verb is 'any'
            if (callback.length === 0 && _isFunction(path)) {
                callback = [path];
                path = verb;
                verb = 'any';
            }

            verb = verb.toLowerCase(); // ensure verb is lower case

            // if path is a string turn it into a regex
            if (path.constructor == String) {

                // Needs to be explicitly set because IE will maintain the index unless NULL is returned,
                // which means that with two consecutive routes that contain params, the second set of params will not be found and end up in splat instead of params
                // https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/RegExp/lastIndex
                PATH_NAME_MATCHER.lastIndex = 0;

                // find the names
                while ((path_match = PATH_NAME_MATCHER.exec(path)) !== null) {
                    param_names.push(path_match[1]);
                }
                // replace with the path replacement
                path = new RegExp(path.replace(PATH_NAME_MATCHER, PATH_REPLACER) + "$");
            }
            // lookup callbacks
            $.each(callback, function (i, cb) {
                if (typeof (cb) === 'string') {
                    callback[i] = app[cb];
                }
            });

            add_route = function (with_verb) {
                var r = { verb: with_verb, path: path, callback: callback, param_names: param_names };
                // add route to routes array
                app.routes[with_verb] = app.routes[with_verb] || [];
                // place routes in order of definition
                app.routes[with_verb].push(r);
            };

            if (verb === 'any') {
                $.each(this.ROUTE_VERBS, function (i, v) { add_route(v); });
            } else {
                add_route(verb);
            }

            // return the app
            return this;
        },

        // Alias for route('get', ...)
        get: _routeWrapper('get'),

        // Alias for route('post', ...)
        post: _routeWrapper('post'),

        // Alias for route('put', ...)
        put: _routeWrapper('put'),

        // Alias for route('delete', ...)
        del: _routeWrapper('delete'),

        // Alias for route('any', ...)
        any: _routeWrapper('any'),

        // `mapRoutes` takes an array of arrays, each array being passed to route()
        // as arguments, this allows for mass definition of routes. Another benefit is
        // this makes it possible/easier to load routes via remote JSON.
        //
        // ### Example
        //
        //      var app = $.sammy(function() {
        //
        //        this.mapRoutes([
        //            ['get', '#/', function() { this.log('index'); }],
        //            // strings in callbacks are looked up as methods on the app
        //            ['post', '#/create', 'addUser'],
        //            // No verb assumes 'any' as the verb
        //            [/dowhatever/, function() { this.log(this.verb, this.path)}];
        //          ]);
        //      });
        //
        mapRoutes: function (route_array) {
            var app = this;
            $.each(route_array, function (i, route_args) {
                app.route.apply(app, route_args);
            });
            return this;
        },

        // A unique event namespace defined per application.
        // All events bound with `bind()` are automatically bound within this space.
        eventNamespace: function () {
            return ['sammy-app', this.namespace].join('-');
        },

        // Works just like `jQuery.fn.bind()` with a couple notable differences.
        //
        // * It binds all events to the application element
        // * All events are bound within the `eventNamespace()`
        // * Events are not actually bound until the application is started with `run()`
        // * callbacks are evaluated within the context of a Sammy.EventContext
        //
        bind: function (name, data, callback) {
            var app = this;
            // build the callback
            // if the arity is 2, callback is the second argument
            if (typeof callback == 'undefined') { callback = data; }
            var listener_callback = function () {
                // pull off the context from the arguments to the callback
                var e, context, data;
                e = arguments[0];
                data = arguments[1];
                if (data && data.context) {
                    context = data.context;
                    delete data.context;
                } else {
                    context = new app.context_prototype(app, 'bind', e.type, data, e.target);
                }
                e.cleaned_type = e.type.replace(app.eventNamespace(), '');
                callback.apply(context, [e, data]);
            };

            // it could be that the app element doesnt exist yet
            // so attach to the listeners array and then run()
            // will actually bind the event.
            if (!this.listeners[name]) { this.listeners[name] = []; }
            this.listeners[name].push(listener_callback);
            if (this.isRunning()) {
                // if the app is running
                // *actually* bind the event to the app element
                this._listen(name, listener_callback);
            }
            return this;
        },

        // Triggers custom events defined with `bind()`
        //
        // ### Arguments
        //
        // * `name` The name of the event. Automatically prefixed with the `eventNamespace()`
        // * `data` An optional Object that can be passed to the bound callback.
        // * `context` An optional context/Object in which to execute the bound callback.
        //   If no context is supplied a the context is a new `Sammy.EventContext`
        //
        trigger: function (name, data) {
            this.$element().trigger([name, this.eventNamespace()].join('.'), [data]);
            return this;
        },

        // Reruns the current route
        refresh: function () {
            this.last_location = null;
            this.trigger('location-changed');
            return this;
        },

        // Takes a single callback that is pushed on to a stack.
        // Before any route is run, the callbacks are evaluated in order within
        // the current `Sammy.EventContext`
        //
        // If any of the callbacks explicitly return false, execution of any
        // further callbacks and the route itself is halted.
        //
        // You can also provide a set of options that will define when to run this
        // before based on the route it proceeds.
        //
        // ### Example
        //
        //      var app = $.sammy(function() {
        //
        //        // will run at #/route but not at #/
        //        this.before('#/route', function() {
        //          //...
        //        });
        //
        //        // will run at #/ but not at #/route
        //        this.before({except: {path: '#/route'}}, function() {
        //          this.log('not before #/route');
        //        });
        //
        //        this.get('#/', function() {});
        //
        //        this.get('#/route', function() {});
        //
        //      });
        //
        // See `contextMatchesOptions()` for a full list of supported options
        //
        before: function (options, callback) {
            if (_isFunction(options)) {
                callback = options;
                options = {};
            }
            this.befores.push([options, callback]);
            return this;
        },

        // A shortcut for binding a callback to be run after a route is executed.
        // After callbacks have no guarunteed order.
        after: function (callback) {
            return this.bind('event-context-after', callback);
        },


        // Adds an around filter to the application. around filters are functions
        // that take a single argument `callback` which is the entire route
        // execution path wrapped up in a closure. This means you can decide whether
        // or not to proceed with execution by not invoking `callback` or,
        // more usefully wrapping callback inside the result of an asynchronous execution.
        //
        // ### Example
        //
        // The most common use case for around() is calling a _possibly_ async function
        // and executing the route within the functions callback:
        //
        //      var app = $.sammy(function() {
        //
        //        var current_user = false;
        //
        //        function checkLoggedIn(callback) {
        //          // /session returns a JSON representation of the logged in user
        //          // or an empty object
        //          if (!current_user) {
        //            $.getJSON('/session', function(json) {
        //              if (json.login) {
        //                // show the user as logged in
        //                current_user = json;
        //                // execute the route path
        //                callback();
        //              } else {
        //                // show the user as not logged in
        //                current_user = false;
        //                // the context of aroundFilters is an EventContext
        //                this.redirect('#/login');
        //              }
        //            });
        //          } else {
        //            // execute the route path
        //            callback();
        //          }
        //        };
        //
        //        this.around(checkLoggedIn);
        //
        //      });
        //
        around: function (callback) {
            this.arounds.push(callback);
            return this;
        },

        // Adds a onComplete function to the application. onComplete functions are executed
        // at the end of a chain of route callbacks, if they call next(). Unlike after,
        // which is called as soon as the route is complete, onComplete is like a final next()
        // for all routes, and is thus run asynchronously
        //
        // ### Example
        //
        //      app.get('/chain',function(context,next) {
        //          console.log('chain1');
        //          next();
        //      },function(context,next) {
        //          console.log('chain2');
        //          next();
        //      });
        //
        //      app.get('/link',function(context,next) {
        //          console.log('link1');
        //          next();
        //      },function(context,next) {
        //          console.log('link2');
        //          next();
        //      });
        //
        //      app.onComplete(function() {
        //          console.log("Running finally");
        //      });
        //
        // If you go to '/chain', you will get the following messages:
        //
        //      chain1
        //      chain2
        //      Running onComplete
        //
        //
        // If you go to /link, you will get the following messages:
        //
        //      link1
        //      link2
        //      Running onComplete
        //
        //
        // It really comes to play when doing asynchronous:
        //
        //      app.get('/chain',function(context,next) {
        //        $.get('/my/url',function() {
        //          console.log('chain1');
        //          next();
        //        });
        //      },function(context,next) {
        //        console.log('chain2');
        //        next();
        //      });
        //
        onComplete: function (callback) {
            this._onComplete = callback;
            return this;
        },

        // Returns `true` if the current application is running.
        isRunning: function () {
            return this._running;
        },

        // Helpers extends the EventContext prototype specific to this app.
        // This allows you to define app specific helper functions that can be used
        // whenever you're inside of an event context (templates, routes, bind).
        //
        // ### Example
        //
        //     var app = $.sammy(function() {
        //
        //       helpers({
        //         upcase: function(text) {
        //          return text.toString().toUpperCase();
        //         }
        //       });
        //
        //       get('#/', function() { with(this) {
        //         // inside of this context I can use the helpers
        //         $('#main').html(upcase($('#main').text());
        //       }});
        //
        //     });
        //
        //
        // ### Arguments
        //
        // * `extensions` An object collection of functions to extend the context.
        //
        helpers: function (extensions) {
            $.extend(this.context_prototype.prototype, extensions);
            return this;
        },

        // Helper extends the event context just like `helpers()` but does it
        // a single method at a time. This is especially useful for dynamically named
        // helpers
        //
        // ### Example
        //
        //     // Trivial example that adds 3 helper methods to the context dynamically
        //     var app = $.sammy(function(app) {
        //
        //       $.each([1,2,3], function(i, num) {
        //         app.helper('helper' + num, function() {
        //           this.log("I'm helper number " + num);
        //         });
        //       });
        //
        //       this.get('#/', function() {
        //         this.helper2(); //=> I'm helper number 2
        //       });
        //     });
        //
        // ### Arguments
        //
        // * `name` The name of the method
        // * `method` The function to be added to the prototype at `name`
        //
        helper: function (name, method) {
            this.context_prototype.prototype[name] = method;
            return this;
        },

        // Actually starts the application's lifecycle. `run()` should be invoked
        // within a document.ready block to ensure the DOM exists before binding events, etc.
        //
        // ### Example
        //
        //     var app = $.sammy(function() { ... }); // your application
        //     $(function() { // document.ready
        //        app.run();
        //     });
        //
        // ### Arguments
        //
        // * `start_url` Optionally, a String can be passed which the App will redirect to
        //   after the events/routes have been bound.
        run: function (start_url) {
            if (this.isRunning()) { return false; }
            var app = this;

            // actually bind all the listeners
            $.each(this.listeners.toHash(), function (name, callbacks) {
                $.each(callbacks, function (i, listener_callback) {
                    app._listen(name, listener_callback);
                });
            });

            this.trigger('run', { start_url: start_url });
            this._running = true;
            // set last location
            this.last_location = null;
            if (!(/\#(.+)/.test(this.getLocation())) && typeof start_url != 'undefined') {
                this.setLocation(start_url);
            }
            // check url
            this._checkLocation();
            this._location_proxy.bind();
            this.bind('location-changed', function () {
                app._checkLocation();
            });

            // bind to submit to capture post/put/delete routes
            this.bind('submit', function (e) {
                if (!Sammy.targetIsThisWindow(e, 'form')) { return true; }
                var returned = app._checkFormSubmission($(e.target).closest('form'));
                return (returned === false) ? e.preventDefault() : false;
            });

            // bind unload to body unload
            $(window).bind('unload', function () {
                app.unload();
            });

            // trigger html changed
            return this.trigger('changed');
        },

        // The opposite of `run()`, un-binds all event listeners and intervals
        // `run()` Automatically binds a `onunload` event to run this when
        // the document is closed.
        unload: function () {
            if (!this.isRunning()) { return false; }
            var app = this;
            this.trigger('unload');
            // clear interval
            this._location_proxy.unbind();
            // unbind form submits
            this.$element().unbind('submit').removeClass(app.eventNamespace());
            // unbind all events
            $.each(this.listeners.toHash(), function (name, listeners) {
                $.each(listeners, function (i, listener_callback) {
                    app._unlisten(name, listener_callback);
                });
            });
            this._running = false;
            return this;
        },

        // Not only runs `unbind` but also destroys the app reference.
        destroy: function () {
            this.unload();
            delete Sammy.apps[this.element_selector];
            return this;
        },

        // Will bind a single callback function to every event that is already
        // being listened to in the app. This includes all the `APP_EVENTS`
        // as well as any custom events defined with `bind()`.
        //
        // Used internally for debug logging.
        bindToAllEvents: function (callback) {
            var app = this;
            // bind to the APP_EVENTS first
            $.each(this.APP_EVENTS, function (i, e) {
                app.bind(e, callback);
            });
            // next, bind to listener names (only if they dont exist in APP_EVENTS)
            $.each(this.listeners.keys(true), function (i, name) {
                if ($.inArray(name, app.APP_EVENTS) == -1) {
                    app.bind(name, callback);
                }
            });
            return this;
        },

        // Returns a copy of the given path with any query string after the hash
        // removed.
        routablePath: function (path) {
            return path.replace(QUERY_STRING_MATCHER, '');
        },

        // Given a verb and a String path, will return either a route object or false
        // if a matching route can be found within the current defined set.
        lookupRoute: function (verb, path) {
            var app = this, routed = false, i = 0, l, route;
            if (typeof this.routes[verb] != 'undefined') {
                l = this.routes[verb].length;
                for (; i < l; i++) {
                    route = this.routes[verb][i];
                    if (app.routablePath(path).match(route.path)) {
                        routed = route;
                        break;
                    }
                }
            }
            return routed;
        },

        // First, invokes `lookupRoute()` and if a route is found, parses the
        // possible URL params and then invokes the route's callback within a new
        // `Sammy.EventContext`. If the route can not be found, it calls
        // `notFound()`. If `raise_errors` is set to `true` and
        // the `error()` has not been overridden, it will throw an actual JS
        // error.
        //
        // You probably will never have to call this directly.
        //
        // ### Arguments
        //
        // * `verb` A String for the verb.
        // * `path` A String path to lookup.
        // * `params` An Object of Params pulled from the URI or passed directly.
        //
        // ### Returns
        //
        // Either returns the value returned by the route callback or raises a 404 Not Found error.
        //
        runRoute: function (verb, path, params, target) {
            var app = this,
                route = this.lookupRoute(verb, path),
                context,
                wrapped_route,
                arounds,
                around,
                befores,
                before,
                callback_args,
                path_params,
                final_returned;

            if (this.debug) {
                this.log('runRoute', [verb, path].join(' '));
            }

            this.trigger('run-route', { verb: verb, path: path, params: params });
            if (typeof params == 'undefined') { params = {}; }

            $.extend(params, this._parseQueryString(path));

            if (route) {
                this.trigger('route-found', { route: route });
                // pull out the params from the path
                if ((path_params = route.path.exec(this.routablePath(path))) !== null) {
                    // first match is the full path
                    path_params.shift();
                    // for each of the matches
                    $.each(path_params, function (i, param) {
                        // if theres a matching param name
                        if (route.param_names[i]) {
                            // set the name to the match
                            params[route.param_names[i]] = _decode(param);
                        } else {
                            // initialize 'splat'
                            if (!params.splat) { params.splat = []; }
                            params.splat.push(_decode(param));
                        }
                    });
                }

                // set event context
                context = new this.context_prototype(this, verb, path, params, target);
                // ensure arrays
                arounds = this.arounds.slice(0);
                befores = this.befores.slice(0);
                // set the callback args to the context + contents of the splat
                callback_args = [context];
                if (params.splat) {
                    callback_args = callback_args.concat(params.splat);
                }
                // wrap the route up with the before filters
                wrapped_route = function () {
                    var returned, i, nextRoute;
                    while (befores.length > 0) {
                        before = befores.shift();
                        // check the options
                        if (app.contextMatchesOptions(context, before[0])) {
                            returned = before[1].apply(context, [context]);
                            if (returned === false) { return false; }
                        }
                    }
                    app.last_route = route;
                    context.trigger('event-context-before', { context: context });
                    // run multiple callbacks
                    if (typeof (route.callback) === "function") {
                        route.callback = [route.callback];
                    }
                    if (route.callback && route.callback.length) {
                        i = -1;
                        nextRoute = function () {
                            i++;
                            if (route.callback[i]) {
                                returned = route.callback[i].apply(context, callback_args);
                            } else if (app._onComplete && typeof (app._onComplete === "function")) {
                                app._onComplete(context);
                            }
                        };
                        callback_args.push(nextRoute);
                        nextRoute();
                    }
                    context.trigger('event-context-after', { context: context });
                    return returned;
                };
                $.each(arounds.reverse(), function (i, around) {
                    var last_wrapped_route = wrapped_route;
                    wrapped_route = function () { return around.apply(context, [last_wrapped_route]); };
                });
                try {
                    final_returned = wrapped_route();
                } catch (e) {
                    this.error(['500 Error', verb, path].join(' '), e);
                }
                return final_returned;
            } else {
                return this.notFound(verb, path);
            }
        },

        // Matches an object of options against an `EventContext` like object that
        // contains `path` and `verb` attributes. Internally Sammy uses this
        // for matching `before()` filters against specific options. You can set the
        // object to _only_ match certain paths or verbs, or match all paths or verbs _except_
        // those that match the options.
        //
        // ### Example
        //
        //     var app = $.sammy(),
        //         context = {verb: 'get', path: '#/mypath'};
        //
        //     // match against a path string
        //     app.contextMatchesOptions(context, '#/mypath'); //=> true
        //     app.contextMatchesOptions(context, '#/otherpath'); //=> false
        //     // equivalent to
        //     app.contextMatchesOptions(context, {only: {path:'#/mypath'}}); //=> true
        //     app.contextMatchesOptions(context, {only: {path:'#/otherpath'}}); //=> false
        //     // match against a path regexp
        //     app.contextMatchesOptions(context, /path/); //=> true
        //     app.contextMatchesOptions(context, /^path/); //=> false
        //     // match only a verb
        //     app.contextMatchesOptions(context, {only: {verb:'get'}}); //=> true
        //     app.contextMatchesOptions(context, {only: {verb:'post'}}); //=> false
        //     // match all except a verb
        //     app.contextMatchesOptions(context, {except: {verb:'post'}}); //=> true
        //     app.contextMatchesOptions(context, {except: {verb:'get'}}); //=> false
        //     // match all except a path
        //     app.contextMatchesOptions(context, {except: {path:'#/otherpath'}}); //=> true
        //     app.contextMatchesOptions(context, {except: {path:'#/mypath'}}); //=> false
        //     // match all except a verb and a path
        //     app.contextMatchesOptions(context, {except: {path:'#/otherpath', verb:'post'}}); //=> true
        //     app.contextMatchesOptions(context, {except: {path:'#/mypath', verb:'post'}}); //=> true
        //     app.contextMatchesOptions(context, {except: {path:'#/mypath', verb:'get'}}); //=> false
        //     // match multiple paths
        //     app.contextMatchesOptions(context, {path: ['#/mypath', '#/otherpath']}); //=> true
        //     app.contextMatchesOptions(context, {path: ['#/otherpath', '#/thirdpath']}); //=> false
        //     // equivalent to
        //     app.contextMatchesOptions(context, {only: {path: ['#/mypath', '#/otherpath']}}); //=> true
        //     app.contextMatchesOptions(context, {only: {path: ['#/otherpath', '#/thirdpath']}}); //=> false
        //     // match all except multiple paths
        //     app.contextMatchesOptions(context, {except: {path: ['#/mypath', '#/otherpath']}}); //=> false
        //     app.contextMatchesOptions(context, {except: {path: ['#/otherpath', '#/thirdpath']}}); //=> true
        //     // match all except multiple paths and verbs
        //     app.contextMatchesOptions(context, {except: {path: ['#/mypath', '#/otherpath'], verb: ['get', 'post']}}); //=> false
        //     app.contextMatchesOptions(context, {except: {path: ['#/otherpath', '#/thirdpath'], verb: ['get', 'post']}}); //=> true
        //
        contextMatchesOptions: function (context, match_options, positive) {
            var options = match_options;
            // normalize options
            if (typeof options === 'string' || _isRegExp(options)) {
                options = { path: options };
            }
            if (typeof positive === 'undefined') {
                positive = true;
            }
            // empty options always match
            if ($.isEmptyObject(options)) {
                return true;
            }
            // Do we have to match against multiple paths?
            if (_isArray(options.path)) {
                var results, numopt, opts, len;
                results = [];
                for (numopt = 0, len = options.path.length; numopt < len; numopt += 1) {
                    opts = $.extend({}, options, { path: options.path[numopt] });
                    results.push(this.contextMatchesOptions(context, opts));
                }
                var matched = $.inArray(true, results) > -1 ? true : false;
                return positive ? matched : !matched;
            }
            if (options.only) {
                return this.contextMatchesOptions(context, options.only, true);
            } else if (options.except) {
                return this.contextMatchesOptions(context, options.except, false);
            }
            var path_matched = true, verb_matched = true;
            if (options.path) {
                if (!_isRegExp(options.path)) {
                    options.path = new RegExp(options.path.toString() + '$');
                }
                path_matched = options.path.test(context.path);
            }
            if (options.verb) {
                if (typeof options.verb === 'string') {
                    verb_matched = options.verb === context.verb;
                } else {
                    verb_matched = options.verb.indexOf(context.verb) > -1;
                }
            }
            return positive ? (verb_matched && path_matched) : !(verb_matched && path_matched);
        },


        // Delegates to the `location_proxy` to get the current location.
        // See `Sammy.DefaultLocationProxy` for more info on location proxies.
        getLocation: function () {
            return this._location_proxy.getLocation();
        },

        // Delegates to the `location_proxy` to set the current location.
        // See `Sammy.DefaultLocationProxy` for more info on location proxies.
        //
        // ### Arguments
        //
        // * `new_location` A new location string (e.g. '#/')
        //
        setLocation: function (new_location) {
            return this._location_proxy.setLocation(new_location);
        },

        // Swaps the content of `$element()` with `content`
        // You can override this method to provide an alternate swap behavior
        // for `EventContext.partial()`.
        //
        // ### Example
        //
        //      var app = $.sammy(function() {
        //
        //        // implements a 'fade out'/'fade in'
        //        this.swap = function(content, callback) {
        //          var context = this;
        //          context.$element().fadeOut('slow', function() {
        //            context.$element().html(content);
        //            context.$element().fadeIn('slow', function() {
        //              if (callback) {
        //                callback.apply();
        //              }
        //            });
        //          });
        //        };
        //
        //      });
        //
        swap: function (content, callback) {
            var $el = this.$element().html(content);
            if (_isFunction(callback)) { callback(content); }
            return $el;
        },

        // a simple global cache for templates. Uses the same semantics as
        // `Sammy.Cache` and `Sammy.Storage` so can easily be replaced with
        // a persistent storage that lasts beyond the current request.
        templateCache: function (key, value) {
            if (typeof value != 'undefined') {
                return _template_cache[key] = value;
            } else {
                return _template_cache[key];
            }
        },

        // clear the templateCache
        clearTemplateCache: function () {
            return (_template_cache = {});
        },

        // This throws a '404 Not Found' error by invoking `error()`.
        // Override this method or `error()` to provide custom
        // 404 behavior (i.e redirecting to / or showing a warning)
        notFound: function (verb, path) {
            var ret = this.error(['404 Not Found', verb, path].join(' '));
            return (verb === 'get') ? ret : true;
        },

        // The base error handler takes a string `message` and an `Error`
        // object. If `raise_errors` is set to `true` on the app level,
        // this will re-throw the error to the browser. Otherwise it will send the error
        // to `log()`. Override this method to provide custom error handling
        // e.g logging to a server side component or displaying some feedback to the
        // user.
        error: function (message, original_error) {
            if (!original_error) { original_error = new Error(); }
            original_error.message = [message, original_error.message].join(' ');
            this.trigger('error', { message: original_error.message, error: original_error });
            if (this.raise_errors) {
                throw (original_error);
            } else {
                this.log(original_error.message, original_error);
            }
        },

        _checkLocation: function () {
            var location, returned;
            // get current location
            location = this.getLocation();
            // compare to see if hash has changed
            if (!this.last_location || this.last_location[0] != 'get' || this.last_location[1] != location) {
                // reset last location
                this.last_location = ['get', location];
                // lookup route for current hash
                returned = this.runRoute('get', location);
            }
            return returned;
        },

        _getFormVerb: function (form) {
            var $form = $(form), verb, $_method;
            $_method = $form.find('input[name="_method"]');
            if ($_method.length > 0) { verb = $_method.val(); }
            if (!verb) { verb = $form[0].getAttribute('method'); }
            if (!verb || verb === '') { verb = 'get'; }
            return $.trim(verb.toString().toLowerCase());
        },

        _checkFormSubmission: function (form) {
            var $form, path, verb, params, returned;
            this.trigger('check-form-submission', { form: form });
            $form = $(form);
            path = $form.attr('action') || '';
            verb = this._getFormVerb($form);

            if (this.debug) {
                this.log('_checkFormSubmission', $form, path, verb);
            }

            if (verb === 'get') {
                params = this._serializeFormParams($form);
                if (params !== '') { path += '?' + params; }
                this.setLocation(path);
                returned = false;
            } else {
                params = $.extend({}, this._parseFormParams($form));
                returned = this.runRoute(verb, path, params, form.get(0));
            }
            return (typeof returned == 'undefined') ? false : returned;
        },

        _serializeFormParams: function ($form) {
            var queryString = "",
                fields = $form.serializeArray(),
                i;
            if (fields.length > 0) {
                queryString = this._encodeFormPair(fields[0].name, fields[0].value);
                for (i = 1; i < fields.length; i++) {
                    queryString = queryString + "&" + this._encodeFormPair(fields[i].name, fields[i].value);
                }
            }
            return queryString;
        },

        _encodeFormPair: function (name, value) {
            return _encode(name) + "=" + _encode(value);
        },

        _parseFormParams: function ($form) {
            var params = {},
                form_fields = $form.serializeArray(),
                i;
            for (i = 0; i < form_fields.length; i++) {
                params = this._parseParamPair(params, form_fields[i].name, form_fields[i].value);
            }
            return params;
        },

        _parseQueryString: function (path) {
            var params = {}, parts, pairs, pair, i;

            parts = path.match(QUERY_STRING_MATCHER);
            if (parts && parts[1]) {
                pairs = parts[1].split('&');
                for (i = 0; i < pairs.length; i++) {
                    pair = pairs[i].split('=');
                    params = this._parseParamPair(params, _decode(pair[0]), _decode(pair[1] || ""));
                }
            }
            return params;
        },

        _parseParamPair: function (params, key, value) {
            if (typeof params[key] !== 'undefined') {
                if (_isArray(params[key])) {
                    params[key].push(value);
                } else {
                    params[key] = [params[key], value];
                }
            } else {
                params[key] = value;
            }
            return params;
        },

        _listen: function (name, callback) {
            return this.$element().bind([name, this.eventNamespace()].join('.'), callback);
        },

        _unlisten: function (name, callback) {
            return this.$element().unbind([name, this.eventNamespace()].join('.'), callback);
        }

    });

    // `Sammy.RenderContext` is an object that makes sequential template loading,
    // rendering and interpolation seamless even when dealing with asynchronous
    // operations.
    //
    // `RenderContext` objects are not usually created directly, rather they are
    // instantiated from an `Sammy.EventContext` by using `render()`, `load()` or
    // `partial()` which all return `RenderContext` objects.
    //
    // `RenderContext` methods always returns a modified `RenderContext`
    // for chaining (like jQuery itself).
    //
    // The core magic is in the `then()` method which puts the callback passed as
    // an argument into a queue to be executed once the previous callback is complete.
    // All the methods of `RenderContext` are wrapped in `then()` which allows you
    // to queue up methods by chaining, but maintaining a guaranteed execution order
    // even with remote calls to fetch templates.
    //
    Sammy.RenderContext = function (event_context) {
        this.event_context = event_context;
        this.callbacks = [];
        this.previous_content = null;
        this.content = null;
        this.next_engine = false;
        this.waiting = false;
    };

    Sammy.RenderContext.prototype = $.extend({}, Sammy.Object.prototype, {

        // The "core" of the `RenderContext` object, adds the `callback` to the
        // queue. If the context is `waiting` (meaning an async operation is happening)
        // then the callback will be executed in order, once the other operations are
        // complete. If there is no currently executing operation, the `callback`
        // is executed immediately.
        //
        // The value returned from the callback is stored in `content` for the
        // subsequent operation. If you return `false`, the queue will pause, and
        // the next callback in the queue will not be executed until `next()` is
        // called. This allows for the guaranteed order of execution while working
        // with async operations.
        //
        // If then() is passed a string instead of a function, the string is looked
        // up as a helper method on the event context.
        //
        // ### Example
        //
        //      this.get('#/', function() {
        //        // initialize the RenderContext
        //        // Even though `load()` executes async, the next `then()`
        //        // wont execute until the load finishes
        //        this.load('myfile.txt')
        //            .then(function(content) {
        //              // the first argument to then is the content of the
        //              // prev operation
        //              $('#main').html(content);
        //            });
        //      });
        //
        then: function (callback) {
            if (!_isFunction(callback)) {
                // if a string is passed to then, assume we want to call
                // a helper on the event context in its context
                if (typeof callback === 'string' && callback in this.event_context) {
                    var helper = this.event_context[callback];
                    callback = function (content) {
                        return helper.apply(this.event_context, [content]);
                    };
                } else {
                    return this;
                }
            }
            var context = this;
            if (this.waiting) {
                this.callbacks.push(callback);
            } else {
                this.wait();
                window.setTimeout(function () {
                    var returned = callback.apply(context, [context.content, context.previous_content]);
                    if (returned !== false) {
                        context.next(returned);
                    }
                }, 0);
            }
            return this;
        },

        // Pause the `RenderContext` queue. Combined with `next()` allows for async
        // operations.
        //
        // ### Example
        //
        //        this.get('#/', function() {
        //          this.load('mytext.json')
        //              .then(function(content) {
        //                var context = this,
        //                    data    = JSON.parse(content);
        //                // pause execution
        //                context.wait();
        //                // post to a url
        //                $.post(data.url, {}, function(response) {
        //                  context.next(JSON.parse(response));
        //                });
        //              })
        //              .then(function(data) {
        //                // data is json from the previous post
        //                $('#message').text(data.status);
        //              });
        //        });
        wait: function () {
            this.waiting = true;
        },

        // Resume the queue, setting `content` to be used in the next operation.
        // See `wait()` for an example.
        next: function (content) {
            this.waiting = false;
            if (typeof content !== 'undefined') {
                this.previous_content = this.content;
                this.content = content;
            }
            if (this.callbacks.length > 0) {
                this.then(this.callbacks.shift());
            }
        },

        // Load a template into the context.
        // The `location` can either be a string specifying the remote path to the
        // file, a jQuery object, or a DOM element.
        //
        // No interpolation happens by default, the content is stored in
        // `content`.
        //
        // In the case of a path, unless the option `{cache: false}` is passed the
        // data is stored in the app's `templateCache()`.
        //
        // If a jQuery or DOM object is passed the `innerHTML` of the node is pulled in.
        // This is useful for nesting templates as part of the initial page load wrapped
        // in invisible elements or `<script>` tags. With template paths, the template
        // engine is looked up by the extension. For DOM/jQuery embedded templates,
        // this isnt possible, so there are a couple of options:
        //
        //  * pass an `{engine:}` option.
        //  * define the engine in the `data-engine` attribute of the passed node.
        //  * just store the raw template data and use `interpolate()` manually
        //
        // If a `callback` is passed it is executed after the template load.
        load: function (location, options, callback) {
            var context = this;
            return this.then(function () {
                var should_cache, cached, is_json, location_array;
                if (_isFunction(options)) {
                    callback = options;
                    options = {};
                } else {
                    options = $.extend({}, options);
                }
                if (callback) { this.then(callback); }
                if (typeof location === 'string') {
                    // it's a path
                    is_json = (location.match(/\.json(\?|$)/) || options.json);
                    should_cache = is_json ? options.cache === true : options.cache !== false;
                    context.next_engine = context.event_context.engineFor(location);
                    delete options.cache;
                    delete options.json;
                    if (options.engine) {
                        context.next_engine = options.engine;
                        delete options.engine;
                    }
                    if (should_cache && (cached = this.event_context.app.templateCache(location))) {
                        return cached;
                    }
                    this.wait();
                    $.ajax($.extend({
                        url: location,
                        data: {},
                        dataType: is_json ? 'json' : 'text',
                        type: 'get',
                        success: function (data) {
                            if (should_cache) {
                                context.event_context.app.templateCache(location, data);
                            }
                            context.next(data);
                        }
                    }, options));
                    return false;
                } else {
                    // it's a dom/jQuery
                    if (location.nodeType) {
                        return location.innerHTML;
                    }
                    if (location.selector) {
                        // it's a jQuery
                        context.next_engine = location.attr('data-engine');
                        if (options.clone === false) {
                            return location.remove()[0].innerHTML.toString();
                        } else {
                            return location[0].innerHTML.toString();
                        }
                    }
                }
            });
        },

        // Load partials
        //
        // ### Example
        //
        //      this.loadPartials({mypartial: '/path/to/partial'});
        //
        loadPartials: function (partials) {
            var name;
            if (partials) {
                this.partials = this.partials || {};
                for (name in partials) {
                    (function (context, name) {
                        context.load(partials[name])
                            .then(function (template) {
                                this.partials[name] = template;
                            });
                    })(this, name);
                }
            }
            return this;
        },

        // `load()` a template and then `interpolate()` it with data.
        //
        // can be called with multiple different signatures:
        //
        //      this.render(callback);
        //      this.render('/location');
        //      this.render('/location', {some: data});
        //      this.render('/location', callback);
        //      this.render('/location', {some: data}, callback);
        //      this.render('/location', {some: data}, {my: partials});
        //      this.render('/location', callback, {my: partials});
        //      this.render('/location', {some: data}, callback, {my: partials});
        //
        // ### Example
        //
        //      this.get('#/', function() {
        //        this.render('mytemplate.template', {name: 'test'});
        //      });
        //
        render: function (location, data, callback, partials) {
            if (_isFunction(location) && !data) {
                // invoked as render(callback)
                return this.then(location);
            } else {
                if (_isFunction(data)) {
                    // invoked as render(location, callback, [partials])
                    partials = callback;
                    callback = data;
                    data = null;
                } else if (callback && !_isFunction(callback)) {
                    // invoked as render(location, data, partials)
                    partials = callback;
                    callback = null;
                }

                return this.loadPartials(partials)
                    .load(location)
                    .interpolate(data, location)
                    .then(callback);
            }
        },

        // `render()` the `location` with `data` and then `swap()` the
        // app's `$element` with the rendered content.
        partial: function (location, data, callback, partials) {
            if (_isFunction(callback)) {
                // invoked as partial(location, data, callback, [partials])
                return this.render(location, data, partials).swap(callback);
            } else if (_isFunction(data)) {
                // invoked as partial(location, callback, [partials])
                return this.render(location, {}, callback).swap(data);
            } else {
                // invoked as partial(location, data, [partials])
                return this.render(location, data, callback).swap();
            }
        },

        // defers the call of function to occur in order of the render queue.
        // The function can accept any number of arguments as long as the last
        // argument is a callback function. This is useful for putting arbitrary
        // asynchronous functions into the queue. The content passed to the
        // callback is passed as `content` to the next item in the queue.
        //
        // ### Example
        //
        //     this.send($.getJSON, '/app.json')
        //         .then(function(json) {
        //           $('#message).text(json['message']);
        //          });
        //
        //
        send: function () {
            var context = this,
                args = _makeArray(arguments),
                fun = args.shift();

            if (_isArray(args[0])) { args = args[0]; }

            return this.then(function (content) {
                args.push(function (response) { context.next(response); });
                context.wait();
                fun.apply(fun, args);
                return false;
            });
        },

        // iterates over an array, applying the callback for each item item. the
        // callback takes the same style of arguments as `jQuery.each()` (index, item).
        // The return value of each callback is collected as a single string and stored
        // as `content` to be used in the next iteration of the `RenderContext`.
        collect: function (array, callback, now) {
            var context = this;
            var coll = function () {
                if (_isFunction(array)) {
                    callback = array;
                    array = this.content;
                }
                var contents = [], doms = false;
                $.each(array, function (i, item) {
                    var returned = callback.apply(context, [i, item]);
                    if (returned.jquery && returned.length == 1) {
                        returned = returned[0];
                        doms = true;
                    }
                    contents.push(returned);
                    return returned;
                });
                return doms ? contents : contents.join('');
            };
            return now ? coll() : this.then(coll);
        },

        // loads a template, and then interpolates it for each item in the `data`
        // array. If a callback is passed, it will call the callback with each
        // item in the array _after_ interpolation
        renderEach: function (location, name, data, callback) {
            if (_isArray(name)) {
                callback = data;
                data = name;
                name = null;
            }
            return this.load(location).then(function (content) {
                var rctx = this;
                if (!data) {
                    data = _isArray(this.previous_content) ? this.previous_content : [];
                }
                if (callback) {
                    $.each(data, function (i, value) {
                        var idata = {}, engine = this.next_engine || location;
                        if (name) {
                            idata[name] = value;
                        } else {
                            idata = value;
                        }
                        callback(value, rctx.event_context.interpolate(content, idata, engine));
                    });
                } else {
                    return this.collect(data, function (i, value) {
                        var idata = {}, engine = this.next_engine || location;
                        if (name) {
                            idata[name] = value;
                        } else {
                            idata = value;
                        }
                        return this.event_context.interpolate(content, idata, engine);
                    }, true);
                }
            });
        },

        // uses the previous loaded `content` and the `data` object to interpolate
        // a template. `engine` defines the templating/interpolation method/engine
        // that should be used. If `engine` is not passed, the `next_engine` is
        // used. If `retain` is `true`, the final interpolated data is appended to
        // the `previous_content` instead of just replacing it.
        interpolate: function (data, engine, retain) {
            var context = this;
            return this.then(function (content, prev) {
                if (!data && prev) { data = prev; }
                if (this.next_engine) {
                    engine = this.next_engine;
                    this.next_engine = false;
                }
                var rendered = context.event_context.interpolate(content, data, engine, this.partials);
                return retain ? prev + rendered : rendered;
            });
        },

        // Swap the return contents ensuring order. See `Application#swap`
        swap: function (callback) {
            return this.then(function (content) {
                this.event_context.swap(content, callback);
                return content;
            }).trigger('changed', {});
        },

        // Same usage as `jQuery.fn.appendTo()` but uses `then()` to ensure order
        appendTo: function (selector) {
            return this.then(function (content) {
                $(selector).append(content);
            }).trigger('changed', {});
        },

        // Same usage as `jQuery.fn.prependTo()` but uses `then()` to ensure order
        prependTo: function (selector) {
            return this.then(function (content) {
                $(selector).prepend(content);
            }).trigger('changed', {});
        },

        // Replaces the `$(selector)` using `html()` with the previously loaded
        // `content`
        replace: function (selector) {
            return this.then(function (content) {
                $(selector).html(content);
            }).trigger('changed', {});
        },

        // trigger the event in the order of the event context. Same semantics
        // as `Sammy.EventContext#trigger()`. If data is omitted, `content`
        // is sent as `{content: content}`
        trigger: function (name, data) {
            return this.then(function (content) {
                if (typeof data == 'undefined') { data = { content: content }; }
                this.event_context.trigger(name, data);
                return content;
            });
        }

    });

    // `Sammy.EventContext` objects are created every time a route is run or a
    // bound event is triggered. The callbacks for these events are evaluated within a `Sammy.EventContext`
    // This within these callbacks the special methods of `EventContext` are available.
    //
    // ### Example
    //
    //       $.sammy(function() {
    //         // The context here is this Sammy.Application
    //         this.get('#/:name', function() {
    //           // The context here is a new Sammy.EventContext
    //           if (this.params['name'] == 'sammy') {
    //             this.partial('name.html.erb', {name: 'Sammy'});
    //           } else {
    //             this.redirect('#/somewhere-else')
    //           }
    //         });
    //       });
    //
    // Initialize a new EventContext
    //
    // ### Arguments
    //
    // * `app` The `Sammy.Application` this event is called within.
    // * `verb` The verb invoked to run this context/route.
    // * `path` The string path invoked to run this context/route.
    // * `params` An Object of optional params to pass to the context. Is converted
    //   to a `Sammy.Object`.
    // * `target` a DOM element that the event that holds this context originates
    //   from. For post, put and del routes, this is the form element that triggered
    //   the route.
    //
    Sammy.EventContext = function (app, verb, path, params, target) {
        this.app = app;
        this.verb = verb;
        this.path = path;
        this.params = new Sammy.Object(params);
        this.target = target;
    };

    Sammy.EventContext.prototype = $.extend({}, Sammy.Object.prototype, {

        // A shortcut to the app's `$element()`
        $element: function () {
            return this.app.$element(_makeArray(arguments).shift());
        },

        // Look up a templating engine within the current app and context.
        // `engine` can be one of the following:
        //
        // * a function: should conform to `function(content, data) { return interpolated; }`
        // * a template path: 'template.ejs', looks up the extension to match to
        //   the `ejs()` helper
        // * a string referring to the helper: "mustache" => `mustache()`
        //
        // If no engine is found, use the app's default `template_engine`
        //
        engineFor: function (engine) {
            var context = this, engine_match;
            // if path is actually an engine function just return it
            if (_isFunction(engine)) { return engine; }
            // lookup engine name by path extension
            engine = (engine || context.app.template_engine).toString();
            if ((engine_match = engine.match(/\.([^\.\?\#]+)(\?|$)/))) {
                engine = engine_match[1];
            }
            // set the engine to the default template engine if no match is found
            if (engine && _isFunction(context[engine])) {
                return context[engine];
            }

            if (context.app.template_engine) {
                return this.engineFor(context.app.template_engine);
            }
            return function (content, data) { return content; };
        },

        // using the template `engine` found with `engineFor()`, interpolate the
        // `data` into `content`
        interpolate: function (content, data, engine, partials) {
            return this.engineFor(engine).apply(this, [content, data, partials]);
        },

        // Create and return a `Sammy.RenderContext` calling `render()` on it.
        // Loads the template and interpolate the data, however does not actual
        // place it in the DOM.
        //
        // ### Example
        //
        //      // mytemplate.mustache <div class="name">{{name}}</div>
        //      render('mytemplate.mustache', {name: 'quirkey'});
        //      // sets the `content` to <div class="name">quirkey</div>
        //      render('mytemplate.mustache', {name: 'quirkey'})
        //        .appendTo('ul');
        //      // appends the rendered content to $('ul')
        //
        render: function (location, data, callback, partials) {
            return new Sammy.RenderContext(this).render(location, data, callback, partials);
        },

        // Create and return a `Sammy.RenderContext` calling `renderEach()` on it.
        // Loads the template and interpolates the data for each item,
        // however does not actually place it in the DOM.
        //
        // `name` is an optional parameter (if it is an array, it is used as `data`,
        // and the third parameter used as `callback`, if set).
        //
        // If `data` is not provided, content from the previous step in the chain
        // (if it is an array) is used, and `name` is used as the key for each
        // element of the array (useful for referencing in template).
        //
        // ### Example
        //
        //      // mytemplate.mustache <div class="name">{{name}}</div>
        //      renderEach('mytemplate.mustache', [{name: 'quirkey'}, {name: 'endor'}])
        //      // sets the `content` to <div class="name">quirkey</div><div class="name">endor</div>
        //      renderEach('mytemplate.mustache', [{name: 'quirkey'}, {name: 'endor'}]).appendTo('ul');
        //      // appends the rendered content to $('ul')
        //
        //      // names.json: ["quirkey", "endor"]
        //      this.load('names.json').renderEach('mytemplate.mustache', 'name').appendTo('ul');
        //      // uses the template to render each item in the JSON array
        //
        renderEach: function (location, name, data, callback) {
            return new Sammy.RenderContext(this).renderEach(location, name, data, callback);
        },

        // create a new `Sammy.RenderContext` calling `load()` with `location` and
        // `options`. Called without interpolation or placement, this allows for
        // preloading/caching the templates.
        load: function (location, options, callback) {
            return new Sammy.RenderContext(this).load(location, options, callback);
        },

        // create a new `Sammy.RenderContext` calling `loadPartials()` with `partials`.
        loadPartials: function (partials) {
            return new Sammy.RenderContext(this).loadPartials(partials);
        },

        // `render()` the `location` with `data` and then `swap()` the
        // app's `$element` with the rendered content.
        partial: function (location, data, callback, partials) {
            return new Sammy.RenderContext(this).partial(location, data, callback, partials);
        },

        // create a new `Sammy.RenderContext` calling `send()` with an arbitrary
        // function
        send: function () {
            var rctx = new Sammy.RenderContext(this);
            return rctx.send.apply(rctx, arguments);
        },

        // Changes the location of the current window. If `to` begins with
        // '#' it only changes the document's hash. If passed more than 1 argument
        // redirect will join them together with forward slashes.
        //
        // ### Example
        //
        //      redirect('#/other/route');
        //      // equivalent to
        //      redirect('#', 'other', 'route');
        //
        redirect: function () {
            var to, args = _makeArray(arguments),
                current_location = this.app.getLocation(),
                l = args.length;
            if (l > 1) {
                var i = 0, paths = [], pairs = [], params = {}, has_params = false;
                for (; i < l; i++) {
                    if (typeof args[i] == 'string') {
                        paths.push(args[i]);
                    } else {
                        $.extend(params, args[i]);
                        has_params = true;
                    }
                }
                to = paths.join('/');
                if (has_params) {
                    for (var k in params) {
                        pairs.push(this.app._encodeFormPair(k, params[k]));
                    }
                    to += '?' + pairs.join('&');
                }
            } else {
                to = args[0];
            }
            this.trigger('redirect', { to: to });
            this.app.last_location = [this.verb, this.path];
            this.app.setLocation(to);
            if (new RegExp(to).test(current_location)) {
                this.app.trigger('location-changed');
            }
        },

        // Triggers events on `app` within the current context.
        trigger: function (name, data) {
            if (typeof data == 'undefined') { data = {}; }
            if (!data.context) { data.context = this; }
            return this.app.trigger(name, data);
        },

        // A shortcut to app's `eventNamespace()`
        eventNamespace: function () {
            return this.app.eventNamespace();
        },

        // A shortcut to app's `swap()`
        swap: function (contents, callback) {
            return this.app.swap(contents, callback);
        },

        // Raises a possible `notFound()` error for the current path.
        notFound: function () {
            return this.app.notFound(this.verb, this.path);
        },

        // Default JSON parsing uses jQuery's `parseJSON()`. Include `Sammy.JSON`
        // plugin for the more conformant "crockford special".
        json: function (string) {
            return $.parseJSON(string);
        },

        // //=> Sammy.EventContext: get #/ {}
        toString: function () {
            return "Sammy.EventContext: " + [this.verb, this.path, this.params].join(' ');
        }

    });

    return Sammy;
});
/**
 * @preserve Slimmage 0.4.2, use with ImageResizer. MIT/Apache2 dual licensed by Imazen 
 */

/* We often use string instead of dot notation to keep 
   Closure Compiler's advanced mode from breaking APIs */
/*jshint sub:true*/

(function (w) { //w==window
    // Enable strict mode
    "use strict";

    // Make sure w is window (For babel-transpiled environments the 'this' keyword may not point to window)
    if (!w || !w.document) {
        w = window;
    }

    var s = window['slimmage'] || {};
    window['slimmage'] = s;
    if (s['verbose'] === undefined) { s['verbose'] = false; }
    if (s['tryWebP'] === undefined) { s['tryWebP'] = false; }
    if (s['maxWidth'] === undefined) { s['maxWidth'] = 2048; }
    if (s['widthStep'] === undefined) { s['widthStep'] = 160; }
    if (s['jpegQuality'] === undefined) { s['jpegQuality'] = 90; }
    if (s['jpegRetinaQuality'] === undefined) { s['jpegRetinaQuality'] = 80; }
    if (s['webpTimeout'] === undefined) { s['webpTimeout'] = 0; }
    s['changed'] = [];

    var log = function () { if (s['verbose'] && w.console && w.console.log) try { w.console.log.apply(w.console, arguments); } catch (e) { } };
    s.beginWebPTest = function () {
        if (!s['tryWebP'] || s._testingWebP) return;
        s._testingWebP = true;

        var WebP = new Image();
        WebP.onload = WebP.onerror = function () {
            s['webp'] = (WebP.height == 2);
            s._testingWebP = false;
            if (s.cr) { s.cr(); }
        };
        WebP.src = 'data:image/webp;base64,UklGRjoAAABXRUJQVlA4IC4AAACyAgCdASoCAAIALmk0mk0iIiIiIgBoSygABc6WWgAA/veff/0PP8bA//LwYAAA';
    };
    //test for webp support ASAP
    s.beginWebPTest();

    s.setAttr = function (elem, name, value) {
        name = name.toLowerCase();
        if (name == "class") { elem.className = value; }
        else if (name == "tabindex") { elem.tabIndex = value; }
        else if (name == "usemap") { elem.useMap = value; }
        else {
            elem.setAttribute(name, value);
        }

    };
    s['setAttribute'] = s.setAttr;

    s.is_blank = function (v) { return v === "none" || v === null || v === undefined || v === "" || v === false; };
    s['getCssValue'] = function (target, hyphenProp) {
        //See http://www.nathanaeljones.com/blog/2013/reading-max-width-cross-browser

        var val = typeof (window.getComputedStyle) != "undefined" && window.getComputedStyle(target, null).getPropertyValue(hyphenProp);

        // Some browsers (IE8, Firefox 28) read "none" when not set. Others (IE6) respond with undefined. A value of
        // "none" is invalid and would cause an exception or be interpreted as 
        if (!s.is_blank(val)) {
            return val;
        }

        if (target.currentStyle) {
            val = target.currentStyle[hyphenProp.replace(/([a-z])\-([a-z])/, function (a, b, c) { return b + c.toUpperCase(); })] || target.currentStyle[hyphenProp];
        }

        return s.is_blank(val) ? null : val;
    };

    s['getCssPixels'] = function (target, hyphenProp) {
        var val = s['getCssValue'](target, hyphenProp);

        if (val === null || val === "0" || val === 0) return val;

        //We can return pixels directly, but not other units
        if (val.slice(-2) == "px") return parseFloat(val.slice(0, -2));

        //Create a temporary sibling div to resolve units into pixels.
        var temp = document.createElement("div");
        temp.style.overflow = temp.style.visibility = "hidden";
        temp.style.cssFloat = "none";
        target.parentNode.appendChild(temp);
        temp.style.width = val;
        var pixels = temp.offsetWidth;
        target.parentNode.removeChild(temp);
        return pixels;
    };

    s.nodesToArray = function (nodeList) {
        var array = [];
        // iterate backwards ensuring that length is an UInt32
        for (var i = nodeList.length >>> 0; i--;) {
            array[i] = nodeList[i];
        }
        return array;
    };

    /*
      No URI decoding/encoding is perfomed on keys or values. Caller's responsibility.
      vistor and mutator are applied to string.replace -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
      params:
      1. entire pair, incl. (optional) &  and = 
      2. '&' (if present)
      3. key
      4. value
      mutator's result is honored. Must return param 1, or provide valid replacement.
      
      injector(query) is responsible for adding additional pairs if required. 
      It must not produce a malformatted query.
    */
    s['mutateUrl'] = function (url, visitor, mutator, injector) {
        var m = /^([^?#]*)?(\?([^#]*))?(#.*)?/.exec(url);
        var q = m[3] || '';

        var qr = /(^&*|&+)([^&=]*)=?([^&]*)/g;
        q.replace(qr, visitor); //read-only, to gather data

        var newq = '?' + q.replace(qr, mutator).replace(/(?:^\?*&*)|(?:[?&]+$)/g, "").replace(/&&+/g, "&");

        return (m[1] || '') + injector(newq) + (m[4] || '');
    };

    //Expects virtual, not device pixel width
    s['getImageInfo'] = function (elementWidth, previousSrc, previousPixelWidth, previousElement) {
        var data = {
            'webp': s['webp'],
            'width': elementWidth,
            'dpr': window.devicePixelRatio || 1,
            'src': previousSrc,
            'element': previousElement
        };
        //Determine quality percentage
        var high_density = s['webp'] ? 65 : s['jpegRetinaQuality'];
        var low_density = s['webp'] ? 78 : s['jpegQuality'];
        data['quality'] = data['dpr'] > 1.49 ? high_density : low_density;

        //Calculate raw pixels using devicePixelRatio. Limit size to maxWidth.
        var idealWidth = elementWidth * data['dpr'];
        //Minimize variants for caching improvements; round up to nearest multiple of widthStep
        data['requestedWidth'] = Math.min(s['maxWidth'], //Limit size to maxWidth
                                  Math.round( //Round in case widthStep isn't an integer
                                    Math.ceil(idealWidth / s['widthStep']) * s['widthStep'] //Divide, ceiling, then multiply
                                            )
                                          );

        var a = s['adjustImageParameters'];
        if (a && typeof (a) === "function") {
            a(data);
        }
        var finalWidth = data['requestedWidth'];

        if (finalWidth > previousPixelWidth) {
            //Never request a smaller image once the larger one has already started loading
            var u = {}; //For storing raw pairs
            var c = {}; //For storing relevant parsed info
            var newSrc = s['mutateUrl'](
              previousSrc,
              //Visitor
              function (_, d, k, v) {
                  u[k.toLowerCase()] = v;
              },
              //Mutator
              function (p, d, k, v) {

                  //Parse existing values so we can make educated calculations for width/height
                  if (c.zoom === undefined) {
                      c.zoom = parseFloat(u.zoom || 1);
                      if (isNaN(c.zoom)) { c.zoom = 1; }
                      c.w = (finalWidth / c.zoom).toFixed();
                  }
                  if (c.ratio === undefined) {
                      var w = parseFloat(u.width || u.w || u.maxwidth);
                      var h = parseFloat(u.height || u.h || u.maxheight);
                      if (!isNaN(w) && !isNaN(h) && w > 0 && h > 0) {
                          c.ratio = w / h;
                          c.h = (((finalWidth / c.zoom) / w) * h).toFixed();
                      } else {
                          c.ratio = 'noclue';
                      }
                  }
                  if (k.match(/^format$/i) && data['webp']) { return d + "format=webp"; }
                  if (k.match(/^quality/i)) { return d + "quality=" + s.getQuality(finalWidth, data['quality']);}
                      

                  if (k.match(/^(w|width|maxwidth)$/i)) { return d + k + "=" + c.w; }
                  if (k.match(/^(h|height|maxheight)$/i)) { return d + k + "=" + c.h; }

                  return p;
              },
              //Injector
              function (q) { return q; });

            return { 'src': newSrc, 'data-pixel-width': finalWidth };
        }
        return null;
    };
    //Ledarna specific method to extract correct quality from finalWidth
    s.getQuality = function (finalWidth, dataQuality) {
        if (finalWidth <= 250) {
            return dataQuality = 95;

        } else if (finalWidth > 250 && finalWidth <= 600) {
            return dataQuality = 90;

        } else if (finalWidth > 600 && finalWidth <= 800) {
            return dataQuality = 85;

        } else if (finalWidth > 800) {
            return dataQuality = 80;

        } else {
            return dataQuality;
        }
    };

    s['adjustImageSrc'] = function (img, previousSrc) {

        var cssMaxWidth = s['getCssPixels'](img, 'max-width');
        var result = s['getImageInfo'](cssMaxWidth,
                                       previousSrc,
                                       img.getAttribute('data-pixel-width') | 0,
                                       img);

        if (result) {
            img.src = result['src'];
            s.setAttr(img, 'data-pixel-width', result['data-pixel-width']);
            if (s['enforceCss']) {
                if (cssMaxWidth < result['data-pixel-width']) {
                    img.style.width = s['getCssValue'](img, 'max-width');
                    s.setAttr(img, 'data-width-enforced', true);
                } else {
                    img.style.width = 'auto';
                }
            }
            s['changed'].push(img);
            log("Slimming: updating " + result['src']);
        } else if (s['enforceCss'] && img.getAttribute('data-width-enforced')) {
            var imageWidth = parseFloat(img.getAttribute('data-pixel-width'));
            if (!isNaN(imageWidth) && cssMaxWidth >= imageWidth) {
                img.style.width = 'auto';
                img.removeAttribute('data-width-enforced');
            }
        }

    };
    s.cr = function (delay) {
        var i, il, j, jl, k, kl;

        if (s.timeoutid > 0) w.clearTimeout(s.timeoutid);
        s.timeoutid = 0;

        if (s._testingWebP && s['webpTimeout'] > 0 && !s.webp_waiting) {
            s.webp_waiting = true;
            delay = s['webpTimeout'];
        }
        if (delay && delay > 0) {
            s.timeoutid = w.setTimeout(s.cr, delay);
            return;
        }
        var stopwatch = new Date().getTime();

        var newImages = 0;
        //1. Copy images out of noscript tags, but hide 'src' attribute as data-src
        var n = s.nodesToArray(w.document.getElementsByTagName("noscript"));
        for (i = 0, il = n.length; i < il; i++) {
            var ns = n[i];
            if (ns.getAttribute("data-slimmage") !== null) {

                var div = w.document.createElement('div');
                var contents = (ns.textContent || ns.innerHTML);
                if (!contents || contents.replace(/[\s\t\r\n]+/, "").length === 0) {
                    //IE doesn't let us touch noscript, so we have to use attributes.
                    var img = new Image();
                    for (var ai = 0; ai < ns.attributes.length; ai++) {
                        var a = ns.attributes[ai];
                        if (a && a.specified && a.name.indexOf("data-img-") === 0) {
                            s.setAttr(img, a.name.slice(9 - a.name.length), a.value);
                        }
                    }
                    div.appendChild(img);
                } else {
                    //noscript isn't part of DOM, so we have to recreate it, unescaping html, src->data-src 
                    div.innerHTML = contents.replace(/\s+src\s*=\s*(['"])/i, " data-src=$1").
                        replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
                }
                //Clear source values before we add it back to the dom, ensure data-slimmage is set.
                var childImages = div.getElementsByTagName("img");
                for (j = 0, jl = childImages.length; j < jl; j++) {
                    var ci = childImages[j];
                    if (ci.src !== null && ci.src.length > 0) {
                        s.setAttr(ci, "data-src", ci.src);
                        ci.src = "";
                    }
                    s.setAttr(ci, "data-slimmage", true);
                    ns.parentNode.insertBefore(ci, ns);
                    newImages++;
                }
                //2. Remove old noscript tags
                ns.parentNode.removeChild(ns);
            }
        }

        //3. Let plugins inject custom behavior
        if ('function' === typeof s['beforeAdjustSrc']) {
            s['beforeAdjustSrc']();
        }

        //4. Find images with data-slimmage and run adjustImageSrc.
        var totalImages = 0;
        var images = s.nodesToArray(w.document.getElementsByTagName("img"));
        for (k = 0, kl = images.length; k < kl; k++) {
            if (images[k].getAttribute("data-slimmage") !== null) {
                var previousSrc = images[k].getAttribute("data-src") || images[k].src;
                s['adjustImageSrc'](images[k], previousSrc);
                totalImages++;
            }
        }

        var changed = s['changed'].slice();
        s['changed'].length = 0;

        //5. Callback when ready
        if ((changed.length > 0 || !s.readyCalled) && 'function' === typeof s['readyCallback']) {
            s['readyCallback'](changed);
            s.readyCalled = true;
        }

        log("Slimmage: restored " + newImages + " images from noscript tags, checked " + totalImages + " images, changed " + changed.length + ". " + (new Date().getTime() - stopwatch) + "ms");
    };

    s['checkResponsiveImages'] = s.cr;
    // Run on resize and domready (w.load as a fallback)
    if (w.addEventListener) {
        w.addEventListener("resize", function () { s.cr(500); }, false);
        w.addEventListener("DOMContentLoaded", function () {
            s.cr();
            // Run once only
            w.removeEventListener("load", s.cr, false);
        }, false);
        w.addEventListener("load", s.cr, false);
    } else if (w.attachEvent) {
        w.attachEvent("onload", s.cr);
        w.attachEvent("onresize", function () { s.cr(500); });
    }

}(this));
/*!
* Clamp.js 0.5.1
*
* Copyright 2011-2013, Joseph Schmitt http://joe.sh
* Released under the WTFPL license
* http://sam.zoy.org/wtfpl/
*/
(function(){window.$clamp=function(c,d){function s(a,b){n.getComputedStyle||(n.getComputedStyle=function(a,b){this.el=a;this.getPropertyValue=function(b){var c=/(\-([a-z]){1})/g;"float"==b&&(b="styleFloat");c.test(b)&&(b=b.replace(c,function(a,b,c){return c.toUpperCase()}));return a.currentStyle&&a.currentStyle[b]?a.currentStyle[b]:null};return this});return n.getComputedStyle(a,null).getPropertyValue(b)}function t(a){a=a||c.clientHeight;var b=u(c);return Math.max(Math.floor(a/b),0)}function x(a){return u(c)*
a}function u(a){var b=s(a,"line-height");"normal"==b&&(b=1.2*parseInt(s(a,"font-size")));return parseInt(b)}function l(a){if(a.lastChild.children&&0<a.lastChild.children.length)return l(Array.prototype.slice.call(a.children).pop());if(a.lastChild&&a.lastChild.nodeValue&&""!=a.lastChild.nodeValue&&a.lastChild.nodeValue!=b.truncationChar)return a.lastChild;a.lastChild.parentNode.removeChild(a.lastChild);return l(c)}function p(a,d){if(d){var e=a.nodeValue.replace(b.truncationChar,"");f||(h=0<k.length?
k.shift():"",f=e.split(h));1<f.length?(q=f.pop(),r(a,f.join(h))):f=null;m&&(a.nodeValue=a.nodeValue.replace(b.truncationChar,""),c.innerHTML=a.nodeValue+" "+m.innerHTML+b.truncationChar);if(f){if(c.clientHeight<=d)if(0<=k.length&&""!=h)r(a,f.join(h)+h+q),f=null;else return c.innerHTML}else""==h&&(r(a,""),a=l(c),k=b.splitOnChars.slice(0),h=k[0],q=f=null);if(b.animate)setTimeout(function(){p(a,d)},!0===b.animate?10:b.animate);else return p(a,d)}}function r(a,c){a.nodeValue=c+b.truncationChar}d=d||{};
var n=window,b={clamp:d.clamp||2,useNativeClamp:"undefined"!=typeof d.useNativeClamp?d.useNativeClamp:!0,splitOnChars:d.splitOnChars||[".","-","\u2013","\u2014"," "],animate:d.animate||!1,truncationChar:d.truncationChar||"\u2026",truncationHTML:d.truncationHTML},e=c.style,y=c.innerHTML,z="undefined"!=typeof c.style.webkitLineClamp,g=b.clamp,v=g.indexOf&&(-1<g.indexOf("px")||-1<g.indexOf("em")),m;b.truncationHTML&&(m=document.createElement("span"),m.innerHTML=b.truncationHTML);var k=b.splitOnChars.slice(0),
h=k[0],f,q;"auto"==g?g=t():v&&(g=t(parseInt(g)));var w;z&&b.useNativeClamp?(e.overflow="hidden",e.textOverflow="ellipsis",e.webkitBoxOrient="vertical",e.display="-webkit-box",e.webkitLineClamp=g,v&&(e.height=b.clamp+"px")):(e=x(g),e<=c.clientHeight&&(w=p(l(c),e)));return{original:y,clamped:w}}})();
!function(n,r){"object"==typeof exports&&"undefined"!=typeof module?module.exports=r():"function"==typeof define&&define.amd?define("underscore",r):(n="undefined"!=typeof globalThis?globalThis:n||self,function(){var t=n._,e=n._=r();e.noConflict=function(){return n._=t,e}}())}(this,(function(){
//     Underscore.js 1.13.6
//     https://underscorejs.org
//     (c) 2009-2022 Jeremy Ashkenas, Julian Gonggrijp, and DocumentCloud and Investigative Reporters & Editors
//     Underscore may be freely distributed under the MIT license.
var n="1.13.6",r="object"==typeof self&&self.self===self&&self||"object"==typeof global&&global.global===global&&global||Function("return this")()||{},t=Array.prototype,e=Object.prototype,u="undefined"!=typeof Symbol?Symbol.prototype:null,o=t.push,i=t.slice,a=e.toString,f=e.hasOwnProperty,c="undefined"!=typeof ArrayBuffer,l="undefined"!=typeof DataView,s=Array.isArray,p=Object.keys,v=Object.create,h=c&&ArrayBuffer.isView,y=isNaN,d=isFinite,g=!{toString:null}.propertyIsEnumerable("toString"),b=["valueOf","isPrototypeOf","toString","propertyIsEnumerable","hasOwnProperty","toLocaleString"],m=Math.pow(2,53)-1;function j(n,r){return r=null==r?n.length-1:+r,function(){for(var t=Math.max(arguments.length-r,0),e=Array(t),u=0;u<t;u++)e[u]=arguments[u+r];switch(r){case 0:return n.call(this,e);case 1:return n.call(this,arguments[0],e);case 2:return n.call(this,arguments[0],arguments[1],e)}var o=Array(r+1);for(u=0;u<r;u++)o[u]=arguments[u];return o[r]=e,n.apply(this,o)}}function _(n){var r=typeof n;return"function"===r||"object"===r&&!!n}function w(n){return void 0===n}function A(n){return!0===n||!1===n||"[object Boolean]"===a.call(n)}function x(n){var r="[object "+n+"]";return function(n){return a.call(n)===r}}var S=x("String"),O=x("Number"),M=x("Date"),E=x("RegExp"),B=x("Error"),N=x("Symbol"),I=x("ArrayBuffer"),T=x("Function"),k=r.document&&r.document.childNodes;"function"!=typeof/./&&"object"!=typeof Int8Array&&"function"!=typeof k&&(T=function(n){return"function"==typeof n||!1});var D=T,R=x("Object"),F=l&&R(new DataView(new ArrayBuffer(8))),V="undefined"!=typeof Map&&R(new Map),P=x("DataView");var q=F?function(n){return null!=n&&D(n.getInt8)&&I(n.buffer)}:P,U=s||x("Array");function W(n,r){return null!=n&&f.call(n,r)}var z=x("Arguments");!function(){z(arguments)||(z=function(n){return W(n,"callee")})}();var L=z;function $(n){return O(n)&&y(n)}function C(n){return function(){return n}}function K(n){return function(r){var t=n(r);return"number"==typeof t&&t>=0&&t<=m}}function J(n){return function(r){return null==r?void 0:r[n]}}var G=J("byteLength"),H=K(G),Q=/\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;var X=c?function(n){return h?h(n)&&!q(n):H(n)&&Q.test(a.call(n))}:C(!1),Y=J("length");function Z(n,r){r=function(n){for(var r={},t=n.length,e=0;e<t;++e)r[n[e]]=!0;return{contains:function(n){return!0===r[n]},push:function(t){return r[t]=!0,n.push(t)}}}(r);var t=b.length,u=n.constructor,o=D(u)&&u.prototype||e,i="constructor";for(W(n,i)&&!r.contains(i)&&r.push(i);t--;)(i=b[t])in n&&n[i]!==o[i]&&!r.contains(i)&&r.push(i)}function nn(n){if(!_(n))return[];if(p)return p(n);var r=[];for(var t in n)W(n,t)&&r.push(t);return g&&Z(n,r),r}function rn(n,r){var t=nn(r),e=t.length;if(null==n)return!e;for(var u=Object(n),o=0;o<e;o++){var i=t[o];if(r[i]!==u[i]||!(i in u))return!1}return!0}function tn(n){return n instanceof tn?n:this instanceof tn?void(this._wrapped=n):new tn(n)}function en(n){return new Uint8Array(n.buffer||n,n.byteOffset||0,G(n))}tn.VERSION=n,tn.prototype.value=function(){return this._wrapped},tn.prototype.valueOf=tn.prototype.toJSON=tn.prototype.value,tn.prototype.toString=function(){return String(this._wrapped)};var un="[object DataView]";function on(n,r,t,e){if(n===r)return 0!==n||1/n==1/r;if(null==n||null==r)return!1;if(n!=n)return r!=r;var o=typeof n;return("function"===o||"object"===o||"object"==typeof r)&&function n(r,t,e,o){r instanceof tn&&(r=r._wrapped);t instanceof tn&&(t=t._wrapped);var i=a.call(r);if(i!==a.call(t))return!1;if(F&&"[object Object]"==i&&q(r)){if(!q(t))return!1;i=un}switch(i){case"[object RegExp]":case"[object String]":return""+r==""+t;case"[object Number]":return+r!=+r?+t!=+t:0==+r?1/+r==1/t:+r==+t;case"[object Date]":case"[object Boolean]":return+r==+t;case"[object Symbol]":return u.valueOf.call(r)===u.valueOf.call(t);case"[object ArrayBuffer]":case un:return n(en(r),en(t),e,o)}var f="[object Array]"===i;if(!f&&X(r)){if(G(r)!==G(t))return!1;if(r.buffer===t.buffer&&r.byteOffset===t.byteOffset)return!0;f=!0}if(!f){if("object"!=typeof r||"object"!=typeof t)return!1;var c=r.constructor,l=t.constructor;if(c!==l&&!(D(c)&&c instanceof c&&D(l)&&l instanceof l)&&"constructor"in r&&"constructor"in t)return!1}o=o||[];var s=(e=e||[]).length;for(;s--;)if(e[s]===r)return o[s]===t;if(e.push(r),o.push(t),f){if((s=r.length)!==t.length)return!1;for(;s--;)if(!on(r[s],t[s],e,o))return!1}else{var p,v=nn(r);if(s=v.length,nn(t).length!==s)return!1;for(;s--;)if(p=v[s],!W(t,p)||!on(r[p],t[p],e,o))return!1}return e.pop(),o.pop(),!0}(n,r,t,e)}function an(n){if(!_(n))return[];var r=[];for(var t in n)r.push(t);return g&&Z(n,r),r}function fn(n){var r=Y(n);return function(t){if(null==t)return!1;var e=an(t);if(Y(e))return!1;for(var u=0;u<r;u++)if(!D(t[n[u]]))return!1;return n!==hn||!D(t[cn])}}var cn="forEach",ln="has",sn=["clear","delete"],pn=["get",ln,"set"],vn=sn.concat(cn,pn),hn=sn.concat(pn),yn=["add"].concat(sn,cn,ln),dn=V?fn(vn):x("Map"),gn=V?fn(hn):x("WeakMap"),bn=V?fn(yn):x("Set"),mn=x("WeakSet");function jn(n){for(var r=nn(n),t=r.length,e=Array(t),u=0;u<t;u++)e[u]=n[r[u]];return e}function _n(n){for(var r={},t=nn(n),e=0,u=t.length;e<u;e++)r[n[t[e]]]=t[e];return r}function wn(n){var r=[];for(var t in n)D(n[t])&&r.push(t);return r.sort()}function An(n,r){return function(t){var e=arguments.length;if(r&&(t=Object(t)),e<2||null==t)return t;for(var u=1;u<e;u++)for(var o=arguments[u],i=n(o),a=i.length,f=0;f<a;f++){var c=i[f];r&&void 0!==t[c]||(t[c]=o[c])}return t}}var xn=An(an),Sn=An(nn),On=An(an,!0);function Mn(n){if(!_(n))return{};if(v)return v(n);var r=function(){};r.prototype=n;var t=new r;return r.prototype=null,t}function En(n){return U(n)?n:[n]}function Bn(n){return tn.toPath(n)}function Nn(n,r){for(var t=r.length,e=0;e<t;e++){if(null==n)return;n=n[r[e]]}return t?n:void 0}function In(n,r,t){var e=Nn(n,Bn(r));return w(e)?t:e}function Tn(n){return n}function kn(n){return n=Sn({},n),function(r){return rn(r,n)}}function Dn(n){return n=Bn(n),function(r){return Nn(r,n)}}function Rn(n,r,t){if(void 0===r)return n;switch(null==t?3:t){case 1:return function(t){return n.call(r,t)};case 3:return function(t,e,u){return n.call(r,t,e,u)};case 4:return function(t,e,u,o){return n.call(r,t,e,u,o)}}return function(){return n.apply(r,arguments)}}function Fn(n,r,t){return null==n?Tn:D(n)?Rn(n,r,t):_(n)&&!U(n)?kn(n):Dn(n)}function Vn(n,r){return Fn(n,r,1/0)}function Pn(n,r,t){return tn.iteratee!==Vn?tn.iteratee(n,r):Fn(n,r,t)}function qn(){}function Un(n,r){return null==r&&(r=n,n=0),n+Math.floor(Math.random()*(r-n+1))}tn.toPath=En,tn.iteratee=Vn;var Wn=Date.now||function(){return(new Date).getTime()};function zn(n){var r=function(r){return n[r]},t="(?:"+nn(n).join("|")+")",e=RegExp(t),u=RegExp(t,"g");return function(n){return n=null==n?"":""+n,e.test(n)?n.replace(u,r):n}}var Ln={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},$n=zn(Ln),Cn=zn(_n(Ln)),Kn=tn.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g},Jn=/(.)^/,Gn={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028","\u2029":"u2029"},Hn=/\\|'|\r|\n|\u2028|\u2029/g;function Qn(n){return"\\"+Gn[n]}var Xn=/^\s*(\w|\$)+\s*$/;var Yn=0;function Zn(n,r,t,e,u){if(!(e instanceof r))return n.apply(t,u);var o=Mn(n.prototype),i=n.apply(o,u);return _(i)?i:o}var nr=j((function(n,r){var t=nr.placeholder,e=function(){for(var u=0,o=r.length,i=Array(o),a=0;a<o;a++)i[a]=r[a]===t?arguments[u++]:r[a];for(;u<arguments.length;)i.push(arguments[u++]);return Zn(n,e,this,this,i)};return e}));nr.placeholder=tn;var rr=j((function(n,r,t){if(!D(n))throw new TypeError("Bind must be called on a function");var e=j((function(u){return Zn(n,e,r,this,t.concat(u))}));return e})),tr=K(Y);function er(n,r,t,e){if(e=e||[],r||0===r){if(r<=0)return e.concat(n)}else r=1/0;for(var u=e.length,o=0,i=Y(n);o<i;o++){var a=n[o];if(tr(a)&&(U(a)||L(a)))if(r>1)er(a,r-1,t,e),u=e.length;else for(var f=0,c=a.length;f<c;)e[u++]=a[f++];else t||(e[u++]=a)}return e}var ur=j((function(n,r){var t=(r=er(r,!1,!1)).length;if(t<1)throw new Error("bindAll must be passed function names");for(;t--;){var e=r[t];n[e]=rr(n[e],n)}return n}));var or=j((function(n,r,t){return setTimeout((function(){return n.apply(null,t)}),r)})),ir=nr(or,tn,1);function ar(n){return function(){return!n.apply(this,arguments)}}function fr(n,r){var t;return function(){return--n>0&&(t=r.apply(this,arguments)),n<=1&&(r=null),t}}var cr=nr(fr,2);function lr(n,r,t){r=Pn(r,t);for(var e,u=nn(n),o=0,i=u.length;o<i;o++)if(r(n[e=u[o]],e,n))return e}function sr(n){return function(r,t,e){t=Pn(t,e);for(var u=Y(r),o=n>0?0:u-1;o>=0&&o<u;o+=n)if(t(r[o],o,r))return o;return-1}}var pr=sr(1),vr=sr(-1);function hr(n,r,t,e){for(var u=(t=Pn(t,e,1))(r),o=0,i=Y(n);o<i;){var a=Math.floor((o+i)/2);t(n[a])<u?o=a+1:i=a}return o}function yr(n,r,t){return function(e,u,o){var a=0,f=Y(e);if("number"==typeof o)n>0?a=o>=0?o:Math.max(o+f,a):f=o>=0?Math.min(o+1,f):o+f+1;else if(t&&o&&f)return e[o=t(e,u)]===u?o:-1;if(u!=u)return(o=r(i.call(e,a,f),$))>=0?o+a:-1;for(o=n>0?a:f-1;o>=0&&o<f;o+=n)if(e[o]===u)return o;return-1}}var dr=yr(1,pr,hr),gr=yr(-1,vr);function br(n,r,t){var e=(tr(n)?pr:lr)(n,r,t);if(void 0!==e&&-1!==e)return n[e]}function mr(n,r,t){var e,u;if(r=Rn(r,t),tr(n))for(e=0,u=n.length;e<u;e++)r(n[e],e,n);else{var o=nn(n);for(e=0,u=o.length;e<u;e++)r(n[o[e]],o[e],n)}return n}function jr(n,r,t){r=Pn(r,t);for(var e=!tr(n)&&nn(n),u=(e||n).length,o=Array(u),i=0;i<u;i++){var a=e?e[i]:i;o[i]=r(n[a],a,n)}return o}function _r(n){var r=function(r,t,e,u){var o=!tr(r)&&nn(r),i=(o||r).length,a=n>0?0:i-1;for(u||(e=r[o?o[a]:a],a+=n);a>=0&&a<i;a+=n){var f=o?o[a]:a;e=t(e,r[f],f,r)}return e};return function(n,t,e,u){var o=arguments.length>=3;return r(n,Rn(t,u,4),e,o)}}var wr=_r(1),Ar=_r(-1);function xr(n,r,t){var e=[];return r=Pn(r,t),mr(n,(function(n,t,u){r(n,t,u)&&e.push(n)})),e}function Sr(n,r,t){r=Pn(r,t);for(var e=!tr(n)&&nn(n),u=(e||n).length,o=0;o<u;o++){var i=e?e[o]:o;if(!r(n[i],i,n))return!1}return!0}function Or(n,r,t){r=Pn(r,t);for(var e=!tr(n)&&nn(n),u=(e||n).length,o=0;o<u;o++){var i=e?e[o]:o;if(r(n[i],i,n))return!0}return!1}function Mr(n,r,t,e){return tr(n)||(n=jn(n)),("number"!=typeof t||e)&&(t=0),dr(n,r,t)>=0}var Er=j((function(n,r,t){var e,u;return D(r)?u=r:(r=Bn(r),e=r.slice(0,-1),r=r[r.length-1]),jr(n,(function(n){var o=u;if(!o){if(e&&e.length&&(n=Nn(n,e)),null==n)return;o=n[r]}return null==o?o:o.apply(n,t)}))}));function Br(n,r){return jr(n,Dn(r))}function Nr(n,r,t){var e,u,o=-1/0,i=-1/0;if(null==r||"number"==typeof r&&"object"!=typeof n[0]&&null!=n)for(var a=0,f=(n=tr(n)?n:jn(n)).length;a<f;a++)null!=(e=n[a])&&e>o&&(o=e);else r=Pn(r,t),mr(n,(function(n,t,e){((u=r(n,t,e))>i||u===-1/0&&o===-1/0)&&(o=n,i=u)}));return o}var Ir=/[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;function Tr(n){return n?U(n)?i.call(n):S(n)?n.match(Ir):tr(n)?jr(n,Tn):jn(n):[]}function kr(n,r,t){if(null==r||t)return tr(n)||(n=jn(n)),n[Un(n.length-1)];var e=Tr(n),u=Y(e);r=Math.max(Math.min(r,u),0);for(var o=u-1,i=0;i<r;i++){var a=Un(i,o),f=e[i];e[i]=e[a],e[a]=f}return e.slice(0,r)}function Dr(n,r){return function(t,e,u){var o=r?[[],[]]:{};return e=Pn(e,u),mr(t,(function(r,u){var i=e(r,u,t);n(o,r,i)})),o}}var Rr=Dr((function(n,r,t){W(n,t)?n[t].push(r):n[t]=[r]})),Fr=Dr((function(n,r,t){n[t]=r})),Vr=Dr((function(n,r,t){W(n,t)?n[t]++:n[t]=1})),Pr=Dr((function(n,r,t){n[t?0:1].push(r)}),!0);function qr(n,r,t){return r in t}var Ur=j((function(n,r){var t={},e=r[0];if(null==n)return t;D(e)?(r.length>1&&(e=Rn(e,r[1])),r=an(n)):(e=qr,r=er(r,!1,!1),n=Object(n));for(var u=0,o=r.length;u<o;u++){var i=r[u],a=n[i];e(a,i,n)&&(t[i]=a)}return t})),Wr=j((function(n,r){var t,e=r[0];return D(e)?(e=ar(e),r.length>1&&(t=r[1])):(r=jr(er(r,!1,!1),String),e=function(n,t){return!Mr(r,t)}),Ur(n,e,t)}));function zr(n,r,t){return i.call(n,0,Math.max(0,n.length-(null==r||t?1:r)))}function Lr(n,r,t){return null==n||n.length<1?null==r||t?void 0:[]:null==r||t?n[0]:zr(n,n.length-r)}function $r(n,r,t){return i.call(n,null==r||t?1:r)}var Cr=j((function(n,r){return r=er(r,!0,!0),xr(n,(function(n){return!Mr(r,n)}))})),Kr=j((function(n,r){return Cr(n,r)}));function Jr(n,r,t,e){A(r)||(e=t,t=r,r=!1),null!=t&&(t=Pn(t,e));for(var u=[],o=[],i=0,a=Y(n);i<a;i++){var f=n[i],c=t?t(f,i,n):f;r&&!t?(i&&o===c||u.push(f),o=c):t?Mr(o,c)||(o.push(c),u.push(f)):Mr(u,f)||u.push(f)}return u}var Gr=j((function(n){return Jr(er(n,!0,!0))}));function Hr(n){for(var r=n&&Nr(n,Y).length||0,t=Array(r),e=0;e<r;e++)t[e]=Br(n,e);return t}var Qr=j(Hr);function Xr(n,r){return n._chain?tn(r).chain():r}function Yr(n){return mr(wn(n),(function(r){var t=tn[r]=n[r];tn.prototype[r]=function(){var n=[this._wrapped];return o.apply(n,arguments),Xr(this,t.apply(tn,n))}})),tn}mr(["pop","push","reverse","shift","sort","splice","unshift"],(function(n){var r=t[n];tn.prototype[n]=function(){var t=this._wrapped;return null!=t&&(r.apply(t,arguments),"shift"!==n&&"splice"!==n||0!==t.length||delete t[0]),Xr(this,t)}})),mr(["concat","join","slice"],(function(n){var r=t[n];tn.prototype[n]=function(){var n=this._wrapped;return null!=n&&(n=r.apply(n,arguments)),Xr(this,n)}}));var Zr=Yr({__proto__:null,VERSION:n,restArguments:j,isObject:_,isNull:function(n){return null===n},isUndefined:w,isBoolean:A,isElement:function(n){return!(!n||1!==n.nodeType)},isString:S,isNumber:O,isDate:M,isRegExp:E,isError:B,isSymbol:N,isArrayBuffer:I,isDataView:q,isArray:U,isFunction:D,isArguments:L,isFinite:function(n){return!N(n)&&d(n)&&!isNaN(parseFloat(n))},isNaN:$,isTypedArray:X,isEmpty:function(n){if(null==n)return!0;var r=Y(n);return"number"==typeof r&&(U(n)||S(n)||L(n))?0===r:0===Y(nn(n))},isMatch:rn,isEqual:function(n,r){return on(n,r)},isMap:dn,isWeakMap:gn,isSet:bn,isWeakSet:mn,keys:nn,allKeys:an,values:jn,pairs:function(n){for(var r=nn(n),t=r.length,e=Array(t),u=0;u<t;u++)e[u]=[r[u],n[r[u]]];return e},invert:_n,functions:wn,methods:wn,extend:xn,extendOwn:Sn,assign:Sn,defaults:On,create:function(n,r){var t=Mn(n);return r&&Sn(t,r),t},clone:function(n){return _(n)?U(n)?n.slice():xn({},n):n},tap:function(n,r){return r(n),n},get:In,has:function(n,r){for(var t=(r=Bn(r)).length,e=0;e<t;e++){var u=r[e];if(!W(n,u))return!1;n=n[u]}return!!t},mapObject:function(n,r,t){r=Pn(r,t);for(var e=nn(n),u=e.length,o={},i=0;i<u;i++){var a=e[i];o[a]=r(n[a],a,n)}return o},identity:Tn,constant:C,noop:qn,toPath:En,property:Dn,propertyOf:function(n){return null==n?qn:function(r){return In(n,r)}},matcher:kn,matches:kn,times:function(n,r,t){var e=Array(Math.max(0,n));r=Rn(r,t,1);for(var u=0;u<n;u++)e[u]=r(u);return e},random:Un,now:Wn,escape:$n,unescape:Cn,templateSettings:Kn,template:function(n,r,t){!r&&t&&(r=t),r=On({},r,tn.templateSettings);var e=RegExp([(r.escape||Jn).source,(r.interpolate||Jn).source,(r.evaluate||Jn).source].join("|")+"|$","g"),u=0,o="__p+='";n.replace(e,(function(r,t,e,i,a){return o+=n.slice(u,a).replace(Hn,Qn),u=a+r.length,t?o+="'+\n((__t=("+t+"))==null?'':_.escape(__t))+\n'":e?o+="'+\n((__t=("+e+"))==null?'':__t)+\n'":i&&(o+="';\n"+i+"\n__p+='"),r})),o+="';\n";var i,a=r.variable;if(a){if(!Xn.test(a))throw new Error("variable is not a bare identifier: "+a)}else o="with(obj||{}){\n"+o+"}\n",a="obj";o="var __t,__p='',__j=Array.prototype.join,"+"print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{i=new Function(a,"_",o)}catch(n){throw n.source=o,n}var f=function(n){return i.call(this,n,tn)};return f.source="function("+a+"){\n"+o+"}",f},result:function(n,r,t){var e=(r=Bn(r)).length;if(!e)return D(t)?t.call(n):t;for(var u=0;u<e;u++){var o=null==n?void 0:n[r[u]];void 0===o&&(o=t,u=e),n=D(o)?o.call(n):o}return n},uniqueId:function(n){var r=++Yn+"";return n?n+r:r},chain:function(n){var r=tn(n);return r._chain=!0,r},iteratee:Vn,partial:nr,bind:rr,bindAll:ur,memoize:function(n,r){var t=function(e){var u=t.cache,o=""+(r?r.apply(this,arguments):e);return W(u,o)||(u[o]=n.apply(this,arguments)),u[o]};return t.cache={},t},delay:or,defer:ir,throttle:function(n,r,t){var e,u,o,i,a=0;t||(t={});var f=function(){a=!1===t.leading?0:Wn(),e=null,i=n.apply(u,o),e||(u=o=null)},c=function(){var c=Wn();a||!1!==t.leading||(a=c);var l=r-(c-a);return u=this,o=arguments,l<=0||l>r?(e&&(clearTimeout(e),e=null),a=c,i=n.apply(u,o),e||(u=o=null)):e||!1===t.trailing||(e=setTimeout(f,l)),i};return c.cancel=function(){clearTimeout(e),a=0,e=u=o=null},c},debounce:function(n,r,t){var e,u,o,i,a,f=function(){var c=Wn()-u;r>c?e=setTimeout(f,r-c):(e=null,t||(i=n.apply(a,o)),e||(o=a=null))},c=j((function(c){return a=this,o=c,u=Wn(),e||(e=setTimeout(f,r),t&&(i=n.apply(a,o))),i}));return c.cancel=function(){clearTimeout(e),e=o=a=null},c},wrap:function(n,r){return nr(r,n)},negate:ar,compose:function(){var n=arguments,r=n.length-1;return function(){for(var t=r,e=n[r].apply(this,arguments);t--;)e=n[t].call(this,e);return e}},after:function(n,r){return function(){if(--n<1)return r.apply(this,arguments)}},before:fr,once:cr,findKey:lr,findIndex:pr,findLastIndex:vr,sortedIndex:hr,indexOf:dr,lastIndexOf:gr,find:br,detect:br,findWhere:function(n,r){return br(n,kn(r))},each:mr,forEach:mr,map:jr,collect:jr,reduce:wr,foldl:wr,inject:wr,reduceRight:Ar,foldr:Ar,filter:xr,select:xr,reject:function(n,r,t){return xr(n,ar(Pn(r)),t)},every:Sr,all:Sr,some:Or,any:Or,contains:Mr,includes:Mr,include:Mr,invoke:Er,pluck:Br,where:function(n,r){return xr(n,kn(r))},max:Nr,min:function(n,r,t){var e,u,o=1/0,i=1/0;if(null==r||"number"==typeof r&&"object"!=typeof n[0]&&null!=n)for(var a=0,f=(n=tr(n)?n:jn(n)).length;a<f;a++)null!=(e=n[a])&&e<o&&(o=e);else r=Pn(r,t),mr(n,(function(n,t,e){((u=r(n,t,e))<i||u===1/0&&o===1/0)&&(o=n,i=u)}));return o},shuffle:function(n){return kr(n,1/0)},sample:kr,sortBy:function(n,r,t){var e=0;return r=Pn(r,t),Br(jr(n,(function(n,t,u){return{value:n,index:e++,criteria:r(n,t,u)}})).sort((function(n,r){var t=n.criteria,e=r.criteria;if(t!==e){if(t>e||void 0===t)return 1;if(t<e||void 0===e)return-1}return n.index-r.index})),"value")},groupBy:Rr,indexBy:Fr,countBy:Vr,partition:Pr,toArray:Tr,size:function(n){return null==n?0:tr(n)?n.length:nn(n).length},pick:Ur,omit:Wr,first:Lr,head:Lr,take:Lr,initial:zr,last:function(n,r,t){return null==n||n.length<1?null==r||t?void 0:[]:null==r||t?n[n.length-1]:$r(n,Math.max(0,n.length-r))},rest:$r,tail:$r,drop:$r,compact:function(n){return xr(n,Boolean)},flatten:function(n,r){return er(n,r,!1)},without:Kr,uniq:Jr,unique:Jr,union:Gr,intersection:function(n){for(var r=[],t=arguments.length,e=0,u=Y(n);e<u;e++){var o=n[e];if(!Mr(r,o)){var i;for(i=1;i<t&&Mr(arguments[i],o);i++);i===t&&r.push(o)}}return r},difference:Cr,unzip:Hr,transpose:Hr,zip:Qr,object:function(n,r){for(var t={},e=0,u=Y(n);e<u;e++)r?t[n[e]]=r[e]:t[n[e][0]]=n[e][1];return t},range:function(n,r,t){null==r&&(r=n||0,n=0),t||(t=r<n?-1:1);for(var e=Math.max(Math.ceil((r-n)/t),0),u=Array(e),o=0;o<e;o++,n+=t)u[o]=n;return u},chunk:function(n,r){if(null==r||r<1)return[];for(var t=[],e=0,u=n.length;e<u;)t.push(i.call(n,e,e+=r));return t},mixin:Yr,default:tn});return Zr._=Zr,Zr}));
 function Tooltip($tooltipLink) {
    var self = this;

    self.$tooltipLink = $tooltipLink;
    self.tooltipBubbleId = self.$tooltipLink.attr("aria-describedby");
    self.$tooltipBubble = $("#" + self.tooltipBubbleId);
    self.attachEvents();
}

Tooltip.prototype.attachEvents = function () {
    var self = this;

    self.$tooltipLink.on("click", function (e) {
        e.preventDefault();
        e.stopPropagation();
        self.openTooltipBubble();
    });

    self.$tooltipLink.on("focus", function() {
        self.openTooltipBubble();
    });

    self.$tooltipLink.on("blur", function() {
        self.closeTooltipBubble();
    });

    $(window).resize(function() {
        self.closeTooltipBubble();
    });

    window.onhashchange = function() {
        self.closeTooltipBubble();
    }
}

Tooltip.prototype.openTooltipBubble = function () {
    var self = this;
    if (!self.$tooltipBubble.hasClass("hideme"))
        return;

    self.closeAllOtherTooltipBubbles();
    self.$tooltipBubble.removeClass("hideme");
    self.$tooltipBubble.css("opacity", 0);
    self.resetTooltipBubblePosition();

    if ($(window).width() < self.$tooltipBubble.outerWidth() * 1.5)
        self.$tooltipBubble.css("max-width", $(window).width() / 1.5);
    else
        self.$tooltipBubble.css("max-width", 450);

    var posLeft = self.$tooltipLink.offset().left + (self.$tooltipLink.outerWidth() / 2) - (self.$tooltipBubble.outerWidth() / 2),
        posTop = self.$tooltipLink.offset().top + 15;

    if (posLeft < 0) {
        posLeft = self.$tooltipLink.offset().left + self.$tooltipLink.outerWidth() / 2 - 20;
        self.$tooltipBubble.addClass("left");
    }
    else
        self.$tooltipBubble.removeClass("left");

    if (posLeft + self.$tooltipBubble.outerWidth() > $(window).width()) {
        posLeft = self.$tooltipLink.offset().left - self.$tooltipBubble.outerWidth() + self.$tooltipLink.outerWidth() / 2 + 20;
        self.$tooltipBubble.addClass("right");
    }
    else
        self.$tooltipBubble.removeClass("right");

    if (posTop < 0) {
        posTop = self.$tooltipLink.offset().top + self.$tooltipLink.outerHeight();
        self.$tooltipBubble.addClass("top");
    }
    else
        self.$tooltipBubble.removeClass("top");

    self.$tooltipBubble
        .css({ left: posLeft, top: posTop })
        .animate({ top: "+=10", opacity: 1 }, 50, function() {
            $("body").one("click.tooltipNamespace touchend.tooltipNamespace", function() { self.closeTooltipBubble(); });
        });
}

Tooltip.prototype.resetTooltipBubblePosition = function () {
    this.$tooltipBubble.css("max-width", "");
    this.$tooltipBubble.css("left", "");
    this.$tooltipBubble.css("top", "");
    this.$tooltipBubble.removeClass("left");
    this.$tooltipBubble.removeClass("right");
    this.$tooltipBubble.removeClass("top");
    this.$tooltipBubble.appendTo("body");
}

Tooltip.prototype.closeSpecificTooltipBubbles = function ($tooltipBubbles) {
    $.each($tooltipBubbles,
        function () {
            if ($(this).hasClass("hideme"))
                return;

            $(this).animate({ top: "-=10", opacity: 0 },
                function () {
                    $(this).addClass("hideme");
                });
        });
}

Tooltip.prototype.closeAllOtherTooltipBubbles = function () {
    var self = this;
    self.closeSpecificTooltipBubbles($(".tooltip-bubble:not(#" + self.tooltipBubbleId + ")"));
}

Tooltip.prototype.closeTooltipBubble = function () {
    var self = this;
    self.closeSpecificTooltipBubbles(self.$tooltipBubble);
    $("body").unbind(".tooltipNamespace");
}

$(function () {
    var targets = $("a.tooltip-link");

    $.each(targets, function () {
        var tooltip = new Tooltip($(this));
    });
});
function formatBytes(a, b) { if (0 == a) return "0 Bytes"; var c = 1024, d = b || 2, e = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"], f = Math.floor(Math.log(a) / Math.log(c)); return parseFloat((a / Math.pow(c, f)).toFixed(d)) + " " + e[f] }

/**
 * Tiny Autocomplete
 * Small and fast autocomplete plugin for Zepto and jQuery.
 * Written by Johan Halse, https://twitter.com/hejsna, johan@varvet.se
 * Contributions by Juha Tauriainen, https://github.com/JuhQ and
 * Phoebe Bright, https://github.com/phoebebright
 * License: http://johanhalse.mit-license.org
 * @version 1.0.0
 * @return {object}         Self
 */

var factory = function ($, window) {
    var TinyAutocomplete = function (el, options) {
        var that = this; // This is just to minify better
        that.field = $(el);
        that.el = null;
        that.json = null;
        that.items = [];
        that.selectedItem = null;
        that.list = $('<ul class="autocomplete-list" />');
        that.lastSearch = null;
        that.options = options;
        that.lastXhr = null;
    };

    TinyAutocomplete.prototype = {
        defaults: {
            minChars: 2,
            markAsBold: true,
            grouped: false,
            queryProperty: "q",
            queryParameters: {},
            method: "get",
            scrollOnFocus: "auto",
            maxItems: 100,
            maxItemsOnMobile: 3,
            mobileWidth: 700,
            keyboardDelay: 300,
            lastItemTemplate: null,
            closeOnSelect: true,
            groupContentName: ".autocomplete-items",
            groupTemplate:
                '<li class="autocomplete-group"><span class="autocomplete-group-header">{{title}}</span><ul class="autocomplete-items" /></li>',
            itemTemplate: '<li class="autocomplete-item">{{title}}</li>',
            showNoResults: false,
            noResultsTemplate:
                '<li class="autocomplete-item">No results for {{title}}</li>',
            wrapClasses: "autocomplete",
            enabled: true,
            excludedFieldNamesFromMarkHit: []
        },

        /**
         * Constructor
         * @return {null}
         */
        init: function () {
            this.defaults.templateMethod = this.template;
            this.settings = $.extend({}, this.defaults, this.options);
            this.setupSettings();
            this.setupMarkup();
            this.setupEvents();

            return this;
        },

        /**
         * Micro-templating utility
         * @param  {string} template Template string with mustache-style curly braces
         * @param  {object} vars     Contains values to interpolate with
         * @return {string}          Interpolated string
         */
        template: function (template, vars) {
            return template.replace(/{{\s*[\w]+\s*}}/g, function (v) {
                return vars[v.substr(2, v.length - 4)];
            });
        },

        /**
         * Debounce function from http://davidwalsh.name/javascript-debounce-function
         * @param  {function} func       function to execute
         * @param  {number}   wait       delay in milliseconds
         * @param  {boolean}  immediate  whether to fire on trailing or leading
         * @return {function}            debounced function
         */
        debounce: function (func, wait, immediate) {
            var timeout;
            return function () {
                var context = this,
                    args = arguments;
                var later = function () {
                    timeout = null;
                    if (!immediate) func.apply(context, args);
                };
                var callNow = immediate && !timeout;
                clearTimeout(timeout);
                timeout = setTimeout(later, wait);
                if (callNow) func.apply(context, args);
            };
        },

        /**
         * Tweak settings a bit, since we don't have any private functions
         * defined at constructor time.
         * @return {null}
         */
        setupSettings: function () {
            if (this.settings.scrollOnFocus == "auto") {
                this.settings.scrollOnFocus = this.isTouchDevice();
            }

            // We might be on a mobile device and have little in the way of
            // vertical real estate to work with. Cap it! This check needs a
            // bit more intelligence to it.
            this.settings.maxItemsOnLarge = this.settings.maxItems;
            if (
                window.innerWidth < this.settings.mobileWidth &&
                this.settings.maxItemsOnMobile !== null
            ) {
                this.settings.maxItems = Math.min(
                    this.settings.maxItems,
                    this.settings.maxItemsOnMobile
                );
            }

            // Using local data or remote url?
            if (this.settings.data) {
                this.request = this.localRequest;
            } else {
                this.request = this.remoteRequest;
            }

            // Set the keyboard delay before search fires
            if (this.settings.keyboardDelay != null) {
                this.request = this.debounce(this.request, this.settings.keyboardDelay);
            }
        },

        /**
         * Register initial callbacks
         * @return {null}
         */
        setupEvents: function () {
            this.el.on("keyup", ".autocomplete-field", $.proxy(this.onKeyUp, this));
            this.el.on(
                "keydown",
                ".autocomplete-field",
                $.proxy(this.onKeyDown, this)
            );
            this.el.on(
                "mousedown",
                ".autocomplete-item",
                $.proxy(this.onClickItem, this)
            );

            this.el.on("blur", ".autocomplete-field", $.proxy(this.closeList, this));
            var self = this;
            // Update maxItems when window size change
            $(window).resize(
                this.debounce(function () {
                    if (
                        window.innerWidth < self.settings.mobileWidth &&
                        self.settings.maxItemsOnMobile !== null
                    ) {
                        self.settings.maxItems = Math.min(
                            self.settings.maxItems,
                            self.settings.maxItemsOnMobile
                        );
                    } else {
                        self.settings.maxItems = self.settings.maxItemsOnLarge;
                    }
                }, 250)
            );

            // Scroll to field if we're on a small device, we need that
            // screen real estate!
            if (this.settings.scrollOnFocus) {
                this.field.on("focus", function () {
                    var h = $(this).offset().top;
                    setTimeout(function () {
                        window.scrollTo(0, h);
                    }, 0);
                });
            }
        },

        /**
         * Wrap field in required markup and set up this.el
         * @return {null}
         */
        setupMarkup: function () {
            this.field.addClass("autocomplete-field");
            this.field.attr("autocomplete", "off");
            this.field.wrap('<div class="' + this.settings.wrapClasses + '" />');
            this.el = this.field.parent();
        },

        /**
         * Fire request to specified url
         * @param  {string} val Value to search for
         * @return {null}
         */
        remoteRequest: function (val) {
            var self = this;
            
            if (!self.settings.enabled)
                return;

            if (self.lastXhr !== null) {
                self.lastXhr.abort();
            }

            this.field.trigger("beforerequest", [this, val]);
            var data = {};
            $.extend(data, this.settings.queryParameters);
            data[this.settings.queryProperty] = val;

            self.lastXhr = $.ajax({
                method: this.settings.method,
                url: this.settings.url,
                dataType: "json",
                data: data,
                success: $.proxy(this.beforeReceiveData, this),
                error: function () { self.field.trigger("requestfailed", [this, val]);}
            });
        },

        /**
         * Match request in local data instead of remote url
         * @param  {string} val Value to search for
         * @return {null}
         */
        localRequest: function (val) {
            if (this.settings.grouped) {
                this.beforeReceiveData(this.matchLocalPatternGrouped(val));
            } else {
                this.beforeReceiveData(this.matchLocalPatternFlat(val));
            }
        },

        /**
         * Match the data in a flat array and return the objects where a
         * hit was found.
         * @param  {string} val Value to search for
         * @return {array}      Array of hits
         */
        matchLocalPatternFlat: function (val) {
            return this.matchArray(val, this.settings.data);
        },

        /**
         * Match the data in a grouped array and return the objects where a
         * hit was found, in the same manner
         * @param  {string} val Value to search for
         * @return {array}      Array of hits
         */
        matchLocalPatternGrouped: function (val) {
            var r = $.extend(true, [], this.settings.data);

            for (var i = 0; i < r.length; i++) {
                var a = this.matchArray(val, r[i].data);
                if (a.length == 0) {
                    r.splice(i, 1);
                    i--;
                } else {
                    r[i].data = a;
                }
            }

            return r;
        },

        /**
         * Return an array of matched values from a source array
         * @param  {string} val String to search for
         * @param  {array} arr  Array to search in
         * @return {array}      Matched array
         */
        matchArray: function (val, arr) {
            var r = [];
            for (var i = 0; i < arr.length; i++) {
                for (var j in arr[i]) {
                    if (
                        (arr[i][j].toLowerCase &&
                            arr[i][j].toLowerCase().indexOf(val.toLowerCase()) > -1) ||
                        arr[i][j] == val
                    ) {
                        r.push(arr[i]);
                        break;
                    }
                }
            }

            return r;
        },

        /**
         * Find DOM object at specified index
         * @param  {number} i Index
         * @return {object}   DOM object
         */
        itemAt: function (i) {
            if (i == null) {
                return $();
            }

            return this.el.find(".autocomplete-item").eq(i);
        },

        /**
         * Find item number for clicked item
         * @param  {object} o The clicked object
         * @return {number}   Item's id in array
         */
        clickedItemAt: function (o) {
            for (var i = 0; i < this.items.length; i++) {
                if (
                    o ==
                    this.el
                        .find(".autocomplete-item")
                        .eq(i)
                        .get(0)
                ) {
                    return i;
                }
            }
            return null;
        },

        /**
         * Select previous item
         * @return {null}
         */
        prevItem: function () {
            this.selectedItem--;
            if (this.selectedItem < 0) {
                this.selectedItem = null;
            }

            this.markSelected(this.selectedItem);
        },

        /**
         * Select next item
         * @return {null}
         */
        nextItem: function () {
            if (this.selectedItem == null) {
                this.selectedItem = -1;
            }
            this.selectedItem++;

            var l = this.settings.lastItemTemplate
                ? this.items.length
                : this.items.length - 1;
            if (this.selectedItem >= l) {
                this.selectedItem = l;
            }

            this.markSelected(this.selectedItem);
        },

        /**
         * Mark an item as selected
         * @param  {number} i Item's id in items array
         * @return {null}
         */
        markSelected: function (i) {
            this.el.find(".active").removeClass("active");
            this.itemAt(i).addClass("active");
        },

        /**
         * Iterate through data, adding <strong> tags for every hit.
         * Splits strings into words using whitespace and matches each
         * word separately.
         * @param  {object} v   Data to operate on
         * @param  {string} str String to search for
         * @return {object}     Processed data object
         */
        markHitText: function (v, str) {
            var words = str.split(" ");
            for (var i in v) {
                if (typeof v[i] == "string" && i != "template" && this.settings.excludedFieldNamesFromMarkHit.indexOf(i) === -1) {
                    var replacements = [str];
                    for (var j = 0; j < words.length; j++) {
                        var word = words[j].trim().replace(/[^a-ö0-9]/gi, ""); // Remove non-alphanumerics
                        if (word.length > 0) {
                            replacements.push(word);
                        }
                    }
                    v[i] = v[i].replace(
                        new RegExp("(" + replacements.join("|") + ")", "gi"),
                        "<strong>$1</strong>"
                    );
                }
            }
            return v;
        },

        /**
         * Render groups. This must be done before calling
         * renderItemsInGroups, since it resets the list markup and
         * attaches a new this.list object.
         * @return {null}
         */
        renderGroups: function () {
            this.list.remove();
            this.list = $('<ul class="autocomplete-list" />');
            for (var i in this.json) {
                this.list.append(
                    this.settings.templateMethod(
                        this.settings.groupTemplate,
                        this.json[i]
                    )
                );
            }

            this.el.append(this.list);
        },

        /**
         * Iterates through items and attaches them to their respective
         * groups.
         * @return {null}
         */
        renderItemsInGroups: function () {
            var v = this.field.val();
            for (var i = 0; i < this.json.length; i++) {
                var group = this.el.find(this.settings.groupContentName).eq(i);
                for (
                    var j = 0;
                    j < this.json[i].data.length && j < this.settings.maxItems;
                    j++
                ) {
                    var jsonData = $.extend({}, this.json[i].data[j]);
                    // Strongify hits
                    if (this.settings.markAsBold) {
                        jsonData = this.markHitText(jsonData, v);
                    }
                    group.append(
                        this.settings.templateMethod(
                            this.json[i].template || this.settings.itemTemplate,
                            jsonData
                        )
                    );
                }
            }
        },

        /**
         * If we're not dealing with groups, just attach items to the list.
         * @return {null}
         */
        renderItemsFlat: function () {
            this.list.remove();

            if (this.json.length === 0)
                return;

            this.list = $('<ul class="autocomplete-list" />');
            var v = this.field.val();
            for (var i = 0; i < this.json.length && i < this.settings.maxItems; i++) {
                var jsonData = $.extend({}, this.json[i]);
                // Strongify hits
                if (this.settings.markAsBold) {
                    jsonData = this.markHitText(jsonData, v);
                }
                this.list.append(
                    this.settings.templateMethod(
                        this.json[i].template || this.settings.itemTemplate,
                        jsonData
                    )
                );
            }
            this.el.append(this.list);
        },

        /**
         * If there's a last "find all results for..." item, this function
         * gets called.
         * @return {null}
         */
        renderLastItem: function () {
            this.list.append(
                this.settings.templateMethod(this.settings.lastItemTemplate, {
                    title: this.field.val()
                })
            );
        },

        /**
         * If there's a "no results found for..." item, this function
         * gets called.
         * @return {null}
         */
        renderNoResults: function () {
            this.list.append(
                this.settings.templateMethod(this.settings.noResultsTemplate, {
                    title: this.field.val()
                })
            );
        },

        /**
         * Removes list from DOM and resets state.
         * @return {null}
         */
        closeList: function () {
            $("html").off("click");
            this.list.remove();
            this.selectedItem = null;
        },

        /**
         * Since groups aren't selectable, we need to fetch the actual
         * selectable items and keep them around in our this.items list.
         * @return {array} List of selectable items
         */
        getItemsFromGroups: function () {
            var r = [];
            for (var i in this.json) {
                for (var j = 0; j < this.json[i].data.length; j++) {
                    if (j < this.settings.maxItems) {
                        r.push(this.json[i].data[j]);
                    }
                }
            }

            return r;
        },

        /**
         * Check whether a value has changed. Used to determine whether or
         * not we fire a new request, since all keypresses generate an
         * event.
         * @return {boolean} True if value has changed since last request
         */
        valueHasChanged: function () {
            if (this.field.val() != this.lastSearch) {
                this.lastSearch = this.field.val();
                return true;
            }
            return false;
        },

        /**
         * A naive implementation of touch detection. In this day and age
         * with Microsoft Surfaces and whatnot, this should probably be
         * replaced with something more intelligent. But let's do that when
         * we find the time.
         * @return {boolean} Whether or not this is a touch device
         */
        isTouchDevice: function () {
            return !!("ontouchstart" in window);
        },

        /**
         * This is mostly an opportunity to hook into the data served by
         * server to do your own thing
         * @param  {object} data JSON from server
         * @param  {object} xhr  XHR object
         * @return {null}
         */
        beforeReceiveData: function (data, xhr) {
            this.json = data;
            this.field.trigger("receivedata", [this, data, xhr]);
            this.onReceiveData(this.json);
        },

        /**
         * Data received from server, determine what to do with it and
         * render everything.
         * @param  {object} data JSON from server
         * @return {null}
         */
        onReceiveData: function (data) {
            this.selectedItem = null;
            if (this.settings.grouped) {
                // First, render groups
                this.renderGroups();

                // Then, render the selectable items
                this.items = this.getItemsFromGroups();
                this.renderItemsInGroups();
            } else {
                this.items = this.json;
                this.renderItemsFlat();
            }

            // If no results, render no results message, if applicable
            if (!this.items.length) {
                if (this.settings.showNoResults) {
                    this.renderNoResults();
                }
            }

            // Render last item, if applicable
            if (this.settings.lastItemTemplate) {
                this.renderLastItem();
            }

            // Click outside should close the list
            $("html").one("click", $.proxy(this.closeList, this));
        },

        /**
         * Keyup handler. If value has changed and contains min number of chars,
         * fire the (debounced) request.
         * @param  {object} e Normalized Event object
         * @return {null}
         */
        onKeyUp: function (e) {
            if (
                this.field.val().length >= this.settings.minChars &&
                this.valueHasChanged()
            ) {
                this.request(this.field.val());
            }
            if (this.field.val() == "") {
                this.lastSearch = "";
                this.closeList();
            }
        },

        /**
         * Keydown handler to take care of keyboard navigation.
         * @param  {object} e Normalized event object
         * @return {null}
         */
        onKeyDown: function (e) {
            if (e.keyCode == 38) {
                // Up
                e.preventDefault();
                this.prevItem();
            }
            if (e.keyCode == 40) {
                // Down
                e.preventDefault();
                this.nextItem();
            }
            if (e.keyCode == 13) {
                // Enter
                this.onPressEnter(e);
            }
            if (e.keyCode == 27) {
                // Esc
                e.preventDefault();
                this.closeList();
            }
        },

        /**
         * Click handler, handle mouse/touch selection of items.
         * @param  {object} e Normalized event object
         * @return {null}
         */
        onClickItem: function (e) {
            var i = this.clickedItemAt(e.currentTarget);
            this.onSelect(e.currentTarget, this.items[i]);
        },

        /**
         * User has pressed enter, select object or perform search.
         * @return {null}
         */
        onPressEnter: function (e) {
            // If field is filled in but no item is selected, we don't block
            // submit
            if (this.selectedItem === null) {
                return true;
            }

            e.preventDefault();
            this.onSelect(
                this.itemAt(this.selectedItem),
                this.items[this.selectedItem]
            );
        },

        /**
         * User has selected an object with mouse or keyboard - act on it
         * and fire any user-supplied callback.
         * @param  {object} item DOM object for the field
         * @param  {object} val  Item value from server
         * @return {null}
         */
        onSelect: function (item, val) {
            if (this.settings.onSelect) {
                this.settings.onSelect.apply(this.field, [item, val]);
            }
            this.lastSearch = this.field.val();
            if (this.settings.closeOnSelect) {
                this.closeList();
            }
        }
    };

    TinyAutocomplete.defaults = TinyAutocomplete.prototype.defaults;

    $.fn.tinyAutocomplete = function (settings) {
        return this.each(function () {
            if (this.tinyAutocomplete) {
                // Prevent TinyAutocomplete from creating a new object. Instead,
                // just update the settings object
                $.extend(this.tinyAutocomplete.settings, settings);
                return this;
            }

            var d = new TinyAutocomplete(this, settings).init();

            // Expose "tinyAutocomplete.settings" to the cold outside
            this.tinyAutocomplete = { settings: d.settings };
        });
    };
};

if (typeof exports !== "undefined") {
    module.exports = factory;
} else {
    factory($, window);
}
/* Font Face Observer v2.0.13 - © Bram Stein. License: BSD-3-Clause */(function(){'use strict';var f,g=[];function l(a){g.push(a);1==g.length&&f()}function m(){for(;g.length;)g[0](),g.shift()}f=function(){setTimeout(m)};function n(a){this.a=p;this.b=void 0;this.f=[];var b=this;try{a(function(a){q(b,a)},function(a){r(b,a)})}catch(c){r(b,c)}}var p=2;function t(a){return new n(function(b,c){c(a)})}function u(a){return new n(function(b){b(a)})}function q(a,b){if(a.a==p){if(b==a)throw new TypeError;var c=!1;try{var d=b&&b.then;if(null!=b&&"object"==typeof b&&"function"==typeof d){d.call(b,function(b){c||q(a,b);c=!0},function(b){c||r(a,b);c=!0});return}}catch(e){c||r(a,e);return}a.a=0;a.b=b;v(a)}}
function r(a,b){if(a.a==p){if(b==a)throw new TypeError;a.a=1;a.b=b;v(a)}}function v(a){l(function(){if(a.a!=p)for(;a.f.length;){var b=a.f.shift(),c=b[0],d=b[1],e=b[2],b=b[3];try{0==a.a?"function"==typeof c?e(c.call(void 0,a.b)):e(a.b):1==a.a&&("function"==typeof d?e(d.call(void 0,a.b)):b(a.b))}catch(h){b(h)}}})}n.prototype.g=function(a){return this.c(void 0,a)};n.prototype.c=function(a,b){var c=this;return new n(function(d,e){c.f.push([a,b,d,e]);v(c)})};
function w(a){return new n(function(b,c){function d(c){return function(d){h[c]=d;e+=1;e==a.length&&b(h)}}var e=0,h=[];0==a.length&&b(h);for(var k=0;k<a.length;k+=1)u(a[k]).c(d(k),c)})}function x(a){return new n(function(b,c){for(var d=0;d<a.length;d+=1)u(a[d]).c(b,c)})};window.Promise||(window.Promise=n,window.Promise.resolve=u,window.Promise.reject=t,window.Promise.race=x,window.Promise.all=w,window.Promise.prototype.then=n.prototype.c,window.Promise.prototype["catch"]=n.prototype.g);}());

(function(){function l(a,b){document.addEventListener?a.addEventListener("scroll",b,!1):a.attachEvent("scroll",b)}function m(a){document.body?a():document.addEventListener?document.addEventListener("DOMContentLoaded",function c(){document.removeEventListener("DOMContentLoaded",c);a()}):document.attachEvent("onreadystatechange",function k(){if("interactive"==document.readyState||"complete"==document.readyState)document.detachEvent("onreadystatechange",k),a()})};function r(a){this.a=document.createElement("div");this.a.setAttribute("aria-hidden","true");this.a.appendChild(document.createTextNode(a));this.b=document.createElement("span");this.c=document.createElement("span");this.h=document.createElement("span");this.f=document.createElement("span");this.g=-1;this.b.style.cssText="max-width:none;display:inline-block;position:absolute;height:100%;width:100%;overflow:scroll;font-size:16px;";this.c.style.cssText="max-width:none;display:inline-block;position:absolute;height:100%;width:100%;overflow:scroll;font-size:16px;";
this.f.style.cssText="max-width:none;display:inline-block;position:absolute;height:100%;width:100%;overflow:scroll;font-size:16px;";this.h.style.cssText="display:inline-block;width:200%;height:200%;font-size:16px;max-width:none;";this.b.appendChild(this.h);this.c.appendChild(this.f);this.a.appendChild(this.b);this.a.appendChild(this.c)}
function t(a,b){a.a.style.cssText="max-width:none;min-width:20px;min-height:20px;display:inline-block;overflow:hidden;position:absolute;width:auto;margin:0;padding:0;top:-999px;white-space:nowrap;font-synthesis:none;font:"+b+";"}function y(a){var b=a.a.offsetWidth,c=b+100;a.f.style.width=c+"px";a.c.scrollLeft=c;a.b.scrollLeft=a.b.scrollWidth+100;return a.g!==b?(a.g=b,!0):!1}function z(a,b){function c(){var a=k;y(a)&&a.a.parentNode&&b(a.g)}var k=a;l(a.b,c);l(a.c,c);y(a)};function A(a,b){var c=b||{};this.family=a;this.style=c.style||"normal";this.weight=c.weight||"normal";this.stretch=c.stretch||"normal"}var B=null,C=null,E=null,F=null;function G(){if(null===C)if(J()&&/Apple/.test(window.navigator.vendor)){var a=/AppleWebKit\/([0-9]+)(?:\.([0-9]+))(?:\.([0-9]+))/.exec(window.navigator.userAgent);C=!!a&&603>parseInt(a[1],10)}else C=!1;return C}function J(){null===F&&(F=!!document.fonts);return F}
function K(){if(null===E){var a=document.createElement("div");try{a.style.font="condensed 100px sans-serif"}catch(b){}E=""!==a.style.font}return E}function L(a,b){return[a.style,a.weight,K()?a.stretch:"","100px",b].join(" ")}
A.prototype.load=function(a,b){var c=this,k=a||"BESbswy",q=0,D=b||3E3,H=(new Date).getTime();return new Promise(function(a,b){if(J()&&!G()){var M=new Promise(function(a,b){function e(){(new Date).getTime()-H>=D?b():document.fonts.load(L(c,'"'+c.family+'"'),k).then(function(c){1<=c.length?a():setTimeout(e,25)},function(){b()})}e()}),N=new Promise(function(a,c){q=setTimeout(c,D)});Promise.race([N,M]).then(function(){clearTimeout(q);a(c)},function(){b(c)})}else m(function(){function u(){var b;if(b=-1!=
f&&-1!=g||-1!=f&&-1!=h||-1!=g&&-1!=h)(b=f!=g&&f!=h&&g!=h)||(null===B&&(b=/AppleWebKit\/([0-9]+)(?:\.([0-9]+))/.exec(window.navigator.userAgent),B=!!b&&(536>parseInt(b[1],10)||536===parseInt(b[1],10)&&11>=parseInt(b[2],10))),b=B&&(f==v&&g==v&&h==v||f==w&&g==w&&h==w||f==x&&g==x&&h==x)),b=!b;b&&(d.parentNode&&d.parentNode.removeChild(d),clearTimeout(q),a(c))}function I(){if((new Date).getTime()-H>=D)d.parentNode&&d.parentNode.removeChild(d),b(c);else{var a=document.hidden;if(!0===a||void 0===a)f=e.a.offsetWidth,
g=n.a.offsetWidth,h=p.a.offsetWidth,u();q=setTimeout(I,50)}}var e=new r(k),n=new r(k),p=new r(k),f=-1,g=-1,h=-1,v=-1,w=-1,x=-1,d=document.createElement("div");d.dir="ltr";t(e,L(c,"sans-serif"));t(n,L(c,"serif"));t(p,L(c,"monospace"));d.appendChild(e.a);d.appendChild(n.a);d.appendChild(p.a);document.body.appendChild(d);v=e.a.offsetWidth;w=n.a.offsetWidth;x=p.a.offsetWidth;I();z(e,function(a){f=a;u()});t(e,L(c,'"'+c.family+'",sans-serif'));z(n,function(a){g=a;u()});t(n,L(c,'"'+c.family+'",serif'));
z(p,function(a){h=a;u()});t(p,L(c,'"'+c.family+'",monospace'))})})};"object"===typeof module?module.exports=A:(window.FontFaceObserver=A,window.FontFaceObserver.prototype.load=A.prototype.load);}());

/*! @vimeo/player v2.15.0 | (c) 2021 Vimeo | MIT License | https://github.com/vimeo/player.js */
!function (e, t) { "object" == typeof exports && "undefined" != typeof module ? module.exports = t() : "function" == typeof define && define.amd ? define(t) : ((e = "undefined" != typeof globalThis ? globalThis : e || self).Vimeo = e.Vimeo || {}, e.Vimeo.Player = t()) }(this, function () { "use strict"; function r(e, t) { for (var n = 0; n < t.length; n++) { var r = t[n]; r.enumerable = r.enumerable || !1, r.configurable = !0, "value" in r && (r.writable = !0), Object.defineProperty(e, r.key, r) } } var e = "undefined" != typeof global && "[object global]" === {}.toString.call(global); function i(e, t) { return 0 === e.indexOf(t.toLowerCase()) ? e : "".concat(t.toLowerCase()).concat(e.substr(0, 1).toUpperCase()).concat(e.substr(1)) } function l(e) { return /^(https?:)?\/\/((player|www)\.)?vimeo\.com(?=$|\/)/.test(e) } function s(e) { var t, n = 0 < arguments.length && void 0 !== e ? e : {}, r = n.id, o = n.url, i = r || o; if (!i) throw new Error("An id or url must be passed, either in an options object or as a data-vimeo-id or data-vimeo-url attribute."); if (t = i, !isNaN(parseFloat(t)) && isFinite(t) && Math.floor(t) == t) return "https://vimeo.com/".concat(i); if (l(i)) return i.replace("http:", "https:"); if (r) throw new TypeError("“".concat(r, "” is not a valid video id.")); throw new TypeError("“".concat(i, "” is not a vimeo.com url.")) } var t = void 0 !== Array.prototype.indexOf, n = "undefined" != typeof window && void 0 !== window.postMessage; if (!(e || t && n)) throw new Error("Sorry, the Vimeo Player API is not available in this browser."); var o, a, u, c = "undefined" != typeof globalThis ? globalThis : "undefined" != typeof window ? window : "undefined" != typeof global ? global : "undefined" != typeof self ? self : {}; function f() { if (void 0 === this) throw new TypeError("Constructor WeakMap requires 'new'"); if (u(this, "_id", "_WeakMap_" + h() + "." + h()), 0 < arguments.length) throw new TypeError("WeakMap iterable is not supported") } function d(e, t) { if (!v(e) || !a.call(e, "_id")) throw new TypeError(t + " method called on incompatible receiver " + typeof e) } function h() { return Math.random().toString().substring(2) } function v(e) { return Object(e) === e } (o = "undefined" != typeof self ? self : "undefined" != typeof window ? window : c).WeakMap || (a = Object.prototype.hasOwnProperty, u = function (e, t, n) { Object.defineProperty ? Object.defineProperty(e, t, { configurable: !0, writable: !0, value: n }) : e[t] = n }, o.WeakMap = (u(f.prototype, "delete", function (e) { if (d(this, "delete"), !v(e)) return !1; var t = e[this._id]; return !(!t || t[0] !== e) && (delete e[this._id], !0) }), u(f.prototype, "get", function (e) { if (d(this, "get"), v(e)) { var t = e[this._id]; return t && t[0] === e ? t[1] : void 0 } }), u(f.prototype, "has", function (e) { if (d(this, "has"), !v(e)) return !1; var t = e[this._id]; return !(!t || t[0] !== e) }), u(f.prototype, "set", function (e, t) { if (d(this, "set"), !v(e)) throw new TypeError("Invalid value used as weak map key"); var n = e[this._id]; return n && n[0] === e ? n[1] = t : u(e, this._id, [e, t]), this }), u(f, "_polyfill", !0), f)); var m, p = (function (e) { var t, n, r; r = function () { var t, n, r, o, i, a, e = Object.prototype.toString, u = "undefined" != typeof setImmediate ? function (e) { return setImmediate(e) } : setTimeout; try { Object.defineProperty({}, "x", {}), t = function (e, t, n, r) { return Object.defineProperty(e, t, { value: n, writable: !0, configurable: !1 !== r }) } } catch (e) { t = function (e, t, n) { return e[t] = n, e } } function c(e, t) { this.fn = e, this.self = t, this.next = void 0 } function l(e, t) { r.add(e, t), n = n || u(r.drain) } function s(e) { var t, n = typeof e; return null == e || "object" != n && "function" != n || (t = e.then), "function" == typeof t && t } function f() { for (var e = 0; e < this.chain.length; e++)!function (e, t, n) { var r, o; try { !1 === t ? n.reject(e.msg) : (r = !0 === t ? e.msg : t.call(void 0, e.msg)) === n.promise ? n.reject(TypeError("Promise-chain cycle")) : (o = s(r)) ? o.call(r, n.resolve, n.reject) : n.resolve(r) } catch (e) { n.reject(e) } }(this, 1 === this.state ? this.chain[e].success : this.chain[e].failure, this.chain[e]); this.chain.length = 0 } function d(e) { var n, r = this; if (!r.triggered) { r.triggered = !0, r.def && (r = r.def); try { (n = s(e)) ? l(function () { var t = new m(r); try { n.call(e, function () { d.apply(t, arguments) }, function () { h.apply(t, arguments) }) } catch (e) { h.call(t, e) } }) : (r.msg = e, r.state = 1, 0 < r.chain.length && l(f, r)) } catch (e) { h.call(new m(r), e) } } } function h(e) { var t = this; t.triggered || (t.triggered = !0, t.def && (t = t.def), t.msg = e, t.state = 2, 0 < t.chain.length && l(f, t)) } function v(e, n, r, o) { for (var t = 0; t < n.length; t++)!function (t) { e.resolve(n[t]).then(function (e) { r(t, e) }, o) }(t) } function m(e) { this.def = e, this.triggered = !1 } function p(e) { this.promise = e, this.state = 0, this.triggered = !1, this.chain = [], this.msg = void 0 } function y(e) { if ("function" != typeof e) throw TypeError("Not a function"); if (0 !== this.__NPO__) throw TypeError("Not a promise"); this.__NPO__ = 1; var r = new p(this); this.then = function (e, t) { var n = { success: "function" != typeof e || e, failure: "function" == typeof t && t }; return n.promise = new this.constructor(function (e, t) { if ("function" != typeof e || "function" != typeof t) throw TypeError("Not a function"); n.resolve = e, n.reject = t }), r.chain.push(n), 0 !== r.state && l(f, r), n.promise }, this.catch = function (e) { return this.then(void 0, e) }; try { e.call(void 0, function (e) { d.call(r, e) }, function (e) { h.call(r, e) }) } catch (e) { h.call(r, e) } } var g = t({}, "constructor", y, !(r = { add: function (e, t) { a = new c(e, t), i ? i.next = a : o = a, i = a, a = void 0 }, drain: function () { var e = o; for (o = i = n = void 0; e;)e.fn.call(e.self), e = e.next } })); return t(y.prototype = g, "__NPO__", 0, !1), t(y, "resolve", function (n) { return n && "object" == typeof n && 1 === n.__NPO__ ? n : new this(function (e, t) { if ("function" != typeof e || "function" != typeof t) throw TypeError("Not a function"); e(n) }) }), t(y, "reject", function (n) { return new this(function (e, t) { if ("function" != typeof e || "function" != typeof t) throw TypeError("Not a function"); t(n) }) }), t(y, "all", function (t) { var a = this; return "[object Array]" != e.call(t) ? a.reject(TypeError("Not an array")) : 0 === t.length ? a.resolve([]) : new a(function (n, e) { if ("function" != typeof n || "function" != typeof e) throw TypeError("Not a function"); var r = t.length, o = Array(r), i = 0; v(a, t, function (e, t) { o[e] = t, ++i === r && n(o) }, e) }) }), t(y, "race", function (t) { var r = this; return "[object Array]" != e.call(t) ? r.reject(TypeError("Not an array")) : new r(function (n, e) { if ("function" != typeof n || "function" != typeof e) throw TypeError("Not a function"); v(r, t, function (e, t) { n(t) }, e) }) }), y }, (n = c)[t = "Promise"] = n[t] || r(), e.exports && (e.exports = n[t]) }(m = { exports: {} }), m.exports), y = new WeakMap; function g(e, t, n) { var r = y.get(e.element) || {}; t in r || (r[t] = []), r[t].push(n), y.set(e.element, r) } function w(e, t) { return (y.get(e.element) || {})[t] || [] } function b(e, t, n) { var r = y.get(e.element) || {}; if (!r[t]) return !0; if (!n) return r[t] = [], y.set(e.element, r), !0; var o = r[t].indexOf(n); return -1 !== o && r[t].splice(o, 1), y.set(e.element, r), r[t] && 0 === r[t].length } var k = ["autopause", "autoplay", "background", "byline", "color", "controls", "dnt", "height", "id", "loop", "maxheight", "maxwidth", "muted", "playsinline", "portrait", "responsive", "speed", "texttrack", "title", "transparent", "url", "width"]; function E(r, e) { var t = 1 < arguments.length && void 0 !== e ? e : {}; return k.reduce(function (e, t) { var n = r.getAttribute("data-vimeo-".concat(t)); return !n && "" !== n || (e[t] = "" === n ? 1 : n), e }, t) } function T(e, t) { var n = e.html; if (!t) throw new TypeError("An element must be provided"); if (null !== t.getAttribute("data-vimeo-initialized")) return t.querySelector("iframe"); var r = document.createElement("div"); return r.innerHTML = n, t.appendChild(r.firstChild), t.setAttribute("data-vimeo-initialized", "true"), t.querySelector("iframe") } function P(i, e, t) { var a = 1 < arguments.length && void 0 !== e ? e : {}, u = 2 < arguments.length ? t : void 0; return new Promise(function (t, n) { if (!l(i)) throw new TypeError("“".concat(i, "” is not a vimeo.com url.")); var e = "https://vimeo.com/api/oembed.json?url=".concat(encodeURIComponent(i)); for (var r in a) a.hasOwnProperty(r) && (e += "&".concat(r, "=").concat(encodeURIComponent(a[r]))); var o = new ("XDomainRequest" in window ? XDomainRequest : XMLHttpRequest); o.open("GET", e, !0), o.onload = function () { if (404 !== o.status) if (403 !== o.status) try { var e = JSON.parse(o.responseText); if (403 === e.domain_status_code) return T(e, u), void n(new Error("“".concat(i, "” is not embeddable."))); t(e) } catch (e) { n(e) } else n(new Error("“".concat(i, "” is not embeddable."))); else n(new Error("“".concat(i, "” was not found."))) }, o.onerror = function () { var e = o.status ? " (".concat(o.status, ")") : ""; n(new Error("There was an error fetching the embed code from Vimeo".concat(e, "."))) }, o.send() }) } function M(e) { if ("string" == typeof e) try { e = JSON.parse(e) } catch (e) { return console.warn(e), {} } return e } function F(e, t, n) { var r, o; e.element.contentWindow && e.element.contentWindow.postMessage && (r = { method: t }, void 0 !== n && (r.value = n), 8 <= (o = parseFloat(navigator.userAgent.toLowerCase().replace(/^.*msie (\d+).*$/, "$1"))) && o < 10 && (r = JSON.stringify(r)), e.element.contentWindow.postMessage(r, e.origin)) } function _(n, r) { var t, e, o = []; (r = M(r)).event ? ("error" === r.event && w(n, r.data.method).forEach(function (e) { var t = new Error(r.data.message); t.name = r.data.name, e.reject(t), b(n, r.data.method, e) }), o = w(n, "event:".concat(r.event)), t = r.data) : !r.method || (e = function (e, t) { var n = w(e, t); if (n.length < 1) return !1; var r = n.shift(); return b(e, t, r), r }(n, r.method)) && (o.push(e), t = r.value), o.forEach(function (e) { try { if ("function" == typeof e) return void e.call(n, t); e.resolve(t) } catch (e) { } }) } var x, C, j, N = new WeakMap, A = new WeakMap, q = {}, Player = function () { function Player(u) { var e, t, c = this, n = 1 < arguments.length && void 0 !== arguments[1] ? arguments[1] : {}; if (!function (e, t) { if (!(e instanceof t)) throw new TypeError("Cannot call a class as a function") }(this, Player), window.jQuery && u instanceof jQuery && (1 < u.length && window.console && console.warn && console.warn("A jQuery object with multiple elements was passed, using the first element."), u = u[0]), "undefined" != typeof document && "string" == typeof u && (u = document.getElementById(u)), e = u, !Boolean(e && 1 === e.nodeType && "nodeName" in e && e.ownerDocument && e.ownerDocument.defaultView)) throw new TypeError("You must pass either a valid element or a valid id."); if ("IFRAME" === u.nodeName || (t = u.querySelector("iframe")) && (u = t), "IFRAME" === u.nodeName && !l(u.getAttribute("src") || "")) throw new Error("The player element passed isn’t a Vimeo embed."); if (N.has(u)) return N.get(u); this._window = u.ownerDocument.defaultView, this.element = u, this.origin = "*"; var r, o = new p(function (i, a) { var e; c._onMessage = function (e) { if (l(e.origin) && c.element.contentWindow === e.source) { "*" === c.origin && (c.origin = e.origin); var t = M(e.data); if (t && "error" === t.event && t.data && "ready" === t.data.method) { var n = new Error(t.data.message); return n.name = t.data.name, void a(n) } var r = t && "ready" === t.event, o = t && "ping" === t.method; if (r || o) return c.element.setAttribute("data-ready", "true"), void i(); _(c, t) } }, c._window.addEventListener("message", c._onMessage), "IFRAME" !== c.element.nodeName && P(s(e = E(u, n)), e, u).then(function (e) { var t, n, r, o = T(e, u); return c.element = o, c._originalElement = u, t = u, n = o, r = y.get(t), y.set(n, r), y.delete(t), N.set(c.element, c), e }).catch(a) }); return A.set(this, o), N.set(this.element, this), "IFRAME" === this.element.nodeName && F(this, "ping"), q.isEnabled && (r = function () { return q.exit() }, q.on("fullscreenchange", function () { (q.isFullscreen ? g : b)(c, "event:exitFullscreen", r), c.ready().then(function () { F(c, "fullscreenchange", q.isFullscreen) }) })), this } var e, t, n; return e = Player, (t = [{ key: "callMethod", value: function (n, e) { var r = this, o = 1 < arguments.length && void 0 !== e ? e : {}; return new p(function (e, t) { return r.ready().then(function () { g(r, n, { resolve: e, reject: t }), F(r, n, o) }).catch(t) }) } }, { key: "get", value: function (n) { var r = this; return new p(function (e, t) { return n = i(n, "get"), r.ready().then(function () { g(r, n, { resolve: e, reject: t }), F(r, n) }).catch(t) }) } }, { key: "set", value: function (n, r) { var o = this; return new p(function (e, t) { if (n = i(n, "set"), null == r) throw new TypeError("There must be a value to set."); return o.ready().then(function () { g(o, n, { resolve: e, reject: t }), F(o, n, r) }).catch(t) }) } }, { key: "on", value: function (e, t) { if (!e) throw new TypeError("You must pass an event name."); if (!t) throw new TypeError("You must pass a callback function."); if ("function" != typeof t) throw new TypeError("The callback must be a function."); 0 === w(this, "event:".concat(e)).length && this.callMethod("addEventListener", e).catch(function () { }), g(this, "event:".concat(e), t) } }, { key: "off", value: function (e, t) { if (!e) throw new TypeError("You must pass an event name."); if (t && "function" != typeof t) throw new TypeError("The callback must be a function."); b(this, "event:".concat(e), t) && this.callMethod("removeEventListener", e).catch(function (e) { }) } }, { key: "loadVideo", value: function (e) { return this.callMethod("loadVideo", e) } }, { key: "ready", value: function () { var e = A.get(this) || new p(function (e, t) { t(new Error("Unknown player. Probably unloaded.")) }); return p.resolve(e) } }, { key: "addCuePoint", value: function (e, t) { var n = 1 < arguments.length && void 0 !== t ? t : {}; return this.callMethod("addCuePoint", { time: e, data: n }) } }, { key: "removeCuePoint", value: function (e) { return this.callMethod("removeCuePoint", e) } }, { key: "enableTextTrack", value: function (e, t) { if (!e) throw new TypeError("You must pass a language."); return this.callMethod("enableTextTrack", { language: e, kind: t }) } }, { key: "disableTextTrack", value: function () { return this.callMethod("disableTextTrack") } }, { key: "pause", value: function () { return this.callMethod("pause") } }, { key: "play", value: function () { return this.callMethod("play") } }, { key: "requestFullscreen", value: function () { return q.isEnabled ? q.request(this.element) : this.callMethod("requestFullscreen") } }, { key: "exitFullscreen", value: function () { return q.isEnabled ? q.exit() : this.callMethod("exitFullscreen") } }, { key: "getFullscreen", value: function () { return q.isEnabled ? p.resolve(q.isFullscreen) : this.get("fullscreen") } }, { key: "requestPictureInPicture", value: function () { return this.callMethod("requestPictureInPicture") } }, { key: "exitPictureInPicture", value: function () { return this.callMethod("exitPictureInPicture") } }, { key: "getPictureInPicture", value: function () { return this.get("pictureInPicture") } }, { key: "unload", value: function () { return this.callMethod("unload") } }, { key: "destroy", value: function () { var n = this; return new p(function (e) { var t; A.delete(n), N.delete(n.element), n._originalElement && (N.delete(n._originalElement), n._originalElement.removeAttribute("data-vimeo-initialized")), n.element && "IFRAME" === n.element.nodeName && n.element.parentNode && n.element.parentNode.removeChild(n.element), n.element && "DIV" === n.element.nodeName && n.element.parentNode && (n.element.removeAttribute("data-vimeo-initialized"), (t = n.element.querySelector("iframe")) && t.parentNode && t.parentNode.removeChild(t)), n._window.removeEventListener("message", n._onMessage), e() }) } }, { key: "getAutopause", value: function () { return this.get("autopause") } }, { key: "setAutopause", value: function (e) { return this.set("autopause", e) } }, { key: "getBuffered", value: function () { return this.get("buffered") } }, { key: "getCameraProps", value: function () { return this.get("cameraProps") } }, { key: "setCameraProps", value: function (e) { return this.set("cameraProps", e) } }, { key: "getChapters", value: function () { return this.get("chapters") } }, { key: "getCurrentChapter", value: function () { return this.get("currentChapter") } }, { key: "getColor", value: function () { return this.get("color") } }, { key: "setColor", value: function (e) { return this.set("color", e) } }, { key: "getCuePoints", value: function () { return this.get("cuePoints") } }, { key: "getCurrentTime", value: function () { return this.get("currentTime") } }, { key: "setCurrentTime", value: function (e) { return this.set("currentTime", e) } }, { key: "getDuration", value: function () { return this.get("duration") } }, { key: "getEnded", value: function () { return this.get("ended") } }, { key: "getLoop", value: function () { return this.get("loop") } }, { key: "setLoop", value: function (e) { return this.set("loop", e) } }, { key: "setMuted", value: function (e) { return this.set("muted", e) } }, { key: "getMuted", value: function () { return this.get("muted") } }, { key: "getPaused", value: function () { return this.get("paused") } }, { key: "getPlaybackRate", value: function () { return this.get("playbackRate") } }, { key: "setPlaybackRate", value: function (e) { return this.set("playbackRate", e) } }, { key: "getPlayed", value: function () { return this.get("played") } }, { key: "getQualities", value: function () { return this.get("qualities") } }, { key: "getQuality", value: function () { return this.get("quality") } }, { key: "setQuality", value: function (e) { return this.set("quality", e) } }, { key: "getSeekable", value: function () { return this.get("seekable") } }, { key: "getSeeking", value: function () { return this.get("seeking") } }, { key: "getTextTracks", value: function () { return this.get("textTracks") } }, { key: "getVideoEmbedCode", value: function () { return this.get("videoEmbedCode") } }, { key: "getVideoId", value: function () { return this.get("videoId") } }, { key: "getVideoTitle", value: function () { return this.get("videoTitle") } }, { key: "getVideoWidth", value: function () { return this.get("videoWidth") } }, { key: "getVideoHeight", value: function () { return this.get("videoHeight") } }, { key: "getVideoUrl", value: function () { return this.get("videoUrl") } }, { key: "getVolume", value: function () { return this.get("volume") } }, { key: "setVolume", value: function (e) { return this.set("volume", e) } }]) && r(e.prototype, t), n && r(e, n), Player }(); return e || (x = function () { for (var e, t = [["requestFullscreen", "exitFullscreen", "fullscreenElement", "fullscreenEnabled", "fullscreenchange", "fullscreenerror"], ["webkitRequestFullscreen", "webkitExitFullscreen", "webkitFullscreenElement", "webkitFullscreenEnabled", "webkitfullscreenchange", "webkitfullscreenerror"], ["webkitRequestFullScreen", "webkitCancelFullScreen", "webkitCurrentFullScreenElement", "webkitCancelFullScreen", "webkitfullscreenchange", "webkitfullscreenerror"], ["mozRequestFullScreen", "mozCancelFullScreen", "mozFullScreenElement", "mozFullScreenEnabled", "mozfullscreenchange", "mozfullscreenerror"], ["msRequestFullscreen", "msExitFullscreen", "msFullscreenElement", "msFullscreenEnabled", "MSFullscreenChange", "MSFullscreenError"]], n = 0, r = t.length, o = {}; n < r; n++)if ((e = t[n]) && e[1] in document) { for (n = 0; n < e.length; n++)o[t[0][n]] = e[n]; return o } return !1 }(), C = { fullscreenchange: x.fullscreenchange, fullscreenerror: x.fullscreenerror }, j = { request: function (o) { return new Promise(function (e, t) { function n() { j.off("fullscreenchange", n), e() } j.on("fullscreenchange", n); var r = (o = o || document.documentElement)[x.requestFullscreen](); r instanceof Promise && r.then(n).catch(t) }) }, exit: function () { return new Promise(function (t, e) { var n, r; j.isFullscreen ? (n = function e() { j.off("fullscreenchange", e), t() }, j.on("fullscreenchange", n), (r = document[x.exitFullscreen]()) instanceof Promise && r.then(n).catch(e)) : t() }) }, on: function (e, t) { var n = C[e]; n && document.addEventListener(n, t) }, off: function (e, t) { var n = C[e]; n && document.removeEventListener(n, t) } }, Object.defineProperties(j, { isFullscreen: { get: function () { return Boolean(document[x.fullscreenElement]) } }, element: { enumerable: !0, get: function () { return document[x.fullscreenElement] } }, isEnabled: { enumerable: !0, get: function () { return Boolean(document[x.fullscreenEnabled]) } } }), q = j, function (e) { function n(e) { "console" in window && console.error && console.error("There was an error creating an embed: ".concat(e)) } var t = 0 < arguments.length && void 0 !== e ? e : document;[].slice.call(t.querySelectorAll("[data-vimeo-id], [data-vimeo-url]")).forEach(function (t) { try { if (null !== t.getAttribute("data-vimeo-defer")) return; var e = E(t); P(s(e), e, t).then(function (e) { return T(e, t) }).catch(n) } catch (e) { n(e) } }) }(), function (e) { var r = 0 < arguments.length && void 0 !== e ? e : document; window.VimeoPlayerResizeEmbeds_ || (window.VimeoPlayerResizeEmbeds_ = !0, window.addEventListener("message", function (e) { if (l(e.origin) && e.data && "spacechange" === e.data.event) for (var t = r.querySelectorAll("iframe"), n = 0; n < t.length; n++)if (t[n].contentWindow === e.source) { t[n].parentElement.style.paddingBottom = "".concat(e.data.data[0].bottom, "px"); break } })) }()), Player });
/*! modernizr 3.6.0 (Custom Build) | MIT *
 * https://modernizr.com/download/?-dataset-input-inputtypes-placeholder-sessionstorage !*/
!function (e, t, n) { function a(e, t) { return typeof e === t } function i() { var e, t, n, i, s, r, u; for (var c in o) if (o.hasOwnProperty(c)) { if (e = [], t = o[c], t.name && (e.push(t.name.toLowerCase()), t.options && t.options.aliases && t.options.aliases.length)) for (n = 0; n < t.options.aliases.length; n++)e.push(t.options.aliases[n].toLowerCase()); for (i = a(t.fn, "function") ? t.fn() : t.fn, s = 0; s < e.length; s++)r = e[s], u = r.split("."), 1 === u.length ? Modernizr[u[0]] = i : (!Modernizr[u[0]] || Modernizr[u[0]] instanceof Boolean || (Modernizr[u[0]] = new Boolean(Modernizr[u[0]])), Modernizr[u[0]][u[1]] = i), l.push((i ? "" : "no-") + u.join("-")) } } function s() { return "function" != typeof t.createElement ? t.createElement(arguments[0]) : c ? t.createElementNS.call(t, "http://www.w3.org/2000/svg", arguments[0]) : t.createElement.apply(t, arguments) } var o = [], r = { _version: "3.6.0", _config: { classPrefix: "", enableClasses: !0, enableJSClass: !0, usePrefixes: !0 }, _q: [], on: function (e, t) { var n = this; setTimeout(function () { t(n[e]) }, 0) }, addTest: function (e, t, n) { o.push({ name: e, fn: t, options: n }) }, addAsyncTest: function (e) { o.push({ name: null, fn: e }) } }, Modernizr = function () { }; Modernizr.prototype = r, Modernizr = new Modernizr, Modernizr.addTest("sessionstorage", function () { var e = "modernizr"; try { return sessionStorage.setItem(e, e), sessionStorage.removeItem(e), !0 } catch (t) { return !1 } }); var l = [], u = t.documentElement, c = "svg" === u.nodeName.toLowerCase(); Modernizr.addTest("dataset", function () { var e = s("div"); return e.setAttribute("data-a-b", "c"), !(!e.dataset || "c" !== e.dataset.aB) }), Modernizr.addTest("placeholder", "placeholder" in s("input") && "placeholder" in s("textarea")); var d = s("input"), p = "autocomplete autofocus list placeholder max min multiple pattern required step".split(" "), f = {}; Modernizr.input = function (t) { for (var n = 0, a = t.length; a > n; n++)f[t[n]] = !!(t[n] in d); return f.list && (f.list = !(!s("datalist") || !e.HTMLDataListElement)), f }(p); var m = "search tel url email datetime date month week time datetime-local number range color".split(" "), h = {}; Modernizr.inputtypes = function (e) { for (var a, i, s, o = e.length, r = "1)", l = 0; o > l; l++)d.setAttribute("type", a = e[l]), s = "text" !== d.type && "style" in d, s && (d.value = r, d.style.cssText = "position:absolute;visibility:hidden;", /^range$/.test(a) && d.style.WebkitAppearance !== n ? (u.appendChild(d), i = t.defaultView, s = i.getComputedStyle && "textfield" !== i.getComputedStyle(d, null).WebkitAppearance && 0 !== d.offsetHeight, u.removeChild(d)) : /^(search|tel)$/.test(a) || (s = /^(url|email)$/.test(a) ? d.checkValidity && d.checkValidity() === !1 : d.value != r)), h[e[l]] = !!s; return h }(m), i(), delete r.addTest, delete r.addAsyncTest; for (var g = 0; g < Modernizr._q.length; g++)Modernizr._q[g](); e.Modernizr = Modernizr }(window, document);
/*!
 * ASP.NET SignalR JavaScript Library 2.4.1
 * http://signalr.net/
 *
 * Copyright (c) .NET Foundation. All rights reserved.
 * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
 *
 */
(function(n,t,i){function w(t,i){var u,f;if(n.isArray(t)){for(u=t.length-1;u>=0;u--)f=t[u],n.type(f)==="string"&&r.transports[f]||(i.log("Invalid transport: "+f+", removing it from the transports list."),t.splice(u,1));t.length===0&&(i.log("No transports remain within the specified transport array."),t=null)}else if(r.transports[t]||t==="auto"){if(t==="auto"&&r._.ieVersion<=8)return["longPolling"]}else i.log("Invalid transport: "+t.toString()+"."),t=null;return t}function b(n){return n==="http:"?80:n==="https:"?443:void 0}function a(n,t){return t.match(/:\d+$/)?t:t+":"+b(n)}function k(t,i){var u=this,r=[];u.tryBuffer=function(i){return t.state===n.signalR.connectionState.connecting?(r.push(i),!0):!1};u.drain=function(){if(t.state===n.signalR.connectionState.connected)while(r.length>0)i(r.shift())};u.clear=function(){r=[]}}var f={nojQuery:"jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.",noTransportOnInit:"No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.",errorOnNegotiate:"Error during negotiation request.",stoppedWhileLoading:"The connection was stopped during page load.",stoppedWhileNegotiating:"The connection was stopped during the negotiate request.",errorParsingNegotiateResponse:"Error parsing negotiate response.",errorRedirectionExceedsLimit:"Negotiate redirection limit exceeded.",errorDuringStartRequest:"Error during start request. Stopping the connection.",errorFromServer:"Error message received from the server: '{0}'.",stoppedDuringStartRequest:"The connection was stopped during the start request.",errorParsingStartResponse:"Error parsing start response: '{0}'. Stopping the connection.",invalidStartResponse:"Invalid start response: '{0}'. Stopping the connection.",protocolIncompatible:"You are using a version of the client that isn't compatible with the server. Client version {0}, server version {1}.",aspnetCoreSignalrServer:"Detected a connection attempt to an ASP.NET Core SignalR Server. This client only supports connecting to an ASP.NET SignalR Server. See https://aka.ms/signalr-core-differences for details.",sendFailed:"Send failed.",parseFailed:"Failed at parsing response: {0}",longPollFailed:"Long polling request failed.",eventSourceFailedToConnect:"EventSource failed to connect.",eventSourceError:"Error raised by EventSource",webSocketClosed:"WebSocket closed.",pingServerFailedInvalidResponse:"Invalid ping response when pinging server: '{0}'.",pingServerFailed:"Failed to ping server.",pingServerFailedStatusCode:"Failed to ping server.  Server responded with status code {0}, stopping the connection.",pingServerFailedParse:"Failed to parse ping server response, stopping the connection.",noConnectionTransport:"Connection is in an invalid state, there is no transport active.",webSocketsInvalidState:"The Web Socket transport is in an invalid state, transitioning into reconnecting.",reconnectTimeout:"Couldn't reconnect within the configured timeout of {0} ms, disconnecting.",reconnectWindowTimeout:"The client has been inactive since {0} and it has exceeded the inactivity timeout of {1} ms. Stopping the connection.",jsonpNotSupportedWithAccessToken:"The JSONP protocol does not support connections that require a Bearer token to connect, such as the Azure SignalR Service."};if(typeof n!="function")throw new Error(f.nojQuery);var r,h,o=t.document.readyState==="complete",e=n(t),c="__Negotiate Aborted__",u={onStart:"onStart",onStarting:"onStarting",onReceived:"onReceived",onError:"onError",onConnectionSlow:"onConnectionSlow",onReconnecting:"onReconnecting",onReconnect:"onReconnect",onStateChanged:"onStateChanged",onDisconnect:"onDisconnect"},v=function(n,i){if(i!==!1){var r;typeof t.console!="undefined"&&(r="["+(new Date).toTimeString()+"] SignalR: "+n,t.console.debug?t.console.debug(r):t.console.log&&t.console.log(r))}},s=function(t,i,r){return i===t.state?(t.state=r,n(t).triggerHandler(u.onStateChanged,[{oldState:i,newState:r}]),!0):!1},y=function(n){return n.state===r.connectionState.disconnected},l=function(n){return n._.keepAliveData.activated&&n.transport.supportsKeepAlive(n)},p=function(i){var f,e;i._.configuredStopReconnectingTimeout||(e=function(t){var i=r._.format(r.resources.reconnectTimeout,t.disconnectTimeout);t.log(i);n(t).triggerHandler(u.onError,[r._.error(i,"TimeoutException")]);t.stop(!1,!1)},i.reconnecting(function(){var n=this;n.state===r.connectionState.reconnecting&&(f=t.setTimeout(function(){e(n)},n.disconnectTimeout))}),i.stateChanged(function(n){n.oldState===r.connectionState.reconnecting&&t.clearTimeout(f)}),i._.configuredStopReconnectingTimeout=!0)};if(r=function(n,t,i){return new r.fn.init(n,t,i)},r._={defaultContentType:"application/x-www-form-urlencoded; charset=UTF-8",ieVersion:function(){var i,n;return t.navigator.appName==="Microsoft Internet Explorer"&&(n=/MSIE ([0-9]+\.[0-9]+)/.exec(t.navigator.userAgent),n&&(i=t.parseFloat(n[1]))),i}(),error:function(n,t,i){var r=new Error(n);return r.source=t,typeof i!="undefined"&&(r.context=i),r},transportError:function(n,t,r,u){var f=this.error(n,r,u);return f.transport=t?t.name:i,f},format:function(){for(var t=arguments[0],n=0;n<arguments.length-1;n++)t=t.replace("{"+n+"}",arguments[n+1]);return t},firefoxMajorVersion:function(n){var t=n.match(/Firefox\/(\d+)/);return!t||!t.length||t.length<2?0:parseInt(t[1],10)},configurePingInterval:function(i){var f=i._.config,e=function(t){n(i).triggerHandler(u.onError,[t])};f&&!i._.pingIntervalId&&f.pingInterval&&(i._.pingIntervalId=t.setInterval(function(){r.transports._logic.pingServer(i).fail(e)},f.pingInterval))}},r.events=u,r.resources=f,r.ajaxDefaults={processData:!0,timeout:null,async:!0,global:!1,cache:!1},r.changeState=s,r.isDisconnecting=y,r.connectionState={connecting:0,connected:1,reconnecting:2,disconnected:4},r.hub={start:function(){throw new Error("SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/js'><\/script>.");}},typeof e.on=="function")e.on("load",function(){o=!0});else e.load(function(){o=!0});r.fn=r.prototype={init:function(t,i,r){var f=n(this);this.url=t;this.qs=i;this.lastError=null;this._={keepAliveData:{},connectingMessageBuffer:new k(this,function(n){f.triggerHandler(u.onReceived,[n])}),lastMessageAt:(new Date).getTime(),lastActiveAt:(new Date).getTime(),beatInterval:5e3,beatHandle:null,totalTransportConnectTimeout:0,redirectQs:null};typeof r=="boolean"&&(this.logging=r)},_parseResponse:function(n){var t=this;return n?typeof n=="string"?t.json.parse(n):n:n},_originalJson:t.JSON,json:t.JSON,isCrossDomain:function(i,r){var u;return(i=n.trim(i),r=r||t.location,i.indexOf("http")!==0)?!1:(u=t.document.createElement("a"),u.href=i,u.protocol+a(u.protocol,u.host)!==r.protocol+a(r.protocol,r.host))},ajaxDataType:"text",contentType:"application/json; charset=UTF-8",logging:!1,state:r.connectionState.disconnected,clientProtocol:"2.1",supportedProtocols:["1.5","2.0","2.1"],negotiateRedirectSupportedProtocols:["2.0","2.1"],reconnectDelay:2e3,transportConnectTimeout:0,disconnectTimeout:3e4,reconnectWindow:3e4,keepAliveWarnAt:2/3,start:function(i,h){var a=this,v={pingInterval:3e5,waitForPageLoad:!0,transport:"auto",jsonp:!1},g,y=a._deferral||n.Deferred(),b=t.document.createElement("a"),nt=function(i,u){i.url===u&&i.baseUrl||(i.url=u,b.href=i.url,b.protocol&&b.protocol!==":"?(i.protocol=b.protocol,i.host=b.host):(i.protocol=t.document.location.protocol,i.host=b.host||t.document.location.host),i.baseUrl=i.protocol+"//"+i.host,i.wsProtocol=i.protocol==="https:"?"wss://":"ws://",i.url.indexOf("//")===0&&(i.url=t.location.protocol+i.url,i.log("Protocol relative URL detected, normalizing it to '"+i.url+"'.")),i.isCrossDomain(i.url)&&(i.log("Auto detected cross domain url."),v.transport==="auto"&&(v.transport=["webSockets","serverSentEvents","longPolling"]),typeof i.withCredentials=="undefined"&&(i.withCredentials=!0),n.support.cors||(i.ajaxDataType="jsonp",i.log("Using jsonp because this browser doesn't support CORS.")),i.contentType=r._.defaultContentType))},d,k;if(a.lastError=null,a._deferral=y,!a.json)throw new Error("SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support, e.g. IE<8.");if(n.type(i)==="function"?h=i:n.type(i)==="object"&&(n.extend(v,i),n.type(v.callback)==="function"&&(h=v.callback)),v.transport=w(v.transport,a),!v.transport)throw new Error("SignalR: Invalid transport(s) specified, aborting start.");return(a._.config=v,!o&&v.waitForPageLoad===!0)?(a._.deferredStartHandler=function(){a.start(i,h)},e.bind("load",a._.deferredStartHandler),y.promise()):a.state===r.connectionState.connecting?y.promise():s(a,r.connectionState.disconnected,r.connectionState.connecting)===!1?(y.resolve(a),y.promise()):(p(a),v.transport==="auto"&&v.jsonp===!0&&(v.transport="longPolling"),a.withCredentials=v.withCredentials,a._originalUrl=a.url,a.ajaxDataType=v.jsonp?"jsonp":"text",nt(a,a.url),n(a).bind(u.onStart,function(){n.type(h)==="function"&&h.call(a);y.resolve(a)}),a._.initHandler=r.transports._logic.initHandler(a),g=function(i,o){var c=r._.error(f.noTransportOnInit);if(o=o||0,o>=i.length){o===0?a.log("No transports supported by the server were selected."):o===1?a.log("No fallback transports were selected."):a.log("Fallback transports exhausted.");n(a).triggerHandler(u.onError,[c]);y.reject(c);a.stop();return}if(a.state!==r.connectionState.disconnected){var p=i[o],h=r.transports[p],v=function(){g(i,o+1)};a.transport=h;try{a._.initHandler.start(h,function(){var f=r._.firefoxMajorVersion(t.navigator.userAgent)>=11,i=!0;a.log("The start request succeeded. Transitioning to the connected state.");l(a)&&r.transports._logic.monitorKeepAlive(a);r.transports._logic.startHeartbeat(a);r._.configurePingInterval(a);s(a,r.connectionState.connecting,r.connectionState.connected)||a.log("WARNING! The connection was not in the connecting state.");a._.connectingMessageBuffer.drain();n(a).triggerHandler(u.onStart);e.bind("unload",function(){a.log("Window unloading, stopping the connection.");a.stop(i)});f&&e.bind("beforeunload",function(){t.setTimeout(function(){a.stop(i)},0)})},v)}catch(w){a.log(h.name+" transport threw '"+w.message+"' when attempting to start.");v()}}},d=a.url+"/negotiate",k=function(t,i){var e=r._.error(f.errorOnNegotiate,t,i._.negotiateRequest);n(i).triggerHandler(u.onError,e);y.reject(e);i.stop()},n(a).triggerHandler(u.onStarting),d=r.transports._logic.prepareQueryString(a,d),a.log("Negotiating with '"+d+"'."),a._.negotiateRequest=function(){var t,h=0,w=100,i,e,o=[],s=[],l=function(n,t){var u=r.transports._logic.prepareQueryString(n,n.url+"/negotiate"),i;return n.log("Negotiating with '"+u+"'."),i={url:u,error:function(t,i){i!==c?k(t,n):y.reject(r._.error(f.stoppedWhileNegotiating,null,n._.negotiateRequest))},success:t},n.accessToken&&(i.headers={Authorization:"Bearer "+n.accessToken}),r.transports._logic.ajax(n,i)},p=function(c){try{t=a._parseResponse(c)}catch(d){k(r._.error(f.errorParsingNegotiateResponse,d),a);return}if(t.availableTransports){e=r._.error(f.aspnetCoreSignalrServer);n(a).triggerHandler(u.onError,[e]);y.reject(e);return}if(!t.ProtocolVersion||a.supportedProtocols.indexOf(t.ProtocolVersion)===-1){e=r._.error(r._.format(f.protocolIncompatible,a.clientProtocol,t.ProtocolVersion));n(a).triggerHandler(u.onError,[e]);y.reject(e);return}if(a.negotiateRedirectSupportedProtocols.indexOf(t.ProtocolVersion)!==-1){if(t.Error){e=r._.error(r._.format(f.errorFromServer,t.Error));n(a).triggerHandler(u.onError,[e]);y.reject(e);return}if(t.RedirectUrl){if(h===w){k(r._.error(f.errorRedirectionExceedsLimit),a);return}v.transport==="auto"&&(v.transport=["webSockets","serverSentEvents","longPolling"]);a.log("Received redirect to: "+t.RedirectUrl);a.accessToken=t.AccessToken;var b=t.RedirectUrl.split("?",2);if(nt(a,b[0]),a._.redirectQs=b.length===2?b[1]:null,a.ajaxDataType==="jsonp"&&a.accessToken){k(r._.error(f.jsonpNotSupportedWithAccessToken),a);return}h++;l(a,p);return}}i=a._.keepAliveData;a.appRelativeUrl=t.Url;a.id=t.ConnectionId;a.token=t.ConnectionToken;a.webSocketServerUrl=t.WebSocketServerUrl;a._.pollTimeout=t.ConnectionTimeout*1e3+1e4;a.disconnectTimeout=t.DisconnectTimeout*1e3;a._.totalTransportConnectTimeout=a.transportConnectTimeout+t.TransportConnectTimeout*1e3;t.KeepAliveTimeout?(i.activated=!0,i.timeout=t.KeepAliveTimeout*1e3,i.timeoutWarning=i.timeout*a.keepAliveWarnAt,a._.beatInterval=(i.timeout-i.timeoutWarning)/3):i.activated=!1;a.reconnectWindow=a.disconnectTimeout+(i.timeout||0);n.each(r.transports,function(n){if(n.indexOf("_")===0||n==="webSockets"&&!t.TryWebSockets)return!0;s.push(n)});n.isArray(v.transport)?n.each(v.transport,function(t,i){n.inArray(i,s)>=0&&o.push(i)}):v.transport==="auto"?o=s:n.inArray(v.transport,s)>=0&&o.push(v.transport);g(o)};return l(a,p)}(),y.promise())},starting:function(t){var i=this;return n(i).bind(u.onStarting,function(){t.call(i)}),i},send:function(n){var t=this;if(t.state===r.connectionState.disconnected)throw new Error("SignalR: Connection must be started before data can be sent. Call .start() before .send()");if(t.state===r.connectionState.connecting)throw new Error("SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.");return t.transport.send(t,n),t},received:function(t){var i=this;return n(i).bind(u.onReceived,function(n,r){t.call(i,r)}),i},stateChanged:function(t){var i=this;return n(i).bind(u.onStateChanged,function(n,r){t.call(i,r)}),i},error:function(t){var i=this;return n(i).bind(u.onError,function(n,r,u){i.lastError=r;t.call(i,r,u)}),i},disconnected:function(t){var i=this;return n(i).bind(u.onDisconnect,function(){t.call(i)}),i},connectionSlow:function(t){var i=this;return n(i).bind(u.onConnectionSlow,function(){t.call(i)}),i},reconnecting:function(t){var i=this;return n(i).bind(u.onReconnecting,function(){t.call(i)}),i},reconnected:function(t){var i=this;return n(i).bind(u.onReconnect,function(){t.call(i)}),i},stop:function(i,h){var a=this,v=a._deferral;if(a._.deferredStartHandler&&e.unbind("load",a._.deferredStartHandler),delete a._.config,delete a._.deferredStartHandler,!o&&(!a._.config||a._.config.waitForPageLoad===!0)){a.log("Stopping connection prior to negotiate.");v&&v.reject(r._.error(f.stoppedWhileLoading));return}if(a.state!==r.connectionState.disconnected)return a.log("Stopping connection."),t.clearTimeout(a._.beatHandle),t.clearInterval(a._.pingIntervalId),a.transport&&(a.transport.stop(a),h!==!1&&a.transport.abort(a,i),l(a)&&r.transports._logic.stopMonitoringKeepAlive(a),a.transport=null),a._.negotiateRequest&&(a._.negotiateRequest.abort(c),delete a._.negotiateRequest),a._.initHandler&&a._.initHandler.stop(),delete a._deferral,delete a.messageId,delete a.groupsToken,delete a.id,delete a._.pingIntervalId,delete a._.lastMessageAt,delete a._.lastActiveAt,a._.connectingMessageBuffer.clear(),n(a).unbind(u.onStart),delete a.accessToken,delete a.protocol,delete a.host,delete a.baseUrl,delete a.wsProtocol,delete a.contentType,a.url=a._originalUrl,a._.redirectQs=null,s(a,a.state,r.connectionState.disconnected),n(a).triggerHandler(u.onDisconnect),a},log:function(n){v(n,this.logging)}};r.fn.init.prototype=r.fn;r.noConflict=function(){return n.connection===r&&(n.connection=h),r};n.connection&&(h=n.connection);n.connection=n.signalR=r})(window.jQuery,window),function(n,t,i){function s(n){n._.keepAliveData.monitoring&&l(n);u.markActive(n)&&(n._.beatHandle=t.setTimeout(function(){s(n)},n._.beatInterval))}function l(t){var i=t._.keepAliveData,u;t.state===r.connectionState.connected&&(u=(new Date).getTime()-t._.lastMessageAt,u>=i.timeout?(t.log("Keep alive timed out.  Notifying transport that connection has been lost."),t.transport.lostConnection(t)):u>=i.timeoutWarning?i.userNotified||(t.log("Keep alive has been missed, connection may be dead/slow."),n(t).triggerHandler(f.onConnectionSlow),i.userNotified=!0):i.userNotified=!1)}function e(n,t){var i=n.url+t;return n.transport&&(i+="?transport="+n.transport.name),u.prepareQueryString(n,i)}function h(n){this.connection=n;this.startRequested=!1;this.startCompleted=!1;this.connectionStopped=!1}var r=n.signalR,f=n.signalR.events,c=n.signalR.changeState,o="__Start Aborted__",u;r.transports={};h.prototype={start:function(n,r,u){var f=this,e=f.connection,o=!1;if(f.startRequested||f.connectionStopped){e.log("WARNING! "+n.name+" transport cannot be started. Initialization ongoing or completed.");return}e.log(n.name+" transport starting.");n.start(e,function(){o||f.initReceived(n,r)},function(t){return o||(o=!0,f.transportFailed(n,t,u)),!f.startCompleted||f.connectionStopped});f.transportTimeoutHandle=t.setTimeout(function(){o||(o=!0,e.log(n.name+" transport timed out when trying to connect."),f.transportFailed(n,i,u))},e._.totalTransportConnectTimeout)},stop:function(){this.connectionStopped=!0;t.clearTimeout(this.transportTimeoutHandle);r.transports._logic.tryAbortStartRequest(this.connection)},initReceived:function(n,i){var u=this,f=u.connection;if(u.startRequested){f.log("WARNING! The client received multiple init messages.");return}u.connectionStopped||(u.startRequested=!0,t.clearTimeout(u.transportTimeoutHandle),f.log(n.name+" transport connected. Initiating start request."),r.transports._logic.ajaxStart(f,function(){u.startCompleted=!0;i()}))},transportFailed:function(i,u,e){var o=this.connection,h=o._deferral,s;this.connectionStopped||(t.clearTimeout(this.transportTimeoutHandle),this.startRequested?this.startCompleted||(s=r._.error(r.resources.errorDuringStartRequest,u),o.log(i.name+" transport failed during the start request. Stopping the connection."),n(o).triggerHandler(f.onError,[s]),h&&h.reject(s),o.stop()):(i.stop(o),o.log(i.name+" transport failed to connect. Attempting to fall back."),e()))}};u=r.transports._logic={ajax:function(t,i){return n.ajax(n.extend(!0,{},n.signalR.ajaxDefaults,{type:"GET",data:{},xhrFields:{withCredentials:t.withCredentials},contentType:t.contentType,dataType:t.ajaxDataType},i))},pingServer:function(t){var e,f,i=n.Deferred();return t.transport?(e=t.url+"/ping",e=u.addQs(e,t.qs),f=u.ajax(t,{url:e,headers:t.accessToken?{Authorization:"Bearer "+t.accessToken}:{},success:function(n){var u;try{u=t._parseResponse(n)}catch(e){i.reject(r._.transportError(r.resources.pingServerFailedParse,t.transport,e,f));t.stop();return}u.Response==="pong"?i.resolve():i.reject(r._.transportError(r._.format(r.resources.pingServerFailedInvalidResponse,n),t.transport,null,f))},error:function(n){n.status===401||n.status===403?(i.reject(r._.transportError(r._.format(r.resources.pingServerFailedStatusCode,n.status),t.transport,n,f)),t.stop()):i.reject(r._.transportError(r.resources.pingServerFailed,t.transport,n,f))}})):i.reject(r._.transportError(r.resources.noConnectionTransport,t.transport)),i.promise()},prepareQueryString:function(n,i){var r;return r=u.addQs(i,"clientProtocol="+n.clientProtocol),r=typeof n._.redirectQs=="string"?u.addQs(r,n._.redirectQs):u.addQs(r,n.qs),n.token&&(r+="&connectionToken="+t.encodeURIComponent(n.token)),n.data&&(r+="&connectionData="+t.encodeURIComponent(n.data)),r},addQs:function(t,i){var r=t.indexOf("?")!==-1?"&":"?",u;if(!i)return t;if(typeof i=="object")return t+r+n.param(i);if(typeof i=="string")return u=i.charAt(0),(u==="?"||u==="&")&&(r=""),t+r+i;throw new Error("Query string property must be either a string or object.");},getUrl:function(n,i,r,f,e){var h=i==="webSockets"?"":n.baseUrl,o=h+n.appRelativeUrl,s="transport="+i;return!e&&n.groupsToken&&(s+="&groupsToken="+t.encodeURIComponent(n.groupsToken)),r?(o+=f?"/poll":"/reconnect",!e&&n.messageId&&(s+="&messageId="+t.encodeURIComponent(n.messageId))):o+="/connect",o+="?"+s,o=u.prepareQueryString(n,o),n.transport&&n.accessToken&&(n.transport.name==="serverSentEvents"||n.transport.name==="webSockets")&&(o+="&access_token="+t.encodeURIComponent(n.accessToken)),e||(o+="&tid="+Math.floor(Math.random()*11)),o},maximizePersistentResponse:function(n){return{MessageId:n.C,Messages:n.M,Initialized:typeof n.S!="undefined"?!0:!1,ShouldReconnect:typeof n.T!="undefined"?!0:!1,LongPollDelay:n.L,GroupsToken:n.G,Error:n.E}},updateGroups:function(n,t){t&&(n.groupsToken=t)},stringifySend:function(n,t){return typeof t=="string"||typeof t=="undefined"||t===null?t:n.json.stringify(t)},ajaxSend:function(t,i){var h=u.stringifySend(t,i),c=e(t,"/send"),o,s=function(t,u){n(u).triggerHandler(f.onError,[r._.transportError(r.resources.sendFailed,u.transport,t,o),i])};return o=u.ajax(t,{url:c,type:t.ajaxDataType==="jsonp"?"GET":"POST",contentType:r._.defaultContentType,headers:t.accessToken?{Authorization:"Bearer "+t.accessToken}:{},data:{data:h},success:function(n){var i;if(n){try{i=t._parseResponse(n)}catch(r){s(r,t);t.stop();return}u.triggerReceived(t,i)}},error:function(n,i){i!=="abort"&&i!=="parsererror"&&s(n,t)}})},ajaxAbort:function(n,t){if(typeof n.transport!="undefined"){t=typeof t=="undefined"?!0:t;var i=e(n,"/abort");u.ajax(n,{url:i,async:t,timeout:1e3,type:"POST",headers:n.accessToken?{Authorization:"Bearer "+n.accessToken}:{},dataType:"text"});n.log("Fired ajax abort async = "+t+".")}},ajaxStart:function(t,i){var h=function(n){var i=t._deferral;i&&i.reject(n)},s=function(i){t.log("The start request failed. Stopping the connection.");n(t).triggerHandler(f.onError,[i]);h(i);t.stop()};t._.startRequest=u.ajax(t,{url:e(t,"/start"),headers:t.accessToken?{Authorization:"Bearer "+t.accessToken}:{},success:function(n,u,f){var e;try{e=t._parseResponse(n)}catch(o){s(r._.error(r._.format(r.resources.errorParsingStartResponse,n),o,f));return}e.Response==="started"?i():s(r._.error(r._.format(r.resources.invalidStartResponse,n),null,f))},error:function(n,i,u){i!==o?s(r._.error(r.resources.errorDuringStartRequest,u,n)):(t.log("The start request aborted because connection.stop() was called."),h(r._.error(r.resources.stoppedDuringStartRequest,null,n)))}})},tryAbortStartRequest:function(n){n._.startRequest&&(n._.startRequest.abort(o),delete n._.startRequest)},tryInitialize:function(n,t,i){t.Initialized&&i?i():t.Initialized&&n.log("WARNING! The client received an init message after reconnecting.")},triggerReceived:function(t,i){t._.connectingMessageBuffer.tryBuffer(i)||n(t).triggerHandler(f.onReceived,[i])},processMessages:function(t,i,f){var e;if(i&&typeof i.I!="undefined"){u.triggerReceived(t,i);return}if(u.markLastMessage(t),i){if(e=u.maximizePersistentResponse(i),e.Error){t.log("Received an error message from the server: "+i.E);n(t).triggerHandler(r.events.onError,[r._.error(i.E,"ServerError")]);t.stop(!1,!1);return}u.updateGroups(t,e.GroupsToken);e.MessageId&&(t.messageId=e.MessageId);e.Messages&&(n.each(e.Messages,function(n,i){u.triggerReceived(t,i)}),u.tryInitialize(t,e,f))}},monitorKeepAlive:function(t){var i=t._.keepAliveData;i.monitoring?t.log("Tried to monitor keep alive but it's already being monitored."):(i.monitoring=!0,u.markLastMessage(t),t._.keepAliveData.reconnectKeepAliveUpdate=function(){u.markLastMessage(t)},n(t).bind(f.onReconnect,t._.keepAliveData.reconnectKeepAliveUpdate),t.log("Now monitoring keep alive with a warning timeout of "+i.timeoutWarning+", keep alive timeout of "+i.timeout+" and disconnecting timeout of "+t.disconnectTimeout))},stopMonitoringKeepAlive:function(t){var i=t._.keepAliveData;i.monitoring&&(i.monitoring=!1,n(t).unbind(f.onReconnect,t._.keepAliveData.reconnectKeepAliveUpdate),t._.keepAliveData={},t.log("Stopping the monitoring of the keep alive."))},startHeartbeat:function(n){n._.lastActiveAt=(new Date).getTime();s(n)},markLastMessage:function(n){n._.lastMessageAt=(new Date).getTime()},markActive:function(n){return u.verifyLastActive(n)?(n._.lastActiveAt=(new Date).getTime(),!0):!1},isConnectedOrReconnecting:function(n){return n.state===r.connectionState.connected||n.state===r.connectionState.reconnecting},ensureReconnectingState:function(t){return c(t,r.connectionState.connected,r.connectionState.reconnecting)===!0&&n(t).triggerHandler(f.onReconnecting),t.state===r.connectionState.reconnecting},clearReconnectTimeout:function(n){n&&n._.reconnectTimeout&&(t.clearTimeout(n._.reconnectTimeout),delete n._.reconnectTimeout)},verifyLastActive:function(t){if((new Date).getTime()-t._.lastActiveAt>=t.reconnectWindow){var i=r._.format(r.resources.reconnectWindowTimeout,new Date(t._.lastActiveAt),t.reconnectWindow);return t.log(i),n(t).triggerHandler(f.onError,[r._.error(i,"TimeoutException")]),t.stop(!1,!1),!1}return!0},reconnect:function(n,i){var f=r.transports[i];if(u.isConnectedOrReconnecting(n)&&!n._.reconnectTimeout){if(!u.verifyLastActive(n))return;n._.reconnectTimeout=t.setTimeout(function(){u.verifyLastActive(n)&&(f.stop(n),u.ensureReconnectingState(n)&&(n.log(i+" reconnecting."),f.start(n)))},n.reconnectDelay)}},handleParseFailure:function(t,i,u,e,o){var s=r._.transportError(r._.format(r.resources.parseFailed,i),t.transport,u,o);e&&e(s)?t.log("Failed to parse server response while attempting to connect."):(n(t).triggerHandler(f.onError,[s]),t.stop())},initHandler:function(n){return new h(n)},foreverFrame:{count:0,connections:{}}}}(window.jQuery,window),function(n,t){var i=n.signalR,u=n.signalR.events,f=n.signalR.changeState,r=i.transports._logic;i.transports.webSockets={name:"webSockets",supportsKeepAlive:function(){return!0},send:function(t,f){var e=r.stringifySend(t,f);try{t.socket.send(e)}catch(o){n(t).triggerHandler(u.onError,[i._.transportError(i.resources.webSocketsInvalidState,t.transport,o,t.socket),f])}},start:function(e,o,s){var h,c=!1,l=this,a=!o,v=n(e);if(!t.WebSocket){s();return}e.socket||(h=e.webSocketServerUrl?e.webSocketServerUrl:e.wsProtocol+e.host,h+=r.getUrl(e,this.name,a),e.log("Connecting to websocket endpoint '"+h+"'."),e.socket=new t.WebSocket(h),e.socket.onopen=function(){c=!0;e.log("Websocket opened.");r.clearReconnectTimeout(e);f(e,i.connectionState.reconnecting,i.connectionState.connected)===!0&&v.triggerHandler(u.onReconnect)},e.socket.onclose=function(t){var r;this===e.socket&&(c&&typeof t.wasClean!="undefined"&&t.wasClean===!1?(r=i._.transportError(i.resources.webSocketClosed,e.transport,t),e.log("Unclean disconnect from websocket: "+(t.reason||"[no reason given]."))):e.log("Websocket closed."),s&&s(r)||(r&&n(e).triggerHandler(u.onError,[r]),l.reconnect(e)))},e.socket.onmessage=function(n){var t;try{t=e._parseResponse(n.data)}catch(i){r.handleParseFailure(e,n.data,i,s,n);return}t&&r.processMessages(e,t,o)})},reconnect:function(n){r.reconnect(n,this.name)},lostConnection:function(n){this.reconnect(n)},stop:function(n){r.clearReconnectTimeout(n);n.socket&&(n.log("Closing the Websocket."),n.socket.close(),n.socket=null)},abort:function(n,t){r.ajaxAbort(n,t)}}}(window.jQuery,window),function(n,t){var i=n.signalR,u=n.signalR.events,e=n.signalR.changeState,r=i.transports._logic,f=function(n){t.clearTimeout(n._.reconnectAttemptTimeoutHandle);delete n._.reconnectAttemptTimeoutHandle};i.transports.serverSentEvents={name:"serverSentEvents",supportsKeepAlive:function(){return!0},timeOut:3e3,start:function(o,s,h){var c=this,l=!1,a=n(o),v=!s,y;if(o.eventSource&&(o.log("The connection already has an event source. Stopping it."),o.stop()),!t.EventSource){h&&(o.log("This browser doesn't support SSE."),h());return}y=r.getUrl(o,this.name,v);try{o.log("Attempting to connect to SSE endpoint '"+y+"'.");o.eventSource=new t.EventSource(y,{withCredentials:o.withCredentials})}catch(p){o.log("EventSource failed trying to connect with error "+p.Message+".");h?h():(a.triggerHandler(u.onError,[i._.transportError(i.resources.eventSourceFailedToConnect,o.transport,p)]),v&&c.reconnect(o));return}v&&(o._.reconnectAttemptTimeoutHandle=t.setTimeout(function(){l===!1&&o.eventSource.readyState!==t.EventSource.OPEN&&c.reconnect(o)},c.timeOut));o.eventSource.addEventListener("open",function(){o.log("EventSource connected.");f(o);r.clearReconnectTimeout(o);l===!1&&(l=!0,e(o,i.connectionState.reconnecting,i.connectionState.connected)===!0&&a.triggerHandler(u.onReconnect))},!1);o.eventSource.addEventListener("message",function(n){var t;if(n.data!=="initialized"){try{t=o._parseResponse(n.data)}catch(i){r.handleParseFailure(o,n.data,i,h,n);return}r.processMessages(o,t,s)}},!1);o.eventSource.addEventListener("error",function(n){var r=i._.transportError(i.resources.eventSourceError,o.transport,n);this===o.eventSource&&(h&&h(r)||(o.log("EventSource readyState: "+o.eventSource.readyState+"."),n.eventPhase===t.EventSource.CLOSED?(o.log("EventSource reconnecting due to the server connection ending."),c.reconnect(o)):(o.log("EventSource error."),a.triggerHandler(u.onError,[r]))))},!1)},reconnect:function(n){r.reconnect(n,this.name)},lostConnection:function(n){this.reconnect(n)},send:function(n,t){r.ajaxSend(n,t)},stop:function(n){f(n);r.clearReconnectTimeout(n);n&&n.eventSource&&(n.log("EventSource calling close()."),n.eventSource.close(),n.eventSource=null,delete n.eventSource)},abort:function(n,t){r.ajaxAbort(n,t)}}}(window.jQuery,window),function(n,t){var r=n.signalR,e=n.signalR.events,o=n.signalR.changeState,i=r.transports._logic,u=function(){var n=t.document.createElement("iframe");return n.setAttribute("style","position:absolute;top:0;left:0;width:0;height:0;visibility:hidden;"),n},f=function(){var i=null,f=1e3,n=0;return{prevent:function(){r._.ieVersion<=8&&(n===0&&(i=t.setInterval(function(){var n=u();t.document.body.appendChild(n);t.document.body.removeChild(n);n=null},f)),n++)},cancel:function(){n===1&&t.clearInterval(i);n>0&&n--}}}();r.transports.foreverFrame={name:"foreverFrame",supportsKeepAlive:function(){return!0},iframeClearThreshold:50,start:function(n,r,e){if(n.accessToken){e&&(n.log("Forever Frame does not support connections that require a Bearer token to connect, such as the Azure SignalR Service."),e());return}var l=this,s=i.foreverFrame.count+=1,h,o=u(),c=function(){n.log("Forever frame iframe finished loading and is no longer receiving messages.");e&&e()||l.reconnect(n)};if(t.EventSource){e&&(n.log("Forever Frame is not supported by SignalR on browsers with SSE support."),e());return}o.setAttribute("data-signalr-connection-id",n.id);f.prevent();h=i.getUrl(n,this.name);h+="&frameId="+s;t.document.documentElement.appendChild(o);n.log("Binding to iframe's load event.");o.addEventListener?o.addEventListener("load",c,!1):o.attachEvent&&o.attachEvent("onload",c);o.src=h;i.foreverFrame.connections[s]=n;n.frame=o;n.frameId=s;r&&(n.onSuccess=function(){n.log("Iframe transport started.");r()})},reconnect:function(n){var r=this;i.isConnectedOrReconnecting(n)&&i.verifyLastActive(n)&&t.setTimeout(function(){if(i.verifyLastActive(n)&&n.frame&&i.ensureReconnectingState(n)){var u=n.frame,t=i.getUrl(n,r.name,!0)+"&frameId="+n.frameId;n.log("Updating iframe src to '"+t+"'.");u.src=t}},n.reconnectDelay)},lostConnection:function(n){this.reconnect(n)},send:function(n,t){i.ajaxSend(n,t)},receive:function(t,u){var f,e,o;if(t.json!==t._originalJson&&(u=t._originalJson.stringify(u)),o=t._parseResponse(u),i.processMessages(t,o,t.onSuccess),t.state===n.signalR.connectionState.connected&&(t.frameMessageCount=(t.frameMessageCount||0)+1,t.frameMessageCount>r.transports.foreverFrame.iframeClearThreshold&&(t.frameMessageCount=0,f=t.frame.contentWindow||t.frame.contentDocument,f&&f.document&&f.document.body)))for(e=f.document.body;e.firstChild;)e.removeChild(e.firstChild)},stop:function(n){var r=null;if(f.cancel(),n.frame){if(n.frame.stop)n.frame.stop();else try{r=n.frame.contentWindow||n.frame.contentDocument;r.document&&r.document.execCommand&&r.document.execCommand("Stop")}catch(u){n.log("Error occurred when stopping foreverFrame transport. Message = "+u.message+".")}n.frame.parentNode===t.document.documentElement&&t.document.documentElement.removeChild(n.frame);delete i.foreverFrame.connections[n.frameId];n.frame=null;n.frameId=null;delete n.frame;delete n.frameId;delete n.onSuccess;delete n.frameMessageCount;n.log("Stopping forever frame.")}},abort:function(n,t){i.ajaxAbort(n,t)},getConnection:function(n){return i.foreverFrame.connections[n]},started:function(t){o(t,r.connectionState.reconnecting,r.connectionState.connected)===!0&&n(t).triggerHandler(e.onReconnect)}}}(window.jQuery,window),function(n,t){var r=n.signalR,u=n.signalR.events,e=n.signalR.changeState,f=n.signalR.isDisconnecting,i=r.transports._logic;r.transports.longPolling={name:"longPolling",supportsKeepAlive:function(){return!1},reconnectDelay:3e3,start:function(o,s,h){var a=this,v=function(){v=n.noop;o.log("LongPolling connected.");s?s():o.log("WARNING! The client received an init message after reconnecting.")},y=function(n){return h(n)?(o.log("LongPolling failed to connect."),!0):!1},c=o._,l=0,p=function(i){t.clearTimeout(c.reconnectTimeoutId);c.reconnectTimeoutId=null;e(i,r.connectionState.reconnecting,r.connectionState.connected)===!0&&(i.log("Raising the reconnect event"),n(i).triggerHandler(u.onReconnect))},w=36e5;o.pollXhr&&(o.log("Polling xhr requests already exists, aborting."),o.stop());o.messageId=null;c.reconnectTimeoutId=null;c.pollTimeoutId=t.setTimeout(function(){(function e(s,h){var g=s.messageId,nt=g===null,k=!nt,tt=!h,d=i.getUrl(s,a.name,k,tt,!0),b={};(s.messageId&&(b.messageId=s.messageId),s.groupsToken&&(b.groupsToken=s.groupsToken),f(s)!==!0)&&(o.log("Opening long polling request to '"+d+"'."),s.pollXhr=i.ajax(o,{xhrFields:{onprogress:function(){i.markLastMessage(o)}},url:d,type:"POST",contentType:r._.defaultContentType,data:b,timeout:o._.pollTimeout,headers:o.accessToken?{Authorization:"Bearer "+o.accessToken}:{},success:function(r){var h,w=0,u,a;o.log("Long poll complete.");l=0;try{h=o._parseResponse(r)}catch(b){i.handleParseFailure(s,r,b,y,s.pollXhr);return}(c.reconnectTimeoutId!==null&&p(s),h&&(u=i.maximizePersistentResponse(h)),i.processMessages(s,h,v),u&&n.type(u.LongPollDelay)==="number"&&(w=u.LongPollDelay),f(s)!==!0)&&(a=u&&u.ShouldReconnect,!a||i.ensureReconnectingState(s))&&(w>0?c.pollTimeoutId=t.setTimeout(function(){e(s,a)},w):e(s,a))},error:function(f,h){var v=r._.transportError(r.resources.longPollFailed,o.transport,f,s.pollXhr);if(t.clearTimeout(c.reconnectTimeoutId),c.reconnectTimeoutId=null,h==="abort"){o.log("Aborted xhr request.");return}if(!y(v)){if(l++,o.state!==r.connectionState.reconnecting&&(o.log("An error occurred using longPolling. Status = "+h+".  Response = "+f.responseText+"."),n(s).triggerHandler(u.onError,[v])),(o.state===r.connectionState.connected||o.state===r.connectionState.reconnecting)&&!i.verifyLastActive(o))return;if(!i.ensureReconnectingState(s))return;c.pollTimeoutId=t.setTimeout(function(){e(s,!0)},a.reconnectDelay)}}}),k&&h===!0&&(c.reconnectTimeoutId=t.setTimeout(function(){p(s)},Math.min(1e3*(Math.pow(2,l)-1),w))))})(o)},250)},lostConnection:function(n){n.pollXhr&&n.pollXhr.abort("lostConnection")},send:function(n,t){i.ajaxSend(n,t)},stop:function(n){t.clearTimeout(n._.pollTimeoutId);t.clearTimeout(n._.reconnectTimeoutId);delete n._.pollTimeoutId;delete n._.reconnectTimeoutId;n.pollXhr&&(n.pollXhr.abort(),n.pollXhr=null,delete n.pollXhr)},abort:function(n,t){i.ajaxAbort(n,t)}}}(window.jQuery,window),function(n){function r(n){return n+s}function c(n,t,i){for(var f=n.length,u=[],r=0;r<f;r+=1)n.hasOwnProperty(r)&&(u[r]=t.call(i,n[r],r,n));return u}function l(t){return n.isFunction(t)?null:n.type(t)==="undefined"?null:t}function u(n){for(var t in n)if(n.hasOwnProperty(t))return!0;return!1}function f(n,t){var i=n._.invocationCallbacks,r,f;u(i)&&n.log("Clearing hub invocation callbacks with error: "+t+".");n._.invocationCallbackId=0;delete n._.invocationCallbacks;n._.invocationCallbacks={};for(f in i)r=i[f],r.method.call(r.scope,{E:t})}function e(t){return n.isFunction(t)&&t.toString().slice(0,256).indexOf("// Call the client hub method")>=0}function i(n,t){return new i.fn.init(n,t)}function t(i,r){var u={qs:null,logging:!1,useDefaultPath:!0};return n.extend(u,r),(!i||u.useDefaultPath)&&(i=(i||"")+"/signalr"),new t.fn.init(i,u)}var o=0,s=".hubProxy",h=n.signalR;i.fn=i.prototype={init:function(n,t){this.state={};this.connection=n;this.hubName=t;this._={callbackMap:{}}},constructor:i,hasSubscriptions:function(){return u(this._.callbackMap)},on:function(t,i,u){var c=this,l=c._.callbackMap,v=!u&&e(i),f,h,s,a;for(u=u||i,u._signalRGuid||(u._signalRGuid=o++),t=t.toLowerCase(),f=l[t],f||(f=[],l[t]=f),s=0;s<f.length;s++)(f[s].guid===u._signalRGuid||v&&f[s].isFromOldGeneratedHubProxy)&&(h=f[s]);return h||(h={guid:u._signalRGuid,eventHandlers:[],isFromOldGeneratedHubProxy:v},l[t].push(h)),a=function(n,t){i.apply(c,t)},h.eventHandlers.push(a),n(c).bind(r(t),a),c},off:function(t,i,u){var s=this,l=s._.callbackMap,f,a=!u&&e(i),h,v,o,c;if(u=u||i,t=t.toLowerCase(),f=l[t],f)if(i){for(o=0;o<f.length;o++)(f[o].guid===u._signalRGuid||a&&f[o].isFromOldGeneratedHubProxy)&&(v=o,h=f[o]);if(h){for(c=0;c<h.eventHandlers.length;c++)n(s).unbind(r(t),h.eventHandlers[c]);f.splice(o,1);f.length===0&&delete l[t]}}else i||(n(s).unbind(r(t)),delete l[t]);return s},invoke:function(t){var i=this,r=i.connection,e=n.makeArray(arguments).slice(1),o=c(e,l),f={H:i.hubName,M:t,A:o,I:r._.invocationCallbackId},u=n.Deferred(),s=function(f){var e=i._maximizeHubResponse(f),s,o;n.extend(i.state,e.State);e.Progress?u.notifyWith?u.notifyWith(i,[e.Progress.Data]):r._.progressjQueryVersionLogged||(r.log("A hub method invocation progress update was received but the version of jQuery in use ("+n.prototype.jquery+") does not support progress updates. Upgrade to jQuery 1.7+ to receive progress notifications."),r._.progressjQueryVersionLogged=!0):e.Error?(e.StackTrace&&r.log(e.Error+"\n"+e.StackTrace+"."),s=e.IsHubException?"HubException":"Exception",o=h._.error(e.Error,s),o.data=e.ErrorData,r.log(i.hubName+"."+t+" failed to execute. Error: "+o.message),u.rejectWith(i,[o])):(r.log("Invoked "+i.hubName+"."+t),u.resolveWith(i,[e.Result]))};return r._.invocationCallbacks[r._.invocationCallbackId.toString()]={scope:i,method:s},r._.invocationCallbackId+=1,n.isEmptyObject(i.state)||(f.S=i.state),r.log("Invoking "+i.hubName+"."+t),r.send(f),u.promise()},_maximizeHubResponse:function(n){return{State:n.S,Result:n.R,Progress:n.P?{Id:n.P.I,Data:n.P.D}:null,Id:n.I,IsHubException:n.H,Error:n.E,StackTrace:n.T,ErrorData:n.D}}};i.fn.init.prototype=i.fn;t.fn=t.prototype=n.connection();t.fn.init=function(t,i){var e={qs:null,logging:!1,useDefaultPath:!0},u=this;n.extend(e,i);n.signalR.fn.init.call(u,t,e.qs,e.logging);u.proxies={};u._.invocationCallbackId=0;u._.invocationCallbacks={};u.received(function(t){var f,o,e,i,s,h;t&&(typeof t.P!="undefined"?(e=t.P.I.toString(),i=u._.invocationCallbacks[e],i&&i.method.call(i.scope,t)):typeof t.I!="undefined"?(e=t.I.toString(),i=u._.invocationCallbacks[e],i&&(u._.invocationCallbacks[e]=null,delete u._.invocationCallbacks[e],i.method.call(i.scope,t))):(f=this._maximizeClientHubInvocation(t),u.log("Triggering client hub event '"+f.Method+"' on hub '"+f.Hub+"'."),s=f.Hub.toLowerCase(),h=f.Method.toLowerCase(),o=this.proxies[s],n.extend(o.state,f.State),n(o).triggerHandler(r(h),[f.Args])))});u.error(function(n,t){var i,r;t&&(i=t.I,r=u._.invocationCallbacks[i],r&&(u._.invocationCallbacks[i]=null,delete u._.invocationCallbacks[i],r.method.call(r.scope,{E:n})))});u.reconnecting(function(){u.transport&&u.transport.name==="webSockets"&&f(u,"Connection started reconnecting before invocation result was received.")});u.disconnected(function(){f(u,"Connection was disconnected before invocation result was received.")})};t.fn._maximizeClientHubInvocation=function(n){return{Hub:n.H,Method:n.M,Args:n.A,State:n.S}};t.fn._registerSubscribedHubs=function(){var t=this;t._subscribedToHubs||(t._subscribedToHubs=!0,t.starting(function(){var i=[];n.each(t.proxies,function(n){this.hasSubscriptions()&&(i.push({name:n}),t.log("Client subscribed to hub '"+n+"'."))});i.length===0&&t.log("No hubs have been subscribed to.  The client will not receive data from hubs.  To fix, declare at least one client side function prior to connection start for each hub you wish to subscribe to.");t.data=t.json.stringify(i)}))};t.fn.createHubProxy=function(n){n=n.toLowerCase();var t=this.proxies[n];return t||(t=i(this,n),this.proxies[n]=t),this._registerSubscribedHubs(),t};t.fn.init.prototype=t.fn;n.hubConnection=t}(window.jQuery,window),function(n){n.signalR.version="2.4.1"}(window.jQuery);
var AccordionAnchorLinkService = /** @class */ (function () {
    function AccordionAnchorLinkService() {
    }
    AccordionAnchorLinkService.prototype.init = function () {
        var self = this;
        $("body").on("click", "a[href*='#heading_']", function (e) {
            var anchorLink = this;
            if (!self.isAnchorLinkHrefEqualToCurrentUrlExceptQuerystringAndHash(anchorLink)) {
                // If the anchor link is to another page than current page we should not do anything
                return;
            }
            e.preventDefault(); // Prevents the default scrolling to the anchor, we want to run an animated scroll instead
            self.scrollToCollapseElementAndOpenIt(anchorLink);
        });
    };
    AccordionAnchorLinkService.prototype.isAnchorLinkHrefEqualToCurrentUrlExceptQuerystringAndHash = function (anchorLink) {
        if (anchorLink.origin !== window.location.origin)
            return false;
        return anchorLink.pathname === window.location.pathname;
    };
    AccordionAnchorLinkService.prototype.scrollToCollapseElementAndOpenIt = function (anchorLink) {
        var self = this;
        var $elementToScrollTo = $(anchorLink.hash);
        var $collapseElementToOpen = self.getCollapseElementToOpen($elementToScrollTo);
        if ($collapseElementToOpen === null)
            return;
        self.scrollToElement($elementToScrollTo, $collapseElementToOpen);
    };
    AccordionAnchorLinkService.prototype.getCollapseElementToOpen = function ($elementToScrollTo) {
        var $collapseGroupElement = $elementToScrollTo.parent(".accordion-group__element");
        return $collapseGroupElement.find(".collapse");
    };
    AccordionAnchorLinkService.prototype.scrollToElement = function ($elementToScrollTo, $collapseElementToOpen) {
        $("html, body")
            .animate({ scrollTop: $elementToScrollTo.offset().top - 10 }, 500)
            .promise()
            .then(function () { $collapseElementToOpen.collapse("show"); });
    };
    return AccordionAnchorLinkService;
}());

/*
 * Responsible to keep the open/collapsed state of each accordion to the url in a querystring if the use the back button
 */
var AccordionStateService = /** @class */ (function () {
    function AccordionStateService() {
        this.openAccordionsQuerystringKey = "openAccordions";
        this.separator = ",";
        // To make the querystring value small we removes this prefix
        this.accordionIdPrefix = "collapse_";
        var self = this;
        self.querystringHelper = new QueryStringHelper();
        self.querystringHelper.modifyCurrentHistoryEntry = true;
    }
    AccordionStateService.prototype.init = function () {
        var self = this;
        self.openAffectedAccordions(function () {
            self.attachEvents();
        });
    };
    AccordionStateService.prototype.openAffectedAccordions = function (callbackFunction) {
        if (callbackFunction === void 0) { callbackFunction = null; }
        var self = this;
        var openedAccordionIds = self.getOpenedAccordionKeysFromQuerystring();
        openedAccordionIds.forEach(function (accordionKey) {
            var accordionId = self.getAccordionIdFromKey(accordionKey);
            var accordion = $("#".concat(accordionId));
            accordion.collapse("show");
        });
        if (callbackFunction !== null)
            return callbackFunction();
    };
    AccordionStateService.prototype.attachEvents = function () {
        var self = this;
        var $body = $("body");
        var collapseSelector = ".faq-list-block .collapse, #faq-searchresult .collapse, .accordion-group.accordion-group--remember-state .collapse, .offer-list-block .collapse";
        $body.on("hide.bs.collapse", collapseSelector, function () {
            var accordionKey = self.getAccordionKey($(this));
            self.removeAccordionKeyFromQuerystring(accordionKey);
        });
        $body.on("show.bs.collapse", collapseSelector, function () {
            var accordionKey = self.getAccordionKey($(this));
            self.addAccordionKeyToQuerystring(accordionKey);
        });
    };
    AccordionStateService.prototype.getAccordionKey = function ($collapse) {
        var self = this;
        var id = $collapse.attr("id");
        return self.getAccordionKeyFromId(id);
    };
    AccordionStateService.prototype.removeAccordionKeyFromQuerystring = function (accordionKey) {
        var self = this;
        var openedAccordionKeys = self.getOpenedAccordionKeysFromQuerystring();
        var index = openedAccordionKeys.indexOf(accordionKey);
        if (index < 0)
            return;
        openedAccordionKeys.splice(index, 1);
        self.setOpenedAccordionKeysToQuerystring(openedAccordionKeys);
    };
    AccordionStateService.prototype.addAccordionKeyToQuerystring = function (accordionKey) {
        var self = this;
        // Removes this accordion key if it exists
        self.removeAccordionKeyFromQuerystring(accordionKey);
        // Adds the accordion key to the last position, this indicates that this accordion was the recently opened accordion
        var openedAccordionKeys = self.getOpenedAccordionKeysFromQuerystring();
        openedAccordionKeys.push(accordionKey);
        self.setOpenedAccordionKeysToQuerystring(openedAccordionKeys);
    };
    AccordionStateService.prototype.getOpenedAccordionKeysFromQuerystring = function () {
        var self = this;
        var openAccordionIds = self.querystringHelper.getParameter(self.openAccordionsQuerystringKey);
        if (openAccordionIds === null)
            return [];
        return openAccordionIds.split(self.separator);
    };
    AccordionStateService.prototype.setOpenedAccordionKeysToQuerystring = function (openedAccordionKeys) {
        var self = this;
        if (openedAccordionKeys.length === 0) {
            self.querystringHelper.removeParameter(self.openAccordionsQuerystringKey);
            return;
        }
        self.querystringHelper.updateParameter(self.openAccordionsQuerystringKey, openedAccordionKeys);
    };
    AccordionStateService.prototype.getAccordionKeyFromId = function (accordionId) {
        var self = this;
        if (accordionId.search("^".concat(self.accordionIdPrefix)) === -1)
            return accordionId;
        return accordionId.substr(self.accordionIdPrefix.length);
    };
    AccordionStateService.prototype.getAccordionIdFromKey = function (accordionKey) {
        var self = this;
        return self.accordionIdPrefix + accordionKey;
    };
    return AccordionStateService;
}());

var AnchorLinkBlockApp = /** @class */ (function () {
    function AnchorLinkBlockApp($el) {
        var _this = this;
        this.$el = $el;
        this.$link = this.$el.find("a");
        this.$link.click(function (e) {
            e.preventDefault();
            _this.scrollToAnchor();
        });
    }
    AnchorLinkBlockApp.prototype.scrollToAnchor = function () {
        var $anchor = $(this.$link.data("anchorselector")).filter(":visible");
        if ($anchor.length) {
            $("html, body").animate({ scrollTop: $anchor.offset().top - 20 }, 500);
        }
    };
    return AnchorLinkBlockApp;
}());

var BlocksInXhtmlMoveToClosestParagraph = /** @class */ (function () {
    // This class moves all the div-tags with a classname to either it's parent sibling or its child sibling, depending on which exists.
    // If no siblings of type <p> exists, do nothing
    function BlocksInXhtmlMoveToClosestParagraph(inlineBlockSelector) {
        $(inlineBlockSelector).each(function () {
            var parentSiblingParagraph = $(this).prev("p");
            var childSiblingParagraph = $(this).next("p");
            if (parentSiblingParagraph.length > 0) {
                $(this).detach().appendTo(parentSiblingParagraph);
                // If there us a sibling of type P below, we merge the two P-tags as well
                if (childSiblingParagraph) {
                    parentSiblingParagraph.append(childSiblingParagraph.detach().html());
                }
            }
            else if (childSiblingParagraph.length > 0) {
                $(this).detach().appendTo(childSiblingParagraph);
            }
        });
    }
    return BlocksInXhtmlMoveToClosestParagraph;
}());

var ConsolLogService = /** @class */ (function () {
    function ConsolLogService() {
    }
    ConsolLogService.prototype.log = function (logObject) {
        console.log(JSON.stringify(logObject));
    };
    return ConsolLogService;
}());

var CookieHandler = /** @class */ (function () {
    function CookieHandler() {
    }
    CookieHandler.prototype.setCookie = function (cookieData) {
        var cookie = cookieData.name + "=" + cookieData.value + ";path=/;samesite=" + cookieData.sameSite;
        if (document.location.protocol === "https:") {
            cookie += ";secure";
        }
        if (cookieData.daysToExpire) {
            var expireDate = new Date();
            expireDate.setTime(expireDate.getTime() + (cookieData.daysToExpire * 24 * 60 * 60 * 1000));
            cookie += ";expires=".concat(expireDate.toUTCString());
        }
        document.cookie = cookie;
    };
    CookieHandler.prototype.getCookie = function (name) {
        name = name + "=";
        var cookies = document.cookie.split(";");
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i];
            while (cookie.charAt(0) === " ") {
                cookie = cookie.substring(1);
            }
            if (cookie.indexOf(name) === 0) {
                return cookie.substring(name.length, cookie.length);
            }
        }
        return "";
    };
    return CookieHandler;
}());
var CookieData = /** @class */ (function () {
    function CookieData(name, value) {
        var self = this;
        self.name = name;
        self.value = value;
        self.sameSite = "Lax";
    }
    return CookieData;
}());

var CustomEventHandler = /** @class */ (function () {
    function CustomEventHandler() {
    }
    CustomEventHandler.prototype.trigger = function (eventName, data) {
        var evt = document.createEvent("CustomEvent");
        evt.initCustomEvent(eventName, false, false, data);
        document.dispatchEvent(evt);
    };
    CustomEventHandler.prototype.subscribe = function (eventName, callBack) {
        document.addEventListener(eventName, function (e) {
            callBack(e.detail);
        });
    };
    CustomEventHandler.employerChangedEventName = "employer-changed";
    CustomEventHandler.changeEmployerModalCanceled = "changeemployermodal-canceled";
    CustomEventHandler.iframeCookieConsentGiven = "iframecookieconsent-given";
    return CustomEventHandler;
}());

var DetectorService = /** @class */ (function () {
    function DetectorService() {
    }
    /*
     * https://stackoverflow.com/questions/31569518/how-to-detect-facebook-in-app-browser
     */
    DetectorService.prototype.isFacebookInApp = function () {
        var ua = navigator.userAgent || navigator.vendor;
        return (ua.indexOf("FBAN") > -1) || (ua.indexOf("FBAV") > -1);
    };
    /*
     * https://stackoverflow.com/questions/9038625/detect-if-device-is-ios
     */
    DetectorService.prototype.isIosDevice = function () {
        return /iPad|iPhone|iPod/.test(navigator.userAgent) && !window["MSStream"];
    };
    return DetectorService;
}());

var DeviceSizeService = /** @class */ (function () {
    function DeviceSizeService() {
    }
    DeviceSizeService.prototype.getDeviceSizeForFormData = function (formData) {
        if (FormData !== null) {
            formData.width = $(window).width().toString();
            formData.height = $(window).height().toString();
            formData.userAgent = navigator.userAgent;
            return formData;
        }
    };
    DeviceSizeService.prototype.getDeviceSize = function (widthElement, heightElement, userAgent) {
        widthElement.val($(window).width().toString());
        heightElement.val($(window).height().toString());
        userAgent.val(navigator.userAgent);
    };
    return DeviceSizeService;
}());

var EmergencyMessageBar = /** @class */ (function () {
    function EmergencyMessageBar(emergencyMessageSelector) {
        this.cookieStorageKey = "EmergencyMessage"; // Must be same as enum CookieName
        this.cookieStorageValue = "true";
        var self = this;
        self.$emergencyMessageBar = $(emergencyMessageSelector);
        if (self.$emergencyMessageBar != null) {
            self.$openView = self.$emergencyMessageBar.find(".emergency-message-bar__open");
            self.$closedView = self.$emergencyMessageBar.find(".emergency-message-bar__closed");
            var closeButton = self.$emergencyMessageBar.find(".emergency-message-bar__open__close-button");
            closeButton.click(function (e) {
                e.preventDefault();
                self.toggleEmergencyMessageBarState();
                if (!self.hasEmergencyCookie()) {
                    self.setEmergencyCookie();
                }
            });
            var openButton = self.$emergencyMessageBar.find(".emergency-message-bar__closed__header");
            openButton.click(function (e) {
                e.preventDefault();
                self.toggleEmergencyMessageBarState();
            });
        }
    }
    EmergencyMessageBar.prototype.toggleEmergencyMessageBarState = function () {
        var self = this;
        self.$closedView.toggle();
        self.$openView.toggle();
    };
    EmergencyMessageBar.prototype.hasEmergencyCookie = function () {
        var self = this;
        var cookieHandler = new CookieHandler();
        var cookie = cookieHandler.getCookie(self.cookieStorageKey);
        if (cookie) {
            return true;
        }
        return false;
    };
    EmergencyMessageBar.prototype.setEmergencyCookie = function () {
        var cookieHandler = new CookieHandler();
        var data = new CookieData(this.cookieStorageKey, this.cookieStorageValue);
        cookieHandler.setCookie(data);
    };
    return EmergencyMessageBar;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
/// <reference path="../../../../Scripts/typings/underscore/underscore.d.ts" />
var EntranceBlock = /** @class */ (function () {
    function EntranceBlock(entranceBlockSelector) {
        var self = this;
        self.$entranceBlock = $(entranceBlockSelector);
        self.$loadMoreEntranceBlocksLink = self.$entranceBlock.find(".entrance-block__load-more");
        if (self.$loadMoreEntranceBlocksLink.length === 1) {
            self.entranceBlockTemplate = _.template($("#entranceBlockTemplate").html());
            self.blockId = self.$entranceBlock.data("blockid");
            self.pageSize = self.$entranceBlock.data("pagesize");
            self.currentPageIndex = 0;
            self.$loadNextPageLink = self.$entranceBlock.find(".entrance-block__load-more");
            self.setUpEventHandlers();
        }
        $(window).on('resize load ajaxStop', function () {
            if (self.timer)
                window.clearTimeout(self.timer);
            self.timer = window.setTimeout(function () {
                self.setupEntranceItemHeightCalculation(true);
            }, 40);
        });
        // run twice to prevent "jumping" on load
        self.setupEntranceItemHeightCalculation(false);
    }
    EntranceBlock.prototype.setUpEventHandlers = function () {
        var self = this;
        self.$loadMoreEntranceBlocksLink.click(function (e) {
            e.preventDefault();
            self.loadNextPage();
        });
    };
    EntranceBlock.prototype.resetTitleHeights = function (titleHeights) {
        $.each(titleHeights, function (e, item) {
            $(item).css("height", "auto");
        });
    };
    EntranceBlock.prototype.setupEntranceItemHeightCalculation = function (isResize) {
        var self = this;
        self.$entranceBlockItems = self.$entranceBlock.find(".entrance-block__box-list .three-columns .entrance-block__box-link");
        if (isResize)
            self.resetTitleHeights(self.$entranceBlockItems);
        var currIndex = 1;
        var currHeight = 0;
        var currRow = [];
        self.$entranceBlockItems.each(function () {
            var currentElementHeight = $(this).outerHeight();
            currHeight = currentElementHeight > currHeight ? currentElementHeight : currHeight;
            currRow.push($(this));
            if (currIndex % 3 === 0 || currIndex === self.$entranceBlockItems.length) {
                $.each(currRow, function (e, item) {
                    $(item).css('height', currHeight);
                });
                currRow = [];
                currHeight = 0;
            }
            currIndex++;
        });
    };
    EntranceBlock.prototype.loadNextPage = function () {
        var self = this;
        self.currentPageIndex++;
        $.getJSON(InternalApiEndpoints.entranceBlock(self.blockId, self.currentPageIndex, self.pageSize), function (data) {
            var templatedHtml = $(self.entranceBlockTemplate({ entrancePageResult: data })); //todo: fh - refactor, should we use require or other amd for this?
            self.$entranceBlock.find(".entrance-block__box-list").append(templatedHtml);
            //TODO: fredrik kollar på ny lösning
            var win;
            win = window;
            win.slimmage.checkResponsiveImages();
            if (!data.HasMorePages) {
                self.$loadNextPageLink.remove();
            }
        });
    };
    return EntranceBlock;
}());

var EpiserverFileUploadService = /** @class */ (function () {
    function EpiserverFileUploadService($fileUploadContainer) {
        var self = this;
        self.$fileUploadContainer = $fileUploadContainer;
        self.$fileUploadButton = self.$fileUploadContainer.find(".file-upload__input-container");
        self.selectedMultipleFilesTemplate = _.template($("#episerver-form-file-input-template").html());
        self.$fileUploadControl = self.$fileUploadContainer.find("[type='file']");
        var fileUploadId = self.$fileUploadControl.attr("id");
        self.$fileDisplay = $("#file-display-".concat(fileUploadId));
        self.$removeFileButton = $("#remove-file-".concat(fileUploadId));
        self.attachEvents();
    }
    EpiserverFileUploadService.prototype.attachEvents = function () {
        var self = this;
        self.$fileUploadControl.change(function (e) {
            var $fileInput = e.target;
            var files = $fileInput.files;
            if (files != null && files.length > 0) {
                var templateData = void 0;
                if ($fileInput.hasAttribute("multiple")) {
                    templateData = {
                        fileDataList: files,
                        fileUpload: null,
                        fileDisplay: null,
                        removeFileButton: null
                    };
                    self.$removeFileButton.show();
                    self.$fileUploadButton.hide();
                }
                else {
                    templateData =
                        {
                            fileDataList: files,
                            fileUpload: "#".concat(self.$fileUploadControl.attr("id")),
                            fileDisplay: "#file-display-".concat(self.$fileUploadControl.attr("id")),
                            removeFileButton: "#remove-file-".concat(self.$fileUploadControl.attr("id"))
                        };
                }
                var templatedHtml = $(self.selectedMultipleFilesTemplate(templateData));
                self.$fileDisplay.html(templatedHtml.html());
                self.$fileDisplay.show();
            }
        });
        self.$fileUploadContainer.on("click", ".file-list__item__remove", function (e) {
            e.preventDefault();
            self.clearFileUpload();
        });
        self.$removeFileButton.click(function (e) {
            e.preventDefault();
            self.clearFileUpload();
        });
    };
    EpiserverFileUploadService.prototype.clearFileUpload = function () {
        var self = this;
        self.$fileDisplay.hide();
        self.$removeFileButton.hide();
        self.$fileUploadButton.show();
        self.$fileUploadControl.wrap("<form>").parent("form").trigger("reset");
        self.$fileUploadControl.unwrap();
    };
    return EpiserverFileUploadService;
}());

var ErrorMessageBox = /** @class */ (function () {
    function ErrorMessageBox(header, description) {
        this.$errorBox = $("<div />");
        this.$errorBox.addClass("error");
        this.$errorBox.addClass("error--no-margin");
        var $errorHeader = $("<h2 />");
        $errorHeader.html(header);
        this.$errorBox.append($errorHeader);
        this.$errorBox.append(description);
    }
    ErrorMessageBox.prototype.append = function ($errorMessageContainer) {
        $errorMessageContainer.empty();
        $errorMessageContainer.append(this.$errorBox);
    };
    ErrorMessageBox.prototype.scrollTo = function (scrollToErrorMessageOffset) {
        $("html, body").animate({ scrollTop: this.$errorBox.offset().top - scrollToErrorMessageOffset }, 500);
    };
    return ErrorMessageBox;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var Expandable = /** @class */ (function () {
    function Expandable(expandableContainerSelector) {
        this.expandables = $(expandableContainerSelector);
        this.setUpExpandables();
    }
    Expandable.prototype.setUpExpandables = function () {
        var self = this;
        this.expandables.each(function (i) {
            // ReSharper disable once SuspiciousThisUsage
            var $expandable = $(this);
            var $expandableArea = $expandable.find(".expandable-hidden");
            var $expandLink = $expandable.find("a.expandable-expand");
            var $minimizeLink = $expandable.find("a.expandable-minimize");
            var noScrollOnClose = $expandable.data("noscrollonclose") === true;
            // Set a unique id using index on expandable area for aria-controls
            var uniqueExpandableAreaId = "exp".concat(i);
            $expandableArea
                .attr("id", uniqueExpandableAreaId)
                .attr("aria-expanded", "false");
            $expandLink
                .attr("aria-expanded", "false")
                .attr("aria-controls", uniqueExpandableAreaId)
                .on("click", function (e) {
                e.preventDefault();
                $expandableArea
                    .slideToggle()
                    .attr("aria-expanded", "true")
                    .focus();
                $expandLink.hide();
                $minimizeLink.show();
            });
            $minimizeLink
                .attr("aria-expanded", "true")
                .attr("aria-controls", uniqueExpandableAreaId)
                .on("click", function (e) {
                e.preventDefault();
                $expandableArea
                    .slideToggle()
                    .attr("aria-expanded", "false");
                $expandLink.show();
                $minimizeLink.hide();
                if (!noScrollOnClose) {
                    $("html,body").animate({
                        scrollTop: self.findElementToScrollTo($expandable).offset().top - 10
                    }, 500);
                }
            });
        });
    };
    Expandable.prototype.findElementToScrollTo = function (expandable) {
        var scrollTo = expandable.parent().find("h1, h2, h3");
        if (!scrollTo.length) {
            scrollTo = expandable.parent().parent().find("h1, h2, h3");
        }
        if (scrollTo.length) {
            return scrollTo;
        }
        return expandable;
    };
    return Expandable;
}());

var FaqFeedback = /** @class */ (function () {
    function FaqFeedback(faqFeedbackSelector) {
        var self = this;
        self.faqFeedBack = $(faqFeedbackSelector);
        if (!self.faqFeedBack.length) {
            return;
        }
        self.positiveConfirm = self.faqFeedBack.find(".faq-feedback__positive-confirm");
        self.negativeForm = self.faqFeedBack.find(".faq-feedback__negative-form");
        self.negativeFormConfirm = self.faqFeedBack.find(".faq-feedback__negative-form-confirm");
        self.isHelpfulRadio = self.faqFeedBack.find("input[type=radio][name=ishelpful]");
        self.feedbackTextInput = self.faqFeedBack.find(".feedbacktext");
        self.pageId = self.faqFeedBack.data("pid");
        self.isHelpfulRadio.change(function () {
            self.acceptIsHelpfulFeedback(this.value);
        });
    }
    FaqFeedback.prototype.acceptIsHelpfulFeedback = function (isHelpful) {
        var self = this;
        if (isHelpful === "true") {
            self.positive();
        }
        else {
            self.negative();
        }
        self.isHelpfulRadio.parent("fieldset").hide();
        var postData = {
            pageId: self.pageId,
            isHelpful: isHelpful
        };
        $.ajax({
            url: InternalApiEndpoints.acceptIsHelpfulFeedback(),
            method: "POST",
            data: JSON.stringify(postData),
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                self.feedbackId = result;
            },
            error: function (xhr, textStatus, error) {
                console.log(xhr.responseText);
                console.log(textStatus);
                console.log(error);
            },
            async: true
        });
    };
    FaqFeedback.prototype.positive = function () {
        this.positiveConfirm.show();
    };
    FaqFeedback.prototype.negative = function () {
        var self = this;
        self.negativeForm.show();
        self.feedbackTextInput.bind("input propertychange", function () {
            if (self.feedbackTextInput.val().length > 0) {
                self.negativeForm.find("label.error").hide();
            }
            else {
                self.negativeForm.find("label.error").show();
            }
        });
        if (GlobalSettingsSingleton.getInstance().isMobileDevice()) {
            $("html,body").animate({
                scrollTop: self.faqFeedBack.offset().top - 10
            }, 500);
        }
        self.faqFeedBack.find(".btn").click(function (e) {
            e.preventDefault();
            if (!self.feedbackTextInput.val()) {
                self.faqFeedBack.find("label.error").show();
            }
            else {
                self.acceptTextFeedback();
            }
        });
    };
    FaqFeedback.prototype.acceptTextFeedback = function () {
        var self = this;
        self.negativeForm.hide();
        self.negativeFormConfirm.show();
        if (GlobalSettingsSingleton.getInstance().isMobileDevice()) {
            $("html,body").animate({
                scrollTop: self.faqFeedBack.offset().top - 10
            }, 500);
        }
        $.ajax({
            url: InternalApiEndpoints.acceptTextFeedback(self.pageId, self.feedbackId),
            method: "POST",
            data: '"' + self.feedbackTextInput.val() + '"',
            contentType: "application/json; charset=utf-8",
            success: function (result) {
            },
            error: function (xhr, textStatus, error) {
                console.log(xhr.responseText);
                console.log(textStatus);
                console.log(error);
            },
            async: true
        });
    };
    return FaqFeedback;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var GlobalSettingsSingleton = /** @class */ (function () {
    function GlobalSettingsSingleton() {
        if (GlobalSettingsSingleton._instance) {
            throw new Error("Error: Instantiation failed: Use GlobalSettingsSingleton.getInstance() instead of new.");
        }
        GlobalSettingsSingleton._instance = this;
    }
    GlobalSettingsSingleton.getInstance = function () {
        return GlobalSettingsSingleton._instance;
    };
    GlobalSettingsSingleton.prototype.isInEditMode = function () {
        return $("body").data("isineditmode");
    };
    GlobalSettingsSingleton.prototype.isInEditOrPreviewMode = function () {
        return $("body").data("isineditorpreviewmode");
    };
    GlobalSettingsSingleton.prototype.isMobileDevice = function () {
        return $("#mobileCheck").is(":hidden");
    };
    GlobalSettingsSingleton.prototype.isTabletDevice = function () {
        return $("#tabletCheck").is(":hidden");
    };
    GlobalSettingsSingleton.prototype.isDesktopDevice = function () {
        var self = this;
        return !self.isMobileDevice() && !self.isTabletDevice();
    };
    GlobalSettingsSingleton.prototype.getCurrentPageId = function () {
        return $("body").data("currentpageid");
    };
    GlobalSettingsSingleton.prototype.getContentVersionCacheKey = function () {
        return $("body").data("cvck");
    };
    GlobalSettingsSingleton.prototype.getStartPageId = function () {
        return $("body").data("startpageid");
    };
    GlobalSettingsSingleton.prototype.getmyPagesStartPageId = function () {
        return $("body").data("mypageid");
    };
    GlobalSettingsSingleton.prototype.getFacebookAppId = function () {
        return $("body").data("fbappid");
    };
    GlobalSettingsSingleton.prototype.getMarketingCloudOrganisationId = function () {
        return $("body").data("mcid");
    };
    GlobalSettingsSingleton.prototype.getSiteUrl = function () {
        return $("body").data("siteurl");
    };
    GlobalSettingsSingleton.prototype.isImpersonatedMember = function () {
        return $("body").data("isimpersonatedmember");
    };
    GlobalSettingsSingleton.prototype.isInPreviewMode = function () {
        return $("body").data("isinpreviewmode");
    };
    GlobalSettingsSingleton.prototype.isAuthenticatedWithMemberNumber = function () {
        return $("body").data("isauthenticatedwithmembernumber");
    };
    GlobalSettingsSingleton.prototype.hasBrowserTouchCapabilities = function () {
        return $("html").hasClass("no-touch");
    };
    GlobalSettingsSingleton._instance = new GlobalSettingsSingleton();
    return GlobalSettingsSingleton;
}());

var GoogleDataLayerService = /** @class */ (function () {
    function GoogleDataLayerService() {
    }
    GoogleDataLayerService.prototype.push = function (trackingObject) {
        window.dataLayer = window.dataLayer || [];
        window.dataLayer.push(trackingObject);
    };
    return GoogleDataLayerService;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
// This class is responsible for wrapping embedded videos (iframes) with a div so that we can make them responsive
var Iframe = /** @class */ (function () {
    function Iframe() {
        var self = this;
        //Check for no-iframe-div class from tinymce to handle screen9 embed code
        var noIframeDiv = $(".no-iframe-div");
        $("iframe:not(.no-iframe-wrapper)").each(function () {
            if (self.hasWidscreenAspectRatio($(this)) && noIframeDiv.length == 0) {
                $(this).wrap($("<div />").addClass("iframe-widescreen-wrapper"));
            }
        });
    }
    Iframe.prototype.hasWidscreenAspectRatio = function ($iframe) {
        var ratio = $iframe.outerHeight() / $iframe.outerWidth();
        return ratio >= 0.54 && ratio <= 0.58;
    };
    return Iframe;
}());

var IframeCookieConsent = /** @class */ (function () {
    function IframeCookieConsent($cookieConsent) {
        this.cookieHandler = new CookieHandler();
        this.iframeCookieConsentCookieName = "IframeCookieConsent";
        this.domain = null;
        this.$el = $cookieConsent;
        this.domain = this.$el.data("iframe-cookie-consent-domain");
        this.$iframe = $("#".concat(this.$el.data("iframe-id")));
        this.customEventHandler = new CustomEventHandler();
        this.attachHandlers();
    }
    IframeCookieConsent.prototype.attachHandlers = function () {
        var self = this;
        self.$el.find(".iframe-cookie-consent__consent-link").click(function (e) {
            e.preventDefault();
            self.giveConsent();
        });
        self.customEventHandler.subscribe("onetrustconsentchanged", function (onetrustActiveGroups) {
            var cookieConsentCategory = self.$el.data("iframe-cookie-consent-category");
            if (onetrustActiveGroups.indexOf(cookieConsentCategory) !== -1) {
                self.removeCookieConsentAndLoadIframe();
            }
        });
        self.customEventHandler.subscribe(CustomEventHandler.iframeCookieConsentGiven, function (domain) {
            if (self.domain === domain) {
                self.removeCookieConsentAndLoadIframe();
            }
        });
    };
    IframeCookieConsent.prototype.removeCookieConsentAndLoadIframe = function () {
        this.removeIframeCookieConsent();
        this.loadIframe();
    };
    IframeCookieConsent.prototype.giveConsent = function () {
        var self = this;
        self.updateIframeCookieConsentCookie();
        self.removeCookieConsentAndLoadIframe();
        self.customEventHandler.trigger(CustomEventHandler.iframeCookieConsentGiven, self.domain);
    };
    IframeCookieConsent.prototype.removeIframeCookieConsent = function () {
        this.$el.remove();
    };
    IframeCookieConsent.prototype.loadIframe = function () {
        var self = this;
        self.$iframe.removeClass("iframe--consent-not-given");
        self.$iframe.attr("src", self.$iframe.data("src"));
        if (self.hasWideScreenAspectRatio(self.$iframe) && self.$iframe.hasClass("add-iframe-wrapper-when-consent-given")) {
            self.$iframe.wrap($("<div />").addClass("iframe-widescreen-wrapper"));
        }
    };
    IframeCookieConsent.prototype.hasWideScreenAspectRatio = function ($iframe) {
        var ratio = $iframe.outerHeight() / $iframe.outerWidth();
        return ratio >= 0.54 && ratio <= 0.58;
    };
    IframeCookieConsent.prototype.updateIframeCookieConsentCookie = function () {
        var self = this;
        var cookie = self.getIframeCookieConsentCookie();
        if (cookie.value.length === 0) {
            cookie.value = self.domain;
        }
        else {
            var iframeCookieConsents = cookie.value.split(",");
            if (iframeCookieConsents.indexOf(self.domain) === -1) {
                cookie.value += ",".concat(self.domain);
            }
        }
        self.cookieHandler.setCookie(cookie);
    };
    IframeCookieConsent.prototype.getIframeCookieConsentCookie = function () {
        var self = this;
        var cookieValue = self.cookieHandler.getCookie(self.iframeCookieConsentCookieName);
        return new CookieData(self.iframeCookieConsentCookieName, cookieValue);
    };
    return IframeCookieConsent;
}());

var ImageHelper = /** @class */ (function () {
    function ImageHelper() {
        var self = this;
        self.imageTemplate = _.template($("#image-template").html());
        self.imageTemplate2 = _.template($("#image-template2").html());
    }
    ImageHelper.prototype.updateSrc = function (imageData) {
        var self = this;
        var url = imageData.imageSrc;
        var querystring = "";
        if (imageData.quality)
            querystring += "quality=true&";
        if (imageData.height)
            querystring += "height=".concat(imageData.height, "&");
        if (imageData.width)
            querystring += "width=".concat(imageData.width, "&");
        if (imageData.mode)
            querystring += "mode=".concat(imageData.mode, "&");
        if (imageData.anchor)
            querystring += "anchor=".concat(imageData.anchor, "&");
        if (querystring.length) {
            querystring = querystring.substring(0, querystring.length - +(querystring.lastIndexOf('&') === querystring.length - 1));
            url += "?".concat(querystring);
        }
        return $(self.imageTemplate({
            imageSrc: url,
            altText: imageData.altText,
            cssClass: imageData.cssClass
        })).html();
    };
    ImageHelper.prototype.updateSrc2 = function (imageData) {
        var self = this;
        var url = imageData.imageSrc;
        var querystring = "";
        if (imageData.quality)
            querystring += "quality=true&";
        if (imageData.height)
            querystring += "height=".concat(imageData.height, "&");
        if (imageData.width)
            querystring += "width=".concat(imageData.width, "&");
        if (imageData.mode)
            querystring += "mode=".concat(imageData.mode, "&");
        if (imageData.anchor)
            querystring += "anchor=".concat(imageData.anchor, "&");
        if (querystring.length) {
            querystring = querystring.substring(0, querystring.length - +(querystring.lastIndexOf('&') === querystring.length - 1));
            url += "?".concat(querystring);
        }
        return $(self.imageTemplate2({
            imageSrc: url,
            altText: imageData.altText,
            cssClass: imageData.cssClass
        })).html();
    };
    return ImageHelper;
}());
var ImageResizerData = /** @class */ (function () {
    function ImageResizerData() {
    }
    return ImageResizerData;
}());

var IndustryWithAssociationFeeSelector = /** @class */ (function () {
    function IndustryWithAssociationFeeSelector(industrySelector, lowestTotalPrice, lowestAssociationFee) {
        var _this = this;
        this.lowestTotalPrice = lowestTotalPrice;
        this.lowestAssociationFee = lowestAssociationFee;
        this.industryDropdown = $(industrySelector);
        this.industryDropdown.on("change", function (e) {
            _this.currentIndustryModel = _this.getCurrentIndustryModel();
            if (_this.onIndustryChange !== undefined) {
                _this.onIndustryChange(_this.currentIndustryModel);
            }
        });
    }
    IndustryWithAssociationFeeSelector.prototype.getCurrentIndustryModel = function () {
        var self = this;
        var model = new IndustryModel();
        model.basePrice = self.lowestTotalPrice;
        model.basePriceMinusDiff = self.lowestTotalPrice - self.lowestAssociationFee;
        if (this.industryDropdown.val().toString().indexOf("|") > 0) {
            model.defaultValSelected = false;
            model.industryPrice = +this.getIndustryPrice(this.industryDropdown.val());
            model.bfName = this.getBfName(this.industryDropdown.val());
            model.totalPrice = (model.industryPrice + self.lowestTotalPrice - self.lowestAssociationFee);
            model.bfUrl = this.getBfUrl(this.industryDropdown.val());
            model.industryId = this.getIndustryId(this.industryDropdown.val());
        }
        else {
            model.defaultValSelected = true;
        }
        return model;
    };
    IndustryWithAssociationFeeSelector.prototype.changeSelectedIndustry = function (industryId) {
        var self = this;
        var optionValue = self.getOptionValue(industryId);
        if (optionValue != null) {
            self.industryDropdown.val(optionValue);
        }
    };
    IndustryWithAssociationFeeSelector.prototype.getIndustryPrice = function (selectedValue) {
        var self = this;
        return +self.getSelectionValuePart(0, selectedValue);
    };
    IndustryWithAssociationFeeSelector.prototype.getBfName = function (selectedValue) {
        var self = this;
        return self.getSelectionValuePart(1, selectedValue);
    };
    IndustryWithAssociationFeeSelector.prototype.getBfUrl = function (selectedValue) {
        var self = this;
        return self.getSelectionValuePart(2, selectedValue);
    };
    IndustryWithAssociationFeeSelector.prototype.getIndustryId = function (optionValue) {
        var self = this;
        return self.getSelectionValuePart(3, optionValue);
    };
    IndustryWithAssociationFeeSelector.prototype.getOptionValue = function (industryId) {
        var self = this;
        var optionValue = null;
        self.industryDropdown.find("option").each(function (index, option) {
            var currentOptionValue = $(option).val();
            if (self.getIndustryId(currentOptionValue) === industryId) {
                optionValue = currentOptionValue;
                return false;
            }
        });
        return optionValue;
    };
    IndustryWithAssociationFeeSelector.prototype.getSelectionValuePart = function (index, selectedValue) {
        if (selectedValue === undefined)
            return "";
        selectedValue = selectedValue.toString();
        return selectedValue.split("|")[index];
    };
    IndustryWithAssociationFeeSelector.prototype.triggerChangeEvent = function () {
        this.industryDropdown.trigger('change');
    };
    IndustryWithAssociationFeeSelector.prototype.hasASelectedIndustry = function () {
        return this.industryDropdown.val().toString().indexOf("|") > 0;
    };
    return IndustryWithAssociationFeeSelector;
}());
var IndustryModel = /** @class */ (function () {
    function IndustryModel() {
        this.industryPrice = 0;
    }
    return IndustryModel;
}());

var InternalApiEndpoints = /** @class */ (function () {
    function InternalApiEndpoints() {
    }
    InternalApiEndpoints.mobileNavigationSiteMenu = function (contentVersionCacheKey, rootpageId, currentPageId) {
        return "/api/sitemenu/mobile/".concat(contentVersionCacheKey, "/").concat(rootpageId, "/").concat(currentPageId);
    };
    InternalApiEndpoints.mobileNavigationMyPagesMenuApi = function (contentVersionCacheKey, rootpageId, currentPageId) {
        return "/api/mypagesmenu/mobile/".concat(contentVersionCacheKey, "/").concat(rootpageId, "/").concat(currentPageId);
    };
    InternalApiEndpoints.entranceBlock = function (blockId, pageIndex, pageSize) {
        return "/api/entranceblock/".concat(blockId, "/").concat(pageIndex, "/").concat(pageSize);
    };
    InternalApiEndpoints.salaryStats = function (selections) {
        return "/api/salarystats/?".concat($.param(selections));
    };
    InternalApiEndpoints.acceptIsHelpfulFeedback = function () {
        return "/api/feedback/";
    };
    InternalApiEndpoints.acceptTextFeedback = function (pageId, feedbackid) {
        return "/api/feedback/".concat(pageId, "/").concat(feedbackid);
    };
    InternalApiEndpoints.globalSearch = function () {
        return "/api/globalsearch/search/";
    };
    InternalApiEndpoints.globalNewsSearch = function () {
        return "/api/globalnewssearch/search";
    };
    InternalApiEndpoints.newsFromRssFeed = function (feedUrl, itemsToTake, categories) {
        if (categories === void 0) { categories = null; }
        var url = "/api/newsfromrss/getnews?url=".concat(feedUrl, "&itemstotake=").concat(itemsToTake);
        if (categories != null) {
            url += "&categories=".concat(categories);
        }
        return url;
    };
    InternalApiEndpoints.globalSearchAutoComplete = function () {
        return "/api/globalsearch/autocomplete/";
    };
    InternalApiEndpoints.facebookFeed = function (blockId, maxPostsInFeed) {
        return "/api/facebookfeedapi/".concat(blockId, "/").concat(maxPostsInFeed);
    };
    InternalApiEndpoints.getCourseStatus = function (palmsCourseLinkPageId) {
        return "/api/course/getcoursestatus?palmsCourseLinkPageId=".concat(palmsCourseLinkPageId);
    };
    InternalApiEndpoints.memberApplication = function () {
        return "/api/memberapplication";
    };
    InternalApiEndpoints.memberRegistration = function () {
        return "/api/memberregistration";
    };
    InternalApiEndpoints.negotiationRequestApplication = function () {
        return "/api/negotiationrequest/";
    };
    InternalApiEndpoints.saveLead = function () {
        return "/api/savelead";
    };
    InternalApiEndpoints.availableJobsApi = function (pageIndex, pageSize, query, sortOrder) {
        return "/api/availablejobsapi?pageIndex=".concat(pageIndex, "&pageSize=").concat(pageSize, "&queryText=").concat(encodeURIComponent(query), "&sortOrder=").concat(sortOrder);
    };
    InternalApiEndpoints.memberReportsApiGetUsersAllMemberReports = function (myMemberReportsPageId) {
        return "/api/memberreportsapi/getusersallmemberreports?myMemberReportsPageId=" + myMemberReportsPageId;
    };
    InternalApiEndpoints.memberReportsApiGetMockedUsersAllMemberReports = function (myMemberReportsPageId) {
        return "/api/memberreportsapi/getmockedusersallmemberreports?myMemberReportsPageId=" + myMemberReportsPageId;
    };
    InternalApiEndpoints.memberReportsApiGetMemberReportFile = function (documentId) {
        return "/api/memberreportsapi/getmemberreportfile?documentId=".concat(documentId);
    };
    InternalApiEndpoints.contractsApiSearchContracts = function (categoryId) {
        return "/api/searchcontracts?contractcategoryid=".concat(encodeURIComponent(categoryId));
    };
    InternalApiEndpoints.contractsApiGetContractFile = function (documentId, contractCategoryId, agreementAreaId) {
        return "/api/getcontractfile/?documentid=".concat(documentId, "&contractcategoryid=").concat(contractCategoryId, "&agreementareaid=").concat(agreementAreaId);
    };
    InternalApiEndpoints.memberServicesDeleteCompany = function () {
        return "/api/membercompany";
    };
    InternalApiEndpoints.searchCompanies = function (query, city, countryCode, pageIndex, pageSize, fillCountriesAndCitiesData) {
        var url = "/api/companies/search/?pageIndex=".concat(pageIndex, "&pageSize=").concat(pageSize);
        if (query !== null && query.length)
            url += "&query=".concat(encodeURIComponent(query));
        if (countryCode !== null && countryCode.length)
            url += "&countryCode=".concat(encodeURIComponent(countryCode));
        if (city !== null && city.length)
            url += "&city=".concat(encodeURIComponent(city));
        if (fillCountriesAndCitiesData !== null && fillCountriesAndCitiesData)
            url += "&fillCountriesAndCitiesData=true";
        return url;
    };
    InternalApiEndpoints.getCompanyDetails = function (bbcId) {
        return "/api/companies/getdetails/?bbcId=".concat(bbcId);
    };
    InternalApiEndpoints.publicSearchCompanies = function (query, city, countryCode, pageIndex, pageSize, fillCountriesAndCitiesData) {
        var url = "/api/companies/publicsearch/?pageIndex=".concat(pageIndex, "&pageSize=").concat(pageSize);
        if (query !== null && query.length)
            url += "&query=".concat(encodeURIComponent(query));
        if (countryCode !== null && countryCode.length)
            url += "&countryCode=".concat(encodeURIComponent(countryCode));
        if (city !== null && city.length)
            url += "&city=".concat(encodeURIComponent(city));
        if (fillCountriesAndCitiesData !== null && fillCountriesAndCitiesData)
            url += "&fillCountriesAndCitiesData=true";
        return url;
    };
    InternalApiEndpoints.publicGetCompanyDetails = function (bbcId) {
        return "/api/companies/publicgetdetails/?bbcId=".concat(bbcId);
    };
    InternalApiEndpoints.changeEmployerByBbcId = function (bbcId) {
        return "/api/companies/changeemployerbybbcid/?bbcId=".concat(bbcId);
    };
    InternalApiEndpoints.changeEmployerManually = function () {
        return "/api/companies/changeemployermanually/";
    };
    InternalApiEndpoints.deleteMemberCompany = function () {
        return "/api/companies/deletemembercompany/";
    };
    InternalApiEndpoints.getMemberCompany = function () {
        return "/api/companies/getmembercompany/";
    };
    InternalApiEndpoints.getSurveyGeneratorSsoLink = function (surveyGeneratorPageId) {
        return "/api/surveygenerator/getsurveygeneratorssolink?surveyGeneratorPageId=".concat(surveyGeneratorPageId);
    };
    InternalApiEndpoints.isCourseValid = function (palmsCourseLinkPageId) {
        return "/api/course/iscoursevalid?palmsCourseLinkPageId=".concat(palmsCourseLinkPageId);
    };
    InternalApiEndpoints.getSession = function () {
        return "/api/login/getsession";
    };
    return InternalApiEndpoints;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var LinkableBlock = /** @class */ (function () {
    function LinkableBlock(editorialBlockSelector) {
        var self = this;
        self.$editorialBlock = $(editorialBlockSelector);
        var target = $(editorialBlockSelector).find(".one-puff-block__link").attr("target");
        if (self.$editorialBlock.length) {
            self.$editorialBlock.addClass("one-puff-block__has-hover");
            self.$editorialBlock.click(function () {
                if (target === "_blank") {
                    window.open($(this).find("a:first").attr("href"));
                }
                else {
                    window.location.assign($(this).find("a:first").attr("href"));
                }
            });
        }
    }
    return LinkableBlock;
}());

var MembershipCostBlock = /** @class */ (function () {
    function MembershipCostBlock(membershipCostBlockSelector) {
        var _this = this;
        this.noBackgroundImageCssClass = "membership-cost-block--no-backgroup-image";
        this.hideCssClass = "hide";
        var self = this;
        self.$membershipCostBlock = $(membershipCostBlockSelector);
        self.$mainColumn = self.$membershipCostBlock.find(".membership-cost-block__main-column");
        self.$feeColumn = self.$membershipCostBlock.find(".membership-cost-block__fee-column");
        self.$membershipCostFeeColumnPrice = self.$feeColumn.find(".membership-cost-block__fee-column__box__price");
        self.$button = self.$feeColumn.find(".membership-cost-block__fee-column__box__button");
        self.industrySelector = new IndustryWithAssociationFeeSelector(membershipCostBlockSelector + "__industry", self.$membershipCostBlock.data("totalfee"), self.$membershipCostBlock.data("lowestassociationfee"));
        self.industrySelector.onIndustryChange = function (industryModel) {
            _this.updateSelectedIndustry(industryModel);
        };
        // If page was loaded by BFCache an industry maybe is selected on page load
        var currentIndustryModel = self.industrySelector.getCurrentIndustryModel();
        self.updateSelectedIndustry(currentIndustryModel);
        //$(window).on("resize", () => {
        //    self.setFeeColumnsHeight();
        //});
    }
    MembershipCostBlock.prototype.updateButtonLink = function () {
        var self = this;
        var queryStringHelper = new QueryStringHelper(self.$button.attr("href"));
        var industryId = self.industrySelector.getCurrentIndustryModel().industryId;
        if (industryId != null) {
            queryStringHelper.updateParameter("industryId", industryId);
        }
        self.$button.attr("href", queryStringHelper.getCurrentUrl());
    };
    MembershipCostBlock.prototype.updateSelectedIndustry = function (industryModel) {
        var self = this;
        if (industryModel.defaultValSelected) {
            self.hidePrice();
        }
        else {
            self.showPrice(industryModel.totalPrice);
            self.updateButtonLink();
        }
        /*self.setFeeColumnsHeight();*/
    };
    //private setFeeColumnsHeight() {
    //    const self = this;
    //    self.$feeColumn.height(self.$mainColumn.outerHeight());
    //}
    MembershipCostBlock.prototype.hidePrice = function () {
        var self = this;
        self.$membershipCostBlock.removeClass(self.noBackgroundImageCssClass);
        self.$feeColumn.addClass(self.hideCssClass);
    };
    MembershipCostBlock.prototype.showPrice = function (price) {
        var self = this;
        self.$membershipCostBlock.addClass(self.noBackgroundImageCssClass);
        self.$feeColumn.removeClass(self.hideCssClass);
        self.$membershipCostFeeColumnPrice.html(price + ":-");
    };
    return MembershipCostBlock;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
/// <reference path="../../../../Scripts/typings/underscore/underscore.d.ts" />
var MobileNavigation = /** @class */ (function () {
    function MobileNavigation(mobileNavigationClosedButtonSelector, mobileNavigationOpenButtonSelector, mobileNavigationContainerSelector, isMyPagesMenu) {
        var _this = this;
        var self = this;
        self.isMyPagesMenu = isMyPagesMenu;
        self.mobileNavigationClosedButton = $(mobileNavigationClosedButtonSelector);
        self.mobileNavigationOpenButton = $(mobileNavigationOpenButtonSelector);
        self.mobileNavigationContainer = $(mobileNavigationContainerSelector);
        if (self.isMyPagesMenu) {
            self.startPageId = GlobalSettingsSingleton.getInstance().getmyPagesStartPageId();
            self.getMobileNavigationApiUrl = InternalApiEndpoints.mobileNavigationMyPagesMenuApi;
        }
        else {
            self.startPageId = GlobalSettingsSingleton.getInstance().getStartPageId();
            self.getMobileNavigationApiUrl = InternalApiEndpoints.mobileNavigationSiteMenu;
        }
        self.mobileNavigationTemplate = _.template($("#mobileMenuTemplate").html());
        self.customEventHandler = new CustomEventHandler();
        self.attachEventListeners();
        self.customEventHandler.subscribe("tools-menu-item-opened", function () {
            _this.closeMobileMenu();
        });
    }
    MobileNavigation.prototype.attachEventListeners = function () {
        var _this = this;
        var self = this;
        this.mobileNavigationOpenButton.on("click", function (e) {
            e.preventDefault();
            _this.closeMobileMenu();
        });
        this.mobileNavigationClosedButton.on("click", function (e) {
            e.preventDefault();
            _this.openMobileMenu();
        });
        $(self.mobileNavigationContainer)
            .on("click", ".mobile-navigation__expand-link", function (e) {
            e.preventDefault();
            var $this = $(this);
            var expandContainer = $this.parents("li").first().find(".mobile-navigation__child-container");
            if ($this.hasClass("mobile-navigation__expand-link--closed")) {
                // open or render level
                var expandPageId = Number($this.data("expandpageid"));
                if (expandContainer.children().length) {
                    expandContainer.show();
                }
                else {
                    self.renderLevel(expandPageId, expandPageId, self.mobileNavigationTemplate, expandContainer);
                }
                $this.addClass("mobile-navigation__expand-link--open");
                $this.removeClass("mobile-navigation__expand-link--closed");
            }
            else {
                // close level
                expandContainer.hide();
                $this.removeClass("mobile-navigation__expand-link--open");
                $this.addClass("mobile-navigation__expand-link--closed");
            }
        });
    };
    MobileNavigation.prototype.openMobileMenu = function () {
        var self = this;
        if (!this.isRenderedForCurrentPage) {
            this.renderLevel(self.startPageId, GlobalSettingsSingleton.getInstance().getCurrentPageId(), this.mobileNavigationTemplate, this.mobileNavigationContainer);
        }
        if (!self.isMyPagesMenu) {
            this.mobileNavigationClosedButton.hide();
            this.mobileNavigationOpenButton.show();
            this.mobileNavigationOpenButton.css("display", "inline-block");
            this.mobileNavigationContainer.show();
        }
        this.isRenderedForCurrentPage = true;
    };
    MobileNavigation.prototype.closeMobileMenu = function () {
        var self = this;
        if (!self.isMyPagesMenu) {
            this.mobileNavigationClosedButton.show();
            this.mobileNavigationOpenButton.hide();
            this.mobileNavigationContainer.hide();
        }
    };
    MobileNavigation.prototype.renderLevel = function (rootPageId, currentPageId, template, renderContainer) {
        var self = this;
        $.getJSON(self.getMobileNavigationApiUrl(GlobalSettingsSingleton.getInstance().getContentVersionCacheKey(), rootPageId, currentPageId), function (data) {
            //todo: kj - refactor, should we use require or other amd for this?
            var templatedHtml = $(template({ menuItems: data, templateFn: template }));
            renderContainer.html(templatedHtml.html());
            if (self.isMyPagesMenu && window.innerWidth <= 1023) {
                setTimeout(function () {
                    $("#my-menu-popout").css("max-height", $(renderContainer).height() + $("#my-menu-popout").height());
                }, 100);
            }
        });
    };
    return MobileNavigation;
}());

var MyInformationSummary = /** @class */ (function () {
    function MyInformationSummary($myInformationSummary) {
        var self = this;
        this.$el = $myInformationSummary;
        this.customEventHandler = new CustomEventHandler();
        this.$employer = this.$el.find(".my-information-summary__employer");
        if (this.$employer.length === 0)
            return;
        this.customEventHandler.subscribe(CustomEventHandler.employerChangedEventName, function (memberCompany) {
            self.renderEmploymentData(memberCompany);
        });
        if (GlobalSettingsSingleton.getInstance().isAuthenticatedWithMemberNumber()) {
            $.getJSON(InternalApiEndpoints.getMemberCompany())
                .done(function (memberCompany) {
                self.renderEmploymentData(memberCompany);
            });
        }
        else {
            self.renderEmploymentData(null);
        }
    }
    MyInformationSummary.prototype.renderEmploymentData = function (memberCompany) {
        this.$employer.html(this.getEmployerHtml(memberCompany));
    };
    MyInformationSummary.prototype.getEmployerHtml = function (memberCompany) {
        if (memberCompany === null)
            return "<em>".concat(this.$employer.data("employerfailed"), "</em>");
        if (memberCompany.hasCompany) {
            if (memberCompany.hasPendingCompanyChangeWithOldWorkplace)
                return "<div><em>".concat(this.$employer.data("employerpendingchangewitholdworkplace"), "</em></div>") + memberCompany.name;
            return memberCompany.name;
        }
        if (memberCompany.hasPendingCompanyChangeWithOldWorkplace)
            return "<em>".concat(this.$employer.data("employerpendingchangewitholdworkplace"), "</em>");
        if (memberCompany.hasPendingCompanyChange)
            return "<em>".concat(this.$employer.data("employerpendingchange"), "</em>");
        if (memberCompany.isUnknown)
            return "<em>".concat(this.$employer.data("employermissing"), "</em>");
        return "";
    };
    return MyInformationSummary;
}());

var NavigateToTop = /** @class */ (function () {
    function NavigateToTop(navigateToTopSelector) {
        var self = this;
        self.$navigateToTop = $(navigateToTopSelector);
        self.setUpEventHandlers();
    }
    NavigateToTop.prototype.setUpEventHandlers = function () {
        var self = this;
        self.$navigateToTop.click(function (e) {
            e.preventDefault();
            window.scrollTo(0, 0);
        });
        $(window).scroll(function () {
            //TODO: ska kanske bytas ut mot eh.. mot eh... en klass som har hand om window scroll
            var window_offset = $(document).scrollTop();
            if (window_offset > 200) {
                self.$navigateToTop.addClass("visible");
            }
            else {
                self.$navigateToTop.removeClass("visible");
            }
        });
    };
    return NavigateToTop;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var OnePuffBlockWithVideo = /** @class */ (function () {
    function OnePuffBlockWithVideo(editorialBlockSelector) {
        var self = this;
        self.$editorialBlock = $(editorialBlockSelector);
        self.$videoContainer = self.$editorialBlock.find(".one-puff-block__media-container__video");
        self.$imageContainer = self.$editorialBlock.find(".one-puff-block__media-container__image");
        self.$videoElement = self.$editorialBlock.find("iframe");
        var videoElementId = self.$videoElement.attr("id");
        var playVideoWhenVideoOverlayIsClicked = self.$editorialBlock.data("playvideowhenoverlayisclicked");
        if (self.$videoElement.hasClass("one-puff-block__vimeo")) {
            self.$imageContainer.click(function (e) {
                self.showVideoAndHideOverlayImage();
                if (playVideoWhenVideoOverlayIsClicked) {
                    var vimeoPlayer = new VimeoPlayer(self.$videoElement);
                    vimeoPlayer.play();
                }
                e.preventDefault();
            });
        }
        else if (self.$videoElement.hasClass("one-puff-block__youtube")) {
            self.$imageContainer.click(function (e) {
                self.showVideoAndHideOverlayImage();
                if (playVideoWhenVideoOverlayIsClicked) {
                    var youtubePlayer = new YoutubePlayer(videoElementId, function () {
                        youtubePlayer.play();
                        e.preventDefault();
                    });
                }
            });
        }
    }
    OnePuffBlockWithVideo.prototype.showVideoAndHideOverlayImage = function () {
        var self = this;
        self.$videoContainer.show();
        self.$imageContainer.hide();
    };
    return OnePuffBlockWithVideo;
}());

var PopoutToggler = /** @class */ (function () {
    function PopoutToggler(popoutTogglerSelector, popoutSelector, calculateToggleableItemHeight, calculatePosition) {
        var self = this;
        self.customEventHandler = new CustomEventHandler();
        self.calculateToggleableItemHeight = calculateToggleableItemHeight;
        self.calculatePosition = calculatePosition;
        self.$popoutToggler = $(popoutTogglerSelector);
        self.$popout = $(popoutSelector);
        self.closeAllPopoutsHandlerBinded = false;
        if (!self.$popoutToggler.length || !self.$popout.length) {
            return;
        }
        self.setUpEventHandlers();
        self.customEventHandler.subscribe("tools-menu-item-opened", function () {
            self.closeAllPopoutsHandler();
        });
    }
    PopoutToggler.prototype.setUpEventHandlers = function () {
        var _this = this;
        var self = this;
        self.$popoutToggler.click(function (e) {
            e.preventDefault();
            var $toggleButton = $(e.currentTarget);
            if ($toggleButton.attr("data-state") != "active") {
                self.customEventHandler.trigger("tools-menu-item-opened", "");
            }
            var $popoverTarget = $("#".concat($toggleButton.attr("data-target")));
            if ($popoverTarget.length) {
                self.toggleActiveElements($toggleButton, $popoverTarget);
            }
            e.stopPropagation();
        });
        self.closeAllPopoutsHandler = function () {
            _this.$popoutToggler.attr("data-state", "non-active");
            _this.$popout.attr("data-state", "closed");
            _this.$popout.attr("aria-hidden", "true");
            // reset height, only if chosen
            if (_this.calculateToggleableItemHeight) {
                _this.$popout.css("max-height", 0);
            }
            $(window).unbind("click", _this.closeAllPopoutsHandler);
            _this.closeAllPopoutsHandlerBinded = false;
        };
        self.$popout.click(function (e) {
            e.stopPropagation();
        });
        $(window).on('resize', function () {
            self.setPopoutPosition(self.$popout);
        });
    };
    PopoutToggler.prototype.toggleActiveElements = function ($toggleButton, $popoverTarget) {
        var self = this;
        // calcualte position, only if active
        if (this.calculatePosition) {
            self.setPopoutPosition($popoverTarget);
        }
        $toggleButton.attr("data-state", $toggleButton.attr("data-state") === "active" ? "non-active" : "active");
        if ($toggleButton.attr("data-state") === "active" && self.closeAllPopoutsHandlerBinded === false) {
            $(window).bind("click", self.closeAllPopoutsHandler);
            self.closeAllPopoutsHandlerBinded = true;
        }
        self.$popoutToggler.not($toggleButton).attr("data-state", "non-active");
        $popoverTarget.attr("data-state", $popoverTarget.attr("data-state") === "open" ? "closed" : "open");
        // calculate height, only if active
        if (this.calculateToggleableItemHeight) {
            self.setChildrenComputedHeight($popoverTarget);
        }
        self.$popout.not($popoverTarget).attr("data-state", "closed");
        self.toggleAriaAttributes($popoverTarget);
        return false;
    };
    PopoutToggler.prototype.setPopoutPosition = function ($popoverTarget) {
        var header = $('.header');
        var adminBar = $('#logged-in-as-member');
        var offsetTop = 0;
        offsetTop = header.outerHeight() + (adminBar != null ? adminBar.outerHeight() : 0);
        $popoverTarget.css('top', offsetTop);
    };
    PopoutToggler.prototype.setChildrenComputedHeight = function ($popoverTarget) {
        var self = this;
        var totalHeight = 0;
        var children = $popoverTarget.children();
        for (var i = 0; i < children.length; i++) {
            totalHeight += $(children[i]).outerHeight();
        }
        $popoverTarget.css("max-height", $popoverTarget.attr("data-state") === "open" ? totalHeight + 50 + "px" : "0");
        self.$popout.not($popoverTarget).css("max-height", 0);
        return false;
    };
    PopoutToggler.prototype.toggleAriaAttributes = function ($popoverTarget) {
        var self = this;
        $popoverTarget.attr("aria-hidden", $popoverTarget.attr("aria-hidden") === "false" ? "true" : "false");
        self.$popout.not($popoverTarget).attr("data-state", "closed");
        return false;
    };
    return PopoutToggler;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var Print = /** @class */ (function () {
    function Print(printBtnSelector) {
        this.printBtn = $(printBtnSelector);
        this.printBtn.on("click", function () {
            window.print();
        });
    }
    return Print;
}());

var SearchClear = /** @class */ (function () {
    function SearchClear() {
        var self = this;
        self.$quickSearchInput = $("#quicksearch-text");
        self.$quickSearchClearButton = $(".searchclear-quick");
        self.$searchPageInput = $("#search-text-field");
        self.$searchPageClearButton = $(".searchclear-searchpage");
        self.$searchJobPageInput = $("#search-available-jobs");
        self.$searchJobPageClearButton = $(".searchclear-jobpage");
        self.bindEvents(self.$quickSearchInput, self.$quickSearchClearButton);
        self.bindEvents(self.$searchPageInput, self.$searchPageClearButton);
        self.bindEvents(self.$searchJobPageInput, self.$searchJobPageClearButton);
        //In case the search on searchpage has a value on pageload
        if ($(".searchpage").length) {
            self.setVisabilityOnButton(self.$searchPageInput, self.$searchPageClearButton);
        }
        //In case the search on available jobs page has a value on pageload
        if ($(".available-jobs").length) {
            self.setVisabilityOnButton(self.$searchJobPageInput, self.$searchJobPageClearButton);
        }
    }
    SearchClear.prototype.bindEvents = function ($searchText, $button) {
        var _this = this;
        var self = this;
        $searchText.on("hidesearchclearbutton", function () {
            $button.hide();
        });
        $searchText.on("keyup", function () {
            self.setVisabilityOnButton($searchText, $button);
        });
        var autocompleteList = $(".autocomplete-list");
        $button.delegate($button, "keydown", function (e) {
            var keyID = e.keyCode;
            switch (keyID) {
                case 32:
                    e.preventDefault();
                    _this.clearSearchTextAndSetFocus($searchText, $button, autocompleteList);
                    break;
                case 13:
                    e.preventDefault();
                    _this.clearSearchTextAndSetFocus($searchText, $button, autocompleteList);
                    break;
                default:
                    break;
            }
        });
        $button.delegate($button, "click", function () {
            self.clearSearchTextAndSetFocus($searchText, $button, autocompleteList);
        });
    };
    SearchClear.prototype.setVisabilityOnButton = function ($searchText, $button) {
        var self = this;
        if ($searchText.val().length > 0) {
            self.showButton($button);
        }
        else {
            self.hideButton($button);
        }
    };
    SearchClear.prototype.showButton = function ($button) {
        $button.show();
    };
    SearchClear.prototype.hideButton = function ($button) {
        $button.hide();
    };
    SearchClear.prototype.clearSearchTextAndSetFocus = function ($searchText, $button, $autoCompleteList) {
        var self = this;
        $searchText.val("");
        $searchText.focus();
        self.hideButton($button);
        $autoCompleteList.remove();
    };
    return SearchClear;
}());

var SharePageService = /** @class */ (function () {
    function SharePageService(shareContainerSelector) {
        this.$shareContainer = $(shareContainerSelector);
        this.attachEvents();
    }
    SharePageService.prototype.attachEvents = function () {
        var _this = this;
        var self = this;
        if (self.$shareContainer == null) {
            return;
        }
        var $twitterBtn = self.$shareContainer.find(".js-share-twitter");
        if ($twitterBtn != null) {
            $twitterBtn.click(function (e) {
                e.preventDefault();
                _this.shareTwitter(e.currentTarget);
            });
        }
        var $facebookBtn = self.$shareContainer.find(".js-share-facebook");
        if ($facebookBtn != null) {
            $facebookBtn.click(function (e) {
                e.preventDefault();
                _this.shareFacebook(e.currentTarget);
            });
        }
        var $facebookMessengerBtn = self.$shareContainer.find(".js-share-facebook-messenger");
        if ($facebookMessengerBtn != null) {
            $facebookMessengerBtn.click(function (e) {
                e.preventDefault();
                _this.shareFacebookMessenger(e.currentTarget);
            });
        }
        var $linkedInBtn = self.$shareContainer.find(".js-share-linkedin");
        if ($linkedInBtn != null) {
            $linkedInBtn.click(function (e) {
                e.preventDefault();
                $linkedInBtn.click(_this.shareLinkedIn(e.currentTarget));
            });
        }
    };
    SharePageService.prototype.getShareData = function () {
        var shareData = new SharePageData();
        shareData.url = $("head meta[property='og:url']").attr("content");
        shareData.description = $("head meta[property='og:description']").attr("content");
        shareData.title = document.title;
        return shareData;
    };
    SharePageService.prototype.getBaseShareInformation = function (clickTarget) {
        var baseShareData = new BaseSharePageData();
        baseShareData.baseUrl = $(clickTarget).data("share-baseurl");
        baseShareData.windowTitle = $(clickTarget).data("window-title");
        return baseShareData;
    };
    SharePageService.prototype.shareFacebook = function (currentTarget) {
        var self = this;
        var baseShareData = self.getBaseShareInformation(currentTarget);
        var shareData = self.getShareData();
        self.openShareWindow(baseShareData.baseUrl + encodeURIComponent(shareData.url), baseShareData.windowTitle);
    };
    SharePageService.prototype.shareFacebookMessenger = function (currentTarget) {
        var self = this;
        var shareData = self.getShareData();
        var baseShareData = self.getBaseShareInformation(currentTarget);
        // Mobile friendly share dialog
        // fb-messenger://share?app_id=<APP_ID>&link=<LINK_TO_SHARE>
        if (GlobalSettingsSingleton.getInstance().isMobileDevice() || this.isMobileOrTablet()) {
            window.open(baseShareData.baseUrl + "?app_id=" + GlobalSettingsSingleton.getInstance().getFacebookAppId() + "&link=" + encodeURIComponent(shareData.url));
        }
        else {
            window.open("http://www.facebook.com/dialog/send" + "?app_id=" + GlobalSettingsSingleton.getInstance().getFacebookAppId() + "&link=" + encodeURIComponent(shareData.url) + "&redirect_uri=" + encodeURIComponent("https://www.facebook.com/dialog/return/close#_=_"));
        }
    };
    SharePageService.prototype.shareTwitter = function (currentTarget) {
        var self = this;
        var baseShareData = self.getBaseShareInformation(currentTarget);
        var shareData = self.getShareData();
        var tweet = "text=" + encodeURIComponent(shareData.title) + "&url=" + encodeURIComponent(shareData.url) + "&lang=sv";
        self.openShareWindow(baseShareData.baseUrl + tweet, baseShareData.windowTitle);
    };
    SharePageService.prototype.shareLinkedIn = function (currentTarget) {
        var self = this;
        var baseShareData = self.getBaseShareInformation(currentTarget);
        var shareData = self.getShareData();
        self.openShareWindow(baseShareData.baseUrl + encodeURIComponent(shareData.url), baseShareData.windowTitle);
    };
    SharePageService.prototype.openShareWindow = function (windowUrl, windowTitle) {
        var width = 900, height = 400, left = ($(window).width() - width) / 2, top = ($(window).height() - height) / 2, opts = "status=0" +
            ",width=" + width +
            ",height=" + height +
            ",top=" + top +
            ",left=" + left;
        window.open(windowUrl, windowTitle, opts);
    };
    SharePageService.prototype.isMobileOrTablet = function () {
        var isMobile = false;
        if (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(navigator.userAgent)
            || /1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(navigator.userAgent.substr(0, 4))) {
            isMobile = true;
        }
        return isMobile;
    };
    return SharePageService;
}());
var SharePageData = /** @class */ (function () {
    function SharePageData() {
    }
    return SharePageData;
}());
var BaseSharePageData = /** @class */ (function () {
    function BaseSharePageData() {
    }
    return BaseSharePageData;
}());

var Spinner = /** @class */ (function () {
    function Spinner($spinner) {
        var self = this;
        self.$spinner = $spinner;
        var actors = {};
        actors.actor_1 = {
            node: $spinner.find("#actor_1")[0],
            type: "circle",
            cx: 50,
            cy: 50,
            dx: 28,
            dy: 29,
            opacity: 1.00
        };
        actors.actor_2 = {
            node: $spinner.find("#actor_2")[0],
            type: "circle",
            cx: 50,
            cy: 50,
            dx: 28,
            dy: 5,
            opacity: 1
        };
        var tricks = {};
        tricks.trick_1 = (function (t, a) {
            a = (function (t) {
                return 0 == t ? 0 : 1 == t ? 1 : (t /= .5) < 1 ? .5 * Math.pow(2, 10 * (t - 1)) : .5 * (-Math.pow(2, -10 * --t) + 2);
            })(a) % 1, a = a * 1 % 1, a = 0 > a ? 1 + a : a;
            var M = a * 1 * 360 * Math.PI / 180, i = t._tMatrix, _ = Math.cos(M), c = Math.sin(M), x = -Math.sin(M), s = Math.cos(M), h = -t.cx * Math.cos(M) + t.cy * Math.sin(M) + t.cx, n = -t.cx * Math.sin(M) - t.cy * Math.cos(M) + t.cy, r = i[0] * _ + i[2] * c, o = i[1] * _ + i[3] * c, y = i[0] * x + i[2] * s, f = i[1] * x + i[3] * s, d = i[0] * h + i[2] * n + i[4], e = i[1] * h + i[3] * n + i[5];
            t._tMatrix[0] = r, t._tMatrix[1] = o, t._tMatrix[2] = y, t._tMatrix[3] = f, t._tMatrix[4] = d, t._tMatrix[5] = e;
        });
        tricks.trick_2 = (function (t, a) {
            a = (function (n) {
                return n;
            })(a) % 1, a = a * 1 % 1, a = 0 > a ? 1 + a : a;
            var M = a * -1 * 360 * Math.PI / 180, i = t._tMatrix, _ = Math.cos(M), c = Math.sin(M), x = -Math.sin(M), s = Math.cos(M), h = -t.cx * Math.cos(M) + t.cy * Math.sin(M) + t.cx, n = -t.cx * Math.sin(M) - t.cy * Math.cos(M) + t.cy, r = i[0] * _ + i[2] * c, o = i[1] * _ + i[3] * c, y = i[0] * x + i[2] * s, f = i[1] * x + i[3] * s, d = i[0] * h + i[2] * n + i[4], e = i[1] * h + i[3] * n + i[5];
            t._tMatrix[0] = r, t._tMatrix[1] = o, t._tMatrix[2] = y, t._tMatrix[3] = f, t._tMatrix[4] = d, t._tMatrix[5] = e;
        });
        var scenarios = {};
        scenarios.scenario_1 = {
            actors: ["actor_1"],
            tricks: [{
                    trick: "trick_1",
                    start: 0.00,
                    end: 1.00
                }],
            startAfter: 0,
            duration: 800,
            actorDelay: 0,
            repeat: 0,
            repeatDelay: 0
        };
        //var window = (<any>window);
        var _reqAnimFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.oRequestAnimationFrame, fnTick = function (t) {
            var r, a, i, e, n, o, s, c, m, f, d, k, w;
            for (c in actors)
                actors[c]._tMatrix = [1, 0, 0, 1, 0, 0];
            for (s in scenarios)
                for (o = scenarios[s], m = t - o.startAfter, r = 0, a = o.actors.length; a > r; r++) {
                    if (i = actors[o.actors[r]], i && i.node && i._tMatrix)
                        for (f = 0, m >= 0 && (d = o.duration + o.repeatDelay, o.repeat > 0 && m > d * o.repeat && (f = 1), f += m % d / o.duration), e = 0, n = o.tricks.length; n > e; e++)
                            k = o.tricks[e], w = (f - k.start) * (1 / (k.end - k.start)), tricks[k.trick] && tricks[k.trick](i, Math.max(0, Math.min(1, w)));
                    m -= o.actorDelay;
                }
            for (c in actors)
                i = actors[c], i && i.node && i._tMatrix && i.node.setAttribute("transform", "matrix(" + i._tMatrix.join() + ")");
            _reqAnimFrame(fnTick);
        };
        _reqAnimFrame(fnTick);
    }
    Spinner.prototype.hide = function () {
        var self = this;
        self.$spinner.addClass("hide");
    };
    Spinner.prototype.show = function () {
        var self = this;
        self.$spinner.removeClass("hide");
    };
    return Spinner;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var TermsCheckbox = /** @class */ (function () {
    function TermsCheckbox($acceptTermsInfoLink) {
        this.$acceptTermsInfoLink = $acceptTermsInfoLink;
        this.setUpEventHandlers();
    }
    TermsCheckbox.prototype.setUpEventHandlers = function () {
        var _this = this;
        this.$acceptTermsInfoLink.on("click", function (e) {
            e.preventDefault();
            _this.$acceptTermsInfoLink.find("span").toggleClass("icon--plus-round--blue icon--minus-round--blue");
            _this.$acceptTermsInfoLink.closest(".terms-checkbox").find(".terms-text").slideToggle("fast");
        });
    };
    return TermsCheckbox;
}());

var TextboxClearer = /** @class */ (function () {
    function TextboxClearer($textbox, clearButtonAltText) {
        var self = this;
        self.$textbox = $textbox;
        self.$clearButton = $("<img loading=\"lazy\" src=\"/Static/img/Icons/icon_erase_16.svg\" tabindex=\"0\" class=\"searchclear\" alt=\"".concat(clearButtonAltText, "\" />\""));
        self.$clearButton.insertAfter(self.$textbox);
        self.attachEvents();
    }
    TextboxClearer.prototype.attachEvents = function () {
        var _this = this;
        var self = this;
        self.$textbox.on("keyup", function () {
            self.updateVisabilityOnClearButton();
        });
        self.$textbox.on("paste", function () {
            setTimeout(function () { self.updateVisabilityOnClearButton(); }, 10);
        });
        self.$clearButton.delegate(self.$clearButton, "keydown", function (e) {
            var keyID = e.keyCode;
            switch (keyID) {
                case 32:
                    e.preventDefault();
                    _this.clearTextboxAndSetFocus();
                    break;
                case 13:
                    e.preventDefault();
                    _this.clearTextboxAndSetFocus();
                    break;
                default:
                    break;
            }
        });
        self.$clearButton.click(function (e) {
            e.preventDefault();
            self.clearTextboxAndSetFocus();
        });
    };
    TextboxClearer.prototype.updateVisabilityOnClearButton = function () {
        if (this.$textbox.val().length > 0) {
            this.showClearButton();
        }
        else {
            this.hideClearButton();
        }
    };
    TextboxClearer.prototype.clearTextboxAndSetFocus = function () {
        this.$textbox.val("");
        this.$textbox.focus();
        this.hideClearButton();
    };
    TextboxClearer.prototype.showClearButton = function () {
        this.$clearButton.show();
    };
    TextboxClearer.prototype.hideClearButton = function () {
        this.$clearButton.hide();
    };
    return TextboxClearer;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var TopNavigationLinkTooltipService = /** @class */ (function () {
    function TopNavigationLinkTooltipService(topNavigationLink) {
        this.topNavigationLink = $(topNavigationLink);
        this.setUpEventHandlers();
    }
    TopNavigationLinkTooltipService.prototype.setUpEventHandlers = function () {
        var self = this;
        this.topNavigationLink.each(function (i) {
            var $topLink = $(this);
            var $linkTooltipText = $topLink.data("link-explanation");
            if ($linkTooltipText.length <= 0)
                return;
            var $tooltip = $("<div class='tooltip-bubble tooltip-bubble--navigation bottom'>");
            $topLink.mouseenter(function (e) {
                $tooltip.html($linkTooltipText);
                $topLink.after($tooltip);
                setTimeout(function () {
                    $tooltip.addClass("active");
                }, 1000);
            }).mouseleave(function (e) {
                $tooltip.removeClass("active");
                $tooltip.remove();
            });
        });
    };
    return TopNavigationLinkTooltipService;
}());

/**
 * This class is responsible for collecting utm params from the url and persist them so
 * other classes can access these params during the browser session
 *
 */
var UtmCampaignService = /** @class */ (function () {
    function UtmCampaignService() {
        this.queryStringHelper = new QueryStringHelper();
        this.sessionTorageKey = "utmparams";
        var utmParamsFromUrl = this.getUtmParamsFromUrl();
        if (utmParamsFromUrl.utmSource !== "" ||
            utmParamsFromUrl.utmMedium !== "" ||
            utmParamsFromUrl.utmCampiagn !== "") {
            this.persistUtmParams(utmParamsFromUrl);
        }
    }
    UtmCampaignService.prototype.getUtmParamsFromUrl = function () {
        var source = this.queryStringHelper.getParameter("utm_source");
        if (source === null) {
            var sourceClsrc = this.queryStringHelper.getParameter("gclsrc");
            if (sourceClsrc === null) {
                source = "";
            }
            else {
                source = sourceClsrc;
            }
        }
        var medium = this.queryStringHelper.getParameter("utm_medium");
        if (medium === null) {
            medium = "";
        }
        var campaign = this.queryStringHelper.getParameter("utm_campaign");
        if (campaign === null) {
            campaign = "";
        }
        return new UtmParamsModel(source, medium, campaign);
    };
    UtmCampaignService.prototype.persistUtmParams = function (utmParams) {
        sessionStorage.setItem(this.sessionTorageKey, JSON.stringify(utmParams));
    };
    UtmCampaignService.prototype.getUtmParams = function () {
        var fromSession = sessionStorage.getItem(this.sessionTorageKey);
        if (fromSession == null) {
            return new UtmParamsModel("", "", "");
        }
        else {
            return JSON.parse(sessionStorage.getItem(this.sessionTorageKey));
        }
    };
    // Fetch utm parameters and populate the hidden fields
    UtmCampaignService.prototype.populateUtmInputFieldsFromQueryString = function (formContainer, campaignFieldName, mediumFieldName, sourceFieldName) {
        var utmParams = this.getUtmParams();
        $(formContainer + " " + campaignFieldName).val(utmParams.utmCampiagn);
        $(formContainer + " " + mediumFieldName).val(utmParams.utmMedium);
        $(formContainer + " " + sourceFieldName).val(utmParams.utmSource);
    };
    return UtmCampaignService;
}());
var UtmParamsModel = /** @class */ (function () {
    function UtmParamsModel(source, medium, campaign) {
        this.utmSource = source;
        this.utmMedium = medium;
        this.utmCampiagn = campaign;
    }
    return UtmParamsModel;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
/// <reference path="../../../../Scripts/typings/jquery.validation/jquery.validation.d.ts" />
var Validation = /** @class */ (function () {
    function Validation(formToValidateSelector, rules, messages, customValidationSummarySelector, activeValidationSummarySelector, hasStepValidation) {
        if (hasStepValidation === void 0) { hasStepValidation = false; }
        this.scrollToErrorMessageOffset = 0;
        var self = this;
        this.formToValidate = $(formToValidateSelector);
        this.activeValidationSummarySelector = activeValidationSummarySelector;
        this.hasStepValidation = hasStepValidation;
        if (customValidationSummarySelector) {
            this.validationSummary = $(customValidationSummarySelector);
        }
        else {
            this.validationSummary = $("div.error");
        }
        this.validationSummaryInfo = this.validationSummary.data("summaryinfo");
        this.errorStep = this.validationSummary.data("step");
        this.rules = rules;
        this.messages = messages;
        $.validator.addMethod("phone", function (value, element) {
            var regexp = /^\+?([0-9-\s \(\)+]){8,14}$/;
            return this.optional(element) || regexp.test(value);
        }, "Telefonnummer måste vara mellan 8 och 14 siffor");
        $.validator.addMethod("newphone", function (value, element) {
            var regexp = /^(?!00)(?!.*\+)[0-9]{8,12}$/;
            return this.optional(element) || regexp.test(value);
        }, "Telefonnummer får bara innehålla siffror, ej börja med 00, och vara max 12 tecken långt");
        $.validator.addMethod("ssn", function (value, element) {
            return this.optional(element) || self.isSsnValid(value);
        }, "Personnumret är ogiltigt");
        $.validator.addMethod("ssnWithCentury", function (value, element) {
            return this.optional(element) || self.isSsnWithCenturyValid(value);
        }, "Personnumret är ogiltigt");
        $.validator.addMethod("orgSsn", function (value, element) {
            var regexp = /^([0-9]{6}-{1}[0-9]{4})$|^([0-9]{10,12})$|^([0-9]{8}-{1}[0-9]{4})$/;
            return this.optional(element) || regexp.test(value);
        }, "Personnumret är ogiltigt");
        $.validator.addMethod("valueNotEquals", function (value, element, arg) {
            return arg !== value;
        }, "");
        $.validator.addMethod("alphanumeric", function (value, element) {
            return this.optional(element) || /^[a-zåäöàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ\d\-_\s]+$/i.test(value);
        }, "Endast bokstäver, siffror och bindestreck är tillåtna");
        $.validator.addMethod("notOnlySpace", function (value, element) {
            return this.optional(element) || /\S/.test(value);
        }, "Enbart blanksteg är ej tillåtet");
        $.validator.addMethod("alphanumericWithAndChar", function (value, element) {
            return this.optional(element) || /^[a-zåäöàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ\d\-_\s\&_]+$/i.test(value);
        }, "Endast bokstäver, siffror och bindestreck är tillåtna");
        $.validator.addMethod("onlyspaceorempty", function (value, element) {
            var regexp = /^\s*$/;
            return this.optional(element) || regexp.test(value);
        }, "Endast whitespace är tillåtet");
        $.validator.addMethod("bankClearing", function (value, element) {
            var regexp = /^(\d){4}$/;
            return this.optional(element) || regexp.test(value);
        }, "Clearingnumret får endast innehålla siffror och måste vara 4 tecken långt");
        $.validator.addMethod("bankAccount", function (value, element) {
            var regexp = /^[0-9\-\s]+$/;
            return this.optional(element) || regexp.test(value);
        }, "Kontonumret får endast bestå av siffror, mellanrum och bindesstreck");
        $.validator.addMethod("bankAccountLength", function (value, element) {
            var regexp = /^(.){0,10}$/;
            return this.optional(element) || regexp.test(value);
        }, "Kontonumret får vara maximalt 10 tecken långt");
        $.validator.addMethod("questionLength", function (value, element) {
            var regexp = /^[\s\S]{0,20000}$/;
            return this.optional(element) || regexp.test(value);
        }, "fältet får vara maximalt 20000 tecken långt");
        $.validator.addMethod("minimumAge", function (value, element) {
            return this.optional(element) || self.isMinimumAge(value);
        }, "Du måste vara 15 år eller över för att skicka en ansökan");
        // The built in email validation in jQuery validation supports eg name@name as a valid email address        
        $.validator.addMethod("customEmail", function (value, element) {
            // If any change is done in this regexp these changes must also be applied to ValidationConstants.cs
            var regexp = /^(?!.*\.{2})[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,20}$/;
            return this.optional(element) || regexp.test(value);
        }, "Du har angivit en felaktig e-postadress");
        this.setUpValidation();
    }
    Validation.prototype.isValid = function () {
        if (this.formToValidate.valid()) {
            this.validationSummary.hide();
            return true;
        }
        else {
            return false;
        }
    };
    Validation.prototype.setUpValidation = function () {
        var self = this;
        this.formToValidate.validate({
            focusInvalid: false,
            ignore: "",
            invalidHandler: function (event, validator) {
                self.showValidationSummary(validator);
            },
            submitHandler: function (form) {
                var subBtn = $(form).find("button");
                subBtn.attr("disabled", "disabled");
                if (subBtn.hasClass("btn--orangeaction")) {
                    subBtn.addClass("btnpushed");
                }
                if (self.customSubmit == null) {
                    form.submit();
                }
                else {
                    self.customSubmit();
                }
            },
            errorPlacement: function (error, element) {
                if (element.is(":checkbox") ||
                    element.is(":radio")) {
                    error.addClass("validation-marker");
                }
                if (self.shouldErrorBeInsertedAfterElement(element)) {
                    error.insertAfter(element);
                    return;
                }
                error.insertBefore(element);
            },
            highlight: function (element, errorClass, validClass) {
                var $element = $(element);
                $element.addClass(errorClass);
                $element.removeClass(validClass);
                if ($element.is(":text") ||
                    $element.attr("type") === "email") {
                    $element.addClass("validation-marker");
                }
            },
            rules: self.rules,
            messages: self.messages
        });
    };
    Validation.prototype.shouldErrorBeInsertedAfterElement = function (element) {
        if (element.data("valposition") !== "before-element-but-after-on-desktop")
            return false;
        if (!GlobalSettingsSingleton.getInstance().isDesktopDevice())
            return false;
        return true;
    };
    Validation.prototype.showValidationSummary = function (validator) {
        var _this = this;
        if (!this.validationSummary.length) {
            return;
        }
        this.validationSummary.empty();
        var errors = validator.numberOfInvalids();
        if (errors) {
            if (this.validationSummaryInfo !== "") {
                $("<div>")
                    .addClass("error-title")
                    .text(this.validationSummaryInfo)
                    .appendTo(this.validationSummary);
            }
            $("<ul>").appendTo(this.validationSummary);
            $.each(validator.errorList, function (index, error) {
                var summaryText = validator.settings.messages[error.element.id].summary;
                var listElement = $("<li>");
                $("<a>")
                    .text(summaryText)
                    .click(function (e) {
                    if (!_this.hasStepValidation || _this.isErrorOnCurrentStep()) {
                        e.preventDefault();
                        var $invalidInput = $(error.element);
                        $("html,body").animate({
                            scrollTop: $invalidInput.parent().offset().top - 200
                        }, 1000, function () {
                            $invalidInput.focus();
                        });
                    }
                })
                    .attr("href", _this.getValidationMessageLink())
                    .appendTo(listElement);
                listElement.appendTo(_this.validationSummary.find("ul"));
            });
            this.validationSummary.show();
            var activeValidationSummary = this.getActiveValidationSummary();
            $("html,body").animate({
                scrollTop: activeValidationSummary.offset().top - this.scrollToErrorMessageOffset
            }, 300, function () {
                activeValidationSummary.find("a").first().focus();
            });
        }
        else {
            this.validationSummary.hide();
        }
    };
    Validation.prototype.isErrorOnCurrentStep = function () {
        return String(this.validationSummary.data("step")) === location.hash[location.hash.length - 1];
    };
    Validation.prototype.getValidationMessageLink = function () {
        if (this.hasStepValidation) {
            return window.location.pathname + "#steg/" + this.validationSummary.data("step");
        }
        else {
            return "#";
        }
    };
    Validation.prototype.getActiveValidationSummary = function () {
        if (this.activeValidationSummarySelector) {
            return $(this.activeValidationSummarySelector);
        }
        return this.validationSummary;
    };
    Validation.prototype.isSsnWithCenturyValid = function (value) {
        if (value === null || value.length < 12) {
            return false;
        }
        return this.isSsnValid(value);
    };
    Validation.prototype.isMinimumAge = function (value) {
        if (value === null || value.length < 12) {
            return false;
        }
        value = value.substring(0, value.length - 4);
        var year = value.substring(0, 4);
        var month = value.substring(4, 6);
        var day = value.substring(6, 8);
        var birthDate = new Date(parseInt(year), parseInt(month) - 1, parseInt(day));
        var ageDifMs = Date.now() - birthDate.getTime();
        var ageDate = new Date(ageDifMs); // miliseconds from epoch
        var age = Math.abs(ageDate.getUTCFullYear() - 1970);
        if (age >= 15) {
            return true;
        }
        return false;
    };
    // Accepts both ssn with or without century
    Validation.prototype.isSsnValid = function (value) {
        // If any change is done in this regexp these changes must also be applied to ValidationConstants.cs
        var regex = /^(19|20)?\d{6}(-)?\d{4}$/;
        if (regex.test(value)) {
            // Check social security number according to http://www.skatteverket.se/privat/folkbokforing/omfolkbokforing/personnumretsuppbyggnad.4.18e1b10334ebe8bc80001502.html
            value = $.trim(value.replace("-", ""));
            var yearNumber = 0;
            var prod = "";
            var controlNumber = "";
            if (value.length === 12) {
                yearNumber = Number(value.substring(0, 4));
                value = value.substring(2);
            }
            if (value.length === 10) {
                if (yearNumber === 0) {
                    yearNumber = 1900 + Number(value.substring(0, 2));
                }
                controlNumber = value.substring(9);
                value = value.substring(0, 9);
            }
            var monthNumber = Number(value.substring(2).substring(0, 2));
            if (monthNumber > 12) {
                return false;
            }
            var dayNumber = Number(value.substring(4).substring(0, 2));
            switch (monthNumber) {
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                case 12:
                    {
                        if (dayNumber > 31)
                            return false;
                        break;
                    }
                case 4:
                case 6:
                case 9:
                case 11:
                    {
                        if (dayNumber > 30)
                            return false;
                        break;
                    }
                case 2:
                    {
                        if (this.leapYear(yearNumber)) {
                            if (dayNumber > 29)
                                return false;
                        }
                        else {
                            if (dayNumber > 28)
                                return false;
                        }
                        break;
                    }
            }
            for (var i = 0; i < value.length; i++) {
                var times = 2;
                if (i % 2 === 1) {
                    times = 1;
                }
                prod = prod + (String)(Number(Number(value[i]) * times));
            }
            var sum = 0;
            for (var j = 0; j < prod.length; j++) {
                sum = sum + Number(prod[j]);
            }
            if (sum.toString().length === 2) {
                sum = Number(sum.toString().substring(1));
            }
            var rest = 10 - sum;
            if (rest === 10) {
                rest = 0;
            }
            return Number(controlNumber) === rest;
        }
        return false;
    };
    Validation.prototype.leapYear = function (year) {
        return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
    };
    return Validation;
}());

var WindowRefreshHubApp = /** @class */ (function () {
    function WindowRefreshHubApp() {
        window.onload = function () {
            var connection = $.connection;
            var hubConnection = connection.windowRefreshHub;
            hubConnection.client.refreshWindow = function () {
                //Added delay to make sure user is logged in before refreshing
                setTimeout(function () {
                    window.location.reload();
                }, 2000);
            };
            connection.hub.start();
        };
    }
    return WindowRefreshHubApp;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var AutoCompleteSearch = /** @class */ (function () {
    function AutoCompleteSearch(searchFieldSelector) {
        var self = this;
        self.$searchField = $(searchFieldSelector);
        self.$searchField.tinyAutocomplete({
            url: InternalApiEndpoints.globalSearchAutoComplete(),
            itemTemplate: '<li class="autocomplete-item"><span>{{title}}</span></li>',
            onSelect: function (element, val) {
                self.$searchField.val(val.title);
                if (self.onSelect !== null) {
                    self.onSelect(val.title);
                }
            },
            showNoResults: false,
            minChars: 3,
            markAsBold: false,
            maxItems: 5
        });
        self.$searchField.on("receivedata", function (e, tinyAutocomplete, json) {
            tinyAutocomplete.json = json.map(function (item) { return ({
                title: item
            }); });
        });
        ;
    }
    return AutoCompleteSearch;
}());

var QueryStringHelper = /** @class */ (function () {
    function QueryStringHelper(baseUrl) {
        if (baseUrl === void 0) { baseUrl = null; }
        var self = this;
        if (baseUrl != null) {
            self.url = baseUrl;
            self.useWindowLocationHrefAsUrlStorage = false;
        }
        else {
            self.url = window.location.href;
            self.useWindowLocationHrefAsUrlStorage = true;
        }
    }
    QueryStringHelper.prototype.getCurrentUrl = function () {
        var self = this;
        return self.url;
    };
    QueryStringHelper.prototype.updateParameter = function (key, value) {
        var self = this;
        if (self.useWindowLocationHrefAsUrlStorage) {
            self.url = window.location.href;
        }
        self.url = self.getCurrentUrlWithUpdatedParameter(key, value);
        self.changeCurrentUrl();
        return self.url;
    };
    QueryStringHelper.prototype.getCurrentUrlWithUpdatedParameter = function (key, value) {
        var self = this;
        var re = new RegExp("([?&])" + key + "=.*?(&|$|#)", "i");
        var separator = self.url.indexOf('?') !== -1 ? "&" : "?";
        if (self.url.match(re)) {
            self.url = self.url.replace(re, '$1' + key + "=" + value + '$2');
        }
        else {
            var hashIndex = self.url.indexOf("#");
            if (hashIndex <= 0) {
                self.url = self.url + separator + key + "=" + value;
            }
            else {
                self.url = self.url.substr(0, hashIndex) + separator + key + "=" + value + self.url.substr(hashIndex);
            }
        }
        return self.url;
    };
    QueryStringHelper.prototype.getParameter = function (name) {
        var self = this;
        if (self.useWindowLocationHrefAsUrlStorage) {
            self.url = window.location.href;
        }
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"), results = regex.exec(self.url);
        if (!results)
            return null;
        if (!results[2])
            return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    };
    QueryStringHelper.prototype.getParameterIgnoreCase = function (name) {
        var self = this;
        if (self.useWindowLocationHrefAsUrlStorage) {
            self.url = window.location.href;
        }
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)", "i"), results = regex.exec(self.url);
        if (!results)
            return null;
        if (!results[2])
            return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    };
    QueryStringHelper.prototype.removeParameter = function (parameter) {
        var self = this;
        if (self.useWindowLocationHrefAsUrlStorage) {
            self.url = window.location.href;
        }
        self.url = self.getCurrentUrlWithRemovedParameter(parameter);
        self.changeCurrentUrl();
        return self.url;
    };
    QueryStringHelper.prototype.changeCurrentUrl = function () {
        var self = this;
        if (!self.useWindowLocationHrefAsUrlStorage)
            return;
        if (window.location.href === self.url)
            return;
        if (self.modifyCurrentHistoryEntry) {
            window.history.replaceState("", "", self.url);
        }
        else {
            window.history.pushState("", "", self.url);
        }
    };
    QueryStringHelper.prototype.getCurrentUrlWithRemovedParameter = function (parameter) {
        var self = this;
        if (self.useWindowLocationHrefAsUrlStorage) {
            self.url = window.location.href;
        }
        var urlparts = self.url.split('?');
        if (urlparts.length >= 2) {
            var querystringAndHashPart = urlparts[1];
            var querystringPart = self.getQuerystringPartFromQuerystringAndHashPart(querystringAndHashPart);
            var hashPart = self.getHashPartFromQuerystringAndHashPart(querystringAndHashPart);
            var prefix = encodeURIComponent(parameter) + '=';
            var pars = querystringPart.split(/[&;]/g);
            for (var i = pars.length; i-- > 0;) {
                if (pars[i].lastIndexOf(prefix, 0) !== -1) {
                    pars.splice(i, 1);
                }
            }
            self.url = urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : "") + hashPart;
        }
        return self.url;
    };
    QueryStringHelper.prototype.getQuerystringPartFromQuerystringAndHashPart = function (querystringAndHashPart) {
        var hashIndex = querystringAndHashPart.indexOf("#");
        if (hashIndex >= 0) {
            return querystringAndHashPart.substr(0, hashIndex);
        }
        return querystringAndHashPart;
    };
    QueryStringHelper.prototype.getHashPartFromQuerystringAndHashPart = function (querystringAndHashPart) {
        var hashIndex = querystringAndHashPart.indexOf("#");
        if (hashIndex >= 0) {
            return querystringAndHashPart.substr(hashIndex);
        }
        return "";
    };
    return QueryStringHelper;
}());

var FacebookPageFeed = /** @class */ (function () {
    function FacebookPageFeed(facebookPageFeedSelector) {
        var self = this;
        self.$facebookPageFeedSelector = $(facebookPageFeedSelector);
        self.$templateContainer = self.$facebookPageFeedSelector.find(".feed-container");
        self.blockId = self.$facebookPageFeedSelector.data("blockid");
        self.maxPostsInFeed = self.$facebookPageFeedSelector.data("maxpostsinfeed");
        self.template = _.template($("#facebook-page-feed-template").html());
        self.populateFeed();
    }
    FacebookPageFeed.prototype.populateFeed = function () {
        var self = this;
        $.getJSON(InternalApiEndpoints.facebookFeed(self.blockId, self.maxPostsInFeed), function (feedData) {
            if (feedData == null) {
                return;
            }
            var templatedHtml = $(self.template({ feedData: feedData }));
            self.$templateContainer.append(templatedHtml);
            self.$facebookPageFeedSelector.find(".facebook-feed__posts__text__message").each(function (index, element) {
                window.$clamp(element, { clamp: 3, useNativeClamp: false });
            });
            self.hideEmptyImages();
        });
    };
    FacebookPageFeed.prototype.hideEmptyImages = function () {
        var self = this;
        self.$facebookPageFeedSelector.find('img').each(function () {
            if (!$(this).attr('src').length) {
                $(this).hide();
            }
        });
    };
    return FacebookPageFeed;
}());
$(function () {
    // ReSharper disable once UnusedLocals
    $(".facebook-feed").each(function () {
        var facebookPageFeed = new FacebookPageFeed("#" + $(this).attr("id"));
    });
});

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var NewsService = /** @class */ (function () {
    function NewsService(searchResultContainer, searchTextboxSelector, allowEmptySearch, cssSelector, useFilter) {
        this.includeGlobalNews = false;
        this.firstView = true; // ugly as hell.... i know
        var self = this;
        self.useFilter = useFilter;
        self.listSize = 10;
        self.cssSelector = cssSelector;
        self.allowEmptySearch = allowEmptySearch;
        self.$searchResultContainer = $(searchResultContainer);
        self.$searchResultList = self.$searchResultContainer.find(cssSelector + "__result__list");
        self.searchResultTemplate = _.template($("#searchListTemplate").html());
        self.$queryTextbox = $(searchTextboxSelector);
        self.$summary = self.$searchResultContainer.find(cssSelector + "__summary");
        self.searchApiUrl = InternalApiEndpoints.globalNewsSearch();
    }
    NewsService.prototype.search = function (pageIndex) {
        if (pageIndex === void 0) { pageIndex = 1; }
        var self = this;
        if (self.$queryTextbox.val().length === 0 && self.allowEmptySearch === false) {
            self.$summary.hide();
            self.$searchResultList.html("");
            self.$searchResultList.append(self.$searchResultContainer.data("emptysearchwordvalidationtext"));
            return;
        }
        self.listSize = self.$searchResultContainer.data("listsize");
        $.getJSON(self.searchApiUrl + "?pageIndex=" + (pageIndex - 1) + "&queryText=" + encodeURIComponent(self.$queryTextbox.val()) + "&labelfilter=" + encodeURIComponent($(self.cssSelector + ' > .quick-search__search-labelfilter').val()) + "&subjectcategoriesfilter=" + $(self.cssSelector + ' > .quick-search__search-subjectcategoriesfilter').val() + "&associationcategoriesfilter=" + $(self.cssSelector + ' > .quick-search__search-associationcategoriesfilter').val() + "&listsize=" + self.listSize + "&types=" + "&includeGlobalNews=" + self.includeGlobalNews, function (searchResult) {
            self.$summary.show();
            var templatedHtml = $(self.searchResultTemplate({ searchResult: searchResult }));
            self.$searchResultList.html("");
            self.$searchResultList.append(templatedHtml);
            var $numberOfHits = self.$searchResultContainer.find(self.cssSelector + "__result__number-of-hits");
            if ($numberOfHits.length) {
                $numberOfHits.html(searchResult.NumberOfHits);
            }
            var $currentSearchQuery = self.$searchResultContainer.find(self.cssSelector + "__result__searchquery");
            if ($currentSearchQuery.length) {
                $currentSearchQuery.html(self.$queryTextbox.val());
            }
            if (self.useFilter) {
                self.chechBoxLogic();
                self.setCheckBoxes();
                self.setShowAllLogic();
            }
            if (self.onSearchComplete != null) {
                self.onSearchComplete(searchResult);
            }
            $('#formsubmitbtn').click(function () {
                $('.search-form').submit();
            });
        }).fail(function () {
            if (self.onSearchFailed != null) {
                self.onSearchFailed();
            }
        });
    };
    NewsService.prototype.chechBoxLogic = function () {
        var that = this;
        that.listofvalues = [];
        that.subjectcategoriesvalues = [];
        that.labelvalues = [];
        that.associationvalues = [];
        $('.search-filter input[type="checkbox"]').click(function () {
            if ($(this).attr("class") === "search-filter__list--label") {
                $("#showalllabels").prop('checked', false);
                that.labelvalues = [];
                $(".search-filter .search-filter__list--labels").find("input:checked").each(function () { that.labelvalues.push($(this).data('category')); });
                that.labelFilter = that.labelvalues.join('|');
                $('.quick-search__search-labelfilter').val(that.labelFilter);
                that.showAllCheckBoxLogic();
            }
            if ($(this).attr("class") === "search-filter__list--subjectcategorie") {
                $("#showallcategories").prop('checked', false);
                that.subjectcategoriesvalues = [];
                $(".search-filter .search-filter__list--subjectcategories").find("input:checked").each(function () { that.subjectcategoriesvalues.push($(this).data('category')); });
                that.subjectCategoriesFilter = that.subjectcategoriesvalues.join('|');
                $('.quick-search__search-subjectcategoriesfilter').val(that.subjectCategoriesFilter);
                that.showAllCheckBoxLogic();
            }
            if ($(this).attr("class") === "search-filter__list--association") {
                $("#showallassociation").prop('checked', false);
                that.associationvalues = [];
                $(".search-filter .search-filter__list--associations").find("input:checked").each(function () { that.associationvalues.push($(this).data('category')); });
                that.associationCategoriesFilter = that.associationvalues.join('|');
                $('.quick-search__search-associationcategoriesfilter').val(that.associationCategoriesFilter);
                that.showAllCheckBoxLogic();
            }
            that.listofvalues = [];
            $(".search-filter").find("input:checked").each(function () { that.listofvalues.push($(this).data('category')); });
            that.filter = that.listofvalues.join('|');
            $('.quick-search__search-filter').val(that.filter);
            if (that.onSearchFilterChanged != null) {
                that.onSearchFilterChanged();
            }
        });
    };
    NewsService.prototype.setCheckBoxes = function () {
        var filters = $('.quick-search__search-filter').val().split('|');
        $.each(filters, function (index, value) {
            if (value !== "") {
                if ($('input[id=' + value + ']') != null) {
                    $('input[id=' + value + ']').prop('checked', true);
                }
            }
        });
    };
    NewsService.prototype.setShowAllLogic = function () {
        var that = this;
        $("#showalllabels").click(function () {
            if (($(this).prop('checked') === true)) {
                that.labelvalues = [];
                $('.quick-search__search-labelfilter').val(that.labelvalues.join('|'));
                $('.search-filter__list--labels input:checkbox').not("#showalllabels").prop('checked', true);
                that.updateacommonfilterholder();
            }
            else {
                $('.search-filter__list--labels input:checkbox').not("#showalllabels").removeAttr('checked');
            }
        });
        $("#showallcategories").click(function () {
            if (($(this).prop('checked') === true)) {
                that.subjectcategoriesvalues = [];
                $('.quick-search__search-subjectcategoriesfilter').val(that.subjectcategoriesvalues.join('|'));
                $('.search-filter__list--subjectcategories input:checkbox').not("#showallcategories").prop('checked', true);
                that.updateacommonfilterholder();
            }
            else {
                $('.search-filter__list--subjectcategories input:checkbox').not("#showallcategories").removeAttr('checked');
            }
        });
        $("#showallassociation").click(function () {
            if (($(this).prop('checked') === true)) {
                that.associationvalues = [];
                $('.quick-search__search-associationcategoriesfilter').val(that.associationvalues.join('|'));
                $('.search-filter__list--associations input:checkbox').not("#showallassociation").prop('checked', true);
                that.updateacommonfilterholder();
            }
            else {
                $('.search-filter__list--associations input:checkbox').not("#showallassociation").removeAttr('checked');
            }
        });
        that.showAllCheckBoxLogic();
    };
    NewsService.prototype.showAllCheckBoxLogic = function () {
        // Type filter
        var $showAllLabels = $("#showalllabels");
        var $typeCheckBoxes = $("input.search-filter__list--label");
        if (this.shouldCheckShowAll($typeCheckBoxes, $showAllLabels)) {
            $showAllLabels.prop('checked', true);
            // if show all is checked we want to check all its categories
            $typeCheckBoxes.each(function () {
                $(this).prop("checked", true);
            });
        }
        // Subject filter
        var $showAllCategories = $("#showallcategories");
        var $subjectCheckBoxes = $("input.search-filter__list--subjectcategorie");
        if (this.shouldCheckShowAll($subjectCheckBoxes, $showAllCategories)) {
            $showAllCategories.prop('checked', true);
            // if show all is checked we want to check all its categories
            $subjectCheckBoxes.each(function () {
                $(this).prop("checked", true);
            });
        }
        // Association filter
        var $showAllAssociations = $("#showallassociation");
        var $associationCheckBoxes = $("input.search-filter__list--association");
        if (this.shouldCheckShowAll($associationCheckBoxes, $showAllAssociations)) {
            $showAllAssociations.prop('checked', true);
            // if show all is checked we want to check all its categories
            $associationCheckBoxes.each(function () {
                $(this).prop("checked", true);
            });
        }
        this.firstView = false;
    };
    NewsService.prototype.shouldCheckShowAll = function (filterCheckBoxes, showAllCheckbox) {
        var allIsSelected = true;
        var atLeastOneIsSelected = false;
        var showAllIsSelected = showAllCheckbox.prop("checked") === true;
        filterCheckBoxes.each(function () {
            if (!$(this).prop("checked") === true) {
                allIsSelected = false;
            }
            else {
                atLeastOneIsSelected = true;
            }
        });
        if (!this.firstView && !showAllIsSelected && !allIsSelected && !atLeastOneIsSelected) {
            return false;
        }
        return allIsSelected || !atLeastOneIsSelected;
    };
    NewsService.prototype.updateacommonfilterholder = function () {
        var that = this;
        that.listofvalues = [];
        $(".search-filter").find("input:checked").each(function () { that.listofvalues.push($(this).data('category')); });
        that.filter = that.listofvalues.join('|');
        $('.quick-search__search-filter').val(that.filter);
    };
    return NewsService;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var NewsListBlockApp = /** @class */ (function () {
    function NewsListBlockApp() {
        var self = this;
        $.each($(".newssearchblock"), function (i, element) {
            self.id = $(element).data("id");
            self.newsListBlock = $('.' + self.id);
            self.$searchResultContainer = $(".newssearchblock" + "." + self.id + "__result");
            self.listSize = self.$searchResultContainer.data("listsize");
            if (!self.newsListBlock.length) {
                return;
            }
            self.includeGlobalNews = self.newsListBlock.data("includeglobalnews");
            self.initializeSearchService();
            self.setLink();
        });
    }
    NewsListBlockApp.prototype.initializeSearchService = function () {
        var self = this;
        self.cssSelector = ".newssearchblock." + self.id;
        self.searchPageResultSelector = ".newssearchblock" + "." + self.id + "__result";
        self.newsService = new NewsService(self.searchPageResultSelector, ".newssearchblock__query-textbox", true, self.cssSelector, false);
        self.newsService.onSearchComplete = function (data) {
            if (data.FindIsDown) {
                $(self.cssSelector + " .link-container--secondary a").hide();
            }
            slimmage.checkResponsiveImages();
        };
        self.newsService.includeGlobalNews = self.includeGlobalNews;
        self.newsService.search(self.getPageIndex());
    };
    NewsListBlockApp.prototype.getPageIndex = function () {
        var self = this;
        return 1;
    };
    NewsListBlockApp.prototype.setLink = function () {
        var self = this;
        var filter = self.newsListBlock.data("readmorelinkfilter");
        var labelFilter = self.newsListBlock.data("readmorelinklabelfilter");
        var subjectFilter = self.newsListBlock.data("readmorelinksubjectfilter");
        var query = "?pageIndex=0" +
            "&queryText=" +
            "&f=" +
            encodeURIComponent(filter) +
            "&lf=" +
            encodeURIComponent(labelFilter) +
            "&sf=" +
            subjectFilter +
            "&af=" +
            $(self.cssSelector + ' > .quick-search__search-associationcategoriesfilter').val() +
            "&listsize=" +
            self.listSize +
            "&includeGlobalNews=" +
            self.includeGlobalNews +
            "&fcs=" +
            self.newsListBlock.data("readmorelinkfilterstatus");
        $(self.cssSelector + " .link-container--secondary a").attr('href', function () { return this.href + query; });
    };
    return NewsListBlockApp;
}());
$(function () {
    // ReSharper disable once UnusedLocals
    var newsListBlockApp = new NewsListBlockApp();
});

var MemberContractBlockApp = /** @class */ (function () {
    function MemberContractBlockApp(contractsPageContainerSelector) {
        this.categoryQueryStringKey = "categoryId";
        this.gtmService = new GoogleDataLayerService();
        var self = this;
        self.queryStringHelper = new QueryStringHelper();
        self.$contractsPageContainer = $(contractsPageContainerSelector);
        self.$searchResultContainer = self.$contractsPageContainer.find(".contracts-results-list");
        self.$contractCategoriesSelectInput = self.$contractsPageContainer.find(".contracts-contractcategories-input");
        self.$templateContainer = self.$contractsPageContainer.find(".contracts-list-container");
        self.$numberOfHitsContainer = self.$contractsPageContainer.find(".number-of-hits");
        self.hitsLabelPart1 = self.$numberOfHitsContainer.data("label-part1");
        self.hitsLabelPart2 = self.$numberOfHitsContainer.data("label-part2");
        self.template = _.template($("#contracts-template").html());
        self.populateSearchChoicesOnLoad();
        self.attachEvents();
        self.searchContracts();
    }
    MemberContractBlockApp.prototype.populateSearchChoicesOnLoad = function () {
        var self = this;
        var onloadChosenQuery = self.queryStringHelper.getParameter(self.categoryQueryStringKey);
        if (onloadChosenQuery) {
            self.$contractCategoriesSelectInput.val(onloadChosenQuery);
        }
    };
    MemberContractBlockApp.prototype.attachEvents = function () {
        var self = this;
        self.$contractCategoriesSelectInput.change(function (e) {
            var query = self.$contractCategoriesSelectInput.val();
            self.updateUrlWithQueryParameter(query);
            self.searchContracts();
        });
    };
    MemberContractBlockApp.prototype.searchContracts = function () {
        var self = this;
        var categoryId = self.$contractCategoriesSelectInput.val();
        if (categoryId && categoryId !== "0") {
            self.showHideSpinner("show");
            self.$searchResultContainer.hide();
            self.$numberOfHitsContainer.hide();
            // ReSharper disable once TsNotResolved
            $.getJSON(InternalApiEndpoints.contractsApiSearchContracts(categoryId), function (contractsData) {
                if (contractsData == null) {
                    self.showHideErrorMessage("show");
                    return;
                }
                else {
                    self.showHideErrorMessage("hide");
                }
                var templateHtml = $(self.template({ searchResult: contractsData.SearchResults }));
                var hitsLabel = self.hitsLabelPart1 + "<strong> " + contractsData.NumberOfHits + " " + self.hitsLabelPart2 + "</strong>";
                self.showHideSpinner("hide");
                self.$searchResultContainer.html("").append(templateHtml).show();
                self.$numberOfHitsContainer.html(hitsLabel).show();
            }).fail(function () {
                self.showHideSpinner("hide");
                self.showHideErrorMessage("show");
            });
        }
        else {
            self.$searchResultContainer.html("").hide();
            self.$numberOfHitsContainer.html("").hide();
        }
    };
    MemberContractBlockApp.prototype.showHideErrorMessage = function (errorMessageStatus) {
        var self = this;
        var errorMsg = self.$contractsPageContainer.find(".error-summary");
        if (errorMessageStatus === "show") {
            errorMsg.show();
        }
        else {
            errorMsg.hide();
        }
    };
    MemberContractBlockApp.prototype.showHideSpinner = function (spinnerStatus) {
        var self = this;
        var spinner = self.$contractsPageContainer.find(".spinner");
        if (spinnerStatus === "show") {
            spinner.show();
        }
        else {
            spinner.hide();
        }
    };
    MemberContractBlockApp.prototype.updateUrlWithQueryParameter = function (query) {
        var self = this;
        if (query === "") {
            self.queryStringHelper.removeParameter(self.categoryQueryStringKey);
        }
        else {
            // ReSharper disable once TsNotResolved
            self.queryStringHelper.updateParameter(self.categoryQueryStringKey, encodeURIComponent(query));
        }
    };
    return MemberContractBlockApp;
}());
$(function () {
    $(".contracts-block").each(function () {
        var myContractsApp = new MemberContractBlockApp(".".concat($(this).data("blockid")));
    });
});

var LeadsGeneratorBlockApp = /** @class */ (function () {
    function LeadsGeneratorBlockApp($leadsGeneratorBlock) {
        var self = this;
        self.leadsGeneratorBlockSelector = "#".concat($leadsGeneratorBlock.attr("id"));
        self.leadsFormSelector = self.leadsGeneratorBlockSelector + " .interestgeneratorblock-form";
        self.$leadsForm = $(self.leadsFormSelector);
        self.$formView = $leadsGeneratorBlock.find(".interest-generator-block__form");
        self.$confirmationView = $leadsGeneratorBlock.find(".interest-generator-block__confirmation");
        self.blockClientIdNumber = self.$leadsForm.data("blockclientidnumber");
        self.validationRules = {};
        self.validationMessages = {};
        /*$(document).ready(function () {*/
        var countrycodeInput = self.$leadsForm.find(".countrycodeinput");
        if (countrycodeInput) {
            countrycodeInput.countrySelect({
                defaultCountry: "se",
                preferredCountries: ["se"],
                responsiveDropdown: true
            });
        }
        /*});*/
        self.addValidationRulesAndMessages();
        self.attachEvents();
    }
    LeadsGeneratorBlockApp.prototype.attachEvents = function () {
        var self = this;
        var $postButton = self.$leadsForm.find("button[name=interestformbutton]");
        $postButton.click(function (e) {
            e.preventDefault();
            if (!self.validation.isValid()) {
                return;
            }
            var leadsFormData = {
                leadsGeneratorBlockId: self.$leadsForm.data("leadsgeneratorblockid"),
                firstname: self.$leadsForm.find(self.getFormElementSelector("input#firstname")).val(),
                lastname: self.$leadsForm.find(self.getFormElementSelector("input#lastname")).val(),
                email: self.$leadsForm.find(self.getFormElementSelector("input#email")).val(),
                phone: self.$leadsForm.find(self.getFormElementSelector("input#phone")).val(),
                countryCodeNumber: self.$leadsForm.find(".countrycodeinput").val(),
            };
            $.ajax({
                url: InternalApiEndpoints.saveLead(),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                method: "POST",
                data: JSON.stringify(leadsFormData)
            })
                .done(function (data) {
                if (data.isValid) {
                    self.onSuccessfulPost();
                }
                else {
                    self.onFailPost();
                }
            })
                .fail(function () {
                self.onFailPost();
            });
        });
    };
    LeadsGeneratorBlockApp.prototype.onSuccessfulPost = function () {
        var self = this;
        var redirectUrl = self.$leadsForm.data("redirectpageaftersubmittedleadurl");
        if (redirectUrl.length) {
            window.location.replace(redirectUrl);
        }
        else {
            self.$formView.hide();
            self.$confirmationView.show();
            $("html,body").animate({
                scrollTop: self.$confirmationView.offset().top - 10
            }, 500);
        }
    };
    LeadsGeneratorBlockApp.prototype.onFailPost = function () {
        var self = this;
        alert(self.$leadsForm.data("errormessage"));
    };
    LeadsGeneratorBlockApp.prototype.addValidationRulesAndMessages = function () {
        var self = this;
        var $firstname = self.getFormElement("input#firstname");
        self.addRuleAndMessage($firstname, { required: true, alphanumeric: true }, { required: $firstname.data("valrequired"), summary: $firstname.data("valsummary") });
        var $lastname = self.getFormElement("input#lastname");
        self.addRuleAndMessage($lastname, { required: true, alphanumeric: true }, { required: $lastname.data("valrequired"), summary: $lastname.data("valsummary") });
        var $email = self.getFormElement("input#email");
        self.addRuleAndMessage($email, { required: true, customEmail: true, email: false }, { required: $email.data("valrequired"), customEmail: $email.data("valemail"), summary: $email.data("valsummary") });
        var $phone = self.getFormElement("input#phone");
        self.addRuleAndMessage($phone, { required: true, newphone: true, number: true }, { required: $phone.data("valrequired"), newphone: $phone.data("valphone"), summary: $phone.data("valsummary") });
        var $acceptsTerms = self.getFormElement("input#acceptsterms");
        self.addRuleAndMessage($acceptsTerms, { required: true }, { required: $acceptsTerms.data("valrequired"), summary: $acceptsTerms.data("valsummary") });
        self.validation = new Validation(self.leadsFormSelector, self.validationRules, self.validationMessages, self.leadsGeneratorBlockSelector + " div.error");
    };
    LeadsGeneratorBlockApp.prototype.getFormElementSelector = function (inputPrefixId) {
        var self = this;
        return "".concat(inputPrefixId, "-").concat(self.blockClientIdNumber);
    };
    LeadsGeneratorBlockApp.prototype.getFormElement = function (inputPrefixId) {
        var self = this;
        var formElementSelector = "".concat(self.getFormElementSelector(inputPrefixId));
        return self.$leadsForm.find(formElementSelector);
    };
    LeadsGeneratorBlockApp.prototype.addRuleAndMessage = function ($input, rule, message) {
        var self = this;
        self.validationRules[$input.attr("name")] = rule;
        self.validationMessages[$input.attr("name")] = message;
    };
    return LeadsGeneratorBlockApp;
}());
$(function () {
    // ReSharper disable once UnusedLocals
    $(".interest-generator-block").each(function () {
        var leadsGeneratorBlockApp = new LeadsGeneratorBlockApp($(this));
    });
});

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var ChefNewsBlockApp = /** @class */ (function () {
    function ChefNewsBlockApp(rssBlock) {
        var self = this;
        self.rssBlock = rssBlock;
        self.$searchResultList = $(rssBlock).find('.chef-news-block__result__list');
        self.searchResultTemplate = _.template($("#chef-news-template").html());
        self.categories = $(rssBlock).data('categories');
        self.feedUrl = $(rssBlock).data('urltofeed');
        self.itemstotake = $(rssBlock).data('itemstotake');
        $(window).on("popstate", function () {
            // Force the search service to initialize to handle bfcache
            self.initializeSearchService();
        });
        self.initializeSearchService();
    }
    ChefNewsBlockApp.prototype.initializeSearchService = function () {
        var self = this;
        if (self.feedUrl != null) {
            $.getJSON(InternalApiEndpoints.newsFromRssFeed(self.feedUrl, self.itemstotake, self.categories), function (searchResult) {
                var templatedHtml = $(self.searchResultTemplate({ searchResult: searchResult }));
                self.$searchResultList.append(templatedHtml);
                self.rssBlock.find(".chef-news-block__link-container").show();
                slimmage.checkResponsiveImages();
            }).fail(function () {
                self.rssBlock.find(".chef-news-block__fallback").show();
            });
        }
    };
    return ChefNewsBlockApp;
}());
$(function () {
    // ReSharper disable once UnusedLocals
    $(".chef-news-block").each(function () {
        var chefNewsBlockApp = new ChefNewsBlockApp($(this));
    });
});

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var RssFeedBlockApp = /** @class */ (function () {
    function RssFeedBlockApp(rssBlock) {
        var self = this;
        self.$searchResultList = rssBlock.find('.rss-feed-block__result__list');
        self.feedUrl = rssBlock.data('urltofeed');
        self.itemstotake = rssBlock.data('itemstotake');
        self.searchResultTemplate = _.template($("#rss-feed-template").html());
        $(window).on("popstate", function () {
            // Force the search service to initialize to handle bfcache
            self.initializeSearchService();
        });
        self.initializeSearchService();
    }
    RssFeedBlockApp.prototype.initializeSearchService = function () {
        var self = this;
        if (self.feedUrl != null) {
            $.getJSON(InternalApiEndpoints.newsFromRssFeed(self.feedUrl, self.itemstotake), function (searchResult) {
                var templatedHtml = $(self.searchResultTemplate({ searchResult: searchResult }));
                self.$searchResultList.append(templatedHtml);
            });
        }
    };
    return RssFeedBlockApp;
}());
$(function () {
    // ReSharper disable once UnusedLocals
    $(".rss-feed-block").each(function () {
        var rssFeedBlockApp = new RssFeedBlockApp($(this));
    });
});

var VimeoPlayer = /** @class */ (function () {
    function VimeoPlayer(vimeoIframe) {
        var self = this;
        self.player = new Vimeo.Player(vimeoIframe[0]);
    }
    VimeoPlayer.prototype.play = function () {
        var self = this;
        self.player.play();
    };
    return VimeoPlayer;
}());

/// <reference path="../../../../Scripts/typings/jquery/jquery.d.ts" />
var YoutubePlayer = /** @class */ (function () {
    function YoutubePlayer(youtubeIframeId, onReadyCallback) {
        var self = this;
        self.onReadyCallback = onReadyCallback;
        self.injectYouTubeApiScript();
        YoutubePlayer.customEventHandler.subscribe("onYouTubePlayerAPIReady", function () {
            self.player = new YT.Player(youtubeIframeId, {
                events: {
                    'onReady': function (event) {
                        self.onReadyCallback();
                    }
                }
            });
        });
    }
    YoutubePlayer.prototype.injectYouTubeApiScript = function () {
        var self = this;
        if (!YoutubePlayer.isYouTubeApiScriptInjected) {
            YoutubePlayer.isYouTubeApiScriptInjected = true;
            var tag = document.createElement('script');
            tag.src = "//www.youtube.com/player_api";
            var firstScriptTag = document.getElementsByTagName('script')[0];
            firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
            // When the .js-file from YouTube is ready it will call the global function onYouTubePlayerAPIReady
            window.onYouTubePlayerAPIReady = self.onYouTubePlayerAPIReady;
        }
    };
    YoutubePlayer.prototype.onYouTubePlayerAPIReady = function () {
        YoutubePlayer.customEventHandler.trigger("onYouTubePlayerAPIReady", null);
    };
    YoutubePlayer.prototype.play = function () {
        var self = this;
        self.player.playVideo();
    };
    YoutubePlayer.isYouTubeApiScriptInjected = false;
    YoutubePlayer.customEventHandler = new CustomEventHandler();
    return YoutubePlayer;
}());

var InformationBrowserBlockApp = /** @class */ (function () {
    function InformationBrowserBlockApp($informationBrowserBlock) {
        var self = this;
        self.$informationBrowserBlock = $informationBrowserBlock;
        if (!self.isBrowserDeprecated()) {
            self.$informationBrowserBlock.find(".information-block__deprecated-browser").hide();
        }
    }
    InformationBrowserBlockApp.prototype.isBrowserDeprecated = function () {
        var self = this;
        // ReSharper disable once InconsistentNaming
        var isUserAgentDeprecated = self.$informationBrowserBlock.data("isuseragentdeprecated");
        if (isUserAgentDeprecated)
            return true;
        return !self.isBrowserSupportingEnoughHtml5Features();
    };
    InformationBrowserBlockApp.prototype.isBrowserSupportingEnoughHtml5Features = function () {
        // We test these five HTML5-features since this is used by EpiServer Forms: https://world.episerver.com/forum/developer-forum/episerver-forms/thread-container/2019/6/which-browsers-does-episerver-forms-supports/
        if (!Modernizr.sessionstorage)
            return false;
        if (!Modernizr.placeholder)
            return false;
        if (!Modernizr.input.required)
            return false;
        if (!Modernizr.dataset)
            return false;
        if (!Modernizr.inputtypes.range)
            return false;
        return true;
    };
    return InformationBrowserBlockApp;
}());

var MarketingCloudPushService = /** @class */ (function () {
    function MarketingCloudPushService() {
        var self = this;
        var bodyTag = $("body");
        self.orgId = bodyTag.data("mcid");
        self.memberSalesforceId = bodyTag.data("mcsfid");
        self.doNotTrack = bodyTag.data("mcdonottrack");
    }
    MarketingCloudPushService.prototype.push = function (contentId, name, category, url, event, keywords) {
        if (category === void 0) { category = ""; }
        if (url === void 0) { url = ""; }
        if (event === void 0) { event = ""; }
        if (keywords === void 0) { keywords = ""; }
        var self = this;
        if (self.canSendPush()) {
            self.performPushToMarketingCloud(self.buildPushValues(contentId, name, url, event, category, keywords));
        }
    };
    MarketingCloudPushService.prototype.performPushToMarketingCloud = function (marketingPush) {
        if (marketingPush.doNotTrack)
            window._etmc.push(["doNotTrack"]);
        window._etmc.push(["setOrgId", marketingPush.orgId.toString()]);
        window._etmc.push(["setUserInfo", { "email": marketingPush.memberSalesforceId }]);
        window._etmc.push(["trackPageView", { "item": marketingPush.pageAttributes.contentId, "url": marketingPush.pageAttributes.url, "title": marketingPush.pageAttributes.name }]);
        if (marketingPush.pageAttributes.category.length > 0) {
            window._etmc.push(["trackPageView", { "category": marketingPush.pageAttributes.category, "url": marketingPush.pageAttributes.url, "title": marketingPush.pageAttributes.name }]);
        }
        var updateItemValues = {
            item: marketingPush.pageAttributes.contentId,
            name: marketingPush.pageAttributes.name,
            url: marketingPush.pageAttributes.url,
            item_type: marketingPush.pageAttributes.itemType,
            availability: marketingPush.pageAttributes.availability,
            publicationdate: marketingPush.pageAttributes.publicationDate.toISOString(),
            category: marketingPush.pageAttributes.category,
            keywords: marketingPush.pageAttributes.keywords
        };
        window._etmc.push(["updateItem", updateItemValues]);
    };
    MarketingCloudPushService.prototype.buildPushValues = function (contentId, name, url, event, category, keywords) {
        var self = this;
        var urlToTrack;
        var queryParam = "?";
        var eventValue = event;
        var pageAttributes = new MarketingCloudPageAttributesModel();
        pageAttributes.contentId = contentId.toString();
        pageAttributes.name = name;
        if (url)
            urlToTrack = url;
        else
            urlToTrack = location.protocol + "//" + location.host + location.pathname;
        if (urlToTrack.indexOf('?') !== -1)
            queryParam = "&";
        if (!event)
            eventValue = self.slugify(name);
        pageAttributes.url = urlToTrack + queryParam + "event=" + eventValue;
        pageAttributes.category = category; // Max one
        pageAttributes.keywords = keywords; // if more than one value should be a string: "keyword1~keyword2~keyword3"
        var marketingPush = new MarketingCloudPushDataModel();
        marketingPush.doNotTrack = self.doNotTrack;
        marketingPush.orgId = self.orgId;
        marketingPush.memberSalesforceId = self.memberSalesforceId;
        marketingPush.pageAttributes = pageAttributes;
        return marketingPush;
    };
    MarketingCloudPushService.prototype.canSendPush = function () {
        var self = this;
        if (self.orgId && self.memberSalesforceId && window._etmc) {
            return true;
        }
        return false;
    };
    MarketingCloudPushService.prototype.slugify = function (string) {
        var a = 'àáâäæãåāăąçćčđďèéêëēėęěğǵḧîïíīįìłḿñńǹňôöòóœøōõőṕŕřßśšşșťțûüùúūǘůűųẃẍÿýžźż·/_,:;';
        var b = 'aaaaaaaaaacccddeeeeeeeegghiiiiiilmnnnnoooooooooprrsssssttuuuuuuuuuwxyyzzz------';
        var p = new RegExp(a.split('').join('|'), 'g');
        return string.toString().toLowerCase()
            .replace(/\s+/g, '-') // Replace spaces with -
            .replace(p, function (c) { return b.charAt(a.indexOf(c)); }) // Replace special characters
            .replace(/&/g, '-och-') // Replace & with 'and'
            .replace(/[^\w\-]+/g, '') // Remove all non-word characters
            .replace(/\-\-+/g, '-') // Replace multiple - with single -
            .replace(/^-+/, '') // Trim - from start of text
            .replace(/-+$/, ''); // Trim - from end of text
    };
    return MarketingCloudPushService;
}());
var MarketingCloudPushDataModel = /** @class */ (function () {
    function MarketingCloudPushDataModel() {
    }
    return MarketingCloudPushDataModel;
}());
var MarketingCloudPageAttributesModel = /** @class */ (function () {
    function MarketingCloudPageAttributesModel() {
        this.publicationDate = new Date('1970-01-01T00:00:00Z');
        this.itemType = "content";
        this.availability = "y";
    }
    return MarketingCloudPageAttributesModel;
}());

var LogoutTracking = /** @class */ (function () {
    function LogoutTracking(trackingClass) {
        if (trackingClass === void 0) { trackingClass = ".logout-link-track-using-marketing-cloud"; }
        this.marketingCloudPushService = new MarketingCloudPushService();
        var self = this;
        self.$foundLogoutButtons = $(trackingClass);
        self.attachTrackingEvents();
    }
    LogoutTracking.prototype.attachTrackingEvents = function () {
        var self = this;
        if (self.$foundLogoutButtons == null) {
            return;
        }
        self.$foundLogoutButtons.click(function (e) {
            var currentLinkTarget = e.currentTarget;
            var url = location.protocol + "//" + location.host + currentLinkTarget.getAttribute("href");
            self.marketingCloudPushService.push(99990003, "Utloggning", "Inaktiv medlem", url, "LogoutSucess");
        });
    };
    return LogoutTracking;
}());

var GlobalAssetsTracking = /** @class */ (function () {
    function GlobalAssetsTracking(trackingUrlAttribute01, trackingUrlAttribute02, trackingId, trackingName, trackingCategory) {
        this.marketingCloudPushService = new MarketingCloudPushService();
        var self = this;
        self.$foundLinks = $('a[href*="/' + trackingUrlAttribute01 + '/"][href*="' + trackingUrlAttribute02 + '"]');
        self.attachTrackingEvents(trackingId, trackingName, trackingCategory);
    }
    GlobalAssetsTracking.prototype.attachTrackingEvents = function (trackingId, trackingName, trackingCategory) {
        var self = this;
        if (self.$foundLinks == null) {
            return;
        }
        self.$foundLinks.click(function (e) {
            var currentLinkTarget = e.currentTarget;
            var url = location.protocol + "//" + location.host + currentLinkTarget.getAttribute("href");
            self.marketingCloudPushService.push(trackingId, trackingName, trackingCategory, url);
        });
    };
    return GlobalAssetsTracking;
}());

var ChangeEmployerBlockApp = /** @class */ (function () {
    function ChangeEmployerBlockApp($changeEmployerBlock) {
        this.modal = null;
        this.escKeyupEventName = "keyup.changeemployerblock";
        this.lastActiveView = null;
        this.manualEmployerViewHash = "#/andraarbetsgivare/manuellt";
        this.selectEmployerViewHash = "#/andraarbetsgivare";
        this.onOpen = null;
        this.onClose = null;
        this.$el = $changeEmployerBlock;
        this.$openModalLink = this.$el.find(".change-employer-block__open-modal");
        this.initRoutes();
    }
    ChangeEmployerBlockApp.prototype.initRoutes = function () {
        var self = this;
        var app = Sammy(".change-employer-block");
        app.get(this.getRoutePath(this.manualEmployerViewHash), function () {
            if (!self.isModalOpen())
                self.openModal();
            var activeView = ChangeEmployerModalView.ManualEmployerView;
            self.lastActiveView = activeView;
            self.modal.setActiveView(activeView);
        });
        app.get(this.getRoutePath(self.selectEmployerViewHash), function () {
            if (!self.isModalOpen())
                self.openModal();
            var activeView = ChangeEmployerModalView.SelectEmployerView;
            self.modal.setActiveView(activeView);
            self.lastActiveView = activeView;
            var globalSettings = GlobalSettingsSingleton.getInstance();
            if (globalSettings.isMobileDevice() || !globalSettings.hasBrowserTouchCapabilities()) {
                self.modal.changeEmployerWorkSituation.setFocusToFirstWorkSituationOption();
            }
            else {
                self.modal.changeEmployerSearch.setFocusToQueryTextbox();
            }
        });
        app.get(this.getRoutePath("(#/)?"), function () {
            /*if (self.isModalOpen())*/
            self.closeModal();
        });
        app.run(window.location.pathname + window.location.search);
    };
    ChangeEmployerBlockApp.prototype.getRoutePath = function (hash) {
        // Will return a regexp that only match current pathname (with or without ending with a backslash) 
        // with empty or any kind of querystring followed be the input parameter hash
        return new RegExp("".concat(window.location.pathname, "/?(\\?.*)?").concat(hash, "$"));
    };
    ChangeEmployerBlockApp.prototype.isModalOpen = function () {
        if (this.modal === null)
            return false;
        return this.modal.isModalOpen();
    };
    ChangeEmployerBlockApp.prototype.openModal = function () {
        this.initModalIfNotAlreadyInitiated();
        if (this.modal.isModalOpen())
            return; // It is already opened
        this.attachEscapeKeyListener();
        this.$openModalLink.hide();
        if (this.onOpen !== null)
            this.onOpen();
        this.modal.open();
    };
    ChangeEmployerBlockApp.prototype.closeModal = function () {
        if (this.modal === null)
            return;
        if (!this.modal.isModalOpen())
            return; // It is already closed
        this.updateOpenModalLinkUrl();
        this.deattachEscKeyListener();
        this.$openModalLink.show();
        if (this.onClose !== null)
            this.onClose();
        this.modal.close();
    };
    ChangeEmployerBlockApp.prototype.updateOpenModalLinkUrl = function () {
        if (this.lastActiveView === null)
            return;
        var hashUrl = this.getHashUrl(this.lastActiveView);
        if (hashUrl !== null)
            this.$openModalLink.attr("href", hashUrl);
    };
    ChangeEmployerBlockApp.prototype.getHashUrl = function (changeEmployerModalView) {
        switch (changeEmployerModalView) {
            case ChangeEmployerModalView.ManualEmployerView:
                return this.manualEmployerViewHash;
            case ChangeEmployerModalView.SelectEmployerView:
                return this.selectEmployerViewHash;
            default:
                return null;
        }
    };
    ChangeEmployerBlockApp.prototype.initModalIfNotAlreadyInitiated = function () {
        if (this.modal !== null)
            return;
        this.modal = new ChangeEmployerModal(this.$el.find(".change-employer-block__modal"));
    };
    ChangeEmployerBlockApp.prototype.attachEscapeKeyListener = function () {
        var self = this;
        $(document).on(self.escKeyupEventName, function (e) {
            if (e.key === "Escape") {
                window.location.href = "#/";
            }
        });
    };
    ChangeEmployerBlockApp.prototype.deattachEscKeyListener = function () {
        $(document).off(this.escKeyupEventName);
    };
    return ChangeEmployerBlockApp;
}());

var ChangeEmployerManually = /** @class */ (function () {
    function ChangeEmployerManually($changeEmployerManually) {
        this.changeEmployerService = new ChangeEmployerService();
        this.gtmService = new GoogleDataLayerService();
        this.onSaved = null;
        var self = this;
        this.$el = $changeEmployerManually;
        this.$saveButton = this.$el.find(".manually-employer-view__save-button");
        this.$errorContainer = this.$el.find(".manually-employer-view__form__error-container");
        this.spinner = new Spinner(this.$el.find(".manually-employer-view__save-spinner"));
        this.$employerName = self.$el.find("#employername");
        this.$address = self.$el.find("#employeraddress");
        this.$zip = self.$el.find("#employerzip");
        this.$city = self.$el.find("#employercity");
        this.$organisationNumber = self.$el.find("#employerorganisationnumber");
        this.$formInputs = self.$el.find(".mb-4 input");
        self.isCurrentUserEditorOrContentViewer = self.$el.data("iscurrentusereditororcontentviewer");
        var validation = this.initValidation();
        validation.customSubmit = function () {
            self.saveEmployer();
        };
        self.initSessionPersistence();
    }
    ChangeEmployerManually.prototype.initSessionPersistence = function () {
        var self = this;
        this.$formInputs.each(function () {
            var sessionStorageKey = self.getSessionStorageKey($(this));
            var value = sessionStorage.getItem(sessionStorageKey);
            if (value !== null) {
                $(this).val(value);
            }
        });
        this.$formInputs.blur(function (e) {
            self.setValueToSessionStorage(e.target);
        });
    };
    ChangeEmployerManually.prototype.setValueToSessionStorage = function (input) {
        var $input = $(input);
        sessionStorage.setItem(this.getSessionStorageKey($input), $input.val());
    };
    ChangeEmployerManually.prototype.resetSessionPersistence = function () {
        var self = this;
        this.$formInputs.each(function () {
            var sessionStorageKey = self.getSessionStorageKey($(this));
            sessionStorage.removeItem(sessionStorageKey);
        });
    };
    ChangeEmployerManually.prototype.getSessionStorageKey = function ($input) {
        return "changeemployer-manually-".concat($input.attr("id"));
    };
    ChangeEmployerManually.prototype.initValidation = function () {
        var validation = new Validation(".create-employer-view__form", {
            'employername': {
                required: true
            },
            'employercity': {
                required: true
            }
        }, {
            'employername': {
                required: $("#employername").data("valrequired"),
                summary: $("#employername").data("valsummary")
            },
            'employercity': {
                required: $("#employercity").data("valrequired"),
                summary: $("#employercity").data("valsummary")
            }
        }, ".create-employer-view__form__error-summary");
        validation.scrollToErrorMessageOffset = 100;
        return validation;
    };
    ChangeEmployerManually.prototype.saveEmployer = function () {
        var self = this;
        if (self.isCurrentUserEditorOrContentViewer) {
            self.handleError("Kan inte spara din nya arbetsgivare", "Du är inte inloggad som medlem och har därför inte tillgång till att ändra din arbetsgivare.");
            self.$saveButton.removeAttr("disabled");
            return;
        }
        var newEmployer = {
            employerName: self.$employerName.val(),
            address: self.$address.val(),
            zip: self.$zip.val(),
            city: self.$city.val(),
            organisationNumber: self.$organisationNumber.val()
        };
        self.$saveButton.hide();
        self.spinner.show();
        $.post(InternalApiEndpoints.changeEmployerManually(), newEmployer)
            .done(function () {
            self.changeEmployerService.triggerEmployerChangedEvent();
            self.gtmService.push({
                "event": "updateArbetsgivare",
                "selectType": "manual"
            });
            window.location.href = "#/";
            if (self.onSaved !== null) {
                self.onSaved();
            }
        })
            .fail(function (jqueryXhr) {
            if (jqueryXhr.status === 401) {
                location.reload();
                return;
            }
            self.handleError(self.$el.data("changeemployererrormessageheader"), self.$el.data("changeemployererrormessagetext"));
        })
            .always(function () {
            self.$saveButton.show();
            self.spinner.hide();
            self.$saveButton.removeAttr("disabled");
        });
    };
    ChangeEmployerManually.prototype.handleError = function (header, description) {
        this.$errorContainer.removeClass("hide");
        var errorMessageBox = new ErrorMessageBox(header, description);
        errorMessageBox.append(this.$errorContainer);
        errorMessageBox.scrollTo(100);
    };
    ChangeEmployerManually.prototype.reset = function () {
        this.$employerName.removeClass("valid").val("");
        this.$address.removeClass("valid").val("");
        this.$zip.removeClass("valid").val("");
        this.$city.removeClass("valid").val("");
        this.$organisationNumber.removeClass("valid").val("");
        this.resetSessionPersistence();
    };
    return ChangeEmployerManually;
}());

var ChangeEmployerModal = /** @class */ (function () {
    function ChangeEmployerModal($changeEmployerModal) {
        this.isModalInitiated = false;
        this.$modal = $changeEmployerModal;
        this.$closeModalLink = this.$modal.find(".modal-cancel");
        this.gtmService = new GoogleDataLayerService();
        this.focusTrap = new FocusTrap(this.$modal, "changeemployerblockfocustrap");
        this.customEventHandler = new CustomEventHandler();
        this.$selectEmployerView = this.$modal.find(".select-employer-view");
        this.$manualEmployerView = this.$modal.find(".manually-employer-view");
        this.initSearchEmployer();
        this.initMyWorkSituation();
        this.initChangeEmployerManually();
    }
    ChangeEmployerModal.prototype.addOverlay = function () {
        this.$overlay = $("<div />").addClass("change-employer-block__overlay");
        this.$overlay.insertAfter(this.$modal);
    };
    ChangeEmployerModal.prototype.removeOverlay = function () {
        this.$overlay.remove();
    };
    ChangeEmployerModal.prototype.initSearchEmployer = function () {
        var self = this;
        self.changeEmployerSearch = new ChangeEmployerSearch(self.$modal.find(".search-employer-section"));
        self.changeEmployerSearch.onSaved = function () {
            self.reset();
        };
    };
    ChangeEmployerModal.prototype.initMyWorkSituation = function () {
        var self = this;
        self.changeEmployerWorkSituation = new ChangeEmployerWorkSituation(self.$modal.find(".work-situation-section"));
        self.changeEmployerWorkSituation.onWorkSituationChanged = function (workSituationType) {
            if (workSituationType === WorkSituationType.Employed) {
                self.changeEmployerSearch.show();
            }
            if (workSituationType === WorkSituationType.NotEmployed) {
                self.changeEmployerSearch.hide();
            }
        };
        self.changeEmployerWorkSituation.changeSelectedWorkSituation(WorkSituationType.Employed);
        self.changeEmployerWorkSituation.onSaved = function () { self.reset(); };
    };
    ChangeEmployerModal.prototype.initChangeEmployerManually = function () {
        var self = this;
        self.changeEmployerManually = new ChangeEmployerManually(self.$manualEmployerView);
        self.changeEmployerManually.onSaved = function () { self.reset(); };
    };
    ChangeEmployerModal.prototype.open = function () {
        var self = this;
        this.addOverlay();
        this.$modal.collapse("show");
        this.focusTrap.activate();
        $("html, body").animate({ scrollTop: self.$modal.offset().top - 5 }, 500);
    };
    ChangeEmployerModal.prototype.close = function () {
        var self = this;
        self.$modal.collapse("hide");
        self.$modal.one("hidden.bs.collapse", function () {
            self.removeOverlay();
        });
        self.focusTrap.inactivate();
    };
    ChangeEmployerModal.prototype.isModalOpen = function () {
        return this.$modal.hasClass("show");
    };
    ChangeEmployerModal.prototype.setActiveView = function (view) {
        if (view === ChangeEmployerModalView.ManualEmployerView) {
            this.$selectEmployerView.addClass("hide");
            this.$manualEmployerView.removeClass("hide");
        }
        else if (view === ChangeEmployerModalView.SelectEmployerView) {
            this.$selectEmployerView.removeClass("hide");
            this.$manualEmployerView.addClass("hide");
        }
        var self = this;
        $("html, body").animate({ scrollTop: self.$modal.offset().top - 5 }, 500);
    };
    ChangeEmployerModal.prototype.reset = function () {
        this.changeEmployerWorkSituation.reset();
        this.changeEmployerSearch.reset();
        this.changeEmployerManually.reset();
    };
    return ChangeEmployerModal;
}());

var ChangeEmployerSearch = /** @class */ (function () {
    function ChangeEmployerSearch($searchEmployerSection) {
        this.onSaved = null;
        var self = this;
        self.$searchEmployerSection = $searchEmployerSection;
        self.searchForm = new ChangeEmployerSearchForm($searchEmployerSection);
        self.searchResult = new ChangeEmployerSearchResult($searchEmployerSection);
        self.searchResult.onSaved = function () {
            if (self.onSaved !== null) {
                self.onSaved();
            }
        };
        //self.searchForm.onAutocompleteOptionSelected = (bbcId: string) => {
        //    self.searchForm.setCountrySelectorVisability(false);
        //    self.searchForm.setCitySelectorVisability(false);
        //    self.searchResult.showDirectHit(bbcId);
        //}
        self.searchForm.onSearch = function (searchParameters, callback) {
            self.searchResult.searchParameters = searchParameters;
            self.searchResult.search(0, callback);
        };
        self.setFocusToQueryTextbox();
        // When initiating the modal for the first time we force this to be visible. Otherwise
        // in can be hidden if the user is using the browser-back-button.
        this.show();
    }
    ChangeEmployerSearch.prototype.show = function () {
        this.$searchEmployerSection.removeClass("hide");
    };
    ChangeEmployerSearch.prototype.hide = function () {
        this.$searchEmployerSection.addClass("hide");
    };
    ChangeEmployerSearch.prototype.reset = function () {
        this.show();
        this.searchForm.reset();
        this.searchResult.reset();
    };
    ChangeEmployerSearch.prototype.setFocusToQueryTextbox = function () {
        this.searchForm.setFocusToQueryTextbox();
    };
    return ChangeEmployerSearch;
}());

var ChangeEmployerSearchForm = /** @class */ (function () {
    //onAutocompleteOptionSelected: Function;
    function ChangeEmployerSearchForm($searchEmployerSection) {
        this.maxItemsInAutocomplete = 5;
        this.defaultCountryCode = "se";
        this.isAutocompleteActive = true;
        var self = this;
        self.$searchEmployerSection = $searchEmployerSection;
        self.$formSection = self.$searchEmployerSection.find(".search-employer-section__form");
        self.$queryTextbox = $searchEmployerSection.find(".search-employer-section__form__query-row__input");
        self.$searchButton = $searchEmployerSection.find(".search-employer-section__form__query-row__search-button");
        self.$showInternationalEmployees = $searchEmployerSection.find(".search-employer-section__form__country-row__show-international-employees");
        self.minHitsToShowCityAndCountryDropdown = self.$searchEmployerSection.data("minhitstoshowcityandcountrydropdown");
        self.$formCountryRow = $searchEmployerSection.find(".search-employer-section__form__country-row");
        self.$formCityRow = $searchEmployerSection.find(".search-employer-section__form__city-row");
        self.$countryDropdownmenu = $searchEmployerSection.find(".search-employer-section__country");
        self.$cityDropdownmenu = $searchEmployerSection.find(".search-employer-section__city");
        self.autocompleteSpinner = new Spinner($searchEmployerSection.find(".search-employer-section__form__query-row__spinner"));
        self.currentQuery = self.$queryTextbox.val();
        self.addressMissingText = self.$searchEmployerSection.data("addressmissingtext");
        self.textboxClearer = new TextboxClearer(self.$queryTextbox, self.$searchEmployerSection.data("clearsearchalttext"));
        // self.initAutocomplete();
        self.$queryTextbox.keypress(function (e) {
            if (e.keyCode === 13) { // If user clicks enter
                //self.toggleAutocompleteEnabled(false);
                self.$searchButton.focus();
                self.$searchButton.click();
            }
        });
        //self.$queryTextbox.keyup(() => {
        //    self.toggleAutocompleteEnabled(self.$queryTextbox.val().length > 0);
        //});
        self.$searchButton.click(function (e) {
            console.log("search");
            e.preventDefault();
            self.search();
        });
        self.$showInternationalEmployees.change(function (e) {
            e.preventDefault();
            //self.changeAutocompleteCountryScope(self.isSearchingInternational() ? null : self.defaultCountryCode);
            if (self.currentQuery === "")
                return;
            self.search();
        });
        self.$countryDropdownmenu.change(function () {
            self.$cityDropdownmenu.val("");
            self.filter(function (searchResult) {
                self.populateCityDropdownmenu(searchResult);
            });
        });
        self.$cityDropdownmenu.change(function () {
            self.filter();
        });
    }
    ChangeEmployerSearchForm.prototype.search = function () {
        var self = this;
        self.autocompleteSpinner.hide();
        self.currentQuery = self.$queryTextbox.val();
        self.setCountrySelectorVisability(false);
        self.setCitySelectorVisability(false);
        self.getSearchResult(function (searchResult) {
            if (self.isSearchingInternational()) {
                self.populateCountryDropdownmenu(searchResult);
                if (searchResult.countries.length === 1) {
                    self.populateCityDropdownmenu(searchResult);
                }
            }
            else {
                self.populateCityDropdownmenu(searchResult);
            }
            self.updateForm(searchResult);
        });
    };
    ChangeEmployerSearchForm.prototype.filter = function (callback) {
        if (callback === void 0) { callback = null; }
        var self = this;
        self.getSearchResult(function (searchResult) {
            self.updateForm(searchResult);
            if (callback !== null) {
                callback(searchResult);
            }
        });
    };
    ChangeEmployerSearchForm.prototype.isSearchingInternational = function () {
        return this.$showInternationalEmployees.is(":checked");
    };
    ChangeEmployerSearchForm.prototype.getSelectedCountryCode = function () {
        if (!this.$showInternationalEmployees.is(":checked"))
            return this.defaultCountryCode;
        var $selectedCountry = this.$countryDropdownmenu.find("option:selected");
        if ($selectedCountry.length === 0)
            return null;
        if ($selectedCountry.val() === "")
            return null;
        return $selectedCountry.val();
    };
    ChangeEmployerSearchForm.prototype.getSelectedCountryName = function () {
        if (!this.$showInternationalEmployees.is(":checked"))
            return "Sverige";
        var $selectedCountry = this.$countryDropdownmenu.find("option:selected");
        if ($selectedCountry.length === 0)
            return null;
        if ($selectedCountry.val() === "")
            return null;
        return $selectedCountry.text();
    };
    ChangeEmployerSearchForm.prototype.getSelectedCity = function () {
        var selectedCity = this.$cityDropdownmenu.find("option:selected");
        if (selectedCity.length === 0)
            return null;
        if (selectedCity.val() === "")
            return null;
        return selectedCity.val();
    };
    ChangeEmployerSearchForm.prototype.setCitySelectorVisability = function (visible) {
        if (visible) {
            this.$formCityRow.removeClass("hide");
        }
        else {
            this.$formCityRow.addClass("hide");
            this.$cityDropdownmenu.val("");
        }
    };
    ChangeEmployerSearchForm.prototype.setCountrySelectorVisability = function (visible) {
        if (visible) {
            this.$formCountryRow.removeClass("hide");
        }
        else {
            this.$formCountryRow.addClass("hide");
            this.$countryDropdownmenu.val("");
        }
    };
    ChangeEmployerSearchForm.prototype.setFocusToQueryTextbox = function () {
        this.$queryTextbox.attr("autofocus", ""); // Forces iPhone devices to set focus to the input field
        this.$queryTextbox.focus();
    };
    ChangeEmployerSearchForm.prototype.updateForm = function (searchResult) {
        this.setCountrySelectorVisability(this.shouldCountrySelecterBeVisible(searchResult));
        this.setCitySelectorVisability(this.shouldCitySelectorBeVisible(searchResult));
    };
    ChangeEmployerSearchForm.prototype.shouldCountrySelecterBeVisible = function (searchResult) {
        if (!this.isSearchingInternational())
            return false;
        if (this.getSelectedCountryCode() !== null)
            return true;
        if (searchResult.countries.length < 2)
            return false;
        return searchResult.hitsTotal >= this.minHitsToShowCityAndCountryDropdown;
    };
    ChangeEmployerSearchForm.prototype.shouldCitySelectorBeVisible = function (searchResult) {
        if (this.getSelectedCity() !== null)
            return true;
        if (searchResult.cities.length < 2)
            return false;
        if (this.isSearchingInternational()) {
            return searchResult.hitsTotal >= this.minHitsToShowCityAndCountryDropdown &&
                (this.getSelectedCountryCode() !== null || searchResult.countries.length === 1);
        }
        else {
            return searchResult.hitsTotal >= this.minHitsToShowCityAndCountryDropdown;
        }
    };
    ChangeEmployerSearchForm.prototype.getSearchResult = function (callback) {
        if (callback === void 0) { callback = null; }
        if (this.onSearch !== null) {
            var searchParameters = new SearchParameters();
            searchParameters.query = this.currentQuery;
            searchParameters.city = this.getSelectedCity();
            searchParameters.countryCode = this.getSelectedCountryCode();
            searchParameters.countryName = this.getSelectedCountryName();
            searchParameters.pageIndex = 0;
            this.onSearch(searchParameters, callback);
            //this.toggleAutocompleteEnabled(false);
        }
    };
    ChangeEmployerSearchForm.prototype.populateCountryDropdownmenu = function (searchResult) {
        var self = this;
        self.$countryDropdownmenu.find("option:not([value=''])").remove();
        $.each(searchResult.countries, function (index, companyCountry) {
            var countryOption = $("<option />");
            countryOption.text(companyCountry.countryName);
            countryOption.val(companyCountry.countryCode);
            self.$countryDropdownmenu.append(countryOption);
        });
    };
    ChangeEmployerSearchForm.prototype.populateCityDropdownmenu = function (searchResult) {
        var self = this;
        self.$cityDropdownmenu.find("option:not([value=''])").remove();
        $.each(searchResult.cities, function (index, companyCity) {
            var cityOption = $("<option />");
            cityOption.text(self.firstLetterUpperCase(companyCity));
            cityOption.val(companyCity);
            self.$cityDropdownmenu.append(cityOption);
        });
    };
    ChangeEmployerSearchForm.prototype.firstLetterUpperCase = function (word) {
        if (word === null || word.length === 0)
            return word;
        return word[0].toUpperCase() + word.slice(1).toLowerCase();
    };
    //private initAutocomplete() {
    //    const self = this;
    //    self.$queryTextbox.tinyAutocomplete({
    //        url: self.getAutocompleteSearchApiUrl(self.defaultCountryCode),
    //        queryProperty: "query",
    //        itemTemplate: '<li class="autocomplete-item"><div>{{name}}</div><div>{{address}}</div><div>{{country}}</div></li>',
    //        onSelect: (element: any, company: any) => {
    //            self.$queryTextbox.val(company.name);
    //            if (self.onAutocompleteOptionSelected !== null) {
    //                self.onAutocompleteOptionSelected(company.bbcId);
    //            }
    //        },
    //        showNoResults: false,
    //        minChars: 1,
    //        markAsBold: true,
    //        maxItems: self.maxItemsInAutocomplete,
    //        maxItemsOnMobile: self.maxItemsInAutocomplete,
    //        keyboardDelay: 100,
    //        excludedFieldNamesFromMarkHit: ["bbcId", "address", "country"]
    //    });
    //    self.$queryTextbox.on("beforerequest",
    //        () => {
    //            self.autocompleteSpinner.show();
    //        });
    //    self.$queryTextbox.on("requestfailed",
    //        () => {
    //            self.autocompleteSpinner.hide();
    //        });
    //    self.$queryTextbox.on("receivedata", (e, tinyAutocomplete, json) => {
    //        self.autocompleteSpinner.hide();
    //        if (!self.isAutocompleteActive) {
    //            tinyAutocomplete.json = [];
    //            return;
    //        }
    //        tinyAutocomplete.json = json.companies.map(company => {
    //            let address: string;
    //            if (company.address || company.city) {
    //                address = company.address + " " + company.city;
    //            } else {
    //                const $addressMissingText = $("<span />").addClass("text--italic").text(self.addressMissingText);
    //                address = $addressMissingText[0].outerHTML;
    //            }
    //            return {
    //                bbcId: company.bbcId,
    //                name: company.name,
    //                address: address,
    //                country: company.countryName
    //            };
    //        });
    //    });
    //}
    //private getAutocompleteSearchApiUrl(countryCode: string): string {
    //    const self = this;
    //    return InternalApiEndpoints.searchCompanies(null, null, countryCode, 0, self.maxItemsInAutocomplete, false);
    //}
    //private changeAutocompleteCountryScope(countryCode: string) {
    //    const self = this;
    //    self.$queryTextbox.tinyAutocomplete({
    //        url: self.getAutocompleteSearchApiUrl(countryCode)
    //    });
    //}
    //private toggleAutocompleteEnabled(enabled: boolean) {
    //    this.$queryTextbox.tinyAutocomplete({
    //        enabled: enabled
    //    });
    //    this.isAutocompleteActive = enabled;
    //}
    ChangeEmployerSearchForm.prototype.reset = function () {
        this.$queryTextbox.removeAttr("autofocus");
        this.$queryTextbox.val("");
        this.textboxClearer.updateVisabilityOnClearButton();
        this.$showInternationalEmployees.prop("checked", false);
        this.setCountrySelectorVisability(false);
        this.setCitySelectorVisability(false);
    };
    return ChangeEmployerSearchForm;
}());

var ChangeEmployerSearchResult = /** @class */ (function () {
    function ChangeEmployerSearchResult($searchEmployerSection) {
        this.gtmService = new GoogleDataLayerService();
        this.changeEmployerService = new ChangeEmployerService();
        this.lastSearchXhr = null;
        this.onSearched = null;
        this.onSaved = null;
        this.searchParameters = new SearchParameters();
        var self = this;
        self.$searchEmployerSection = $searchEmployerSection;
        self.companySearchHitTemplate = _.template($searchEmployerSection.find("#search-employer-section__search-result-template").html());
        self.$companySearchResult = $searchEmployerSection.find(".search-employer-section__search-result");
        self.$searchSummaryText = self.$searchEmployerSection.find(".search-employer-section__search-result__search-summary-text");
        self.$companySearchResultHits = self.$companySearchResult.find(".search-employer-section__search-result__hits");
        self.$companySearchResultFooter = $searchEmployerSection.find(".search-employer-section__search-result__footer");
        self.$companySearchResultPager = self.$companySearchResult.find(".search-employer-section__search-result__footer__pager");
        self.companySearchResultPagerSpinner = new Spinner(self.$companySearchResult.find(".search-employer-section__search-result__footer__pager-spinner"));
        self.$companySearchResultPagerShowNextPageLink = self.$companySearchResult.find(".search-employer-section__search-result__pager__show-next-page-link");
        self.$companySearchResultCannotFindEmployerLink = self.$companySearchResult.find(".search-employer-section__search-result__footer__cannot-find-employer-link");
        self.$errorContainer = self.$searchEmployerSection.find(".search-employer-section__error");
        self.isCurrentUserEditorOrContentViewer = self.$searchEmployerSection.data("iscurrentusereditororcontentviewer");
        self.companySearchSpinner = new Spinner(self.$searchEmployerSection.find(".search-employer-section__search-spinner"));
        self.pageSize = self.$companySearchResult.data("pagesize");
        self.$companySearchResultPagerShowNextPageLink.click(function (e) {
            e.preventDefault();
            self.$companySearchResultPagerShowNextPageLink.hide();
            self.companySearchResultPagerSpinner.show();
            self.search(self.searchParameters.pageIndex + 1);
        });
        self.$companySearchResult.on("show.bs.collapse", ".collapse", function () {
            var $companyAccordionGroup = $(this).parents(".accordion-group");
            var companyDetailsIsAlreadyPopulated = $companyAccordionGroup.find(".search-employer-section__search-result__company-detail").length === 0;
            var $loadDetailsSpinner = new Spinner($companyAccordionGroup.find(".search-employer-section__search-result__hits__load-details-spinner"));
            if (!companyDetailsIsAlreadyPopulated) {
                $loadDetailsSpinner.show();
            }
            var bbcId = $companyAccordionGroup.data("bbcid");
            var $changeEmployerLink = $companyAccordionGroup.find(".search-employer-section__search-result__hits__change-employer");
            self.attachEventsToChangeEmployerButton($changeEmployerLink, bbcId);
            if (companyDetailsIsAlreadyPopulated)
                return;
            self.getCompanyDetails(bbcId, function (company) {
                self.populateCompanyDetails($companyAccordionGroup, company);
            }, function () {
                $loadDetailsSpinner.hide();
            });
        });
    }
    ChangeEmployerSearchResult.prototype.search = function (pageIndex, callback) {
        if (pageIndex === void 0) { pageIndex = 0; }
        if (callback === void 0) { callback = null; }
        var self = this;
        self.searchParameters.pageIndex = pageIndex;
        self.hideError();
        if (self.searchParameters.query.length === 0) {
            var searchResult = new SearchResult();
            searchResult.hitsTotal = 0;
            searchResult.pageIndex = 0;
            searchResult.pageSize = self.pageSize;
            searchResult.hasMorePages = false;
            searchResult.companies = [];
            self.updateSearchArea(searchResult, new SearchSummary(self.searchParameters));
            return;
        }
        if (pageIndex === 0) {
            self.companySearchSpinner.show();
            self.$companySearchResult.addClass("hide");
        }
        var searchApiUrl = InternalApiEndpoints.searchCompanies(self.searchParameters.query, self.searchParameters.city, self.searchParameters.countryCode, pageIndex, self.pageSize, pageIndex === 0);
        var searchStartedTime = window.performance.now();
        if (this.lastSearchXhr !== null) {
            this.lastSearchXhr.abort();
        }
        this.lastSearchXhr = $.getJSON(searchApiUrl)
            .done(function (searchResult) {
            var searchTotalTime = window.performance.now() - searchStartedTime;
            var minimumProgressBarShowTime = 500;
            var timeoutTime = Math.max(minimumProgressBarShowTime - searchTotalTime, 0);
            setTimeout(function () {
                self.updateSearchArea(searchResult, new SearchSummary(self.searchParameters));
                self.hideSearchSpinners();
                if (callback !== null)
                    callback(searchResult);
            }, timeoutTime);
        })
            .fail(function (jqueryXhr) {
            if (jqueryXhr.status === 401) {
                location.reload();
                return;
            }
            if (jqueryXhr.statusText === "abort") // If request is aborted, the member has made a new search before the previous search result was received
                return;
            self.handleError(self.$searchEmployerSection.data("searchemployererrormessageheader"), self.$searchEmployerSection.data("searchemployererrormessagetext"), false);
            self.hideSearchSpinners();
        });
    };
    ChangeEmployerSearchResult.prototype.hideSearchSpinners = function () {
        this.companySearchSpinner.hide();
        this.companySearchResultPagerSpinner.hide();
    };
    ChangeEmployerSearchResult.prototype.handleError = function (header, description, scrollToErrorMessage) {
        var errorMessageBox = new ErrorMessageBox(header, description);
        errorMessageBox.append(this.$errorContainer);
        this.$errorContainer.removeClass("hide");
        this.$companySearchResult.addClass("hide");
        if (scrollToErrorMessage) {
            errorMessageBox.scrollTo(100);
        }
    };
    //showDirectHit(bbcId: string) {
    //    const self = this;
    //    self.getCompanyDetails(bbcId, (company => {
    //        const searchResult = new SearchResult();
    //        searchResult.hitsTotal = 1;
    //        searchResult.pageIndex = 0;
    //        searchResult.pageSize = self.pageSize;
    //        searchResult.hasMorePages = false;
    //        searchResult.companies = [company];
    //        self.hideError();
    //        const searchSummary = new SearchSummary();
    //        searchSummary.query = company.name;
    //        searchSummary.countryCode = company.countryCode;
    //        searchSummary.countryName = company.countryName;
    //        searchSummary.isDirectHit = true;
    //        self.updateSearchArea(searchResult, searchSummary);
    //        self.populateCompanyDetails(self.$companySearchResultHits.find(".accordion-group"), company);
    //    }));
    //}
    ChangeEmployerSearchResult.prototype.updateSearchArea = function (searchResult, searchSummary) {
        this.hideError();
        this.updateSearchSummaryText(searchResult, searchSummary);
        this.updateSearchHits(searchResult);
        this.updatePager(searchResult);
        this.$companySearchResult.removeClass("hide");
        if (this.onSearched !== null) {
            this.onSearched(searchResult);
        }
    };
    ChangeEmployerSearchResult.prototype.attachEventsToChangeEmployerButton = function ($changeEmployerLink, bbcId) {
        var self = this;
        var clickEventname = "click.searchEmployer";
        $changeEmployerLink.unbind(clickEventname).bind(clickEventname, function (e) {
            e.preventDefault();
            $changeEmployerLink.hide();
            var spinner = new Spinner($changeEmployerLink.parent().find(".search-employer-section__search-result__hits__save-spinner"));
            spinner.show();
            self.changeEmployer(bbcId);
        });
    };
    ChangeEmployerSearchResult.prototype.updatePager = function (searchResult) {
        var self = this;
        var showFooter = false;
        if (searchResult.hasMorePages) {
            self.$companySearchResultPagerShowNextPageLink.show();
            self.$companySearchResultPager.removeClass("hide");
            showFooter = true;
        }
        else {
            self.$companySearchResultPager.addClass("hide");
        }
        if (searchResult.companies.length === 0) {
            self.$companySearchResultCannotFindEmployerLink.addClass("hide");
        }
        else {
            self.$companySearchResultCannotFindEmployerLink.removeClass("hide");
            showFooter = true;
        }
        if (showFooter) {
            self.$companySearchResultFooter.removeClass("hide");
        }
        else {
            self.$companySearchResultFooter.addClass("hide");
        }
    };
    ChangeEmployerSearchResult.prototype.updateSearchSummaryText = function (searchResult, searchSummary) {
        var employerSearchSummaryText = this.getSearchSummaryText(searchResult, searchSummary);
        employerSearchSummaryText = this.replaceSearchSummaryPlaceholders(employerSearchSummaryText, searchResult, searchSummary);
        this.$searchSummaryText.html(employerSearchSummaryText);
    };
    ChangeEmployerSearchResult.prototype.getSearchSummaryText = function (searchResult, searchSummary) {
        if (searchSummary.isDirectHit) {
            if (searchSummary.isSearchingInSweden())
                return this.$searchEmployerSection.data("employersearchsummaryswedendirecthit");
            return this.$searchEmployerSection.data("employersearchsummaryinternationaldirecthit");
        }
        if (searchSummary.query.length === 0)
            return this.$searchEmployerSection.data("employersearchsummarywhenemptyquery");
        if (searchResult.hitsTotal === 0)
            return this.$searchEmployerSection.data("employersearchsummarywhenhavingnohitstext");
        if (searchSummary.isSearchingInSweden()) {
            if (searchSummary.city !== null) {
                return this.$searchEmployerSection.data("employersearchsummaryswedenwithparameterquerytextandcity");
            }
            else {
                return this.$searchEmployerSection.data("employersearchsummaryswedenwithparameterquerytext");
            }
        }
        if (searchSummary.countryCode !== null && searchSummary.city !== null)
            return this.$searchEmployerSection.data("employersearchsummaryinternationalwithparameterquerycountryandcity");
        if (searchSummary.countryCode === null && searchSummary.city !== null)
            return this.$searchEmployerSection.data("employersearchsummaryinternationalwithparameterqueryandcity");
        if (searchSummary.countryCode !== null && searchSummary.city === null)
            return this.$searchEmployerSection.data("employersearchsummaryinternationalwithparameterqueryandcountry");
        if (searchSummary.countryCode === null && searchSummary.city === null)
            return this.$searchEmployerSection.data("employersearchsummaryinternationalwithparameterquery");
        return "";
    };
    ChangeEmployerSearchResult.prototype.replaceSearchSummaryPlaceholders = function (searchSummaryText, searchResult, searchParameters) {
        searchSummaryText = this.replaceSearchSummaryPlaceholder(searchSummaryText, "query", searchParameters.query);
        searchSummaryText = this.replaceSearchSummaryPlaceholder(searchSummaryText, "city", searchParameters.city);
        searchSummaryText = this.replaceSearchSummaryPlaceholder(searchSummaryText, "country", searchParameters.countryName);
        searchSummaryText = this.replaceSearchSummaryPlaceholder(searchSummaryText, "hitstotal", searchResult.hitsTotal.toString());
        searchSummaryText = this.replaceSearchSummaryPlaceholder(searchSummaryText, "displayedhits", (searchResult.pageIndex * searchResult.pageSize + searchResult.companies.length).toString());
        return searchSummaryText;
    };
    ChangeEmployerSearchResult.prototype.replaceSearchSummaryPlaceholder = function (searchSummaryText, placeholderName, value) {
        if (value === null)
            value = "";
        return searchSummaryText.replace(new RegExp("\\[".concat(placeholderName, "\\]"), "g"), value);
    };
    ChangeEmployerSearchResult.prototype.updateSearchHits = function (searchResult) {
        var self = this;
        var templatedHtml = $(self.companySearchHitTemplate({ searchResult: searchResult }));
        if (searchResult.pageIndex === 0) {
            self.$companySearchResultHits.empty();
        }
        self.$companySearchResultHits.append(templatedHtml);
        if (searchResult.hitsTotal === 1) {
            self.$companySearchResultHits.find(".collapse").collapse("show");
        }
    };
    ChangeEmployerSearchResult.prototype.populateCompanyDetails = function ($accordionGroup, company) {
        $accordionGroup.find(".search-employer-section__search-result__zip").replaceWith(company.zipCode);
        if (company.phone) {
            $accordionGroup.find(".search-employer-section__search-result__phone__value").replaceWith(company.phone);
            $accordionGroup.find(".search-employer-section__search-result__phone").show();
        }
        if (company.organisationNumber) {
            $accordionGroup.find(".search-employer-section__search-result__orgnr__value").replaceWith(company.organisationNumber);
            $accordionGroup.find(".search-employer-section__search-result__orgnr").show();
        }
    };
    ChangeEmployerSearchResult.prototype.getCompanyDetails = function (bbcId, successCallback, alwaysCallback) {
        if (alwaysCallback === void 0) { alwaysCallback = null; }
        $.getJSON(InternalApiEndpoints.getCompanyDetails(encodeURIComponent(bbcId)))
            .done(function (company) {
            successCallback(company);
        })
            .always(function () {
            if (alwaysCallback !== null) {
                alwaysCallback();
            }
        });
    };
    ChangeEmployerSearchResult.prototype.changeEmployer = function (bbcId) {
        var self = this;
        if (self.isCurrentUserEditorOrContentViewer) {
            self.handleError("Kan inte spara din nya arbetsgivare", "Du är inte inloggad som medlem och har därför inte tillgång till att ändra din arbetsgivare.", true);
            return;
        }
        $.post(InternalApiEndpoints.changeEmployerByBbcId(bbcId))
            .done(function () {
            self.changeEmployerService.triggerEmployerChangedEvent();
            window.location.href = "#/";
            self.gtmService.push({
                "event": "updateArbetsgivare",
                "selectType": "list"
            });
            if (self.onSaved !== null) {
                self.onSaved();
            }
        })
            .fail(function (jqueryXhr) {
            if (jqueryXhr.status === 401) {
                location.reload();
                return;
            }
            self.handleError(self.$searchEmployerSection.data("changeemployererrormessageheader"), self.$searchEmployerSection.data("changeemployererrormessagetext"), true);
        });
    };
    ChangeEmployerSearchResult.prototype.hideError = function () {
        this.$errorContainer.addClass("hide");
    };
    ChangeEmployerSearchResult.prototype.reset = function () {
        this.$companySearchResult.addClass("hide");
        this.hideError();
    };
    return ChangeEmployerSearchResult;
}());

var ChangeEmployerService = /** @class */ (function () {
    function ChangeEmployerService() {
        this.customEventHandler = new CustomEventHandler();
        this.gtmService = new GoogleDataLayerService();
    }
    ChangeEmployerService.prototype.triggerEmployerChangedEvent = function () {
        var self = this;
        $.getJSON(InternalApiEndpoints.getMemberCompany())
            .done(function (memberCompany) {
            self.customEventHandler.trigger(CustomEventHandler.employerChangedEventName, memberCompany);
        })
            .fail(function () {
            self.customEventHandler.trigger(CustomEventHandler.employerChangedEventName, null);
        });
    };
    return ChangeEmployerService;
}());

var ChangeEmployerWorkSituation = /** @class */ (function () {
    function ChangeEmployerWorkSituation($workSituationSection) {
        this.changeEmployerService = new ChangeEmployerService();
        var self = this;
        self.$workSituationSection = $workSituationSection;
        self.$workSituationRadioButtons = self.$workSituationSection.find("input[name='worksituation']");
        self.$notEmployedSection = self.$workSituationSection.find(".work-situation-section__notemployed");
        self.$saveNotEmployedLink = self.$workSituationSection.find(".work-situation-section__notemployed__save-button");
        self.$errorContainer = self.$workSituationSection.find(".work-situation-section__notemployed_error-container");
        self.spinner = new Spinner(self.$workSituationSection.find(".work-situation-section__notemployed__save-spinner"));
        self.isCurrentUserEditorOrContentViewer = self.$workSituationSection.data("iscurrentusereditororcontentviewer");
        self.attachEvents();
    }
    ChangeEmployerWorkSituation.prototype.changeSelectedWorkSituation = function (workSituationType) {
        var self = this;
        if (workSituationType === WorkSituationType.Employed) {
            self.$workSituationRadioButtons.filter("[value='employed']").click();
        }
        else if (workSituationType === WorkSituationType.NotEmployed) {
            self.$workSituationRadioButtons.filter("[value='notemployed']").click();
        }
    };
    ChangeEmployerWorkSituation.prototype.attachEvents = function () {
        var self = this;
        self.$workSituationRadioButtons.change(function (e) {
            if (self.onWorkSituationChanged === null)
                return;
            var workSituationType = WorkSituationType.NotSet;
            var selectedRadioButtonValue = self.$workSituationRadioButtons.filter(":checked").val();
            if (selectedRadioButtonValue === "employed") {
                workSituationType = WorkSituationType.Employed;
                self.$notEmployedSection.addClass("hide");
            }
            else if (selectedRadioButtonValue === "notemployed") {
                workSituationType = WorkSituationType.NotEmployed;
                self.$notEmployedSection.removeClass("hide");
            }
            self.onWorkSituationChanged(workSituationType);
        });
        self.$saveNotEmployedLink.click(function (e) {
            e.preventDefault();
            self.deleteMemberCompany();
        });
    };
    ChangeEmployerWorkSituation.prototype.deleteMemberCompany = function () {
        var self = this;
        if (self.isCurrentUserEditorOrContentViewer) {
            self.handleError("Kan inte spara din arbetssituation", "Du är inte inloggad som medlem och har därför inte tillgång till att ändra din arbetsgivare.");
            return;
        }
        self.$saveNotEmployedLink.hide();
        self.spinner.show();
        $.post({
            url: InternalApiEndpoints.deleteMemberCompany()
        })
            .done(function () {
            self.changeEmployerService.triggerEmployerChangedEvent();
            window.location.href = "#/";
            if (self.onSaved !== null) {
                self.onSaved();
            }
        })
            .fail(function (jqueryXhr) {
            if (jqueryXhr.status === 401) {
                location.reload();
                return;
            }
            self.handleError(self.$workSituationSection.data("saveemployederrormessageheader"), self.$workSituationSection.data("saveemployederrormessagetext"));
        })
            .always(function () {
            self.$saveNotEmployedLink.show();
            self.spinner.hide();
        });
    };
    ChangeEmployerWorkSituation.prototype.handleError = function (header, description) {
        this.$errorContainer.removeClass("hide");
        var errorMessageBox = new ErrorMessageBox(header, description);
        errorMessageBox.append(this.$errorContainer);
        errorMessageBox.scrollTo(100);
    };
    ChangeEmployerWorkSituation.prototype.setFocusToFirstWorkSituationOption = function () {
        var $firstWorkSituationOption = this.$workSituationRadioButtons.first();
        $firstWorkSituationOption.attr("autofocus", ""); // Forces iPhone devices to set focus to the input field
        $firstWorkSituationOption.focus();
    };
    ChangeEmployerWorkSituation.prototype.reset = function () {
        this.changeSelectedWorkSituation(WorkSituationType.Employed);
    };
    return ChangeEmployerWorkSituation;
}());

var FocusTrap = /** @class */ (function () {
    function FocusTrap($focusTrapArea, customEventFocusSuffixName) {
        this.tabbableElementsSelector = "select, input, textarea, button, a";
        this.detectorService = new DetectorService();
        this.inactivatedTabIndexAttributeName = "data-inactivatedtabindex";
        this.$focusTrapArea = $focusTrapArea;
        this.focusEventName = "focus.".concat(customEventFocusSuffixName);
        this.$root = $("body");
    }
    FocusTrap.prototype.activate = function () {
        var self = this;
        self.$root.on(self.focusEventName, self.tabbableElementsSelector, function (e) {
            if (self.isFocusInFocusTrapArea(e.target))
                return;
            self.setFocusToFirstTabbableElementInFocusTrapArea();
        });
        this.setInputTextsOutsideModalToNonTabbableForIosDevices();
    };
    FocusTrap.prototype.inactivate = function () {
        this.$root.off(this.focusEventName, this.tabbableElementsSelector);
        this.resetInputTextsOutsideModalToTabbableForIosDevices();
    };
    FocusTrap.prototype.isFocusInFocusTrapArea = function (currentFocusElement) {
        return this.$focusTrapArea.has(currentFocusElement).length > 0;
    };
    FocusTrap.prototype.setFocusToFirstTabbableElementInFocusTrapArea = function () {
        this.$focusTrapArea.find(this.tabbableElementsSelector).first().focus();
    };
    // IOS devices can with the virtual keyboard tab to next/prev input field of type text. When doing this IOS devices scrolls
    // to the specific input field which can be outside our focus trap. This results in an incorrect position.
    FocusTrap.prototype.setInputTextsOutsideModalToNonTabbableForIosDevices = function () {
        if (!this.detectorService.isIosDevice())
            return;
        var self = this;
        this.getAllInputTextsOutsideFocusArea().each(function (index, input) {
            var $input = $(input);
            if ($input.attr("tabindex")) {
                $input.attr(self.inactivatedTabIndexAttributeName, $input.attr("tabindex"));
            }
            else {
                $input.attr(self.inactivatedTabIndexAttributeName, "");
            }
            $input.attr("tabindex", "-1");
        });
    };
    FocusTrap.prototype.resetInputTextsOutsideModalToTabbableForIosDevices = function () {
        if (!this.detectorService.isIosDevice())
            return;
        var self = this;
        this.getAllInputTextsOutsideFocusArea().each(function (index, input) {
            var $input = $(input);
            var inactivatedTabindex = $input.attr(self.inactivatedTabIndexAttributeName);
            if (inactivatedTabindex !== undefined) {
                if (inactivatedTabindex) {
                    $input.attr("tabindex", inactivatedTabindex);
                }
                else {
                    $input.removeAttr("tabindex");
                }
                $input.removeAttr(self.inactivatedTabIndexAttributeName);
            }
        });
    };
    FocusTrap.prototype.getAllInputTextsOutsideFocusArea = function () {
        return $("input[type='text']").not(this.$focusTrapArea.find("input"));
    };
    return FocusTrap;
}());

var ChangeEmployerModalView;
(function (ChangeEmployerModalView) {
    ChangeEmployerModalView[ChangeEmployerModalView["SelectEmployerView"] = 0] = "SelectEmployerView";
    ChangeEmployerModalView[ChangeEmployerModalView["ManualEmployerView"] = 1] = "ManualEmployerView";
})(ChangeEmployerModalView || (ChangeEmployerModalView = {}));

var CompanyLocation = /** @class */ (function () {
    function CompanyLocation() {
    }
    return CompanyLocation;
}());

var SearchParameters = /** @class */ (function () {
    function SearchParameters() {
        this.query = null;
        this.city = null;
        this.countryCode = null;
        this.countryName = null;
        this.pageIndex = null;
    }
    return SearchParameters;
}());

var SearchResult = /** @class */ (function () {
    function SearchResult() {
        this.hitsTotal = null;
        this.pageIndex = null;
        this.pageSize = null;
        this.hasMorePages = null;
        this.companies = [];
        this.countries = null;
        this.cities = null;
    }
    return SearchResult;
}());

var SearchResultCompany = /** @class */ (function () {
    function SearchResultCompany() {
        this.bbcId = null;
        this.name = null;
        this.address = null;
        this.zipCode = null;
        this.city = null;
        this.phone = null;
        this.organisationNumber = null;
        this.countryCode = null;
        this.countryName = null;
    }
    return SearchResultCompany;
}());

var SearchSummary = /** @class */ (function () {
    function SearchSummary(searchParameters) {
        if (searchParameters === void 0) { searchParameters = null; }
        this.query = null;
        this.city = null;
        this.countryCode = null;
        this.countryName = null;
        this.pageIndex = null;
        if (searchParameters === null)
            return;
        this.query = searchParameters.query;
        this.city = searchParameters.city;
        this.countryCode = searchParameters.countryCode;
        this.countryName = searchParameters.countryName;
        this.pageIndex = searchParameters.pageIndex;
    }
    SearchSummary.prototype.isSearchingInSweden = function () {
        return this.countryCode !== null && this.countryCode.toLowerCase() === "se";
    };
    return SearchSummary;
}());

var WorkSituationType;
(function (WorkSituationType) {
    WorkSituationType[WorkSituationType["NotSet"] = 0] = "NotSet";
    WorkSituationType[WorkSituationType["Employed"] = 1] = "Employed";
    WorkSituationType[WorkSituationType["NotEmployed"] = 2] = "NotEmployed";
})(WorkSituationType || (WorkSituationType = {}));

var EmploymentBlock2App = /** @class */ (function () {
    function EmploymentBlock2App($employmentBlock) {
        var self = this;
        this.$el = $employmentBlock;
        this.$memberHasEmploymentView = this.$el.find(".employment-block2__member-has-employment");
        this.$employmentMissingView = this.$el.find(".employment-block2__employment-missing");
        this.$memberHasPendingChangeView = this.$el.find(".employment-block2__member-has-pending-change");
        this.$errorView = this.$el.find(".employment-block2__error");
        this.customEventHandler = new CustomEventHandler();
        this.$changeEmployerBlockContainer = this.$el.find(".employment-block2__change-employer-block");
        this.$employerDataContainer = this.$memberHasEmploymentView.find(".employment-block2__member-has-employment__employer-data-container");
        this.customEventHandler.subscribe(CustomEventHandler.employerChangedEventName, function (memberCompany) {
            self.updateEmployerData(memberCompany);
        });
        this.initChangeEmployerBlock();
        var globalSettingsInstance = GlobalSettingsSingleton.getInstance();
        if (globalSettingsInstance.isInEditMode()) {
            var memberCompany = new MemberCompany();
            memberCompany.name = "Exempelföretaget AB";
            memberCompany.address = "Solvägen 3";
            memberCompany.area = "Stockholm";
            memberCompany.country = "Sverige";
            memberCompany.organisationNumber = "5561177541";
            self.updateEmployerData(memberCompany);
        }
        else if (!globalSettingsInstance.isAuthenticatedWithMemberNumber()) {
            self.updateEmployerData(null);
        }
        else {
            self.getMemberCompany(function (memberCompany) {
                self.updateEmployerData(memberCompany);
            });
        }
    }
    EmploymentBlock2App.prototype.initChangeEmployerBlock = function () {
        var _this = this;
        var $employmentContainer = this.$el.find(".employment-block2__employment");
        var changeEmployerBlock = new ChangeEmployerBlockApp(this.$el.find(".change-employer-block"));
        changeEmployerBlock.onOpen = function () { $employmentContainer.hide(); };
        changeEmployerBlock.onClose = function () {
            $employmentContainer.show();
            _this.customEventHandler.trigger(CustomEventHandler.changeEmployerModalCanceled, null);
        };
    };
    EmploymentBlock2App.prototype.updateEmployerData = function (memberCompany) {
        var self = this;
        var $activeView = self.getCorrespondingView(memberCompany);
        if ($activeView === self.$memberHasEmploymentView) {
            self.initMemberHasEmploymentView(memberCompany);
        }
        if (GlobalSettingsSingleton.getInstance().isInEditMode()) {
            self.setAllViewsActive();
        }
        else {
            self.setActiveView($activeView);
            self.setInnerActiveView(memberCompany, $activeView);
        }
    };
    EmploymentBlock2App.prototype.getCorrespondingView = function (memberCompany) {
        if (memberCompany === null)
            return this.$errorView;
        else if (memberCompany.hasPendingCompanyChange)
            return this.$memberHasPendingChangeView;
        else if (memberCompany.isUnknown)
            return this.$employmentMissingView;
        return this.$memberHasEmploymentView;
    };
    EmploymentBlock2App.prototype.setAllViewsActive = function () {
        this.$memberHasEmploymentView.show();
        this.$employmentMissingView.show();
        this.$memberHasPendingChangeView.show();
        this.$errorView.show();
    };
    EmploymentBlock2App.prototype.setActiveView = function ($activeView) {
        this.$memberHasEmploymentView.hide();
        this.$employmentMissingView.hide();
        this.$memberHasPendingChangeView.hide();
        this.$errorView.hide();
        $activeView.show();
        var showChangeEmployerLink = $activeView.data("showchangeemployerlink");
        if (showChangeEmployerLink)
            this.$changeEmployerBlockContainer.show();
        else
            this.$changeEmployerBlockContainer.hide();
    };
    EmploymentBlock2App.prototype.setInnerActiveView = function (memberCompany, $activeView) {
        var self = this;
        var $hasPendingCompanyChangeWithOldWorkplaceView = self.$el.find(".employment-block2__haspendingcompanychangewitholdworkplaceview");
        var $employmentDefaultView = self.$el.find(".employment-block2__defaultview");
        if (memberCompany.hasPendingCompanyChangeWithOldWorkplace && $activeView !== self.$memberHasEmploymentView) {
            $hasPendingCompanyChangeWithOldWorkplaceView.show();
            $employmentDefaultView.hide();
        }
        else {
            $hasPendingCompanyChangeWithOldWorkplaceView.hide();
            $employmentDefaultView.show();
        }
    };
    EmploymentBlock2App.prototype.initMemberHasEmploymentView = function (memberCompany) {
        var self = this;
        var $employerData = $("<div />");
        $employerData.append($("<div />").addClass("text--bold").addClass("margin--bottom--5").html(memberCompany.name));
        var $employerDataDetails = $("<div />").addClass("line-height--sm");
        $employerDataDetails.append($("<div />").html(memberCompany.address));
        $employerDataDetails.append($("<div />").html(memberCompany.area));
        $employerDataDetails.append($("<div />").html(memberCompany.country));
        if (memberCompany.organisationNumber !== null && memberCompany.organisationNumber !== "") {
            var organisationNumberLabel = self.$employerDataContainer.data("organizationnumberlabel");
            $employerDataDetails.append($("<div />").html(organisationNumberLabel + " " + memberCompany.organisationNumber));
        }
        $employerData.append($employerDataDetails);
        self.$employerDataContainer.empty();
        self.$employerDataContainer.append($employerData);
        var $hasPendingCompanyChangeWithOldWorkplaceInfo = self.$el.find(".employment-block2__employment__haspendingcompanychangewitholdworkplaceinfo");
        if (memberCompany.hasPendingCompanyChangeWithOldWorkplace) {
            $hasPendingCompanyChangeWithOldWorkplaceInfo.show();
        }
        else {
            $hasPendingCompanyChangeWithOldWorkplaceInfo.hide();
        }
    };
    EmploymentBlock2App.prototype.getMemberCompany = function (callback) {
        $.getJSON(InternalApiEndpoints.getMemberCompany())
            .done(function (memberCompany) {
            if (callback !== null) {
                callback(memberCompany);
            }
        })
            .fail(function () {
            callback(null);
        });
    };
    return EmploymentBlock2App;
}());

var MemberCompany = /** @class */ (function () {
    function MemberCompany() {
    }
    return MemberCompany;
}());

var MrbInput = /** @class */ (function () {
    function MrbInput($el) {
        var self = this;
        self.$el = $el;
        self.$input = $el.find("input");
    }
    MrbInput.prototype.val = function () {
        return this.getFormElement().val();
    };
    MrbInput.prototype.getFormElement = function () {
        return this.$input;
    };
    MrbInput.prototype.getValidationMessage = function (key) {
        return this.$input.data(key);
    };
    return MrbInput;
}());

var MrbIndustrySelect = /** @class */ (function () {
    function MrbIndustrySelect($el, formSelector) {
        this.hideCssClass = "hide";
        this.queryStringHelper = new QueryStringHelper();
        var self = this;
        self.$el = $el;
        self.$input = $el.find("select");
        self.$priceContainer = self.$el.find(".member-registration-industry__price-container");
        self.$price = self.$priceContainer.find(".member-registration-industry__price-container__price");
        self.industrySelector = new IndustryWithAssociationFeeSelector(formSelector + " .member-registration-industry select", self.$el.data("totalfee"), self.$el.data("lowestassociationfee"));
        self.industrySelector.onIndustryChange = function (industryModel) {
            self.updateSelectedIndustry(industryModel);
        };
        self.setIndustrySelectorValue();
    }
    MrbIndustrySelect.prototype.val = function () {
        return this.industrySelector.getCurrentIndustryModel();
    };
    MrbIndustrySelect.prototype.getFormElement = function () {
        return this.$input;
    };
    MrbIndustrySelect.prototype.getValidationMessage = function (key) {
        return this.$input.data(key);
    };
    MrbIndustrySelect.prototype.setIndustrySelectorValue = function () {
        var self = this;
        var industryId = self.queryStringHelper.getParameter("industryId");
        if (industryId != null) {
            self.industrySelector.changeSelectedIndustry(industryId);
            self.updateSelectedIndustry(self.industrySelector.getCurrentIndustryModel());
        }
    };
    MrbIndustrySelect.prototype.updateSelectedIndustry = function (industryModel) {
        var self = this;
        if (industryModel.defaultValSelected) {
            self.hidePrice();
        }
        else {
            self.showPrice(industryModel.totalPrice);
        }
    };
    MrbIndustrySelect.prototype.hidePrice = function () {
        var self = this;
        self.$priceContainer.addClass(self.hideCssClass);
    };
    MrbIndustrySelect.prototype.showPrice = function (price) {
        var self = this;
        self.$priceContainer.removeClass(self.hideCssClass);
        self.$price.html(price + ":-");
    };
    return MrbIndustrySelect;
}());

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var MrbFirstnameInput = /** @class */ (function (_super) {
    __extends(MrbFirstnameInput, _super);
    function MrbFirstnameInput() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return MrbFirstnameInput;
}(MrbInput));

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var MrbLastnameInput = /** @class */ (function (_super) {
    __extends(MrbLastnameInput, _super);
    function MrbLastnameInput() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return MrbLastnameInput;
}(MrbInput));

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var MrbTitleInput = /** @class */ (function (_super) {
    __extends(MrbTitleInput, _super);
    function MrbTitleInput() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return MrbTitleInput;
}(MrbInput));

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var MrbEmployerInput = /** @class */ (function (_super) {
    __extends(MrbEmployerInput, _super);
    function MrbEmployerInput() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return MrbEmployerInput;
}(MrbInput));

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var MrbEmailInput = /** @class */ (function (_super) {
    __extends(MrbEmailInput, _super);
    function MrbEmailInput() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return MrbEmailInput;
}(MrbInput));

var MrbUnionSelect = /** @class */ (function () {
    function MrbUnionSelect($el) {
        var self = this;
        self.$el = $el;
        self.$select = $el.find("select");
    }
    MrbUnionSelect.prototype.val = function () {
        return this.getSelectedOption().val();
    };
    MrbUnionSelect.prototype.getFormElement = function () {
        return this.$select;
    };
    MrbUnionSelect.prototype.getSelectedOption = function () {
        return this.$select.children("option").filter(":selected");
    };
    MrbUnionSelect.prototype.getValidationMessage = function (key) {
        return this.$select.data(key);
    };
    return MrbUnionSelect;
}());

var MrbTermsCheckbox = /** @class */ (function () {
    function MrbTermsCheckbox($el) {
        var self = this;
        self.$el = $el;
        self.$input = $el.find("input");
    }
    MrbTermsCheckbox.prototype.val = function () {
        return this.$input.val();
    };
    MrbTermsCheckbox.prototype.getFormElement = function () {
        return this.$input;
    };
    MrbTermsCheckbox.prototype.getValidationMessage = function (key) {
        return this.$input.data(key);
    };
    return MrbTermsCheckbox;
}());

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var MrbCivicRegistrationNumberInput = /** @class */ (function (_super) {
    __extends(MrbCivicRegistrationNumberInput, _super);
    function MrbCivicRegistrationNumberInput() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return MrbCivicRegistrationNumberInput;
}(MrbInput));

var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        if (typeof b !== "function" && b !== null)
            throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var MrbPhoneInput = /** @class */ (function (_super) {
    __extends(MrbPhoneInput, _super);
    function MrbPhoneInput() {
        return _super !== null && _super.apply(this, arguments) || this;
    }
    return MrbPhoneInput;
}(MrbInput));

var MrbSubmitButton = /** @class */ (function () {
    function MrbSubmitButton($el) {
        this.onSubmit = null;
        var self = this;
        self.$el = $el;
        self.$button = $el.find("button");
        self.confirmationPageUrl = self.$el.data("confirmationpageurl");
        self.$button.click(function (e) {
            e.preventDefault();
            if (self.onSubmit !== null) {
                self.onSubmit(self.confirmationPageUrl);
            }
        });
    }
    MrbSubmitButton.prototype.setDisabled = function () {
        this.$button.attr("disabled", "disabled");
    };
    MrbSubmitButton.prototype.setBtnPushed = function () {
        this.$button.addClass("btnpushed");
    };
    return MrbSubmitButton;
}());

var MrbFormData = /** @class */ (function () {
    function MrbFormData() {
    }
    return MrbFormData;
}());

var MrbForm = /** @class */ (function () {
    function MrbForm($el) {
        this.industrySelect = null;
        this.firstnameInput = null;
        this.lastnameInput = null;
        this.titleInput = null;
        this.countrycodeInput = null;
        this.phoneInput = null;
        this.civicRegistrationNumberInput = null;
        this.employerInput = null;
        this.emailInput = null;
        this.unionSelect = null;
        this.termsCheckbox = null;
        this.submitButton = null;
        this.validationRules = {};
        this.validationMessages = {};
        this.utmCampaignService = new UtmCampaignService();
        var self = this;
        self.$el = $el;
        self.blockId = parseInt($el.data("blockid"));
        self.memberApplicationPostFailedErrorMessage = self.$el.data("memberapplicationpostfailederrormessage");
        self.initializeFormElements();
    }
    MrbForm.prototype.initializeFormElements = function () {
        var _this = this;
        var self = this;
        var $industrySelect = self.$el.find(".member-registration-industry");
        if ($industrySelect.length) {
            self.industrySelect = new MrbIndustrySelect($industrySelect, "#".concat(self.$el.attr("id")));
            var $industry = self.industrySelect.getFormElement();
            self.addValidation($industry, { valueNotEquals: "0" }, { valueNotEquals: $industry.data("valrequired"), summary: $industry.data("valsummary") });
        }
        var $firstnameInput = self.$el.find(".member-registration-firstname");
        if ($firstnameInput.length) {
            self.firstnameInput = new MrbFirstnameInput($firstnameInput);
            var $firstname = self.firstnameInput.getFormElement();
            self.addValidation($firstname, { required: true, alphanumeric: true }, { required: $firstname.data("valrequired"), summary: $firstname.data("valsummary") });
        }
        var $lastnameInput = self.$el.find(".member-registration-lastname");
        if ($lastnameInput.length) {
            self.lastnameInput = new MrbLastnameInput($lastnameInput);
            var $lastname = self.lastnameInput.getFormElement();
            self.addValidation($lastname, { required: true, alphanumeric: true }, { required: $lastname.data("valrequired"), summary: $lastname.data("valsummary") });
        }
        var $titleInput = self.$el.find(".member-registration-title");
        if ($titleInput.length) {
            self.titleInput = new MrbTitleInput($titleInput);
            var $title = self.titleInput.getFormElement();
            self.addValidation($title, { required: true, alphanumeric: true }, { required: $title.data("valrequired"), summary: $title.data("valsummary") });
        }
        var $countrycodeContainer = self.$el.find(".member-registration-countrycode");
        if ($countrycodeContainer.length) {
            self.countrycodeInput = $countrycodeContainer.find("input:first");
            /*const $countrycode = self.countrycodeInput.getFormElement();*/
            if (self.countrycodeInput) {
                self.countrycodeInput.countrySelect({
                    defaultCountry: "se",
                    preferredCountries: ["se"],
                    responsiveDropdown: true
                });
            }
        }
        var $phoneInput = self.$el.find(".member-registration-phone");
        if ($phoneInput.length) {
            self.phoneInput = new MrbPhoneInput($phoneInput);
            var $phone = self.phoneInput.getFormElement();
            self.addValidation($phone, { required: true, newphone: true, number: true }, { required: $phone.data("valrequired"), newphone: $phone.data("valphone"), summary: $phone.data("valsummary") });
        }
        var $civicRegistrationNumberInput = self.$el.find(".member-registration-civicregistrationnumber");
        if ($civicRegistrationNumberInput.length) {
            self.civicRegistrationNumberInput = new MrbCivicRegistrationNumberInput($civicRegistrationNumberInput);
            var $civicRegistrationNumber = self.civicRegistrationNumberInput.getFormElement();
            self.addValidation($civicRegistrationNumber, { required: true, ssnWithCentury: true, number: false, minimumAge: true }, { required: $civicRegistrationNumber.data("valrequired"), ssnWithCentury: $civicRegistrationNumber.data("valssn"), summary: $civicRegistrationNumber.data("valsummary") });
        }
        var $employerInput = self.$el.find(".member-registration-employer");
        if ($employerInput.length) {
            self.employerInput = new MrbEmployerInput($employerInput);
            var $employer = self.employerInput.getFormElement();
            self.addValidation($employer, { required: true, alphanumeric: true }, { required: $employer.data("valrequired"), summary: $employer.data("valsummary") });
        }
        var $unionSelect = self.$el.find(".member-registration-union");
        if ($unionSelect.length) {
            self.unionSelect = new MrbUnionSelect($unionSelect);
            var $union = self.unionSelect.getFormElement();
            self.addValidation($union, { valueNotEquals: "0" }, { valueNotEquals: $union.data("valrequired"), summary: $union.data("valsummary") });
        }
        var $emailInput = self.$el.find(".member-registration-email");
        if ($emailInput.length) {
            self.emailInput = new MrbEmailInput($emailInput);
            var $email = self.emailInput.getFormElement();
            self.addValidation($email, { required: true, customEmail: true, email: false }, { required: $email.data("valrequired"), customEmail: $email.data("valemail"), summary: $email.data("valsummary") });
        }
        var $termsCheckbox = self.$el.find(".member-registration-terms");
        if ($termsCheckbox.length) {
            self.termsCheckbox = new MrbTermsCheckbox($termsCheckbox);
            var $terms = self.termsCheckbox.getFormElement();
            self.addValidation($terms, { required: true }, { required: $terms.data("valrequired"), summary: $terms.data("valsummary") });
        }
        var $submitButton = self.$el.find(".member-registration-submit-button");
        if ($submitButton.length) {
            self.submitButton = new MrbSubmitButton($submitButton);
            self.submitButton.onSubmit = function (confirmationPageUrl) {
                if (!self.validation.isValid()) {
                    return;
                }
                _this.submitButton.setDisabled();
                _this.submitButton.setBtnPushed();
                _this.submitMemberRegistration(confirmationPageUrl);
            };
        }
        var formSelector = "#".concat(self.$el.attr("id"));
        self.validation = new Validation(formSelector, self.validationRules, self.validationMessages, formSelector + " div.error");
    };
    MrbForm.prototype.addValidation = function ($input, rule, message) {
        var self = this;
        self.validationRules[$input.attr("name")] = rule;
        self.validationMessages[$input.attr("name")] = message;
    };
    MrbForm.prototype.submitMemberRegistration = function (confirmationPageUrl) {
        var self = this;
        var formData = self.getMemberRegistrationFormData();
        self.postMemberApplication(formData, function () {
            location.href = confirmationPageUrl;
        }, function () {
            alert(self.memberApplicationPostFailedErrorMessage);
        });
    };
    MrbForm.prototype.getMemberRegistrationFormData = function () {
        var formData = new MrbFormData();
        if (this.industrySelect !== null) {
            formData.industryChoise = this.industrySelect.val();
        }
        if (this.employerInput !== null) {
            formData.employer = this.employerInput.val();
        }
        if (this.titleInput !== null) {
            formData.title = this.titleInput.val();
        }
        if (this.civicRegistrationNumberInput !== null) {
            formData.socialSecurityNumber = this.civicRegistrationNumberInput.val();
        }
        if (this.countrycodeInput !== null) {
            formData.countrycodenumber = this.countrycodeInput.val();
        }
        if (this.phoneInput !== null) {
            formData.phone = this.phoneInput.val();
        }
        if (this.firstnameInput !== null) {
            formData.firstname = this.firstnameInput.val();
        }
        if (this.lastnameInput !== null) {
            formData.lastname = this.lastnameInput.val();
        }
        if (this.unionSelect !== null) {
            formData.unionText = this.unionSelect.val();
        }
        if (this.emailInput !== null) {
            formData.email = this.emailInput.val();
        }
        if (this.termsCheckbox !== null) {
            formData.acceptsTerms = this.termsCheckbox.val();
        }
        if (this.industrySelect !== null) {
            formData.associationName = this.industrySelect.val() != null
                ? this.industrySelect.val().bfName
                : "";
        }
        var utmParams = this.utmCampaignService.getUtmParams();
        formData.utmSource = utmParams.utmSource;
        formData.utmCampaign = utmParams.utmCampiagn;
        formData.utmMedium = utmParams.utmMedium;
        formData.sourceId = this.blockId;
        return formData;
    };
    MrbForm.prototype.postMemberApplication = function (memberApplicationData, onSuccess, onError) {
        $.ajax({
            url: InternalApiEndpoints.memberRegistration(),
            dataType: "json",
            method: "POST",
            data: memberApplicationData,
        })
            .done(function (data) {
            if (data.success === true) {
                onSuccess();
            }
            else {
                onError();
            }
        })
            .fail(function (data) {
            onError();
        });
    };
    return MrbForm;
}());

var MemberRegistrationBlockApp = /** @class */ (function () {
    function MemberRegistrationBlockApp($el) {
        this.$el = $el;
        this.$mrbForm = new MrbForm($el.find(".member-registration-block__form"));
    }
    return MemberRegistrationBlockApp;
}());
$(function () {
    $(".member-registration-block").each(function () {
        var memberRegistrationBlockApp = new MemberRegistrationBlockApp($(this));
    });
});

var OfferItemBlockApp = /** @class */ (function () {
    function OfferItemBlockApp(selector) {
        this.selector = selector;
        this.$el = $(selector);
        this.attachEvents();
    }
    OfferItemBlockApp.prototype.attachEvents = function () {
        var self = this;
        var $body = $("body");
        var $header = this.$el.find(".accordion-group__element__header");
        var collapseSelector = self.selector + " .collapse";
        $body.on("hidden.bs.collapse", collapseSelector, function () {
            $header.removeClass("body-expanded");
        });
        $body.on("show.bs.collapse", collapseSelector, function () {
            $header.addClass("body-expanded");
        });
    };
    return OfferItemBlockApp;
}());
$(function () {
    // ReSharper disable once UnusedLocals
    $(".offer-item-block").each(function () {
        var offerItemBlockApp = new OfferItemBlockApp("#" + $(this).attr("id"));
    });
});


$(document).ready(function () {
    var myModalEl = document.querySelector('.myinformationupdatemodal');
    var isRebusPage = document.getElementById('rebus-page-link');
    if (myModalEl && !isRebusPage) {
        $(myModalEl).detach().appendTo('#main-content-container')
        var modal = bootstrap.Modal.getOrCreateInstance(myModalEl);
        modal.show();
    }

    
});

function myInformationModalSetCookie() {
    document.cookie = "HideUpdateInformationModal=true;path=/";
}

function myInformationModalRedirectToSettingsPage(settingsPageUrl) {
    /*myInformationModalSetCookie();*/
    myInformationModalCorrectInformationHandler();
    window.location.href = settingsPageUrl;
}

function myInformationModalCorrectInformationHandler() {
    myInformationModalSetCookie();
    $.ajax({
        url: "/api/myinformation/myinformationiscorrect", type: 'patch',
        dataType: 'JSON', success: function (result) {
            //console.log(result);
            //console.log(result.isSuccess)
        }
    });
}
var CompanySelectBlockApp = /** @class */ (function () {
    function CompanySelectBlockApp(companySelectBlock) {
        var _this = this;
        /*private readonly $openModalLink: JQuery;*/
        this.modal = null;
        this.escKeyupEventName = "keyup.changeCompanyblock";
        this.lastActiveView = null;
        this.manualCompanyViewHash = "#/sokarbetsgivare/manuellt";
        this.selectCompanyViewHash = "#/steg/2";
        this.onOpen = null;
        this.onClose = null;
        this.$el = companySelectBlock;
        this.initModalIfNotAlreadyInitiated();
        $(document).ready(function () {
            _this.initRoutes();
        });
    }
    CompanySelectBlockApp.prototype.initRoutes = function () {
        var self = this;
        var app = Sammy(".company-select-block");
        app.get(this.getRoutePath(this.manualCompanyViewHash), function () {
            $('.search-company-section__search-result__hits__select-company-orgnrerror.error').hide();
            var activeView = CompanySelectModalView.ManualCompanyView;
            self.lastActiveView = activeView;
            self.modal.setActiveView(activeView);
        });
        app.get(this.getRoutePath(this.selectCompanyViewHash), function () {
            var activeView = CompanySelectModalView.SelectCompanyView;
            self.modal.setActiveView(activeView);
            self.lastActiveView = activeView;
            var globalSettings = GlobalSettingsSingleton.getInstance();
            if (globalSettings.isMobileDevice() || !globalSettings.hasBrowserTouchCapabilities()) {
                self.modal.changeCompanyWorkSituation.setFocusToFirstWorkSituationOption();
            }
            else {
                self.modal.changeCompanySearch.setFocusToQueryTextbox();
            }
        });
        app.get(this.getRoutePath("(#/)?"), function () {
            /*if (self.isModalOpen())*/
            self.closeModal();
        });
        //Do nothing on undefined routes
        app.get(/.*/, function () {
        });
        app.run(window.location.pathname + window.location.search);
    };
    CompanySelectBlockApp.prototype.getRoutePath = function (hash) {
        // Will return a regexp that only match current pathname (with or without ending with a backslash) 
        // with empty or any kind of querystring followed be the input parameter hash
        return new RegExp("".concat(window.location.pathname, "/?(\\?.*)?").concat(hash, "$"));
    };
    //isModalOpen(): boolean {
    //    if (this.modal === null)
    //        return false;
    //    return this.modal.isModalOpen();
    //}
    //openModal() {
    //    this.initModalIfNotAlreadyInitiated();
    //    //if (this.modal.isModalOpen())
    //    //    return; // It is already opened
    //    this.attachEscapeKeyListener();
    //   /* this.$openModalLink.hide();*/
    //    if (this.onOpen !== null)
    //        this.onOpen();
    //    this.modal.open();
    //}
    CompanySelectBlockApp.prototype.closeModal = function () {
        if (this.modal === null)
            return;
        this.updateOpenModalLinkUrl();
        this.deattachEscKeyListener();
        /*this.$openModalLink.show();*/
    };
    CompanySelectBlockApp.prototype.updateOpenModalLinkUrl = function () {
        if (this.lastActiveView === null)
            return;
        var hashUrl = this.getHashUrl(this.lastActiveView);
        //if (hashUrl !== null)
        //this.$openModalLink.attr("href", hashUrl);
    };
    CompanySelectBlockApp.prototype.getHashUrl = function (changecompanyModalView) {
        switch (changecompanyModalView) {
            case CompanySelectModalView.ManualCompanyView:
                return this.manualCompanyViewHash;
            case CompanySelectModalView.SelectCompanyView:
                return this.selectCompanyViewHash;
            default:
                return null;
        }
    };
    CompanySelectBlockApp.prototype.initModalIfNotAlreadyInitiated = function () {
        if (this.modal !== null)
            return;
        this.modal = new CompanySelectModal(this.$el.find(".company-select-block__container"));
    };
    CompanySelectBlockApp.prototype.attachEscapeKeyListener = function () {
        var self = this;
        $(document).on(self.escKeyupEventName, function (e) {
            if (e.key === "Escape") {
                window.location.href = "#/";
            }
        });
    };
    CompanySelectBlockApp.prototype.deattachEscKeyListener = function () {
        $(document).off(this.escKeyupEventName);
    };
    return CompanySelectBlockApp;
}());

var CompanySelectManually = /** @class */ (function () {
    function CompanySelectManually($changecompanyManually) {
        var _this = this;
        this.gtmService = new GoogleDataLayerService();
        this.selectedCompanies = [];
        this.onSaved = null;
        var self = this;
        this.$el = $changecompanyManually;
        this.$saveButton = this.$el.find(".manually-company-view__save-button");
        this.$errorContainer = this.$el.find(".manually-company-view__form__error-container");
        this.spinner = new Spinner(this.$el.find(".manually-company-view__save-spinner"));
        this.$companyName = $("#companyname");
        this.$address = $("#companyaddress");
        this.$zip = $("#companyzip");
        this.$city = $("#companycity");
        this.$organisationNumber = $("#companyorganisationnumber");
        this.$formInputs = self.$el.find(".mb-4 input");
        self.$selectedCompaniesContainer = $(".selected-companies-list-container");
        self.$selectedCompaniesOrgNrLabel = self.$selectedCompaniesContainer.data("selectedcompaniesorgnrlabel");
        self.$selectedCompaniesAddressLabel = self.$selectedCompaniesContainer.data("selectedcompaniesaddresslabel");
        self.$selectedCompaniesCityLabel = self.$selectedCompaniesContainer.data("selectedcompaniescitylabel");
        self.companySelectService = CompanySelectService.getInstance();
        /*const manuallAddCompanyValidation = this.initValidation();*/
        self.isCurrentUserEditorOrContentViewer = self.$el.data("iscurrentusereditororcontentviewer");
        self.$saveButton.on('click', function (e) { return _this.handleSaveButtonClick(e); });
    }
    CompanySelectManually.prototype.handleSaveButtonClick = function (e) {
        var manuallAddCompanyValidation = this.initValidation();
        e.preventDefault();
        //console.log("manuallAddCompanyValidation: ", manuallAddCompanyValidation);
        //console.log(this.$companyName);
        var newCompany = new CompanySelectCompany('', // bbcId is empty since it's not fetched from an API
        this.$companyName.val(), this.$address.val(), this.$zip.val(), this.$city.val(), '', // phone is empty since it's not fetched from an API
        this.$organisationNumber.val(), '', // countryCode is empty since it's not fetched from an API
        '', // countryName is empty since it's not fetched from an API
        true // assuming added manually
        );
        if (this.canAddCompany(newCompany)) {
            this.hideOrgLabel();
            if (manuallAddCompanyValidation.isValid()) {
                this.companySelectService.addCompany(newCompany);
                this.displayCompanies();
            }
        }
        else {
            var orgLabel = $("#orgnummervalidationlabel");
            if (orgLabel.length === 0) {
                orgLabel = $(document.createElement('label'));
                var validationText = $(".search-company-section__search-result__hits").data("validationtext");
                orgLabel.attr("id", "orgnummervalidationlabel");
                orgLabel.addClass('manually-added-orgnr-error error'); // Adds the classes to the label
                orgLabel.css('display', 'none'); // Sets the display style to none initially
                orgLabel.text(validationText);
                this.$organisationNumber.before(orgLabel);
            }
            else {
                var validationText = $(".search-company-section__search-result__hits").data("validationtext");
                orgLabel.text(validationText);
            }
            orgLabel.show();
        }
    };
    CompanySelectManually.prototype.hideOrgLabel = function () {
        var orgLabel = $("#orgnummervalidationlabel");
        if (orgLabel.length > 0) {
            orgLabel.hide();
        }
    };
    CompanySelectManually.prototype.addCompanyToList = function () {
        // Create a new CompanySelectCompany object using the form fields
        var newCompany = new CompanySelectCompany('', // bbcId is empty since it's not fetched from an API
        this.$companyName.val(), this.$address.val(), this.$zip.val(), this.$city.val(), '', // phone is empty since it's not fetched from an API
        this.$organisationNumber.val(), '', // countryCode is empty since it's not fetched from an API
        '', // countryName is empty since it's not fetched from an API
        true // assuming added manually
        );
        if (this.canAddCompany(newCompany)) {
            this.companySelectService.addCompany(newCompany);
            this.displayCompanies();
        }
        else {
            var validationText = $(".search-company-section__search-result__hits").data("validationtext");
            var orgLabel = $(document.createElement('label'));
            orgLabel.addClass('manually-added-orgnr-error error'); // Adds the classes to the label
            orgLabel.css('display', 'none'); // Sets the display style to none initially
            orgLabel.text(validationText);
            this.$organisationNumber.before(orgLabel);
            orgLabel.show();
        }
    };
    CompanySelectManually.prototype.canAddCompany = function (newCompany) {
        this.selectedCompanies = this.companySelectService.getCompanies();
        if (this.selectedCompanies.length === 0) {
            return true; // Allow the first company to be added
        }
        return this.selectedCompanies.every(function (company) { return company.organisationNumber === newCompany.organisationNumber; })
            && !this.selectedCompanies.some(function (company) { return company.name === newCompany.name && company.street === newCompany.street; });
    };
    CompanySelectManually.prototype.displayCompanies = function () {
        var _this = this;
        var companyListElement = document.getElementById('company-list');
        var defaultemptytextelement = $('#none-selected-company-text');
        if (!companyListElement) {
            console.error('Element with id "company-list" not found.');
            return;
        }
        if (this.selectedCompanies.length > 0) {
            defaultemptytextelement.hide();
        }
        companyListElement.innerHTML = '';
        this.selectedCompanies.forEach(function (company) {
            var _a;
            var companyItem = document.createElement('li');
            companyItem.className = 'company-info';
            companyItem.dataset.bbcId = company.bbcId;
            companyItem.dataset.name = company.name;
            companyItem.dataset.street = company.street;
            companyItem.dataset.zipCode = company.zipCode;
            companyItem.dataset.city = company.city;
            companyItem.dataset.phone = company.phone; // Assuming empty for now
            companyItem.dataset.organisationNumber = company.organisationNumber;
            companyItem.dataset.countryCode = company.countryCode; // Assuming empty for now
            companyItem.dataset.countryName = company.countryName; // Assuming empty for now
            companyItem.dataset.addedManually = company.addedManually !== undefined ? (_a = company.addedManually) === null || _a === void 0 ? void 0 : _a.toString() : 'false';
            ; // Convert boolean to string
            var companyDiv = document.createElement('div');
            companyDiv.className = 'company-info-text';
            var spacerDiv = document.createElement('div');
            companyDiv.className = 'company-info-space';
            // Create the h3 element
            var companyNameElement = document.createElement('h4');
            companyNameElement.textContent = company.name;
            // Create the p element
            var companyStreetElement = document.createElement('p');
            var companyZipElement = document.createElement('p');
            var companyOrgNrElement = document.createElement('p');
            companyOrgNrElement.innerHTML = _this.$selectedCompaniesOrgNrLabel + ": <br />" + company.organisationNumber + "<br /> <br />";
            companyStreetElement.innerHTML = _this.$selectedCompaniesAddressLabel + ":  <br />" + company.street + ", " + company.zipCode + " " + company.city;
            /* companyZipElement.textContent = this.$selectedCompaniesCityLabel + ": " + company.zipCode + " " +company.city;*/
            //// Create the p element
            //const companyStreetElement = document.createElement('p');
            //const companyZipElement = document.createElement('p');
            //const companyOrgNrElement = document.createElement('p');
            //companyOrgNrElement.textContent = this.$selectedCompaniesOrgNrLabel + ": " + company.organisationNumber;
            //companyStreetElement.textContent = this.$selectedCompaniesAddressLabel + ": " + company.street;
            //companyZipElement.textContent = this.$selectedCompaniesCityLabel + ": " + company.zipCode;
            // Append the h3 and p elements to the li
            companyDiv.appendChild(companyNameElement);
            companyDiv.appendChild(companyOrgNrElement);
            companyDiv.appendChild(companyStreetElement);
            companyDiv.appendChild(companyZipElement);
            // Create the delete button
            var deleteButton = document.createElement('img');
            deleteButton.src = "/Static/img/Icons/icon-close-round-red.svg";
            deleteButton.loading = "lazy";
            deleteButton.alt = "ta bort";
            var hrElement = document.createElement('hr');
            companyItem.appendChild(companyDiv);
            companyItem.appendChild(spacerDiv);
            companyItem.appendChild(deleteButton);
            // Append the li to the ul
            companyListElement.appendChild(companyItem);
            companyListElement.appendChild(hrElement);
            // Add click event listener to remove the li element
            deleteButton.addEventListener('click', function () {
                companyListElement.removeChild(companyItem);
                companyListElement.removeChild(hrElement);
                if (!company.bbcId) {
                    _this.companySelectService.removeManualCompany(company.name);
                }
                else {
                    _this.companySelectService.removeCompany(company.bbcId);
                }
                _this.selectedCompanies = _this.companySelectService.getCompanies();
            });
        });
        this.reset();
    };
    //private initSessionPersistence() {
    //    const self = this;
    //    this.$formInputs.each(function () {
    //        const sessionStorageKey = self.getSessionStorageKey($(this));
    //        const value = sessionStorage.getItem(sessionStorageKey);
    //        if (value !== null) {
    //            $(this).val(value);
    //        }
    //    });
    //    this.$formInputs.blur(e => {
    //        self.setValueToSessionStorage(e.target);
    //    });
    //}
    //private setValueToSessionStorage(input: Element) {
    //    const $input = $(input);
    //    sessionStorage.setItem(this.getSessionStorageKey($input), $input.val());
    //}
    //private resetSessionPersistence() {
    //    const self = this;
    //    this.$formInputs.each(function () {
    //        const sessionStorageKey = self.getSessionStorageKey($(this));
    //        sessionStorage.removeItem(sessionStorageKey);
    //    });
    //}
    //private getSessionStorageKey($input: JQuery): string {
    //    return `changecompany-manually-${$input.attr("id")}`;
    //}
    CompanySelectManually.prototype.initValidation = function () {
        var validation = new Validation("#create-company-view__form", {
            'companyname': {
                required: true,
                notOnlySpace: true,
            },
            'companycity': {
                required: true,
                notOnlySpace: true
            },
            'companyaddress': {
                required: true
            },
            'companyzip': {
                required: true
            },
            'companyorganisationnumber': {
                required: true
            }
        }, {
            'companyname': {
                required: $("#companyname").data("valrequired"),
                summary: $("#companyname").data("valsummary")
            },
            'companycity': {
                required: $("#companycity").data("valrequired"),
                summary: $("#companycity").data("valsummary")
            },
            'companyaddress': {
                required: $("#companyaddress").data("valrequired"),
                summary: $("#companyaddress").data("valsummary")
            },
            'companyzip': {
                required: $("#companyzip").data("valrequired"),
                summary: $("#companyzip").data("valsummary")
            },
            'companyorganisationnumber': {
                required: $("#companyorganisationnumber").data("valrequired"),
                summary: $("#companyorganisationnumber").data("valsummary")
            }
        }, ".create-company-view__form__error-summary");
        validation.scrollToErrorMessageOffset = 100;
        return validation;
    };
    //private savecompany() {
    //    const self = this;
    //    if (self.isCurrentUserEditorOrContentViewer) {
    //        self.handleError("Kan inte spara din nya arbetsgivare", "Du är inte inloggad som medlem och har därför inte tillgång till att ändra din arbetsgivare.");
    //        self.$saveButton.removeAttr("disabled");
    //        return;
    //    }
    //    const newcompany = {
    //        companyName: self.$companyName.val(),
    //        address: self.$address.val(),
    //        zip: self.$zip.val(),
    //        city: self.$city.val(),
    //        organisationNumber: self.$organisationNumber.val()
    //    }
    //    self.$saveButton.hide();
    //    self.spinner.show();
    //    $.post(InternalApiEndpoints.changecompanyManually(), newcompany)
    //        .done(() => {
    //            self.changecompanyService.triggercompanyChangedEvent();
    //            self.gtmService.push({
    //                "event": "updateArbetsgivare",
    //                "selectType": "manual"
    //            });
    //            window.location.href = "#/";
    //            if (self.onSaved !== null) {
    //                self.onSaved();
    //            }
    //        })
    //        .fail((jqueryXhr: JQueryXHR) => {
    //            if (jqueryXhr.status === 401) {
    //                location.reload();
    //                return;
    //            }
    //            self.handleError(
    //                self.$el.data("changecompanyerrormessageheader"),
    //                self.$el.data("changecompanyerrormessagetext"));
    //        })
    //        .always(() => {
    //            self.$saveButton.show();
    //            self.spinner.hide();
    //            self.$saveButton.removeAttr("disabled");
    //        });
    //}
    //private handleError(header: string, description: string) {
    //    this.$errorContainer.removeClass("hide");
    //    const errorMessageBox = new ErrorMessageBox(header, description);
    //    errorMessageBox.append(this.$errorContainer);
    //    errorMessageBox.scrollTo(100);
    //}
    CompanySelectManually.prototype.reset = function () {
        this.$companyName.removeClass("valid").val("");
        this.$address.removeClass("valid").val("");
        this.$zip.removeClass("valid").val("");
        this.$city.removeClass("valid").val("");
        this.$organisationNumber.removeClass("valid").val("");
        //this.resetSessionPersistence();
    };
    return CompanySelectManually;
}());

var CompanySelectModal = /** @class */ (function () {
    function CompanySelectModal($changeCompanyModal) {
        this.isModalInitiated = false;
        this.$modal = $changeCompanyModal;
        this.$closeModalLink = this.$modal.find(".modal-cancel");
        this.gtmService = new GoogleDataLayerService();
        this.focusTrap = new FocusTrap(this.$modal, "changecompanyblockfocustrap");
        this.customEventHandler = new CustomEventHandler();
        this.$selectCompanyView = this.$modal.find(".select-company-view");
        this.$manualCompanyView = this.$modal.find(".manually-company-view");
        this.$companySelectHeader = this.$modal.find(".company-select-header");
        this.initSearchCompany();
        this.initMyWorkSituation();
        this.initChangeCompanyManually();
    }
    CompanySelectModal.prototype.addOverlay = function () {
        this.$overlay = $("<div />").addClass("change-company-block__overlay");
        this.$overlay.insertAfter(this.$modal);
    };
    CompanySelectModal.prototype.removeOverlay = function () {
        this.$overlay.remove();
    };
    CompanySelectModal.prototype.initSearchCompany = function () {
        var self = this;
        self.changeCompanySearch = new CompanySelectSearch(self.$modal.find(".search-company-section"));
        self.changeCompanySearch.onSaved = function () {
            self.reset();
        };
    };
    CompanySelectModal.prototype.initMyWorkSituation = function () {
        var self = this;
        self.changeCompanyWorkSituation = new CompanySelectWorkSituation(self.$modal.find(".work-situation-section"));
        self.changeCompanyWorkSituation.onWorkSituationChanged = function (workSituationType) {
            if (workSituationType === CompanySelectworkSituationType.Employed) {
                self.changeCompanySearch.show();
            }
            if (workSituationType === CompanySelectworkSituationType.NotEmployed) {
                self.changeCompanySearch.hide();
            }
        };
        self.changeCompanyWorkSituation.changeSelectedWorkSituation(CompanySelectworkSituationType.Employed);
        self.changeCompanyWorkSituation.onSaved = function () { self.reset(); };
    };
    CompanySelectModal.prototype.initChangeCompanyManually = function () {
        var self = this;
        self.changeCompanyManually = new CompanySelectManually(self.$manualCompanyView);
        self.changeCompanyManually.onSaved = function () { self.reset(); };
    };
    //open() {
    //    const self = this;
    //    this.addOverlay();
    //    this.$modal.collapse("show");
    //    this.focusTrap.activate();
    //    $("html, body").animate({ scrollTop: self.$modal.offset().top - 5 }, 500);
    //}
    //close() {
    //    const self = this;
    //    self.$modal.collapse("hide");
    //    self.$modal.one("hidden.bs.collapse", () => { // If using 'on' instead of 'one' can result in that the overlay removes when minimizing a company details
    //        self.removeOverlay();
    //    });
    //    self.focusTrap.inactivate();
    //}
    CompanySelectModal.prototype.isModalOpen = function () {
        return this.$modal.hasClass("show");
    };
    CompanySelectModal.prototype.setActiveView = function (view) {
        if (view === CompanySelectModalView.ManualCompanyView) {
            this.$selectCompanyView.addClass("hide");
            this.$companySelectHeader.addClass("hide");
            this.$manualCompanyView.removeClass("hide");
        }
        else if (view === CompanySelectModalView.SelectCompanyView) {
            this.$selectCompanyView.removeClass("hide");
            this.$companySelectHeader.removeClass("hide");
            this.$manualCompanyView.addClass("hide");
        }
        var self = this;
        $("html, body").animate({ scrollTop: self.$modal.offset().top - 5 }, 500);
    };
    CompanySelectModal.prototype.reset = function () {
        this.changeCompanyWorkSituation.reset();
        this.changeCompanySearch.reset();
        this.changeCompanyManually.reset();
    };
    return CompanySelectModal;
}());

var CompanySelectSearch = /** @class */ (function () {
    function CompanySelectSearch($searchCompanySection) {
        this.onSaved = null;
        var self = this;
        self.$searchCompanySection = $searchCompanySection;
        self.searchForm = new CompanySelectSearchForm($searchCompanySection);
        self.searchResult = new CompanySelectSearchResult($searchCompanySection);
        self.searchResult.onSaved = function () {
            if (self.onSaved !== null) {
                self.onSaved();
            }
        };
        //self.searchForm.onAutocompleteOptionSelected = (bbcId: string) => {
        //    self.searchForm.setCountrySelectorVisability(false);
        //    self.searchForm.setCitySelectorVisability(false);
        //    self.searchResult.showDirectHit(bbcId);
        //}
        self.searchForm.onSearch = function (searchParameters, callback) {
            self.searchResult.searchParameters = searchParameters;
            self.searchResult.search(0, callback);
        };
        self.setFocusToQueryTextbox();
        // When initiating the modal for the first time we force this to be visible. Otherwise
        // in can be hidden if the user is using the browser-back-button.
        this.show();
    }
    CompanySelectSearch.prototype.show = function () {
        this.$searchCompanySection.removeClass("hide");
    };
    CompanySelectSearch.prototype.hide = function () {
        this.$searchCompanySection.addClass("hide");
    };
    CompanySelectSearch.prototype.reset = function () {
        this.show();
        this.searchForm.reset();
        this.searchResult.reset();
    };
    CompanySelectSearch.prototype.setFocusToQueryTextbox = function () {
        this.searchForm.setFocusToQueryTextbox();
    };
    return CompanySelectSearch;
}());

var CompanySelectSearchForm = /** @class */ (function () {
    //onAutocompleteOptionSelected: Function;
    function CompanySelectSearchForm($searchCompanySection) {
        this.maxItemsInAutocomplete = 5;
        this.defaultCountryCode = "se";
        this.isAutocompleteActive = true;
        var self = this;
        self.$searchCompanySection = $searchCompanySection;
        self.$formSection = self.$searchCompanySection.find(".search-company-section__form");
        self.$queryTextbox = $searchCompanySection.find(".search-company-section__form__query-row__input");
        self.$searchButton = $searchCompanySection.find(".search-company-section__form__query-row__search-button");
        self.$showInternationalEmployees = $searchCompanySection.find(".search-company-section__form__country-row__show-international-employees");
        self.minHitsToShowCityAndCountryDropdown = self.$searchCompanySection.data("minhitstoshowcityandcountrydropdown");
        self.$formCountryRow = $searchCompanySection.find(".search-company-section__form__country-row");
        self.$formCityRow = $searchCompanySection.find(".search-company-section__form__city-row");
        self.$countryDropdownmenu = $searchCompanySection.find(".search-company-section__country");
        self.$cityDropdownmenu = $searchCompanySection.find(".search-company-section__form__city-row__select-bold");
        self.autocompleteSpinner = new Spinner($searchCompanySection.find(".search-company-section__form__query-row__spinner"));
        self.currentQuery = self.$queryTextbox.val();
        self.addressMissingText = self.$searchCompanySection.data("addressmissingtext");
        self.textboxClearer = new TextboxClearer(self.$queryTextbox, self.$searchCompanySection.data("clearsearchalttext"));
        //Not sure if this should be done in this ts
        self.$communeDropdownmenu = $('#counties');
        self.$communeDropdownmenu.change(function () {
            if ($(this).val() !== 'none') {
                $('#place-for-negotiation').show();
            }
            else {
                $('#place-for-negotiation').hide();
            }
        });
        // self.initAutocomplete();
        self.$queryTextbox.keypress(function (e) {
            if (e.keyCode === 13) { // If user clicks enter
                //self.toggleAutocompleteEnabled(false);
                e.preventDefault();
                self.$searchButton.focus();
                self.$searchButton.click();
            }
        });
        //self.$queryTextbox.keyup(() => {
        //    self.toggleAutocompleteEnabled(self.$queryTextbox.val().length > 0);
        //});
        self.$searchButton.click(function (e) {
            e.preventDefault();
            self.search();
            self.adjustSelectWidth();
        });
        self.$showInternationalEmployees.change(function (e) {
            e.preventDefault();
            //self.changeAutocompleteCountryScope(self.isSearchingInternational() ? null : self.defaultCountryCode);
            if (self.currentQuery === "")
                return;
            self.search();
        });
        self.$countryDropdownmenu.change(function () {
            self.$cityDropdownmenu.val("");
            self.filter(function (searchResult) {
                self.populateCityDropdownmenu(searchResult);
            });
        });
        self.$cityDropdownmenu.change(function () {
            self.filter();
            self.adjustSelectWidth();
        });
    }
    CompanySelectSearchForm.prototype.search = function () {
        var self = this;
        self.autocompleteSpinner.hide();
        self.currentQuery = self.$queryTextbox.val();
        self.setCountrySelectorVisability(false);
        self.setCitySelectorVisability(false);
        self.getSearchResult(function (searchResult) {
            if (self.isSearchingInternational()) {
                self.populateCountryDropdownmenu(searchResult);
                if (searchResult.countries.length === 1) {
                    self.populateCityDropdownmenu(searchResult);
                }
            }
            else {
                self.populateCityDropdownmenu(searchResult);
            }
            self.updateForm(searchResult);
        });
    };
    CompanySelectSearchForm.prototype.filter = function (callback) {
        if (callback === void 0) { callback = null; }
        var self = this;
        self.getSearchResult(function (searchResult) {
            self.updateForm(searchResult);
            if (callback !== null) {
                callback(searchResult);
            }
        });
    };
    CompanySelectSearchForm.prototype.adjustSelectWidth = function () {
        var self = this;
        // Create a temporary span element to measure the text width
        var $tempSpan = $('<span></span>').appendTo('body');
        // Apply the same styles as the select element to the span
        var styles = window.getComputedStyle(self.$cityDropdownmenu[0]);
        $tempSpan.css({
            fontFamily: styles.fontFamily,
            fontSize: styles.fontSize,
            fontWeight: styles.fontWeight,
            fontStyle: styles.fontStyle,
            position: 'absolute',
            whiteSpace: 'nowrap',
            visibility: 'hidden'
        });
        // Set the text of the span to the selected option's text
        var selectedText = self.$cityDropdownmenu.find('option:selected').text();
        $tempSpan.text(selectedText);
        // Calculate the width of the span and set the select width
        var newWidth = $tempSpan[0].offsetWidth + 18;
        self.$cityDropdownmenu.css('width', "".concat(newWidth, "px"));
        // Remove the temporary span from the DOM
        $tempSpan.remove();
    };
    CompanySelectSearchForm.prototype.isSearchingInternational = function () {
        return this.$showInternationalEmployees.is(":checked");
    };
    CompanySelectSearchForm.prototype.getSelectedCountryCode = function () {
        if (!this.$showInternationalEmployees.is(":checked"))
            return this.defaultCountryCode;
        var $selectedCountry = this.$countryDropdownmenu.find("option:selected");
        if ($selectedCountry.length === 0)
            return null;
        if ($selectedCountry.val() === "")
            return null;
        return $selectedCountry.val();
    };
    CompanySelectSearchForm.prototype.getSelectedCountryName = function () {
        if (!this.$showInternationalEmployees.is(":checked"))
            return "Sverige";
        var $selectedCountry = this.$countryDropdownmenu.find("option:selected");
        if ($selectedCountry.length === 0)
            return null;
        if ($selectedCountry.val() === "")
            return null;
        return $selectedCountry.text();
    };
    CompanySelectSearchForm.prototype.getSelectedCity = function () {
        var selectedCity = this.$cityDropdownmenu.find("option:selected");
        if (selectedCity.length === 0)
            return null;
        if (selectedCity.val() === "")
            return null;
        return selectedCity.val();
    };
    CompanySelectSearchForm.prototype.setCitySelectorVisability = function (visible) {
        if (visible) {
            this.$formCityRow.removeClass("hide");
        }
        else {
            this.$formCityRow.addClass("hide");
            this.$cityDropdownmenu.val("");
        }
    };
    CompanySelectSearchForm.prototype.setCountrySelectorVisability = function (visible) {
        if (visible) {
            this.$formCountryRow.removeClass("hide");
        }
        else {
            this.$formCountryRow.addClass("hide");
            this.$countryDropdownmenu.val("");
        }
    };
    CompanySelectSearchForm.prototype.setFocusToQueryTextbox = function () {
        this.$queryTextbox.attr("autofocus", ""); // Forces iPhone devices to set focus to the input field
        this.$queryTextbox.focus();
    };
    CompanySelectSearchForm.prototype.updateForm = function (searchResult) {
        this.setCountrySelectorVisability(this.shouldCountrySelecterBeVisible(searchResult));
        this.setCitySelectorVisability(this.shouldCitySelectorBeVisible(searchResult));
    };
    CompanySelectSearchForm.prototype.shouldCountrySelecterBeVisible = function (searchResult) {
        if (!this.isSearchingInternational())
            return false;
        if (this.getSelectedCountryCode() !== null)
            return true;
        if (searchResult.countries.length < 2)
            return false;
        return searchResult.hitsTotal >= this.minHitsToShowCityAndCountryDropdown;
    };
    CompanySelectSearchForm.prototype.shouldCitySelectorBeVisible = function (searchResult) {
        if (this.getSelectedCity() !== null)
            return true;
        if (searchResult.cities.length < 2)
            return false;
        if (this.isSearchingInternational()) {
            return searchResult.hitsTotal >= this.minHitsToShowCityAndCountryDropdown &&
                (this.getSelectedCountryCode() !== null || searchResult.countries.length === 1);
        }
        else {
            return searchResult.hitsTotal >= this.minHitsToShowCityAndCountryDropdown;
        }
    };
    CompanySelectSearchForm.prototype.getSearchResult = function (callback) {
        if (callback === void 0) { callback = null; }
        if (this.onSearch !== null) {
            var searchParameters = new CompanySelectSearchParameters();
            searchParameters.query = this.currentQuery;
            searchParameters.city = this.getSelectedCity();
            searchParameters.countryCode = this.getSelectedCountryCode();
            searchParameters.countryName = this.getSelectedCountryName();
            searchParameters.pageIndex = 0;
            this.onSearch(searchParameters, callback);
            //this.toggleAutocompleteEnabled(false);
        }
    };
    CompanySelectSearchForm.prototype.populateCountryDropdownmenu = function (searchResult) {
        var self = this;
        self.$countryDropdownmenu.find("option:not([value=''])").remove();
        $.each(searchResult.countries, function (index, companyCountry) {
            var countryOption = $("<option />");
            countryOption.text(companyCountry.countryName);
            countryOption.val(companyCountry.countryCode);
            self.$countryDropdownmenu.append(countryOption);
        });
    };
    CompanySelectSearchForm.prototype.populateCityDropdownmenu = function (searchResult) {
        var self = this;
        self.$cityDropdownmenu.find("option:not([value=''])").remove();
        $.each(searchResult.cities, function (index, companyCity) {
            var cityOption = $("<option />");
            cityOption.text(self.firstLetterUpperCase(companyCity));
            cityOption.val(companyCity);
            self.$cityDropdownmenu.append(cityOption);
        });
    };
    CompanySelectSearchForm.prototype.firstLetterUpperCase = function (word) {
        if (word === null || word.length === 0)
            return word;
        return word[0].toUpperCase() + word.slice(1).toLowerCase();
    };
    //private initAutocomplete() {
    //    const self = this;
    //    self.$queryTextbox.tinyAutocomplete({
    //        url: self.getAutocompleteSearchApiUrl(self.defaultCountryCode),
    //        queryProperty: "query",
    //        itemTemplate: '<li class="autocomplete-item"><div>{{name}}</div><div>{{address}}</div><div>{{country}}</div></li>',
    //        onSelect: (element: any, company: any) => {
    //            self.$queryTextbox.val(company.name);
    //            if (self.onAutocompleteOptionSelected !== null) {
    //                self.onAutocompleteOptionSelected(company.bbcId);
    //            }
    //        },
    //        showNoResults: false,
    //        minChars: 1,
    //        markAsBold: true,
    //        maxItems: self.maxItemsInAutocomplete,
    //        maxItemsOnMobile: self.maxItemsInAutocomplete,
    //        keyboardDelay: 100,
    //        excludedFieldNamesFromMarkHit: ["bbcId", "address", "country"]
    //    });
    //    self.$queryTextbox.on("beforerequest",
    //        () => {
    //            self.autocompleteSpinner.show();
    //        });
    //    self.$queryTextbox.on("requestfailed",
    //        () => {
    //            self.autocompleteSpinner.hide();
    //        });
    //    self.$queryTextbox.on("receivedata", (e, tinyAutocomplete, json) => {
    //        self.autocompleteSpinner.hide();
    //        if (!self.isAutocompleteActive) {
    //            tinyAutocomplete.json = [];
    //            return;
    //        }
    //        tinyAutocomplete.json = json.companies.map(company => {
    //            let address: string;
    //            if (company.address || company.city) {
    //                address = company.address + " " + company.city;
    //            } else {
    //                const $addressMissingText = $("<span />").addClass("text--italic").text(self.addressMissingText);
    //                address = $addressMissingText[0].outerHTML;
    //            }
    //            return {
    //                bbcId: company.bbcId,
    //                name: company.name,
    //                address: address,
    //                country: company.countryName
    //            };
    //        });
    //    });
    //}
    //private getAutocompleteSearchApiUrl(countryCode: string): string {
    //    const self = this;
    //    return InternalApiEndpoints.searchCompanies(null, null, countryCode, 0, self.maxItemsInAutocomplete, false);
    //}
    //private changeAutocompleteCountryScope(countryCode: string) {
    //    const self = this;
    //    self.$queryTextbox.tinyAutocomplete({
    //        url: self.getAutocompleteSearchApiUrl(countryCode)
    //    });
    //}
    //private toggleAutocompleteEnabled(enabled: boolean) {
    //    this.$queryTextbox.tinyAutocomplete({
    //        enabled: enabled
    //    });
    //    this.isAutocompleteActive = enabled;
    //}
    CompanySelectSearchForm.prototype.reset = function () {
        this.$queryTextbox.removeAttr("autofocus");
        this.$queryTextbox.val("");
        this.textboxClearer.updateVisabilityOnClearButton();
        this.$showInternationalEmployees.prop("checked", false);
        this.setCountrySelectorVisability(false);
        this.setCitySelectorVisability(false);
    };
    return CompanySelectSearchForm;
}());

var CompanySelectSearchResult = /** @class */ (function () {
    function CompanySelectSearchResult($searchCompanySection) {
        this.gtmService = new GoogleDataLayerService();
        this.lastSearchXhr = null;
        this.onSearched = null;
        this.onSaved = null;
        this.searchParameters = new CompanySelectSearchParameters();
        var self = this;
        self.$searchCompanySection = $searchCompanySection;
        self.companySearchHitTemplate = _.template($searchCompanySection.find("#search-company-section__search-result-template").html());
        self.$companySearchResult = $searchCompanySection.find(".search-company-section__search-result");
        self.$searchSummaryText = self.$searchCompanySection.find(".search-company-section__search-result__search-summary-text");
        self.$companySearchResultHits = self.$companySearchResult.find(".search-company-section__search-result__hits");
        self.$companySearchResultFooter = $searchCompanySection.find(".search-company-section__search-result__footer");
        self.$companySearchResultPager = self.$companySearchResult.find(".search-company-section__search-result__footer__pager");
        self.companySearchResultPagerSpinner = new Spinner(self.$companySearchResult.find(".search-company-section__search-result__footer__pager-spinner"));
        self.$companySearchResultPagerShowNextPageLink = self.$companySearchResult.find(".search-company-section__search-result__pager__show-next-page-link");
        self.$companySearchResultCannotFindcompanyLink = self.$companySearchResult.find(".search-company-section__search-result__footer__cannot-find-company-link");
        self.$errorContainer = self.$searchCompanySection.find(".search-company-section__error");
        self.isCurrentUserEditorOrContentViewer = self.$searchCompanySection.data("iscurrentusereditororcontentviewer");
        self.$selectedCompaniesContainer = $(".selected-companies-list-container");
        self.$selectedCompaniesOrgNrLabel = self.$selectedCompaniesContainer.data("selectedcompaniesorgnrlabel");
        self.$selectedCompaniesAddressLabel = self.$selectedCompaniesContainer.data("selectedcompaniesaddresslabel");
        self.$selectedCompaniesCityLabel = self.$selectedCompaniesContainer.data("selectedcompaniescitylabel");
        self.$noneSelectedCompanyText = $('#none-selected-company-text');
        self.companySearchSpinner = new Spinner(self.$searchCompanySection.find(".search-company-section__search-spinner"));
        self.companySelectService = CompanySelectService.getInstance();
        self.selectedCompanies = self.companySelectService.getCompanies();
        self.pageSize = self.$companySearchResult.data("pagesize");
        self.pager = new Pager(".pager-container");
        self.pager.pagerSettings.pageSize = self.pageSize;
        self.$companySearchResult.on("click", ".search-company-section__search-result__hits__select-company-btn", function () {
            var $button = $(this);
            var $company = $(this).closest(".company");
            self.handleButtonClick($company, $button);
        });
    }
    CompanySelectSearchResult.prototype.handleButtonClick = function ($company, $button) {
        var self = this;
        var companyDetailsIsAlreadyPopulated = $company.find(".search-company-section__search-result__company-detail").length > 0;
        var $loadDetailsSpinner = new Spinner($company.find(".search-company-section__search-result__hits__load-details-spinner"));
        if (!companyDetailsIsAlreadyPopulated) {
            $loadDetailsSpinner.show();
        }
        var bbcId = $company.data("bbcid");
        self.addCompanyToList(bbcId, $company, $button);
        if (companyDetailsIsAlreadyPopulated)
            return;
        self.getCompanyDetails(bbcId, function (company) {
            self.populateCompanyDetails($company, company);
        }, function () {
            $loadDetailsSpinner.hide();
        });
    };
    CompanySelectSearchResult.prototype.search = function (pageIndex, callback) {
        if (pageIndex === void 0) { pageIndex = 0; }
        if (callback === void 0) { callback = null; }
        var self = this;
        self.searchParameters.pageIndex = pageIndex;
        self.hideError();
        if (self.searchParameters.query.length === 0) {
            var searchResult = new SearchComanySelectResult();
            searchResult.hitsTotal = 0;
            searchResult.pageIndex = 0;
            searchResult.pageSize = self.pageSize;
            searchResult.hasMorePages = false;
            searchResult.companies = [];
            self.updateSearchArea(searchResult, new SearchCompanySelectSummary(self.searchParameters));
            return;
        }
        if (pageIndex === 0) {
            self.companySearchSpinner.show();
            self.$companySearchResult.addClass("hide");
        }
        var searchApiUrl = InternalApiEndpoints.publicSearchCompanies(self.searchParameters.query, self.searchParameters.city, self.searchParameters.countryCode, pageIndex, self.pageSize, pageIndex === 0);
        var searchStartedTime = window.performance.now();
        if (this.lastSearchXhr !== null) {
            this.lastSearchXhr.abort();
        }
        this.lastSearchXhr = $.getJSON(searchApiUrl)
            .done(function (searchResult) {
            var searchTotalTime = window.performance.now() - searchStartedTime;
            var minimumProgressBarShowTime = 500;
            var timeoutTime = Math.max(minimumProgressBarShowTime - searchTotalTime, 0);
            setTimeout(function () {
                self.pager.onPageIndexUpdated = function (newPageIndex) {
                    self.search(newPageIndex - 1);
                };
                self.updateSearchArea(searchResult, new SearchCompanySelectSummary(self.searchParameters));
                self.hideSearchSpinners();
                if (callback !== null)
                    callback(searchResult);
            }, timeoutTime);
        })
            .fail(function (jqueryXhr) {
            if (jqueryXhr.status === 401) {
                location.reload();
                return;
            }
            if (jqueryXhr.statusText === "abort") // If request is aborted, the member has made a new search before the previous search result was received
                return;
            self.handleError(self.$searchCompanySection.data("searchcompanyerrormessageheader"), self.$searchCompanySection.data("searchcompanyerrormessagetext"), false);
            self.hideSearchSpinners();
        });
    };
    CompanySelectSearchResult.prototype.hideSearchSpinners = function () {
        this.companySearchSpinner.hide();
        this.companySearchResultPagerSpinner.hide();
    };
    CompanySelectSearchResult.prototype.handleError = function (header, description, scrollToErrorMessage) {
        var errorMessageBox = new ErrorMessageBox(header, description);
        errorMessageBox.append(this.$errorContainer);
        this.$errorContainer.removeClass("hide");
        this.$companySearchResult.addClass("hide");
        if (scrollToErrorMessage) {
            errorMessageBox.scrollTo(100);
        }
    };
    CompanySelectSearchResult.prototype.updateSearchArea = function (searchResult, searchSummary) {
        this.hideError();
        this.updateSearchSummaryText(searchResult, searchSummary);
        this.updateSearchHits(searchResult);
        this.updatePager(searchResult);
        this.$companySearchResult.removeClass("hide");
        if (this.onSearched !== null) {
            this.onSearched(searchResult);
        }
    };
    CompanySelectSearchResult.prototype.updatePager = function (searchResult) {
        var self = this;
        var pagerSettings = new PagerSettings();
        pagerSettings.pageSize = self.pageSize;
        pagerSettings.numOfPages = Math.ceil(searchResult.hitsTotal / pagerSettings.pageSize);
        pagerSettings.currentPageIndex = searchResult.pageIndex + 1;
        self.pager.pagerSettings = pagerSettings;
        self.pager.updatePager();
        self.$companySearchResultCannotFindcompanyLink.removeClass("hide");
        if (searchResult.hitsTotal > pagerSettings.pageSize) {
            self.$companySearchResultFooter.removeClass("hide");
        }
        else {
            self.$companySearchResultFooter.addClass("hide");
        }
    };
    CompanySelectSearchResult.prototype.updateSearchSummaryText = function (searchResult, searchSummary) {
        var companySearchSummaryText = this.getSearchSummaryText(searchResult, searchSummary);
        companySearchSummaryText = this.replaceSearchSummaryPlaceholders(companySearchSummaryText, searchResult, searchSummary);
        this.$searchSummaryText.html(companySearchSummaryText);
    };
    CompanySelectSearchResult.prototype.getSearchSummaryText = function (searchResult, searchSummary) {
        if (searchSummary.isDirectHit) {
            if (searchSummary.isSearchingInSweden())
                return this.$searchCompanySection.data("companysearchsummaryswedendirecthit");
            //return this.$searchCompanySection.data("companysearchsummaryinternationaldirecthit");
        }
        if (searchSummary.query.length === 0)
            return this.$searchCompanySection.data("companysearchsummarywhenemptyquery");
        if (searchResult.hitsTotal === 0)
            return this.$searchCompanySection.data("companysearchsummarywhenhavingnohitstext");
        if (searchSummary.isSearchingInSweden()) {
            if (searchSummary.city !== null) {
                return this.$searchCompanySection.data("companysearchsummaryswedenwithparameterquerytextandcity");
            }
            else {
                return this.$searchCompanySection.data("companysearchsummaryswedenwithparameterquerytext");
            }
        }
        //if (searchSummary.countryCode !== null && searchSummary.city !== null)
        //    return this.$searchCompanySection.data("companysearchsummaryinternationalwithparameterquerycountryandcity");
        //if (searchSummary.countryCode === null && searchSummary.city !== null)
        //    return this.$searchCompanySection.data("companysearchsummaryinternationalwithparameterqueryandcity");
        //if (searchSummary.countryCode !== null && searchSummary.city === null)
        //    return this.$searchCompanySection.data("companysearchsummaryinternationalwithparameterqueryandcountry");
        //if (searchSummary.countryCode === null && searchSummary.city === null)
        //    return this.$searchCompanySection.data("companysearchsummaryinternationalwithparameterquery");
        return "";
    };
    CompanySelectSearchResult.prototype.replaceSearchSummaryPlaceholders = function (searchSummaryText, searchResult, searchParameters) {
        searchSummaryText = this.replaceSearchSummaryPlaceholder(searchSummaryText, "query", searchParameters.query);
        searchSummaryText = this.replaceSearchSummaryPlaceholder(searchSummaryText, "city", searchParameters.city);
        searchSummaryText = this.replaceSearchSummaryPlaceholder(searchSummaryText, "hitstotal", searchResult.hitsTotal.toString());
        searchSummaryText = this.replaceSearchSummaryPlaceholder(searchSummaryText, "displayedhits", this.GetDisplayedHitsRange(searchResult));
        return searchSummaryText;
    };
    CompanySelectSearchResult.prototype.GetDisplayedHitsRange = function (searchResult) {
        var start = (searchResult.pageIndex * searchResult.pageSize) + 1;
        var end = start + searchResult.companies.length - 1;
        var range = "".concat(start, "-").concat(end);
        return range;
    };
    CompanySelectSearchResult.prototype.replaceSearchSummaryPlaceholder = function (searchSummaryText, placeholderName, value) {
        if (value === null)
            value = "";
        return searchSummaryText.replace(new RegExp("\\[".concat(placeholderName, "\\]"), "g"), "<span class=\"search-summary-text__highlight\">".concat(value, "</span>")).replace(/(&nbsp;|\s)+/g, ' ');
    };
    CompanySelectSearchResult.prototype.updateSearchHits = function (searchResult) {
        var _this = this;
        /*console.log(searchResult);*/
        var self = this;
        var templatedHtml = $(self.companySearchHitTemplate({ searchResult: searchResult }));
        self.$companySearchResultHits.empty().append(templatedHtml);
        if (this.selectedCompanies.length > 0) {
            this.selectedCompanies.forEach(function (company) {
                _this.handleAddButtonToggle(company.bbcId);
            });
        }
        if (searchResult.hitsTotal === 1) {
            self.$companySearchResultHits.find(".collapse").collapse("show");
        }
    };
    CompanySelectSearchResult.prototype.handleAddButtonToggle = function (bbcId) {
        var $companySearchElement = $('.company[data-bbcid="' + bbcId + '"]');
        $companySearchElement.find(".search-company-section__search-result__hits__select-company-btn").toggle();
        $companySearchElement.find(".search-company-section__search-result__hits__added-text").toggleClass("hide");
    };
    CompanySelectSearchResult.prototype.populateCompanyDetails = function ($company, company) {
        $company.find(".search-company-section__search-result__zip").replaceWith(company.zipCode);
        if (company.phone) {
            $company.find(".search-company-section__search-result__phone__value").replaceWith(company.phone);
            $company.find(".search-company-section__search-result__phone").show();
        }
        if (company.organisationNumber) {
            $company.find(".search-company-section__search-result__orgnr__value").replaceWith(company.organisationNumber);
            $company.find(".search-company-section__search-result__orgnr").show();
        }
    };
    CompanySelectSearchResult.prototype.getCompanyDetails = function (bbcId, successCallback, alwaysCallback) {
        if (alwaysCallback === void 0) { alwaysCallback = null; }
        $.getJSON(InternalApiEndpoints.publicGetCompanyDetails(encodeURIComponent(bbcId)))
            .done(function (company) {
            successCallback(company);
        })
            .always(function () {
            if (alwaysCallback !== null) {
                alwaysCallback();
            }
        });
    };
    CompanySelectSearchResult.prototype.addCompanyToList = function (bbcId, $company, $button) {
        var _this = this;
        this.getCompanyDetails(bbcId, function (company) {
            $('.search-company-section__search-result__hits__select-company-orgnrerror.error').hide();
            if (_this.canAddCompany(company)) {
                _this.companySelectService.addCompany(company);
                _this.displayCompanies();
                $button.hide();
                $company.find(".search-company-section__search-result__hits__added-text").removeClass("hide");
            }
            else {
                var validationText = _this.$companySearchResultHits.data("validationtext");
                var labelAboveButton = $button.prev('label');
                labelAboveButton.text(validationText);
                labelAboveButton.show();
            }
        });
    };
    CompanySelectSearchResult.prototype.canAddCompany = function (newCompany) {
        this.selectedCompanies = this.companySelectService.getCompanies();
        if (this.selectedCompanies.length === 0) {
            return true; // Allow the first company to be added
        }
        return this.selectedCompanies.every(function (company) { return company.organisationNumber === newCompany.organisationNumber; })
            && !this.selectedCompanies.some(function (company) { return company.name === newCompany.name && company.street === newCompany.street; });
    };
    CompanySelectSearchResult.prototype.displayCompanies = function () {
        var _this = this;
        var companyListElement = document.getElementById('company-list');
        if (!companyListElement) {
            console.error('Element with id "company-list" not found.');
            return;
        }
        this.selectedCompanies = this.companySelectService.getCompanies();
        if (this.selectedCompanies.length > 0) {
            this.$noneSelectedCompanyText.hide();
        }
        companyListElement.innerHTML = '';
        this.selectedCompanies.forEach(function (company) {
            var companyItem = document.createElement('li');
            companyItem.className = 'company-info';
            companyItem.dataset.bbcId = company.bbcId;
            companyItem.dataset.name = company.name;
            companyItem.dataset.street = company.street;
            companyItem.dataset.zipCode = company.zipCode;
            companyItem.dataset.city = company.city;
            companyItem.dataset.phone = company.phone;
            companyItem.dataset.organisationNumber = company.organisationNumber;
            companyItem.dataset.countryCode = company.countryCode;
            companyItem.dataset.countryName = company.countryName;
            companyItem.dataset.addedManually = 'false';
            var companyDiv = document.createElement('div');
            companyDiv.className = 'company-info-text';
            var spacerDiv = document.createElement('div');
            companyDiv.className = 'company-info-space';
            // Create the h3 element
            var companyNameElement = document.createElement('h4');
            companyNameElement.textContent = company.name;
            // Create the p element
            var companyStreetElement = document.createElement('p');
            var companyZipElement = document.createElement('p');
            var companyOrgNrElement = document.createElement('p');
            companyOrgNrElement.innerHTML = _this.$selectedCompaniesOrgNrLabel + ": <br />" + company.organisationNumber + "<br /> <br />";
            companyStreetElement.innerHTML = _this.$selectedCompaniesAddressLabel + ":  <br />" + company.street + ", " + company.zipCode + " " + company.city;
            /* companyZipElement.textContent = this.$selectedCompaniesCityLabel + ": " + company.zipCode + " " +company.city;*/
            // Append the h3 and p elements to the li
            companyDiv.appendChild(companyNameElement);
            companyDiv.appendChild(companyOrgNrElement);
            companyDiv.appendChild(companyStreetElement);
            companyDiv.appendChild(companyZipElement);
            // Create the delete button
            var deleteButton = document.createElement('img');
            deleteButton.src = "/Static/img/Icons/icon-close-round-red.svg";
            deleteButton.loading = "lazy";
            deleteButton.alt = "ta bort";
            var hrElement = document.createElement('hr');
            companyItem.appendChild(companyDiv);
            companyItem.appendChild(spacerDiv);
            companyItem.appendChild(deleteButton);
            // Append the li to the ul
            companyListElement.appendChild(companyItem);
            companyListElement.appendChild(hrElement);
            // Add click event listener to remove the li element
            deleteButton.addEventListener('click', function () {
                $('.search-company-section__search-result__hits__select-company-orgnrerror.error').hide();
                companyListElement.removeChild(companyItem);
                companyListElement.removeChild(hrElement);
                if (!company.bbcId) {
                    _this.companySelectService.removeManualCompany(company.name);
                }
                else {
                    _this.companySelectService.removeCompany(company.bbcId);
                    _this.handleAddButtonToggle(company.bbcId);
                }
                _this.selectedCompanies = _this.companySelectService.getCompanies();
            });
        });
    };
    CompanySelectSearchResult.prototype.hideError = function () {
        this.$errorContainer.addClass("hide");
    };
    CompanySelectSearchResult.prototype.reset = function () {
        this.$companySearchResult.addClass("hide");
        this.hideError();
    };
    return CompanySelectSearchResult;
}());

var CompanySelectService = /** @class */ (function () {
    function CompanySelectService() {
        this.customEventHandler = new CustomEventHandler();
        this.gtmService = new GoogleDataLayerService();
        this.selectedCompanies = [];
        this.initializeCompanies();
    }
    CompanySelectService.prototype.triggerEmployerChangedEvent = function () {
        var self = this;
        $.getJSON(InternalApiEndpoints.getMemberCompany())
            .done(function (memberCompany) {
            self.customEventHandler.trigger(CustomEventHandler.employerChangedEventName, memberCompany);
        })
            .fail(function () {
            self.customEventHandler.trigger(CustomEventHandler.employerChangedEventName, null);
        });
    };
    CompanySelectService.prototype.saveCompaniesToSessionStorage = function (companies) {
        sessionStorage.setItem('companySelectAddedCompanies', JSON.stringify(companies));
        if (companies.length === 0)
            this.displayCompanyPlaceHolder();
    };
    CompanySelectService.prototype.loadCompaniesFromSessionStorage = function () {
        var companies = sessionStorage.getItem('companySelectAddedCompanies');
        return companies ? JSON.parse(companies) : [];
    };
    CompanySelectService.prototype.addCompany = function (company) {
        this.selectedCompanies.push(company);
        this.saveCompaniesToSessionStorage(this.selectedCompanies);
    };
    CompanySelectService.prototype.removeCompany = function (bbcId) {
        this.selectedCompanies = this.selectedCompanies.filter(function (company) { return company.bbcId !== bbcId; });
        this.saveCompaniesToSessionStorage(this.selectedCompanies);
    };
    CompanySelectService.prototype.removeManualCompany = function (name) {
        this.selectedCompanies = this.selectedCompanies.filter(function (company) { return company.name !== name; });
        this.saveCompaniesToSessionStorage(this.selectedCompanies);
    };
    CompanySelectService.getInstance = function () {
        if (!CompanySelectService.instance) {
            CompanySelectService.instance = new CompanySelectService();
        }
        return CompanySelectService.instance;
    };
    CompanySelectService.prototype.getCompanies = function () {
        if (this.selectedCompanies.length === 0) {
            this.initializeCompanies();
        }
        return this.selectedCompanies;
    };
    CompanySelectService.prototype.initializeCompanies = function () {
        this.displayCompanyPlaceHolder();
        this.selectedCompanies = this.loadCompaniesFromSessionStorage();
    };
    CompanySelectService.prototype.displayCompanyPlaceHolder = function () {
        var $companyListElement = $('#none-selected-company-text');
        if (!$companyListElement) {
            console.error('Element with id "none-selected-company-text" not found.');
            return;
        }
        $companyListElement.show();
    };
    return CompanySelectService;
}());

var CompanySelectWorkSituation = /** @class */ (function () {
    function CompanySelectWorkSituation($workSituationSection) {
        this.changeEmployerService = new CompanySelectService();
        var self = this;
        self.$workSituationSection = $workSituationSection;
        self.$workSituationRadioButtons = self.$workSituationSection.find("input[name='worksituation']");
        self.$notEmployedSection = self.$workSituationSection.find(".work-situation-section__notemployed");
        self.$saveNotEmployedLink = self.$workSituationSection.find(".work-situation-section__notemployed__save-button");
        self.$errorContainer = self.$workSituationSection.find(".work-situation-section__notemployed_error-container");
        self.spinner = new Spinner(self.$workSituationSection.find(".work-situation-section__notemployed__save-spinner"));
        self.isCurrentUserEditorOrContentViewer = self.$workSituationSection.data("iscurrentusereditororcontentviewer");
        self.attachEvents();
    }
    CompanySelectWorkSituation.prototype.changeSelectedWorkSituation = function (workSituationType) {
        var self = this;
        if (workSituationType === CompanySelectworkSituationType.Employed) {
            self.$workSituationRadioButtons.filter("[value='employed']").click();
        }
        else if (workSituationType === CompanySelectworkSituationType.NotEmployed) {
            self.$workSituationRadioButtons.filter("[value='notemployed']").click();
        }
    };
    CompanySelectWorkSituation.prototype.attachEvents = function () {
        var self = this;
        self.$workSituationRadioButtons.change(function (e) {
            if (self.onWorkSituationChanged === null)
                return;
            var workSituationType = CompanySelectworkSituationType.NotSet;
            var selectedRadioButtonValue = self.$workSituationRadioButtons.filter(":checked").val();
            if (selectedRadioButtonValue === "employed") {
                workSituationType = CompanySelectworkSituationType.Employed;
                self.$notEmployedSection.addClass("hide");
            }
            else if (selectedRadioButtonValue === "notemployed") {
                workSituationType = CompanySelectworkSituationType.NotEmployed;
                self.$notEmployedSection.removeClass("hide");
            }
            self.onWorkSituationChanged(workSituationType);
        });
        self.$saveNotEmployedLink.click(function (e) {
            e.preventDefault();
            self.deleteMemberCompany();
        });
    };
    CompanySelectWorkSituation.prototype.deleteMemberCompany = function () {
        var self = this;
        if (self.isCurrentUserEditorOrContentViewer) {
            self.handleError("Kan inte spara din arbetssituation", "Du är inte inloggad som medlem och har därför inte tillgång till att ändra din arbetsgivare.");
            return;
        }
        self.$saveNotEmployedLink.hide();
        self.spinner.show();
        $.post({
            url: InternalApiEndpoints.deleteMemberCompany()
        })
            .done(function () {
            self.changeEmployerService.triggerEmployerChangedEvent();
            window.location.href = "#/";
            if (self.onSaved !== null) {
                self.onSaved();
            }
        })
            .fail(function (jqueryXhr) {
            if (jqueryXhr.status === 401) {
                location.reload();
                return;
            }
            self.handleError(self.$workSituationSection.data("saveemployederrormessageheader"), self.$workSituationSection.data("saveemployederrormessagetext"));
        })
            .always(function () {
            self.$saveNotEmployedLink.show();
            self.spinner.hide();
        });
    };
    CompanySelectWorkSituation.prototype.handleError = function (header, description) {
        this.$errorContainer.removeClass("hide");
        var errorMessageBox = new ErrorMessageBox(header, description);
        errorMessageBox.append(this.$errorContainer);
        errorMessageBox.scrollTo(100);
    };
    CompanySelectWorkSituation.prototype.setFocusToFirstWorkSituationOption = function () {
        var $firstWorkSituationOption = this.$workSituationRadioButtons.first();
        $firstWorkSituationOption.attr("autofocus", ""); // Forces iPhone devices to set focus to the input field
        $firstWorkSituationOption.focus();
    };
    CompanySelectWorkSituation.prototype.reset = function () {
        this.changeSelectedWorkSituation(CompanySelectworkSituationType.Employed);
    };
    return CompanySelectWorkSituation;
}());

var CompanySelectFocusTrap = /** @class */ (function () {
    function CompanySelectFocusTrap($focusTrapArea, customEventFocusSuffixName) {
        this.tabbableElementsSelector = "select, input, textarea, button, a";
        this.detectorService = new DetectorService();
        this.inactivatedTabIndexAttributeName = "data-inactivatedtabindex";
        this.$focusTrapArea = $focusTrapArea;
        this.focusEventName = "focus.".concat(customEventFocusSuffixName);
        this.$root = $("body");
    }
    CompanySelectFocusTrap.prototype.activate = function () {
        var self = this;
        self.$root.on(self.focusEventName, self.tabbableElementsSelector, function (e) {
            if (self.isFocusInFocusTrapArea(e.target))
                return;
            self.setFocusToFirstTabbableElementInFocusTrapArea();
        });
        this.setInputTextsOutsideModalToNonTabbableForIosDevices();
    };
    CompanySelectFocusTrap.prototype.inactivate = function () {
        this.$root.off(this.focusEventName, this.tabbableElementsSelector);
        this.resetInputTextsOutsideModalToTabbableForIosDevices();
    };
    CompanySelectFocusTrap.prototype.isFocusInFocusTrapArea = function (currentFocusElement) {
        return this.$focusTrapArea.has(currentFocusElement).length > 0;
    };
    CompanySelectFocusTrap.prototype.setFocusToFirstTabbableElementInFocusTrapArea = function () {
        this.$focusTrapArea.find(this.tabbableElementsSelector).first().focus();
    };
    // IOS devices can with the virtual keyboard tab to next/prev input field of type text. When doing this IOS devices scrolls
    // to the specific input field which can be outside our focus trap. This results in an incorrect position.
    CompanySelectFocusTrap.prototype.setInputTextsOutsideModalToNonTabbableForIosDevices = function () {
        if (!this.detectorService.isIosDevice())
            return;
        var self = this;
        this.getAllInputTextsOutsideFocusArea().each(function (index, input) {
            var $input = $(input);
            if ($input.attr("tabindex")) {
                $input.attr(self.inactivatedTabIndexAttributeName, $input.attr("tabindex"));
            }
            else {
                $input.attr(self.inactivatedTabIndexAttributeName, "");
            }
            $input.attr("tabindex", "-1");
        });
    };
    CompanySelectFocusTrap.prototype.resetInputTextsOutsideModalToTabbableForIosDevices = function () {
        if (!this.detectorService.isIosDevice())
            return;
        var self = this;
        this.getAllInputTextsOutsideFocusArea().each(function (index, input) {
            var $input = $(input);
            var inactivatedTabindex = $input.attr(self.inactivatedTabIndexAttributeName);
            if (inactivatedTabindex !== undefined) {
                if (inactivatedTabindex) {
                    $input.attr("tabindex", inactivatedTabindex);
                }
                else {
                    $input.removeAttr("tabindex");
                }
                $input.removeAttr(self.inactivatedTabIndexAttributeName);
            }
        });
    };
    CompanySelectFocusTrap.prototype.getAllInputTextsOutsideFocusArea = function () {
        return $("input[type='text']").not(this.$focusTrapArea.find("input"));
    };
    return CompanySelectFocusTrap;
}());

//class CompanySelectAddedCompanies {
//    companies: CompanySelectCompany[] = [];
//}
var CompanySelectCompany = /** @class */ (function () {
    function CompanySelectCompany(bbcId, name, street, zipCode, city, phone, organisationNumber, countryCode, countryName, addedManually) {
        this.bbcId = null;
        this.name = null;
        this.street = null;
        this.zipCode = null;
        this.city = null;
        this.phone = null;
        this.organisationNumber = null;
        this.countryCode = null;
        this.countryName = null;
        this.bbcId = bbcId !== null && bbcId !== void 0 ? bbcId : "";
        this.name = name !== null && name !== void 0 ? name : "";
        this.street = street !== null && street !== void 0 ? street : "";
        this.zipCode = zipCode !== null && zipCode !== void 0 ? zipCode : "";
        this.city = city !== null && city !== void 0 ? city : "";
        this.phone = phone !== null && phone !== void 0 ? phone : "";
        this.organisationNumber = organisationNumber !== null && organisationNumber !== void 0 ? organisationNumber : "";
        this.countryCode = countryCode !== null && countryCode !== void 0 ? countryCode : "";
        this.countryName = countryName !== null && countryName !== void 0 ? countryName : "";
        this.addedManually = addedManually !== undefined ? addedManually : false;
    }
    return CompanySelectCompany;
}());

var CompanySelectLocation = /** @class */ (function () {
    function CompanySelectLocation() {
    }
    return CompanySelectLocation;
}());

var CompanySelectModalView;
(function (CompanySelectModalView) {
    CompanySelectModalView[CompanySelectModalView["SelectCompanyView"] = 0] = "SelectCompanyView";
    CompanySelectModalView[CompanySelectModalView["ManualCompanyView"] = 1] = "ManualCompanyView";
})(CompanySelectModalView || (CompanySelectModalView = {}));

var CompanySelectSearchParameters = /** @class */ (function () {
    function CompanySelectSearchParameters() {
        this.query = null;
        this.city = null;
        this.countryCode = null;
        this.countryName = null;
        this.pageIndex = null;
    }
    return CompanySelectSearchParameters;
}());

var CompanySelectworkSituationType;
(function (CompanySelectworkSituationType) {
    CompanySelectworkSituationType[CompanySelectworkSituationType["NotSet"] = 0] = "NotSet";
    CompanySelectworkSituationType[CompanySelectworkSituationType["Employed"] = 1] = "Employed";
    CompanySelectworkSituationType[CompanySelectworkSituationType["NotEmployed"] = 2] = "NotEmployed";
})(CompanySelectworkSituationType || (CompanySelectworkSituationType = {}));

var SearchComanySelectResult = /** @class */ (function () {
    function SearchComanySelectResult() {
        this.hitsTotal = null;
        this.pageIndex = null;
        this.pageSize = null;
        this.hasMorePages = null;
        this.companies = [];
        this.countries = null;
        this.cities = null;
    }
    return SearchComanySelectResult;
}());

var SearchCompanySelectSummary = /** @class */ (function () {
    function SearchCompanySelectSummary(searchParameters) {
        if (searchParameters === void 0) { searchParameters = null; }
        this.query = null;
        this.city = null;
        this.countryCode = null;
        this.countryName = null;
        this.pageIndex = null;
        if (searchParameters === null)
            return;
        this.query = searchParameters.query;
        this.city = searchParameters.city;
        this.countryCode = searchParameters.countryCode;
        this.countryName = searchParameters.countryName;
        this.pageIndex = searchParameters.pageIndex;
    }
    SearchCompanySelectSummary.prototype.isSearchingInSweden = function () {
        return this.countryCode !== null && this.countryCode.toLowerCase() === "se";
    };
    return SearchCompanySelectSummary;
}());

var SearchResultCompanySelect = /** @class */ (function () {
    function SearchResultCompanySelect() {
        this.bbcId = null;
        this.name = null;
        this.address = null;
        this.zipCode = null;
        this.city = null;
        this.phone = null;
        this.organisationNumber = null;
        this.countryCode = null;
        this.countryName = null;
    }
    return SearchResultCompanySelect;
}());

// ReSharper disable UnusedLocals
var GlobalApp = /** @class */ (function () {
    function GlobalApp() {
        $(".information-browser-block")
            .each(function () {
            var informationBrowserBlock = new InformationBrowserBlockApp($(this));
        });
        var font = new FontFaceObserver("Glypha");
        font.load(null, 7000).then(function () {
            $("body").removeClass("fallback-font");
        }, function () {
            console.log("Font is not available");
        });
        var iframe = new Iframe();
        var windowRefreshHubApp = new WindowRefreshHubApp();
        var utmCampaignService = new UtmCampaignService();
        var deviceSizeService = new DeviceSizeService();
        var expandable = new Expandable(".expandable");
        var mobileNavigation = new MobileNavigation("#mobile-navigation-closed", "#mobile-navigation-open", ".mobile-navigation__container", false);
        var mypagesmobileNavigation = new MobileNavigation("#toggle-my-menu[data-state='non-active']", "#toggle-my-menu[data-state='active']", ".mypages-mobile-navigation__container", true);
        var print = new Print(".print-button");
        var sharePageService = new SharePageService(".share-module");
        $(".accept-terms-info-link")
            .each(function () {
            var termsCheckbox = new TermsCheckbox($(this));
        });
        /*        var cookieBar = new CookieBar(".cookie-bar");*/
        var emergencyMessageBar = new EmergencyMessageBar(".emergency-message-bar");
        var popoutToggler = new PopoutToggler("#toggle-my-menu", "[data-function='popout']", true, true);
        var quicksearchToggler = new PopoutToggler("#quicksearch-toggler", "[data-function='quicksearch']", false);
        var topNavigationLinkTooltip = new TopNavigationLinkTooltipService(".top-navigation__link");
        var autoCompleteSearch = new AutoCompleteSearch(".autocomplete-search");
        autoCompleteSearch.onSelect = function () {
            $("#quicksearch-container .search-form").submit();
        };
        var searchClear = new SearchClear();
        var blocksInXhtmlMoveToClosestParagraph = new BlocksInXhtmlMoveToClosestParagraph("span.move-me-to-closest-p");
        $(".EPiServerForms .FormFileUpload")
            .each(function () {
            var episerverFileUploadService = new EpiserverFileUploadService($(this));
        });
        $(".entrance-block")
            .each(function () {
            var entranceBlock = new EntranceBlock("#" + $(this).attr("id"));
        });
        $(".linkable-block")
            .each(function () {
            var linkableBlock = new LinkableBlock("#" + $(this).attr("id"));
        });
        $(".faq-feedback")
            .each(function () {
            var faqFeedback = new FaqFeedback("#" + $(this).attr("id"));
        });
        $(".one-puff-block.one-puff-block__has-video")
            .each(function () {
            var onePuffBlockWithVideo = new OnePuffBlockWithVideo("#" + $(this).attr("id"));
        });
        $(".membership-cost-block")
            .each(function () {
            var membershipCostBlock = new MembershipCostBlock("#" + $(this).attr("id"));
        });
        $(".employment-block2").each(function () {
            var employmentBlock2 = new EmploymentBlock2App($(this));
        });
        $(".my-information-summary").each(function () {
            var myInformationSummary = new MyInformationSummary($(this));
        });
        $(".anchorlinkblock").each(function () {
            var anchorLinkBlockApp = new AnchorLinkBlockApp($(this));
        });
        var logoutTracking = new LogoutTracking();
        var globalAssetsTracking = new GlobalAssetsTracking("globalassets", "lathund-linkedin.pdf", 7697, "Tips för en bättre Linkedinprofil - Klickat på lathund-linkedin.pdf", "Inaktiv medlem");
        var accordionAnchorLinkService = new AccordionAnchorLinkService();
        accordionAnchorLinkService.init();
        $(".iframe-cookie-consent").each(function () {
            var iframeCookieConsent = new IframeCookieConsent($(this));
        });
        //$(".feedback-tab").each(function () {
        //    const cookieFeedbackToggler = new CookieFeedbackToggler($(this));
        //})
        $(window).load(function () {
            // We want to execute this accordionStateService as late as possible since another script may be manipulating the DOM:
            // this could result in unwanted behaviour. For example the member registration page where the content areas
            // are removed from the DOM between the different steps.
            var accordionStateService = new AccordionStateService();
            accordionStateService.init();
        });
        if (GlobalSettingsSingleton.getInstance().isInEditMode()) {
            $('.displayInEditMode').show();
        }
    }
    return GlobalApp;
}());
$(function () {
    var customEventHandler = new CustomEventHandler();
    imageHelper = new ImageHelper();
    var globalApp = new GlobalApp();
});

